python - 如何使用线性回归模型生成单个预测值?
问题描述
我在 Jupyter Notebook 中使用 Scikit-learn 创建了三个机器学习模型(线性回归、Dtree 和随机森林)。模型的目的是根据几个旋风参数(预测器/输入)预测旋风器的大小(预测/输出 ROCI)。有 9004 行。以下是线性回归模型的示例。
In[31]: df.head()
Out[31]: NAME LAT LON Pc Penv ROCI Vmax Pdc
0 HECTOR -15 128 985 1000 541 18 -15
1 HECTOR -15 127 990 1000 541 15.4 -10
2 HECTOR -16 126 992 1000 530 15 -8
3 HECTOR -16.3 126 992 1000 480 15.4 -8
4 HECTOR -16.5 126 992 1000 541 15.4 -8
In [32]: X=df[['LAT','LON','Pc','Vmax','Pdc=Pc-Penv']]
y=df['ROCI']
In [33]: X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.4)
In [34]: lm=LinearRegression()
In [35]: lm.fit(X_train,y_train)
Out [35]: LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None,
normalize=False)
In [36]: print(lm.intercept_)
lm.coef_
-3464.3452921023572
Out [36]: array([-2.94229126, 0.29875575, 3.65214265, -1.25577799,
-6.43917746])
In [37]: predictions=lm.predict(X_test)
predictions
Out [37]:array([401.02108725, 420.01451472, 434.4241271 , ...,
287.67803538, 343.80516896, 340.1007666 ])
In [38]: plt.scatter(y_test,predictions)
plt.xlabel('Recorded')
plt.ylabel('Predicted')
*figure to display accuracy*
现在,当我尝试在 lm.predict() 中输入单个值时,出现以下错误:
ValueError: Expected 2D array, got scalar array instead:
array=300.
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.
我认为这是因为我的模型是使用 5 列训练的,因此尝试输入数据集的第一行:
In [39]: lm.predict(-15,128,985,18,-15)
...
...
TypeError: predict() takes 2 positional arguments but 6 were
given
按照建议尝试 array.reshape 我得到:
In [49]: lm.predict(X_test.reshape(-1, 1))
...
...
AttributeError: 'DataFrame' object has no attribute 'reshape'
现在我很困惑!请您帮助我使用我的模型给我一个预测值。我应该在 lm.predict() 中输入什么?我基本上只想说“Pc=990,Vmax=18,Pdc=-12”,我得到类似“ROCI=540”的东西。感谢您的时间。
解决方案
如果要预测数据的第一行,则应首先将其作为数组:
import numpy as np
first_row = np.array([-15, 128, 985, 18, -15])
那么,当
lm.predict(first_row)
产生与您报告的错误相似的错误,
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.
遵循消息中的建议,即:
lm.predict(first_row.reshape(1, -1))
推荐阅读
- elasticsearch - Kibana 得到这个,解析异常:没有为 [_source] 错误注册 [query]
- racket - 球拍 - 评估 S 表达式
- sql - 选择没有分配“事物”的用户数量
- r - scale_gradientn 中更陡峭的梯度
- ios - 使用唯一键快速合并字典
- vba - 如何让我的代码识别具有特定字符串 STRUCTURE 的单元格,同时忽略其他单元格?
- tmux - 如何启动两个不同环境的 tmux 会话?
- python - 来自 REST API 的 JSON 响应中的键列表不同
- android - 如何从 pdf 中制作 base 64 字符串在图库中选择
- ios - 将过滤器“小于或等于”应用于 URL