首页 > 解决方案 > 显示 100 个 mnist 数据集

问题描述

这是我用来打印 100 mnist 数据的原始未简化图片的代码,但它不断给我一个错误。即使尝试了很多,我也找不到解决方案。征求建议

 from sklearn.datasets import fetch_openml
   mnist = fetch_openml('mnist_784')
   X = mnist["data"]
   y = mnist["target"]
   X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000],y[60000:]
   pca = PCA()
   pca.fit(X_train)
   cumsum = np.cumsum(pca.explained_variance_ratio_)
   d = np.argmax(cumsum >= 0.90) + 1

   #Setup a figure 8 inches by 8 inches
   fig = plt.figure(figsize=(8,8))
   fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
    for i in range(100):
        ax = fig.add_subplot(10, 10, i+1, xticks=[], yticks=[])
        ax.imshow(X_train[i].reshape(28,28), cmap=plt.cm.bone, interpolation='nearest')
        plt.show()

标签: pythonmatplotlibscikit-learnmnist

解决方案


这就是您的情节显示声明仍在循环中的地方。只需将其移出循环,它就会显示正常。试一试下面的内容;

from sklearn.datasets import fetch_openml
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt

mnist = fetch_openml('mnist_784')
X = mnist["data"]
y = mnist["target"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, 
 random_state=44)
pca = PCA()
pca.fit(X_train)

fig = plt.figure(figsize=(8,8))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(100):
    ax = fig.add_subplot(10, 10, i+1, xticks=[], yticks=[])
    ax.imshow(X_train[i].reshape(28,28), cmap=plt.cm.bone, interpolation='nearest')

plt.show()

推荐阅读