我正在尝试从 MNIST 数据集中绘制 10 个样本。每个数字之一。这是代码:
import sklearn
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
mnist = datasets.fetch_mldata('MNIST original')
y = mnist.target
X = mnist.data
for i in range(10):
im_idx = np.argwhere(y == i)[0]
print(im_idx)
plottable_image = np.reshape(X[im_idx], (28, 28))
plt.imshow(plottable_image, cmap='gray_r')
plt.subplot(2, 5, i + 1)
plt.plot()
由于某种原因,零数字在图中被跳过。
为什么?
最佳答案
好的,我知道了。问题是您在绘制 imshow
之后定义子图。所以你的第一个子图被第二个覆盖了。要使您的代码正常工作,只需按如下方式交换两个命令的顺序。另外,我不明白你为什么在最后使用 plt.plot()
。
plt.subplot(2, 5, i + 1) # <-- You have put this command after imshow
plt.imshow(plottable_image, cmap='gray_r')
这是您知识的另一个替代方法:
fig = plt.figure()
for i in range(10):
im_idx = np.argwhere(y == i)[0]
plottable_image = np.reshape(X[im_idx], (28, 28))
ax = fig.add_subplot(2, 5, i+1)
ax.imshow(plottable_image, cmap='gray_r')
您还可以使用以下代码进一步缩短 Scott 的代码(在下面发布):
fig, ax = plt.subplots(2,5)
for i, ax in enumerate(ax.flatten()):
im_idx = np.argwhere(y == i)[0]
plottable_image = np.reshape(X[im_idx], (28, 28))
ax.imshow(plottable_image, cmap='gray_r')
关于python - 绘制 MNIST 样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53837545/