python - 绘制 MNIST 样本

标签 python matplotlib data-science mnist

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

enter image description here

关于python - 绘制 MNIST 样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53837545/

相关文章:

python - 文件/目录删除时提示

Python Matplotlib : black squares when saving eps of plot of masked array, 为什么?

python - 如何在 python 中处理数据但添加到 MERN Stack 应用程序

python - 这是生成 rsa key 的正确方法吗?

python - 通过在两个 Pandas 数据帧之间迭代来识别相似的值。

python - Visual Studio 2012 中的 IronPython

python - 在 matplotlib 中绘制值与字符串的关系?

python - 如何绘制任意一点抛物线的斜率(切线)?

python - 如何删除文本列中的微小变化

python - 无论如何知道sklearn GridSearch的进展