matplotlib - Matplotlib ValueError:num 必须是 1 <= num <= 20,而不是 0
问题描述
我正在关注在 MNIST 手写数字上在 Keras中构建自动编码器的教程。下面是代码:
input_img = Input(shape=(28, 28, 1)) # adapt this if using `channels_first` image data format
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)
# at this point the representation is (4, 4, 8) i.e. 128-dimensional
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 = 10
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
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)
# display reconstruction
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)
is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
。您不能使用 0 作为子图的索引,这会导致该错误。您应该改为使用i+1
in yourplt.subplot()
来获得正确的轴。
推荐阅读
- r - ggraph 弧形图剪辑标签文本
- python - JupyterLab / Python / Pandas - Comparing two Dataframes
- javascript - React 自定义轮播优化
- node.js - NodeJS - 控制器没有将 JSON 返回到路由
- css - 使用 flexbox 设计带有主要内容 + 粘性页眉/页脚的侧边栏
- c - c语言,指针运算
- xamarin - 如何在 Xamarin 中实现带有尾随图标的材料概述文本字段。形式
- java - 在 Consumer 之间均匀分布 Kafka 分区
- yarnpkg - 为我的项目安装纱线时版本描述符“berry”无效
- r - 如何使用ggplot2将图例标题和键顺序和颜色更改为R中的多层条形图