01-线性回归-波士顿房价

理论推导

线性回归问题说明

有N个样本\((X_{i}, Y_{i}), i\in (1,2\cdots N)\)\(X_{i} = [X_{i}^{1}, X_{i}^{2}, \cdots X_{i}^{m-1}]\)表示每个样本有m-1个特征。

现在为每个样本均添加一个值为1的特征,也就是令\(X_{i} = [X_{i}^{1},X_{i}^{2},\cdots X_{i}^{m-1},X_{i}^{m}]\),其中\(X_{i}^{m} = 1\)

这样操作本质就是将\(w*X + b\)中的\(w\)\(b\)合为一个\(W\),便于计算。

要拟合的回归方程形式为\(\bar{Y} = X \cdot W\),其中

\(X = \begin{bmatrix} X_{1}^{1},X_{1}^{2},\cdots ,X_{1}^{m}\\ X_{2}^{1},X_{2}^{2},\cdots ,X_{2}^{m}\\ \vdots\\ X_{N}^{1},X_{N}^{2},\cdots ,X_{N}^{m}\\ \end{bmatrix},Y = \begin{bmatrix} Y_{1}\\ Y_{2}\\ \vdots\\ Y_{N}\\ \end{bmatrix},W = \begin{bmatrix} W_{1}\\ W_{2}\\ \vdots \\ W_{m}\\ \end{bmatrix}\)

得到的W要使得最小二乘代价函数

\(\mathit{cost} = \frac{1}{2N}\sum_{i=1}^{N}(\bar{Y_{i}} - Y_{i})^{2}=\frac{1}{2N}\sum_{i=1}^{N}(X_{i}\cdot W - Y_{i})^{2}=\frac{1}{2N}(X\cdot W-Y)^{2}\)

最小。

正规方程推导

由上可知,也就是使\((X\cdot W - Y)^{2}\)的值最小。令

\(C = (X\cdot W - Y)^{2}\\ ........ =(X \cdot W - Y)^{T}\cdot (X \cdot W - Y)\\ ........=W^{T}\cdot X^{T}\cdot X\cdot W-W^{T}\cdot X^{T}\cdot Y-Y^{T}\cdot X\cdot W + Y^{T}\cdot Y\)

计算导数,令其等于0,也就是有

\(\frac{d \mathit{C}}{dW} =2 \times X^{T}\cdot X\cdot W -X^{T}\cdot Y-(Y^{T}\cdot X)^{T}\\ ............=2 \times( X^{T}\cdot X\cdot W -X^{T}\cdot Y)\\ ............=0\\ \\ ........\Rightarrow X^{T}\cdot X\cdot W =X^{T}\cdot Y\\ ........\Rightarrow \mathbf{W = (X^{T}\cdot X)^{-1}\cdot X^{T}\cdot Y }\)

梯度下降推导
计算代价函数\(\mathit{cost}\)\(W\)的梯度:

\(\bigtriangledown \mathit{cost} = \frac{1}{2N} \bigtriangledown \mathit{C}\\ ...............=\frac{1}{N}(X^{T}\cdot X\cdot W-X^{T}\cdot Y)\\ ...............=\frac{1}{N}(X^{T}\cdot (X\cdot W -Y))\)

更新W:

\(\mathbf{W = W - \boldsymbol{\eta} \times \boldsymbol{\bigtriangledown \mathit{cost}} }\)

其中\(\eta\)表示学习率。

数据文件

数据文件

波士顿房价数据集:Boston.csv

数据集说明

基于不同库的代码文件

Sklearn

# Linear_Regression_Sklearn.py


posted @ 2019-08-30 10:46  linus_gau  阅读(204)  评论(0)    收藏  举报
TOP