python - 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
解决方案
你应该告诉我们一些关于代码和数据的事情。是你写的还是别人的?它是新的,还是以前有效,可能在其他情况下?什么是:
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]])
我最初应该扩展zip
with :tuple
In [502]: x[tuple(zip(*tmp))]
Out[502]: array([ 4, 13, 2, 11])
解决了这个问题后,我现在怀疑这段代码最初适用于 Python2。
推荐阅读
- python - 使用 Barcode,python 将多个条形码写入一个文件
- dart - 如何在 Flutter 中返回部分 Widget 列表
- c# - ASP.NET Core 2.1 cookie 身份验证似乎具有服务器关联性
- scala - 使用 Web 套接字的 Akka http 内存泄漏
- php - 即使使用 utf8mb4_unicode_ci,MySQL 也会出现“不正确的字符串值”错误
- kotlin - GlobalScope vs LifecycleOwner:CoroutineScope
- c++ - 如何确保在 C++ 中只输出 6 位、0 填充的十六进制值?
- javascript - createMemoryHistory 仍然报告“浏览器历史需要一个 DOM”
- reactjs - 重置表单后如何更改状态?
- python - 如何在redis中获取特定范围内的索引键?