机器学习库的线性回归预测
大体分为四个步骤:
1.对数据进行预处理
2.创建线性回归模型
3.使用原始数据对线性回归模型进行训练
4.使用训练好的模型对待预测数据进行预测
import numpy as np
from sklearn import linear_modelx = np.array([[1000, 35], [1200, 38], [1100, 36], [1300, 40], [900, 32], [1400, 42], [1050, 34], [1250, 39], [1150, 37], [800, 30]])
y = np.array([8.2, 9.5, 8.8, 10.1, 7.5, 10.8, 8.4, 9.8, 9.1, 7.2])xs = np.array([[1180, 37], [1500, 45]])
# 对xs中大于43的样本进行修正
xs_processed = xs.copy()
xs_processed[:, 1] = np.where(xs_processed[:, 1] > 43, 43, xs_processed[:, 1])#使用原始数据对模型进行训练
model = linear_model.LinearRegression()
model.fit(x, y)#使用训练后的模型对待预测样本进行预测
predictions = model.predict(xs_processed)
for i in range(len(xs)):print(f"原始参数:{xs[i]} - 预处理后参数:{xs_processed[i]} \- 预测能耗:{predictions[i]:.2f} kW·h")
if predictions[0]>8.5 and predictions[0]<9.5:print('第一个待预测样本的预测值在 8.5~9.5 kW・h 范围内(合理区间)。')
else:print('第一个待预测样本的预测值不在 8.5~9.5 kW・h 范围内(合理区间)。')