使用sklearn的predict函数预测单一值

我正在学习机器学习,视频课程中讲师展示了如何使用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)数组)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注