线性回归

1.基本形式

线性回归(Linear Regression)是利用数理统计中回归分析,来确定两种或两种以上变量间相互依赖的定量关系的一种统计分析方法。
回归分析中,只包括一个自变量和一个因变量,且二者的关系可用一条直线近似表示,这种回归分析称为一元线性回归分析。如果回归分析中包括两个或两个以上的自变量,且因变量和自变量之间是线性关系,则称为多元线性回归分析。

假设有m个样本,每个样本对应于n维特征和一个输出结果,如下:
egin{align} otag
(x_{1}{(1)},x_{2}{(1)},...,x_{n}{(1)},y{(1)}),(x_{1}{(2)},x_{2}{(2)},...,x_{n}{(2)},y{(2)}),...,(x_{1}{(m)},x_{2}{(m)},...,x_{n}{(m)},y{(m)})
end{align}
线性模型如下:
egin{align} otag
h(x^{(i)})=w_{1}x_{1}+w_{2}x_{2}+...+w_{n}x_{n}+b
end{align}
用矩阵形式表示如下:
egin{align} otag
h(X)=XW+b
end{align}
其中

[X=egin{bmatrix} x_{1}^{(1)} & x_{2}^{(1)} & ... & x_{n}^{(1)}\ x_{1}^{(2)} & x_{2}^{(2)} & ... & x_{n}^{(2)}\ ... & ... & ... & ...\ x_{1}^{(m)} & x_{2}^{(m)} & ... & x_{n}^{(m)} end{bmatrix},W=egin{bmatrix} w_{1}\ w_{2}\ ...\ w_{n} end{bmatrix} ]

2.损失函数

一般线性回归用均方误差作为损失函数(loss function),如下:
egin{align} otag
J(w)=sum_{i=1}{m}(h(x{(i)})-y{(i)}){2}
end{align}

3.参数计算

参数计算即求出W和b,即对损失函数进行优化,使损失函数取得最小值。有以下两种方法。

3.1正规方程

最小二乘法可以将误差方程转化为有确定解的代数方程组(其方程式数目正好等于未知数的个数),从而可求解出这些未知参数。这个有确定解的代数方程组称为最小二乘法估计的正规方程。
正规方程公式为
egin{align} otag
W=(X{T}X){-1}X^{T}y
end{align}

3.2梯度下降

在求解损失函数的最小值时,可以通过梯度下降(Gradient Descent)来一步步的迭代求解,得到最小化的损失函数和模型参数值。
梯度下降法是按下面的流程进行的:

  1. 首先对w赋值,这个值可以是随机的,也可以让w是一个全零的向量。
  2. 改变w的值,使得J(w)按梯度下降的方向进行减少。

梯度下降法只能寻找局部极小值。因为梯度下降法在每次下降的时候都要选择最佳方向,而这个最佳方向是针对局部来考虑的,不同的起始点局部特征都是不同的,选择的最佳方向当然也是不同,导致最后寻找到的极小值并不是全局极小值,而是局部极小值。

3.3两种算法比较

梯度下降 正规方程
需要选择学习率 不需要
需要多次迭代 一次计算得出
当特征数量很大时也能较好适用 当特征数量很大时,运算代价大

4.Python实现

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
from sklearn.linear_model import SGDRegressor
from sklearn.metrics import mean_squared_error


boston = load_boston()

x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.25)

x_stds = StandardScaler()
x_train = x_stds.fit_transform(x_train)
x_test = x_stds.transform(x_test)

y_stds = StandardScaler()
y_train = y_stds.fit_transform(y_train.reshape(-1, 1))

lr = LinearRegression()
lr.fit(x_train, y_train)
y_lr_predict = y_stds.inverse_transform(lr.predict(x_test))
print(mean_squared_error(y_test, y_lr_predict))

gd = SGDRegressor()
gd.fit(x_train, y_train)
y_gd_predict = y_stds.inverse_transform(gd.predict(x_test))
print(mean_squared_error(y_test, y_gd_predict))

人生就是一列开往坟墓的列车,路途上会有很多站,很难有人可以至始至终陪着走完,当陪你的人要下车时,即使不舍,也该心存感激,然后挥手道别。——《龙猫》

原文地址:https://www.cnblogs.com/dblsha/p/10284810.html