将数据加载到临时 numpy 数组时出错:"IndexError: index 0 is out of bounds for axis 0 with size 0"



我有以下代码。我正在检索一个图像的预测结果,并将其存储在tmpnumpy数组中。

print(predictions.shape) # 14,14,512
tmp=np.zeros((0, 14, 14, 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, 14, 512))
>>> tmp
array([], shape=(0, 14, 14, 512), dtype=float64)

要用零初始化tmp,可以执行以下操作:

>>> tmp = np.zeros((14, 14, 512))
>>> tmp
array([[[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.]],
...

完整示例

import numpy as np
predictions = np.random.randint(9, size=(14 * 14 * 512)).reshape((14, 14, 512))
print(f"shape of predictions: {predictions.shape}")
tmp = np.zeros((14, 14, 512))
tmp[0,:,:] = predictions[0,:]
print(f"shape of tmp: {tmp.shape}")
print(f"tmp data:n{tmp}")

输出

shape of predictions: (14, 14, 512)
shape of tmp: (14, 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.]]
...

另请参阅

"索引0超出大小为0的轴0的界限"是什么意思

相关内容

最新更新