Search code examples
pythonmnistdata-augmentation

Index out of bounds error in images displays


let us consider following code :

from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
X_train =X_train.reshape(X_train.shape[0],1,28,28)
X_test =X_test.reshape(X_test.shape[0],1,28,28)
X_train =X_train.astype('float32')
X_test =X_test.astype('float32')
datagen =ImageDataGenerator(featurewise_center=True,featurewise_std_normalization=True)
datagen.fit(X_train)
for X_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9):
# create a grid of 3x3 images
 for i in range(9):
     plt.subplot(330 + 1 + i)
     plt.imshow(X_batch[i].reshape(28, 28), cmap=plt.get_cmap('gray'))
# show the plot
plt.show()
break 

it gives me following error :

IndexError: index 6 is out of bounds for axis 0 with size 6

it should be noted that previous code for generating mnist dataset works fine

from keras.datasets import mnist
import matplotlib.pyplot as plt
(X_train,y_train),(X_test,y_test) =mnist.load_data()
for i in range(0, 9):
  plt.subplot(330 + 1 + i)
  plt.imshow(X_train[i], cmap=plt.get_cmap('gray'))
plt.show()

here is its result : enter image description here


Solution

  • You have wrong indentation, plt.show and break should be at the level of the inner loop but you have them at the level of the outer loop.

    for X_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9):
      for i in range(9):
        plt.subplot(330 + 1 + i)
        plt.imshow(X_batch[i].reshape(28, 28), cmap=plt.get_cmap('gray'))
      # show the plot
      plt.show()
      break