一、线性回归API
sklearn.linear_model.LinearRegression(fit_intercept=True)
- 通过正规方程优化
- 参数:fit_intercept,是否计算偏置
- 属性:LinearRegression.coef_ (回归系数) LinearRegression.intercept_(偏置)
sklearn.linear_model.SGDRegressor(loss=“squared_loss”, fit_intercept=True, learning_rate =‘constant’, eta0=0.01)
- 参数:loss(损失函数类型),fit_intercept(是否计算偏置),learning_rate (学习率),eta0(eta是η的读音,eta和η均是学习率代表字符,0表示初始,eta和0合在一起就是初始学习率)
- 属性:SGDRegressor.coef_ (回归系数)SGDRegressor.intercept_ (偏置)
二、实操
(一)案例背景介绍
(二)案例分析
回归当中的数据大小不一致,是否会导致结果影响较大。所以需要做标准化处理。
- 数据分割与标准化处理
- 回归预测
- 线性回归的算法效果评估
(三)回归性能评估
均方误差(Mean Squared Error, MSE)评价机制:
MSE=1m∑i=1m(yi−y^)2\Large MSE = \frac{1}{m}\sum_{i=1}^{m}(y^i-\hat{y})^2MSE=m1∑i=1m(yi−y^)2
sklearn中的API:sklearn.metrics.mean_squared_error(y_true, y_pred)
- 均方误差回归损失
- y_true:真实值
- y_pred:预测值
- return:浮点数结果
(四)代码实现
# 0.导包
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression,SGDRegressor
from sklearn.metrics import mean_squared_error
# 1.加载数据
boston = load_boston()
# print(boston)
# 2.数据集划分
x_train,x_test,y_train,y_test =train_test_split(boston.data,boston.target,test_size=0.2,random_state=22)
# 3.标准化
process=StandardScaler()
x_train=process.fit_transform(x_train)
x_test=process.transform(x_test)
# 4.模型训练
# 4.1 实例化
# model =LinearRegression(fit_intercept=True) #正规方程
model = SGDRegressor(learning_rate='constant',eta0=0.01) #坡度下降
# 4.2 训练模型
model.fit(x_train,y_train)
# print(model.coef_)
# print(model.intercept_)
# 5.预测
y_predict=model.predict(x_test)
print(y_predict)
# 6.模型评估
print(mean_squared_error(y_test,y_predict))