我正在按照Keras中构建自编码器的教程学习MNIST手写数字识别。以下是代码:
input_img = Input(shape=(28, 28, 1)) # 如果使用`channels_first`图像数据格式,请调整此处x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)x = MaxPooling2D((2, 2), padding='same')(x)x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)x = MaxPooling2D((2, 2), padding='same')(x)x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)encoded = MaxPooling2D((2, 2), padding='same')(x)# 此时表示为(4, 4, 8),即128维x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)x = UpSampling2D((2, 2))(x)x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)x = UpSampling2D((2, 2))(x)x = Conv2D(16, (3, 3), activation='relu')(x)x = UpSampling2D((2, 2))(x)decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)autoencoder = Model(input_img, decoded)autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
在加载Mnist数据集并训练我们的模型后,我们将在这里绘制原始和重建的图像
decoded_imgs = autoencoder.predict(x_test)n = 10plt.figure(figsize=(20, 4))for i in range(n): # 显示原始图像 ax = plt.subplot(2, n, i) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # 显示重建图像 ax = plt.subplot(2, n, i + n) plt.imshow(decoded_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)plt.show()
我搜索了很多试图解决这个问题但没有找到解决方案,以下是显示的错误:
---------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-35-d0a536786436> in <module>() 5 for i in range(n): 6 # display original----> 7 ax = plt.subplot(2, n, i) 8 plt.imshow(x_test[i].reshape(28, 28)) 9 plt.gray()2 frames/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_subplots.py in __init__(self, fig, *args, **kwargs) 64 if num < 1 or num > rows*cols: 65 raise ValueError(---> 66 f"num must be 1 <= num <= {rows*cols}, not {num}") 67 self._subplotspec = GridSpec( 68 rows, cols, figure=self.figure)[int(num) - 1]ValueError: num must be 1 <= num <= 20, not 0<Figure size 1440x288 with 0 Axes>
回答:
在第一次循环中,i==0,因为range(10)
是[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
。你不能使用0作为子图的索引,这会导致该错误。你应该在plt.subplot()
中使用i+1
来获得正确的轴。