简体   繁体   English

通过预测从 sklearn 预测 1 个值

[英]predicting 1 value by predict from sklearn

I am studying machine learning and in the video course lecturer shows how to predict 1 value by predict function from sklearn.我正在学习机器学习,在视频课程讲师中展示了如何通过预测来自 sklearn 的 function 来预测 1 个值。 He just executes it with a float parameter and it works fine.他只是用浮点参数执行它,它工作正常。 But when I try to do the same I receive a ValueError:但是当我尝试做同样的事情时,我收到一个 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.

I tried to reshape it but I get the same error:我试图重塑它,但我得到了同样的错误:

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

Please tell me maybe there are some changes in the library from version to version (the course is few years old).请告诉我,库中的版本可能会有所变化(课程已有几年历史了)。 And how is it possible to get the one feature for one sample?怎么可能为一个样本获得一个特征?

There are two issues:有两个问题:

  • You reshape your array but call predict with the same float (instead of the reshaped array, ie linear_regressor.predict(6.5) instead of linear_regressor.predict(lvl_of_interest) )你重塑你的数组,但用相同的浮点数调用 predict (而不是重塑的数组,即linear_regressor.predict(6.5)而不是linear_regressor.predict(lvl_of_interest)

  • Furthermore, np.reshape should be reassigned:此外,应重新分配 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)

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

(nb: if you inspect shapes, you transform a (1,) array into a (1,1)) (注意:如果您检查形状,则将 (1,) 数组转换为 (1,1))

LinearRegression().predict() expects as 2-dimensional feature array for X . LinearRegression().predict()期望X的二维特征数组。

You can make your array 2-dimensional with .reshape(1, -1) like the error message suggests or just make it 2-dimensional from the start:您可以使用.reshape(1, -1)将数组设为二维,就像错误消息所建议的那样,或者从一开始就将其设为二维:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM