CNN 入门, pycharm 报错:数组是 0 维的,但是有 1 个被索引了

2022-02-11 17:01:53 +08:00
 ALLROBOT

IndexError: too many indices for array: array is 0-dimensional, but 1 were indexedS

计算误差项反向传播,结果报错了

具体代码参见https://github.com/allrobot/Transit_Depot/tree/main/cnn

教程抄的代码,搞不懂有一个被索引了表达什么意思,能指教一下这里如何处理吗?

1870 次点击
所在节点    Python
5 条回复
013231
2022-02-11 17:37:14 +08:00
这是 numpy 的错误。对 0 维数组(一个标量转化成的数组)索引导致的。你看看 conv 的前 3 个参数是哪个出问题了。
qwq11
2022-02-11 17:44:10 +08:00
0 维:
arr
1 维:
arr[i]
二维:
arr[i, j]
三维:
arr[i, j, k]
不知道 0 维怎么表示,总之就是 n 维数组你需要 n 个 index 去索引,但是对于 0 维数组你使用了 1 个 index 去索引
ALLROBOT
2022-02-11 19:04:27 +08:00
@qwq11 @013231 原来是这么解释的,感谢!报错挺奇怪的,conv 参数分别是卷积输入矩阵、卷积核( filter )、输出矩阵(全零矩阵)、步长和偏置项,计算的是卷积输出
```python
def conv(input_array, kernel_array, output_array, stride, bias):
"""
计算卷积,自动适配输入为 2D 和 3D 的情况
"""
channel_number = input_array.ndim
output_width = output_array.shape[1]
output_height = output_array.shape[0]
kernel_width = kernel_array.shape[-1]
kernel_height = kernel_array.shape[-2]
for i in range(output_height):
for j in range(output_width):
output_array[i][j] = (get_patch(input_array, i, j, kernel_width,
kernel_height, stride) * kernel_array
).sum() + bias
```

怎么会提示下标太多,多了一个 indexed ?
013231
2022-02-11 19:10:10 +08:00
@ALLROBOT 问题不在 conv 内部,是调用处的问题。padded_array 或 flipped_weights 是 0 维数组。
ALLROBOT
2022-02-11 19:35:43 +08:00
@013231 解决了,教程的 CNN 代码是 python2 ,我改成 python3 ,有些函数不兼容导致报错~
上面 180 度翻转误差项矩阵的代码中,map 在 py2 返回列表,py3 返回迭代器
添加 list 就完事了
```
flipped_weights = np.array(list(map(
lambda i: np.rot90(i, 2),
filter.get_weights())))
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/833250

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX