首页 > 解决方案 > IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引 men2n

问题描述

我收到此错误如何解决此问题

def fprop(self, input_data, target_data):
    tmp = [(t, i) for i, t in enumerate(target_data)]
    z = zip(*tmp)  # unzipping trick !
    cost = np.sum(np.log(input_data[z]))
    if self.size_average:
        cost /= input_data.shape[1]

错误

cost = np.sum(np.log(input_data[z]))
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

标签: pythonnumpy

解决方案


你应该告诉我们一些关于代码和数据的事情。是你写的还是别人的?它是新的,还是以前有效,可能在其他情况下?什么是:

input_data, target_data

但是让我们做一个合理的猜测,并逐步探索代码(这是您应该自己完成的事情):

In [485]: alist = [1,3,0,2]                                                                                  
In [486]: tmp = [(t,i) for i,t in enumerate(alist)]                                                          
In [487]: tmp                                                                                                
Out[487]: [(1, 0), (3, 1), (0, 2), (2, 3)]
In [488]: z = zip(*tmp)                                                                                      
In [489]: z                                                                                                  
Out[489]: <zip at 0x7ff381d50188>

在 Python 3 中,zip生成一个zip对象,一个生成器。这显然不能成为任何事物的索引。

我们可以把它变成一个列表,这是 Python2 会做的:

In [490]: list(z)                                                                                            
Out[490]: [(1, 3, 0, 2), (0, 1, 2, 3)]

但是那个元组列表有点好:

In [491]: x = np.arange(16).reshape(4,4)                                                                     
In [492]: x[_490]                                                                                            
/usr/local/bin/ipython3:1: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
  #!/usr/bin/python3
Out[492]: array([ 4, 13,  2, 11])

如果我们把它变成一个元组的元组,numpy就可以在没有警告的情况下工作:

In [493]: x[tuple(_490)]                                                                                     
Out[493]: array([ 4, 13,  2, 11])

这与使用alist每列选择一个值相同:

In [494]: x[alist, np.arange(4)]                                                                             
Out[494]: array([ 4, 13,  2, 11])

In [495]: x                                                                                                  
Out[495]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

我最初应该扩展zipwith :tuple

In [502]: x[tuple(zip(*tmp))]                                                                                
Out[502]: array([ 4, 13,  2, 11])

解决了这个问题后,我现在怀疑这段代码最初适用于 Python2。


推荐阅读