线性回归
线性回归是利用回归方程(函数)对一个或多个自变量(特征值)和因变量(目标值)之间关系进行建模的一种分析方式。
通用公式
损失函数
y_i为第i个训练样本的真实值
h(x_i)为第i个训练样本特征值组合预测函数
又称最小二乘法
优化方法一:正规方程
x为特征值矩阵,y为目标值矩阵。直接求到最好的结果
缺点:当特征过多过复杂时,求解速度太慢并且得不到结果
优化方法二:梯度下降
α为学习速率,需要手动指定(超参数),α旁边的整体表示方向沿着这个函数下降的方向找,最后就能找到山谷的最低点,然后更新W值
使用:面对训练数据规模十分庞大的任务,能够找到较好的结果
线性回归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=‘invscaling’,eta0=0.01)
- SGDRegressor类实现了随机梯度下降学习,它支持不同的loss函数和正则化惩罚项来拟合线性回归模型。
- loss:损失函数
loss=“squared_loss”:普通最小二乘法 - fit_intercept:是否计算偏置
- learning_rate:string,optional
- SGDRegressor.coef_:回归系数
- SGDRegressor.intercept_:偏置
回归性能评估
均方误差
sklearn.metrics.mean_squared_error(y_ture,y_pred)
- 均方误差回归损失
- y__true:真实值
- y_pred:预测值
- return:浮点数结果
封装好的使用正规方程优化的线性回归模型
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import matplotlib.pyplot as plt
#线性回归-正规方程
class Linear:
def __init__