Matplotlib ValueError: num必须在1到20之间,不能为0

我正在按照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来获得正确的轴。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注