我正在学习机器学习,视频课程中讲师展示了如何使用sklearn中的predict函数预测单一值。他只是用一个浮点数参数执行它,并且运行良好。但是当我尝试同样操作时,我收到了一个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)
请告诉我是否是因为库版本之间的变化(课程已经有几年了)。并且如何能够为一个样本获取一个特征?
回答:
有两个问题:
-
你重塑了数组但仍然用同一个浮点数调用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)
或者在一行中:linear_regressor.predict(np.array([6.5]).reshape(1,-1))
(注意:如果你检查形状,你将一个(1,)数组转换成了一个(1,1)数组)