图像显示中的索引越界错误

Index out of bounds error in images displays

让我们考虑以下代码:

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 

它给我以下错误:

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

需要注意的是之前生成mnist数据集的代码工作正常

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()

这是它的结果:

您的缩进有误,plt.showbreak 应该位于内部循环的级别,但您的缩进位于外部循环的级别。

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