我正在运行以下代码,其中函数weighted_values返回具有指定概率的随机值序列。我正在使用这个答案中的这个函数生成具有权重的离散随机变量
以下是我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此代码时,有时会收到此错误
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
Run Code Online (Sandbox Code Playgroud)
谁能建议我做错了什么以及如何修改它?
该错误告诉我您有一个形状为(n,3)(轴 1 大小为 3)的数组,并且您试图用3
In [9]: np.ones((5,3))[:,3]
...
IndexError: index 3 is out of bounds for axis 1 with size 3
Run Code Online (Sandbox Code Playgroud)
在问题陈述中:
values[np.digitize(random_sample(size), bins)]
Run Code Online (Sandbox Code Playgroud)
我建议检查values. 手边看起来它是 2 的np.arange(M+1)位置M。那是 3 号,但是 1d。
还np.digitize(random_sample(size), bins)生产什么?
当您遇到此类错误时,您需要检查可疑数组的形状,并检查索引值的范围。我们只能通过阅读您的代码来猜测这么多。
| 归档时间: |
|
| 查看次数: |
36556 次 |
| 最近记录: |