【问题标题】:plotting MNIST samples绘制 MNIST 样本
【发布时间】:2019-05-19 03:18:07
【问题描述】:

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

由于某种原因,图中的零位被跳过了。

为什么?

【问题讨论】:

    标签: python matplotlib data-science mnist


    【解决方案1】:

    试试这个:

    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')
    

    输出:

    【讨论】:

    • 这也是您的解决方案的赞成票:) 检查我对您的代码的替代缩短答案
    【解决方案2】:

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

    【讨论】:

    • 寻找 OP 代码起作用的原因?为您的解决方案 +1。
    • @ScottBoston:找到问题
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2014-10-06
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多