【问题标题】:predicting 1 value by predict from sklearn通过预测从 sklearn 预测 1 个值
【发布时间】:2020-07-14 23:10:58
【问题描述】:

我正在学习机器学习,在视频课程中,讲师展示了如何通过 sklearn 的预测函数预测 1 个值。他只是用一个浮点参数执行它,它工作正常。但是当我尝试做同样的事情时,我收到一个 ValueError:

>linear_regressor.predict(6.5)

ValueError: Expected 2D array, got scalar array instead:
array=6.5.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

我试图重塑它,但我得到了同样的错误:

lvl_of_interest =  np.array([6.5])
np.reshape(lvl_of_interest,(1,-1))
linear_regressor.predict(6.5)

请告诉我,库中的版本可能会有所变化(该课程已有几年历史了)。一个样本如何获得一个特征?

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    有两个问题:

    • 您重塑了数组,但使用相同的浮点数调用 predict(而不是重塑后的数组,即 linear_regressor.predict(6.5) 而不是 linear_regressor.predict(lvl_of_interest)

    • 此外,应重新分配 np.reshape :

      lvl_of_interest =  np.array([6.5])
      lvl_of_interest = np.reshape(lvl_of_interest,(1,-1))
      linear_regressor.predict(lvl_of_interest)
      

    或在 1 行中:linear_regressor.predict(np.array([6.5]).reshape(1,-1))

    (nb : 如果您检查形状,则将 (1,) 数组转换为 (1,1))

    【讨论】:

    • 非常感谢!首先是愚蠢的问题。出于某种原因,我认为 reshape 会改变数组本身,并且不会返回结果。
    • 没有愚蠢的问题;) 就地重塑有点棘手,您必须直接修改形状属性:level_of_interest.shape = (1,1) btw,如果它解决了您的问题,您可以将其标记为“已接受的答案”:)
    【解决方案2】:

    LinearRegression().predict() 期望为X 的二维特征数组。

    您可以使用.reshape(1, -1) 将数组设为二维,就像错误消息所建议的那样,或者从一开始就将其设为二维:

    linear_regressor.predict(np.array([[6.5]]))
    

    【讨论】:

    • 显然甚至不需要np.array()linear_regressor.predict([[6.5]]) 也可以正常工作。
    • 是的,预测将 array_like 作为输入(不仅仅是 np.array)。请参阅stackoverflow.com/questions/40378427/… 和 sklearn 文档
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2014-04-03
    • 2017-08-22
    • 2017-09-28
    • 2019-07-22
    • 2017-06-24
    • 1970-01-01
    相关资源
    最近更新 更多