绘制 MNIST 样本

plotting MNIST samples

我正在尝试从 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()

由于某种原因,零数字在图中被跳过。

为什么?

试试这个:

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

fig, ax = plt.subplots(2,5)
ax = ax.flatten()
for i in range(10):
    im_idx = np.argwhere(y == i)[0]
    print(im_idx)
    plottable_image = np.reshape(X[im_idx], (28, 28))
    ax[i].imshow(plottable_image, cmap='gray_r')

输出:

好的,我明白了。问题是您在绘制 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')