使用 sklearn 在 MNIST 数据集上进行手写数字识别

问题描述

我想使用 sklearn 在 MNIST 数据集上构建手写数字识别,并且我想为特征 (x) 和标签 (y) 洗牌我的训练集。但它显示一个 KeyError。让我知道正确的做法是什么。

    from sklearn.datasets import fetch_openml
    mnist = fetch_openml('mnist_784')
    x,y=mnist['data'],mnist['target']
    x.shape
    y.shape
    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    digit = np.array(x.iloc[45])
    digit_img = digit.reshape(28,28)
    plt.imshow(digit_img,cmap=matplotlib.cm.binary,interpolation="nearest")
    plt.axis("off")
    y.iloc[45]
    x_train,x_test = x[:60000],x[60000:]
    y_train,y_test=y[:60000],y[60000:]
    import numpy as np
    shuffled = np.random.permutation(60000)
    x_train=x_train[shuffled] -->
    y_train = y_train[shuffled] --> these two lines are throwing error

解决方法

请检查 type(x_train) 是 numpy.ndarray 还是 DataFrame。 自 Scikit-Learn 0.24 起,fetch_openml() 默认返回 Pandas DataFrame。 如果是数据帧,则不能使用 x_train[shuffled],它用于数组。 而是使用 x_train.iloc[shuffled]