索引错误:索引 3 超出了大小为 3 的轴 1 的范围 [英] Index Error: index 3 is out of bounds for axis 1 with size 3

查看:200
本文介绍了索引错误:索引 3 超出了大小为 3 的轴 1 的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行以下代码,其中函数 weighted_values 返回具有指定概率的随机值序列.我正在使用此答案中的此函数 Generating Discrete-or-numpy具有权重的随机变量

I am running the following code where the function weighted_values returns a sequence of random values with probabilities as specified. I am using this function from this answer Generating discrete random variables with weights

以下是我的代码:

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)

但是,当我运行此代码时,有时会出现此错误

However when I run this code, sometimes I get this error that

 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

谁能建议我做错了什么以及如何修改它?

Can anyone suggest what I am doing wrong and how to modify it?

推荐答案

错误告诉我你有一个形状为 (n,3) (axis 1 size 3) 的数组,并且你尝试使用 3

The error tells me that you have an array with shape (n,3) (axis 1 size 3), and that you trying to index it with 3

In [9]: np.ones((5,3))[:,3]
... 
IndexError: index 3 is out of bounds for axis 1 with size 3

在问题陈述中:

values[np.digitize(random_sample(size), bins)]

我建议检查 values 的形状.手边看起来它是 np.arange(M+1),其中 M 是 2.这是大小 3,但是 1d.

I'd suggest checking the shape of values. Off hand it looks like it is np.arange(M+1) where M is 2. That's size 3, but 1d.

还有 np.digitize(random_sample(size), bins) 产生什么?

当您遇到此类错误时,您需要检查可疑数组的形状,并检查索引值的范围.仅通过阅读您的代码,我们只能猜测这么多.

When you have errors like this you need to check the shape of suspected arrays, and check the range of values of the indices. We can only guess so much from just reading your code.

这篇关于索引错误:索引 3 超出了大小为 3 的轴 1 的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆