MNIST 随机样本绘图不起作用

MNIST random sample plotting is not working

我正在随机抽取 MNIST data set,但它显示错误。我哪里做错了?

import sklearn
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import fetch_openml

mnist = fetch_openml('mnist_784')
y = mnist.target
X = mnist.data.astype('float64')

fig, ax = plt.subplots(2, 5)
ax = ax.flatten()
for i in range(10):
    im_idx = np.argwhere(y == str(i))[0]    # Pandas versions bug - it worked in PyCharm. {Kindly, what is an alternate way to fix it?}
    print(im_idx)
    plottable_image = np.reshape(X[im_idx], (28, 28))
    ax[i].imshow(plottable_image, cmap='gray_r')

错误显示:

ValueError: Length of passed values is 1, index implies 70000.

你得到结果的错误是因为 np.argwhere(y == i) returns 是一个空数组,那是因为你试图在 y 和 [=14= 填充的数组之间进行比较] 值和 i 这是一个 int.

以下更改将修复它:

im_idx = np.argwhere(y == str(i))[0]

这是匹配 NumPy 操作的转换:

y = mnist.target.to_numpy()
X = mnist.data.astype('float64').to_numpy()