1

I have the following code. I am retrieving the prediction results of one image and storing it in a tmp numpy array.

print(predictions.shape) # 14,14,512
tmp=np.zeros((0, 14, 14, 512))
for i in range(0, 1):
   tmp[i,:,:]=predictions[i,:]

Error received running the above code.

IndexError: index 0 is out of bounds for axis 0 with size 0
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117

1 Answers1

1

The call to numpy.zeros() with a tuple starting with zero results in the array being empty.

>>> import numpy as np
>>> tmp = np.zeros((0, 14, 14, 512))
>>> tmp
array([], shape=(0, 14, 14, 512), dtype=float64)

To initialize tmp with zeros, you could do:

>>> 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.]],
...

Complete example

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}")

Output

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.]]

 ...

See also

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117