【问题标题】:Index out of bounds error in images displays图像显示中的索引超出范围错误
【发布时间】:2020-07-24 14:24:29
【问题描述】:

让我们考虑以下代码:

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

这是它的结果:

【问题讨论】:

    标签: python mnist data-augmentation


    【解决方案1】:

    你有错误的缩进,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 
    

    【讨论】:

    • 你能用几句话解释一下在这种情况下缩进和超出索引错误之间的关系吗?
    • 您希望循环运行 9 次 - (3x3) 网格,然后您需要从该循环中中断,否则您的循环将继续,您的逻辑将沿线某处中断。由于break 在您的代码中缩进不正确,它不会在应该执行的时候执行(即在外循环的第一遍之后)。
    • 那么第二个循环的最佳选择是什么?它应该是 9 还是某个数字,这使得第一个循环运行的次数之间存在关系?例如批量大小或类似的东西
    • 取决于您想要实现的目标。你想显示所有 MNIST 中的 50000 多张图像吗?
    • 在这种情况下,你的循环就好了。外循环与它无关,它只是循环遍历所有图像——这就是为什么你需要打破它。您只需要确保内部循环范围和plt.subplot(330 + 1 + i) 中的数字兼容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多