Python 索引错误:索引 3 超出了大小为 3 的轴 1 的范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41665398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Index Error: index 3 is out of bounds for axis 1 with size 3
提问by pikachuchameleon
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
我正在运行以下代码,其中函数weighted_values
返回具有指定概率的随机值序列。我正在使用这个答案中的这个函数生成具有权重的离散随机变量
The following is my code:
以下是我的代码:
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?
谁能建议我做错了什么以及如何修改它?
回答by hpaulj
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
该错误告诉我您有一个形状为(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
In the problem statement:
在问题陈述中:
values[np.digitize(random_sample(size), bins)]
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.
我建议检查values
. 手边看起来它是 2 的np.arange(M+1)
位置M
。那是 3 号,但是 1d。
Also what does np.digitize(random_sample(size), bins)
produce?
还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.
当您遇到此类错误时,您需要检查可疑数组的形状,并检查索引值的范围。我们只能通过阅读您的代码来猜测这么多。
回答by Edward
This is caused because Python (unlike R) is zero-based. That means if you have three elements their indexes are 0,1,2 not 1,2,3. So if you are trying to reference "3" it will be pulling the fourth element from the array not the third (because zero is the first)
这是因为 Python(与 R 不同)是从零开始的。这意味着如果你有三个元素,它们的索引是 0,1,2 而不是 1,2,3。因此,如果您尝试引用“3”,它将从数组中提取第四个元素而不是第三个元素(因为零是第一个)