我运行以下代码,其中函数weighted_values
返回具有指定概率的随机值序列。我使用这个功能,从这个答案Generating discrete random variables with weights索引错误:索引3超出大小为3的轴1的边界
以下是我的代码:
def weighted_values(values, probabilities, size):
bins = np.add.accumulate(probabilities)
return np.array(values[np.digitize(random_sample(size), bins)])
def weak_softmax(a):
b=np.exp(a)
return b/(1+sum(b))
elements=np.array([1,2,3])
prob=np.array([0.2,0.5,0.3])
system_index=0;
T=10;M=2;
for t in np.arange(T):
prob=weak_softmax(np.random.uniform(0,1,M+1));
system_index=weighted_values(np.arange(M+1),prob,1)[0]
print(system_index)
然而,当我运行此代码,有时我得到这个错误
Traceback (most recent call last):
File "gradient_checking.py", line 75, in <module>
system_index=weighted_values(np.arange(M+1),prob,1)[0]
File "gradient_checking.py", line 57, in weighted_values
return np.array(values[np.digitize(random_sample(size), bins)])
IndexError: index 3 is out of bounds for axis 1 with size 3
任何人都可以提出什么我做错了,如何修改它?
你可以发布你的整个代码以及完整的错误和它被抛出的行吗?什么是'random_sample(...)'在做什么? –
@Shiva:random_sample显然会产生介于0和1之间的统一随机数,正如前面答案的链接所述。 – pikachuchameleon