调用线性回归算法拟合生成的数据得到线性方程
1.生成用于回归分析的有一个特征的数据集
import numpy as np
import matplotlib.pyplot as plt
#导入回归模型生成器
from sklearn.datasets import make_regression
#导入线性回归模型,注意L和R要大写
from sklearn.linear_model import LinearRegression
#生成用于回归分析的数据集,样本量为100,random_state是随机种子,确保每次生成的随机序列一致,1个特征,噪声为50
X,y=make_regression(n_sample=100,n_features=1,n_informative=1,random_state=3,
noise=50
2.使用线性回归模型进行拟合
#训练数据,接口是fit
lr=LinearRegression().fit(X,y)
3.画出线性回归模型的图形
#z是生成的等差数列,用来画线性模型图形
z=np.linspace(-3,3,100).reshape(-,1)
plt.scatter(X,y,c='b',s=60)
plt.plot(z,lr.predict(z),c='purple')
#默认不支持中文,修改RC参数让其支持中文
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
plt.title('线性回归')
4.输出线性回归模型的系数、截距和方程
print('直线的斜率是:{:.2f}'.format(lr.coef_[0]))
print('直线的截距是:{:.2f}'.format(lr.intercept_))
print('直线的方程是:{:.2f}'.format(lr.coef_[0],'X1','{:.2f}'.format(lr.intercept_))
5.生成用于回归分析的有两个特征的数据集
#导入数据集拆分工具
from sklearn.model_selection import train_test_split
#生成用于回归分析的有两个特征的数据集
X,y=make_regression(n_samples=300,n_features=2,n_informative=2,random_state=38
6.使用线性回归模型对数据进行拟合,并输出模型系数、截距
#拆分数据(注意这边可以巧记为x,x,y,y,以防遗漏)
X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=8)
#训练模型(因为是训练数据,所以括号里是X_train,y_train)
lr2=LinearRegression().fit(X_train,y_train)
#预测数据
y_predict=lr2.predict(X_test)
#输出模型斜率、截距、方程
print('lr2.coef_:{}'.format(lr2.coef_[:]))
print('lr2.intercept_:{}'.format(lr2.intercept_))
print('回归方程为 y={:.2f}'.format(lr2.coef_[0]),'X1','+{:.2f}'.format(lr2.coef_[1],'X2','+{:.16f}'.format(lr2.intercept_))
#画出真实值与测试值曲线对比
import matplotlib.pyplot as plt
sorted(y_test)
plt.plot(range(len(y_test)),sorted(y_test),c="black",label="Data"
plt.legend()
plt.show()
plt.plot(range(len(y_predict)),sorted(y_predict),c="red",label="Predict")
plt.show()
7.评估线性回归模型
#均方误差MSE(真实值与预测值差的平方取平均)【RMSE是均方根误差,即把MSE开根号】
from sklearn.metrics import mean_squared_error as MSE
MSE(y_test,y_predict)
#平方绝对误差MAE
真实值与预测值之间差的绝对值的平均
from sklearn.metrics import mean_absolute_error as MAE
MAE(y_predict,y_test)
#可解释性方差
可解释性方差的范围在[0~1]之间,越接近1越好 【注意 真实值在前,预测值在后,如果是0,就是过拟合,反而也不好】
from sklearn.metrics import r2_score
r2_score(y_test,y_predict)