前言:大多数模型都是直接给出公式,其实自己私下有推导,涉及好多自己不懂的数学知识,会一点点补充的
机器学习专栏:机器学习专栏
文章目录
线性回归(预测)
1、单变量线性回归
1.1基本原理
给定数据集
D
=
(
x
(
1
)
;
x
(
2
)
;
.
.
.
;
x
(
m
)
)
D=(x^{(1)};x^{(2)};...;x^{(m)})
D=(x(1);x(2);...;x(m)),其中
x
(
i
)
x^{(i)}
x(i)表示第
i
i
i个样本点
x
(
i
)
∈
R
x^{(i)}\in{R}
x(i)∈R(表示只有一个属性值),线性回归试图学的预测模型如下:
h
θ
(
x
(
i
)
)
=
θ
0
+
θ
1
x
(
i
)
h_\theta (x^{(i)})=\theta_0+\theta_1x^{(i)}
hθ(x(i))=θ0+θ1x(i)
其中:
h
θ
(
x
(
i
)
)
h_\theta (x^{(i)} )
hθ(x(i))表示预测值,
θ
j
\theta_j
θj表示模型参数
1.2最小二乘法
如何确定
θ
j
\theta_j
θj的值呢?——最小二乘法,这是其实一个凸优化问题
均方误差(MSE):
M
S
E
(
θ
0
,
θ
1
)
=
1
m
∑
i
=
1
m
(
h
θ
(
x
(
i
)
)
−
y
(
i
)
)
2
MSE(\theta_0,\theta_1)=\frac{1}{m}\sum_{i=1}^{m}{(h_\theta(x^{(i)})-y^{(i)})^2}
MSE(θ0,θ1)=m1i=1∑m(hθ(x(i))−y(i))2
我们通过最小化MSE确定
θ
j
\theta_j
θj的值,最小化所有样本到直线上的欧式距离最小,即:
(
θ
0
∗
,
θ
1
∗
)
=
a
r
g
m
i
n
(
θ
0
,
θ
1
)
∑
i
=
1
m
(
h
θ
(
x
(
i
)
)
−
y
(
i
)
)
2
(\theta _0^{*},\theta_1^{*})=\mathop{arg\;min}\limits_{(\theta_0,\theta_1)}\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})^2
(θ0∗,θ1∗)=(θ0,θ1)argmini=1∑m(hθ(x(i))−y(i))2
最小二乘法步骤:
1、将
M
S
E
(
θ
0
,
θ
1
)
MSE(\theta_0,\theta_1)
MSE(θ0,θ1)对
θ
0
,
θ
1
\theta_0,\theta_1
θ0,θ1求导得:
{
∂
M
S
E
(
θ
0
,
θ
1
)
∂
θ
1
=
2
m
(
θ
1
∑
i
=
1
m
x
(
i
)
2
−
∑
i
=
1
m
(
y
(
i
)
−
θ
0
)
x
(
i
)
)
∂
M
S
E
(
θ
0
,
θ
1
)
∂
θ
0
=
2
m
(
m
θ
0
−
∑
i
=
1
m
(
y
(
i
)
−
θ
1
x
(
i
)
)
)
\left\{ \begin{aligned} \frac{\partial MSE(\theta_0,\theta_1)}{\partial \theta_1}=\frac{2}{m}(\theta_1\sum_{i=1}^{m}{x^{(i)}}^2-\sum_{i=1}^{m}(y^{(i)}-\theta_0){x^{(i)}})\\ \frac{\partial MSE(\theta_0,\theta_1)}{\partial \theta_0}=\frac{2}{m}(m\theta_0-\sum_{i=1}^{m}(y^{(i)}-\theta_1{x^{(i)}})) \end{aligned} \right.
⎩⎪⎪⎪⎪⎨⎪⎪⎪⎪⎧∂θ1∂MSE(θ0,θ1)=m2(θ1i=1∑mx(i)2−i=1∑m(y(i)−θ0)x(i))∂θ0∂MSE(θ0,θ1)=m2(mθ0−i=1∑m(y(i)−θ1x(i)))
2、令上式为0,可以得
θ
0
\theta_0
θ0和
θ
1
\theta_1
θ1的闭式解:
{
θ
1
=
∑
i
=
1
m
y
(
i
)
(
x
(
i
)
−
x
ˉ
)
∑
i
=
1
m
x
(
i
)
2
−
1
m
(
∑
i
=
1
m
x
(
i
)
)
2
θ
0
=
1
m
∑
i
=
1
m
(
y
(
i
)
−
θ
1
x
(
i
)
)
\left\{ \begin{aligned} \theta_1=\frac{\sum_{i=1}^{m}y^{(i)}({x^{(i)}} -\bar{x})}{\sum_{i=1}^{m}{x^{(i)}}^2-\frac{1}{m}(\sum_{i=1}^{m}{x^{(i)}})^2}\\ \theta_0=\frac{1}{m}\sum_{i=1}^{m}(y^{(i)}-\theta_1{x^{(i)}}) \end{aligned} \right.
⎩⎪⎪⎪⎪⎨⎪⎪⎪⎪⎧θ1=∑i=1mx(i)2−m1(∑i=1mx(i))2∑i=1my(i)(x(i)−xˉ)θ0=m1i=1∑m(y(i)−θ1x(i))
1.3sklearn实现单变量线性回归
这里我使用datasets,熟悉一下,后面将通过pandas加载数据集,更符号实际应用情况
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 9 22:43:52 2019
@author: 1
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
#导入波士顿房价数据集load_diabetes()
diabetes = datasets.load_diabetes()
# Use only one feature
#np.newaxis的作用就是在这一位置增加一个一维
diabetes_X = diabetes.data[:, np.newaxis, 2]
#diabetes_X.shape=(422x1)
#划分训练集和测试集
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
#构造线性回归模型
regr = linear_model.LinearRegression()
#拟合训练集
regr.fit(diabetes_X_train, diabetes_y_train)
#测试集的预测值
diabetes_y_pred = regr.predict(diabetes_X_test)
#线性模型的系数
print('Coefficients: \n', regr.coef_)
#均方差
print("Mean squared error: %.2f"
% mean_squared_error(diabetes_y_test, diabetes_y_pred))
#R2决定系数(拟合优度)
print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
#真实值
plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
#预测值
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
#指定坐标轴刻度为无刻度
plt.xticks(())
plt.yticks(())
plt.show()
2、多元线性回归
2.1基本原理
上面介绍的单变量线性回归是比较特殊的情况,通常我们获得的数据是
D
=
(
x
(
1
)
,
y
(
1
)
)
;
(
x
(
2
)
,
y
(
2
)
)
;
.
.
.
;
(
x
(
m
)
,
y
(
i
)
)
D={(x^{(1)},y^{(1)});(x^{(2)},y^{(2)});...;(x^{(m)},y^{(i)} )}
D=(x(1),y(1));(x(2),y(2));...;(x(m),y(i)),其中
x
(
i
)
x^{(i)}
x(i)表示第
i
i
i个样本点
x
(
i
)
∈
R
n
x^{(i)}\in{R^n}
x(i)∈Rn(表示有n个属性值),多元线性回归试图学的预测模型如下:
h
θ
(
x
(
i
)
)
=
θ
0
+
θ
1
x
1
(
i
)
+
θ
2
x
2
(
i
)
+
.
.
.
.
+
θ
n
x
n
(
i
)
h_\theta(x^{(i)})=\theta_0+\theta_1x_1^{(i)}+\theta_2x_2^{(i)}+....+\theta_nx_n^{(i)}
hθ(x(i))=θ0+θ1x1(i)+θ2x2(i)+....+θnxn(i)
其中:
h
θ
(
x
(
i
)
)
h_\theta (x^{(i)} )
hθ(x(i))表示预测值,
θ
j
\theta_j
θj表示模型参数,
θ
0
\theta_0
θ0亦称为模型偏置(bias)
预测模型可写成向量表达式:
h
θ
(
x
(
i
)
)
=
θ
T
x
(
i
)
h_\theta(x^{(i)})=\theta^Tx^{(i)}
hθ(x(i))=θTx(i)
向量表达式参数简单介绍:
θ
=
[
θ
0
θ
1
:
θ
n
]
\theta=\begin{bmatrix} \theta_0\\\theta_1\\:\\\theta_n \end{bmatrix}
θ=⎣⎢⎢⎡θ0θ1:θn⎦⎥⎥⎤,
x
(
i
)
=
[
x
0
(
i
)
x
1
(
i
)
:
x
n
(
i
)
]
x^{(i)}=\begin{bmatrix} x_0^{(i)}\\ x_1^{(i)}\\ :\\ x_n^{(i)} \end{bmatrix}
x(i)=⎣⎢⎢⎢⎡x0(i)x1(i):xn(i)⎦⎥⎥⎥⎤,其中
x
0
(
i
)
x_0^{(i)}
x0(i)值为1
【注意】多元线性回归与多重线性回归的区别,多重回归是“multiple regerssion”,而多元回归是“multivariate regression”,两者为不同概念,适用的条件不一样,我也不是统计学出身,了解不多,欢迎大家评论区讨论!
多元线性回归的代价函数为:
J
(
θ
)
=
1
2
m
∑
i
=
1
m
(
h
θ
(
x
(
i
)
)
−
y
(
i
)
)
2
J(\theta)=\frac {1}{2m}\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})^2
J(θ)=2m1i=1∑m(hθ(x(i))−y(i))2
矩阵形式为:
M
S
E
(
θ
)
=
1
m
(
X
θ
−
Y
)
T
(
X
θ
−
Y
)
J
(
θ
)
=
1
2
m
(
X
θ
−
Y
)
T
(
X
θ
−
Y
)
MSE(\theta)=\frac{1}{m}(X\theta-Y)^T(X\theta-Y) \\ J(\theta)=\frac{1}{2m}(X\theta-Y)^T(X\theta-Y)
MSE(θ)=m1(Xθ−Y)T(Xθ−Y)J(θ)=2m1(Xθ−Y)T(Xθ−Y)
其中:
X
=
[
x
(
1
)
T
x
(
2
)
T
:
x
(
m
)
T
]
=
[
x
0
(
1
)
x
1
(
1
)
.
.
.
x
n
(
1
)
x
0
(
2
)
x
1
(
2
)
.
.
.
x
n
(
2
)
:
:
.
.
.
:
x
0
(
m
)
x
1
(
m
)
.
.
.
x
n
(
m
)
]
X=\begin{bmatrix} {x^{(1)}}^T\\ {x^{(2)}}^T\\ :\\ {x^{(m)}}^T \end{bmatrix}=\begin{bmatrix} x_0^{(1)} & x_1^{(1)} &... &x_n^{(1)} \\ x_0^{(2)} & x_1^{(2)} &... &x_n^{(2)} \\ : & : &... &:\\ x_0^{(m)} & x_1^{(m)} &... &x_n^{(m)} \end{bmatrix}
X=⎣⎢⎢⎢⎡x(1)Tx(2)T:x(m)T⎦⎥⎥⎥⎤=⎣⎢⎢⎢⎡x0(1)x0(2):x0(m)x1(1)x1(2):x1(m)............xn(1)xn(2):xn(m)⎦⎥⎥⎥⎤表示训练集,
Y
=
[
y
(
1
)
y
(
2
)
:
y
(
m
)
]
Y=\begin{bmatrix} y^{(1)}\\ y^{(2)}\\ :\\ y^{(m)} \end{bmatrix}
Y=⎣⎢⎢⎡y(1)y(2):y(m)⎦⎥⎥⎤由所有训练样本输出构成的向量,
θ
=
[
θ
0
θ
1
:
θ
n
]
\theta=\begin{bmatrix} \theta_0\\ \theta_1\\ :\\ \theta_n\end{bmatrix}
θ=⎣⎢⎢⎡θ0θ1:θn⎦⎥⎥⎤
2.2正规方程法
同样对于多元线性回归,最小化均方误差(同样这也是一个凸优化问题):
θ
∗
=
a
r
g
m
i
n
M
S
E
(
θ
)
\theta^*=arg\;minMSE(\theta)
θ∗=argminMSE(θ)
M
S
E
(
θ
)
MSE(\theta)
MSE(θ)对
θ
\theta
θ求导得(涉及矩阵的求导运算):
∂
M
S
E
(
θ
)
∂
θ
=
2
X
T
(
X
θ
−
Y
)
\frac{\partial MSE(\theta)}{\partial \theta} =2X^T(X\theta-Y)
∂θ∂MSE(θ)=2XT(Xθ−Y)
令上式为0,可得到
θ
\theta
θ最优解的闭式解(涉及矩阵的逆运算):
θ
∗
=
(
X
T
X
)
−
1
X
T
Y
\theta^*=(X^TX)^{-1}X^TY
θ∗=(XTX)−1XTY
2.3梯度下降法
要理解梯度下降法首先要知道梯度的概念:梯度的本意是一个向量,表示某一函数在该点处的方向导数沿着该方向取得最大值,即函数在该点处沿着该方向(此梯度的方向)变化最快,变化率最大(为该梯度的模),其实这里面的数学知识还是有点复杂的
梯度下降法就是不断找函数下降最快的方向,以找到最优解(线性回归找到的肯定是最优解)
梯度下降公式:
θ
j
:
=
θ
j
−
α
∂
∂
θ
j
J
(
θ
)
θ
j
:
=
θ
j
−
α
m
∑
i
=
1
m
(
(
y
θ
(
x
(
i
)
)
−
y
(
i
)
)
x
j
(
i
)
)
\theta_j:=\theta_j-\alpha\frac{\partial}{\partial\theta_j}J(\theta) \\ \theta_j:=\theta_j-\frac{\alpha}{m}\sum_{i=1}^{m}((y_\theta(x^{(i)})-y^{(i)})x_j^{(i)})
θj:=θj−α∂θj∂J(θ)θj:=θj−mαi=1∑m((yθ(x(i))−y(i))xj(i))
这里的
α
\alpha
α相当于步长,
∂
∂
θ
j
J
(
θ
)
\frac{\partial}{\partial\theta_j}J(\theta)
∂θj∂J(θ)是下降的速率(含方向)
【多元线性回归梯度下降公式的简单推导】
θ
j
:
=
θ
j
−
α
∂
∂
θ
j
J
(
θ
)
θ
j
:
=
θ
j
−
α
∂
∂
θ
j
[
1
2
m
∑
i
=
1
m
(
h
θ
(
x
(
i
)
)
−
y
(
i
)
)
2
]
θ
j
:
=
θ
j
−
α
m
(
(
h
θ
(
x
(
i
)
)
−
y
(
i
)
)
∂
h
θ
(
x
(
i
)
)
∂
θ
j
)
θ
j
:
=
θ
j
−
α
m
∑
i
=
1
m
(
(
y
θ
(
x
(
i
)
)
−
y
(
i
)
)
x
j
(
i
)
)
\theta_j:=\theta_j-\alpha\frac{\partial}{\partial\theta_j}J(\theta) \\ \theta_j:=\theta_j-\alpha\frac{\partial}{\partial\theta_j}[\frac {1}{2m}\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})^2] \\ \theta_j:=\theta_j-\frac{\alpha}{m}((h_\theta(x^{(i)})-y^{(i)})\frac{\partial h_\theta(x^{(i)})}{\partial \theta_j}) \\ \theta_j:=\theta_j-\frac{\alpha}{m}\sum_{i=1}^{m}((y_\theta(x^{(i)})-y^{(i)})x_j^{(i)})
θj:=θj−α∂θj∂J(θ)θj:=θj−α∂θj∂[2m1i=1∑m(hθ(x(i))−y(i))2]θj:=θj−mα((hθ(x(i))−y(i))∂θj∂hθ(x(i)))θj:=θj−mαi=1∑m((yθ(x(i))−y(i))xj(i))
2.4sklearn实现多元线性回归
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:43:52 2019
@author: 1
"""
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import pandas as pd
from sklearn.model_selection import train_test_split
#导入波士顿房价数据集load_diabetes()
diabetes_X=pd.read_csv('D:\workspace\python\machine learning\data\diabetes_data.csv\X.csv',sep=' ',header=None)
diabetes_Y=pd.read_csv('D:\workspace\python\machine learning\data\diabetes_target.csv\y.csv',sep=' ',header=None)
#利用sklearn里面的包来对数据集进行划分,以此来创建训练集和测试集
#train_size表示训练集所占总数据集的比例
diabetes_X_train,diabetes_X_test,diabetes_y_train,diabetes_y_test = train_test_split(diabetes_X.iloc[:,:4],diabetes_Y,train_size=.80)
#构造线性回归模型
regr = linear_model.LinearRegression()
#拟合训练集
regr.fit(diabetes_X_train, diabetes_y_train)
#测试集的预测值
diabetes_y_pred = regr.predict(diabetes_X_test)
#线性模型的系数
print('Coefficients: \n', regr.coef_)
print('intercept: \n',regr.intercept_)
#均方差
print("Mean squared error: %.2f"
% mean_squared_error(diabetes_y_test, diabetes_y_pred))
#R2决定系数(拟合优度)
print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
#预测值和真实值对比图
plt.plot(range(len(diabetes_y_pred)), diabetes_y_pred, 'b', label="predict")
plt.plot(range(len(diabetes_y_test)), diabetes_y_test, 'r', label="test")
plt.xticks(())
plt.yticks(())
plt.show()
2.5模型优化
2.5.1多项式回归
当线性模型太简单导致欠拟合的时候,可以通过增加多项式特征来让模型更好的适应我们的数据,比如房价和房子的长以及宽之间的关系等。而且通过观察数据,分析数据的特征,我们可以令 x 1 = x 1 2 , x 2 = x 2 3 x_1=x_1^2,x_2=x_2^3 x1=x12,x2=x23将模型转化为线性模型。
2.5.2sklearn实现多项式回归
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 19:55:39 2019
@author: 1
"""
#导入多项式模块
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
#管道模型,将线性回归和多项式串起来
from sklearn.pipeline import Pipeline
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
#导入波士顿房价数据集load_diabetes()
diabetes_X=pd.read_csv('D:\workspace\python\machine learning\data\diabetes_data.csv\X.csv',sep=' ',header=None)
diabetes_Y=pd.read_csv('D:\workspace\python\machine learning\data\diabetes_target.csv\y.csv',sep=' ',header=None)
#数据集的划分
diabetes_X_train,diabetes_X_test,diabetes_y_train,diabetes_y_test = train_test_split(diabetes_X,diabetes_Y,train_size=.80)
#线性模型
regr=LinearRegression(normalize=True)#normalize=True表示标准化
pf=PolynomialFeatures(degree=2,interaction_only=True)#interaction_only=True去除高次幂特征
#管道机制实现了对全部步骤的流式化封装和管理
pf_regr=Pipeline([('pf',pf),('regr',regr)])
pf_regr.fit(diabetes_X_train,diabetes_y_train)
diabetes_y_pred = pf_regr.predict(diabetes_X_test)
print('Coefficients: \n',regr.coef_)
print('intercept: \n',regr.intercept_)
#均方差
print("Mean squared error: %.2f" % mean_squared_error(diabetes_y_test, diabetes_y_pred))
#R2决定系数(拟合优度)
print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
#预测值和真实值对比图
plt.plot(range(len(diabetes_y_pred)), diabetes_y_pred, 'b', label="predict")
plt.plot(range(len(diabetes_y_test)), diabetes_y_test, 'r', label="test")
plt.xticks(())
plt.yticks(())
plt.show()
回归结果评价:回归模型的评价指标