【问题标题】:Sklearn SGDClassifier "Found array with dim 3. Estimator expected <= 2" with after reshaping MNISTSklearn SGDClassifier“找到暗淡3的数组。估计器预期<= 2”与重塑MNIST后
【发布时间】:2020-07-05 00:56:16
【问题描述】:

我是 python 和 ml 的新手,只是尝试使用 mnist 我的程序是这样的

from sklearn.datasets import fetch_openml
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier
import numpy as np

mist=fetch_openml('mnist_784',version=1)
mist.keys()
x,y=mist['data'],mist['target']
x.shape
images = x[1]
images=images.reshape(28,28)
plt.imshow(images)
plt.show()
y=y.astype(np.uint8)
y[0]
xtrain,xtest,ytrain,ytest=x[:60000],x[60000:],y[:60000],y[60000:]
ytrain_5=(ytrain==5)
ytest_5=(ytest==5)
sgd = SGDClassifier(random_state=42)
sgd.fit(xtrain,ytrain_5)
sgd.predict([images])

并且正在抛出错误:

找到暗淡为 3 的数组。预计估计器

【问题讨论】:

    标签: python numpy scikit-learn


    【解决方案1】:

    使用这一行:

    sgd.predict(images.reshape(1, 784))
    

    该算法是使用扁平化的数组(70000, 784) 训练的,因此您需要在通过之前将images 扁平化为形状(1, 784)。您之前已将其重塑为 (28, 28)

    完整代码:

    from sklearn.datasets import fetch_openml
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    from sklearn.linear_model import SGDClassifier
    import numpy as np
    
    mist=fetch_openml('mnist_784',version=1)
    x,y=mist['data'],mist['target']
    images = x[1]
    images=images.reshape(28,28)
    y=y.astype(np.uint8)
    xtrain,xtest,ytrain,ytest=x[:60000],x[60000:],y[:60000],y[60000:]
    ytrain_5=(ytrain==5)
    ytest_5=(ytest==5)
    sgd = SGDClassifier(random_state=42)
    sgd.fit(xtrain,ytrain_5)
    sgd.predict(images.reshape(1, 784))
    

    【讨论】:

    • 我不这么认为。复制并粘贴上面的代码,你会看到。我唯一改变的是我提到的那一行。
    • thnaks @Nicolas 成功了,我真的不知道为什么我第一次尝试时没有成功。
    猜你喜欢
    • 2017-03-26
    • 2020-07-10
    • 2019-06-01
    • 2018-01-16
    • 2018-06-08
    • 2016-04-30
    • 2016-04-24
    • 2016-11-28
    • 2021-04-16
    相关资源
    最近更新 更多