python - np.where IndexError 异常
问题描述
我有一个非常简单的代码如下:
import numpy as np
num_classes = 12
im_pred = np.random.randint(0, num_classes, (224, 244))
img = np.zeros((224, 224, 3))
print(im_pred.shape)
#(224, 244)
print(img.shape)
#(224, 224, 3)
for i in range(num_classes):
img[np.where(im_pred==i), :] = [225, 0, 0]
Traceback(最近一次调用最后一次):
文件“”,第 2 行,在 <module>
IndexError:索引 227 超出轴 0 的范围,大小为 224
x, y = np.where(im_pred==i)
print(np.max(x), np.max(y))
#223 243
为什么我得到一个IndexError
?至于我的理解np.where
,返回的索引值应该小于224
.
让我知道。我开始怀疑numpy
安装是否有问题。
谢谢。
解决方案
No Numpy is not buggy. Look at how you defined im_pred for a second, you are drawing a random integer between 0 and 11 for an array which has size 224 by 244. So the reason it is throwing an error is because the dimension of size 244 is too large for your variable img which is only 224 by 224 by 3. I think you may have meant for both to have the same 1rst and second dimensions, something like
img = np.zeros((224,244,3))
推荐阅读
- c++ - 将 std::get 作为参数传递给函数的函数对象
- date - 如何在 Google 表格中将 HTTP 标头日期转换为日期?
- java - 如何修复错误以便我可以使用插入排序
- java - 如何结合java嵌套列表和sum特定变量
- pandas - 计算数据框中的值
- hyperledger-fabric - 错误:没有来自任何对等方的有效响应。执行交易失败 无法启动链码
- javascript - 通过 express 从 mongo 获取数据,构建对象并发送到 React
- python - 确定事件之间的天数,不包括python中的周末
- c# - VsCode 快捷方式不去实现
- google-sheets - COUNTA 在期望 0 时返回 1,即使使用了 IFNA