如何解决将数据加载到临时numpy数组中时出错:“ IndexError:索引0超出了大小为0的轴0的范围” 输出
我有以下代码。我正在检索一张图像的预测结果,并将其存储在tmp
numpy数组中。
print(predictions.shape) # 14,14,512
tmp=np.zeros((0,512))
for i in range(0,1):
tmp[i,:,:]=predictions[i,:]
运行上述代码时收到错误。
IndexError: index 0 is out of bounds for axis 0 with size 0
解决方法
以元组从零开始的对numpy.zeros()
的调用导致数组为空。
>>> import numpy as np
>>> tmp = np.zeros((0,14,512))
>>> tmp
array([],shape=(0,512),dtype=float64)
要用零初始化tmp
,可以执行以下操作:
>>> tmp = np.zeros((14,512))
>>> tmp
array([[[0.,0.,...,0.],[0.,0.]],...
完整示例
import numpy as np
predictions = np.random.randint(9,size=(14 * 14 * 512)).reshape((14,512))
print(f"shape of predictions: {predictions.shape}")
tmp = np.zeros((14,512))
tmp[0,:,:] = predictions[0,:]
print(f"shape of tmp: {tmp.shape}")
print(f"tmp data:\n{tmp}")
输出
shape of predictions: (14,512)
shape of tmp: (14,512)
tmp data:
[[[0. 0. 8. ... 6. 8. 1.]
[8. 6. 0. ... 4. 5. 3.]
[7. 6. 2. ... 6. 7. 6.]
...
[4. 2. 4. ... 1. 5. 8.]
[4. 3. 8. ... 0. 5. 0.]
[4. 5. 3. ... 0. 0. 1.]]
[[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
...
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]]
...
另请参见
What does 'index 0 is out of bounds for axis 0 with size 0' mean?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。