机器学习算法第二篇
- 本文目内容:梯度下降法算法推导
- 本文基于多元线性回归
- 数学核心向
一 逻辑推演
-
有数据Data( 上标为列号,下标为行号)
⎣⎢⎢⎢⎢⎢⎢⎡x11x12x13..x1mx21...x22...x23...........x2m...xn1xn2xn3..xnmy1y2y3..ym⎦⎥⎥⎥⎥⎥⎥⎤
令x_data=⎣⎢⎢⎢⎢⎢⎢⎡x11x12x13..x1mx21...x22...x23...........x2m...xn1xn2xn3..xnm⎦⎥⎥⎥⎥⎥⎥⎤
令y_data=⎣⎢⎢⎢⎢⎢⎢⎡y1y2y3..ym⎦⎥⎥⎥⎥⎥⎥⎤
-
设回归线
hθ(x) :
θ1x1+θ2x2+...+θnxn=0
任意点
P(x1,x2...xn)带入该式可得到点P到回归线的距离d
-
线性回归的目标为:求合适的参数
(θ1,θ2...θn)组成的超平面
hθ(x)
使得众测试点带入该式后所得的值(误差)的平方和最小
即 :
min(∑d2)
即 :拟合度最高
-
根据3式构建代价函数 costfunction
J(θ1,θ2...θn)=2m1i=1∑m(hθ(xi)−yi)2
该函数表示训练集所有的m个点带入后 距离回归线的距离的平方和
-
函数结构观念调整: 在训练阶段, 代价函数的x 与y 都是已知量
θ为变量量
因此3式所述的目标等价于求函数
J(θ1,θ2...θn)的值取最小值时候的变量
(θ1,θ2...θn)
二 梯度下降法:
- 概念:
通过将各变量
(θ1,θ2...θn)不断朝函数取得极值时的变量
(ω1,ω2...ωn)方向靠拢,从而获得代价函数取最小值时候的各
(θ1,θ2...θn)参数
方法一:
方法一更易于理解,但计算复杂度较高,求导难度大
- 对变量
(θ1,θ2...θn)进行初始随机赋值
θ1=1,θ1=5,θ3=0.5,θn=10
2. 对函数的表达式的逐个变量
(θ1,θ2...θn)求偏导,得到
∇J(θ1,θ2...θn)=(∂θ1∂f,∂θ2∂f,∂θ3∂f...∂θi∂f)
∂θ1∂f=m1i=1∑m(hθ(xi)−yi)x1i∂θ2∂f=m1i=1∑m(hθ(xi)−yi)x2i......∂θn∂f=m1i=1∑m(hθ(xi)−yi)xni
-
设定学习率 控制每次迭代 变量的移动距离
lR=0.001,该参数为示例,应按照实际情况调整
-
分别对每个变量进行迭代
θ1=θ1−lR∂θ1∂fθ2=θ2−lR∂θ2∂fθ3=θ3−lR∂θ3∂f......θm=θm−lR∂θm1∂f
5.重复第四步到足够次数,可得到距离代价函数取最小值时候的变量
(ω1,ω2...ωn)极为接近的变量
(θ1,θ2...θn)
方法二
方法二:将代价函数矩阵化,从而极大化简计算复杂度和求导复杂度
- 子式矩阵化
-
θ=⎣⎢⎢⎢⎢⎢⎢⎡θ1θ2θ3..θm⎦⎥⎥⎥⎥⎥⎥⎤
-
J(θ1,θ2...θn)⇒J(θ)
-
yi⇒Y=y_data=⎣⎢⎢⎢⎢⎢⎢⎡y1y2y3..ym⎦⎥⎥⎥⎥⎥⎥⎤
-
xi⇒X=x_data=⎣⎢⎢⎢⎢⎢⎢⎡x11x12x13..x1mx21...x22...x23...........x2m...xn1xn2xn3..xnm⎦⎥⎥⎥⎥⎥⎥⎤
-
hθ(xi)⇒⎣⎢⎢⎢⎢⎢⎢⎡hθ(x1)hθ(x2)hθ(x3)..hθ(xm)⎦⎥⎥⎥⎥⎥⎥⎤=⎣⎢⎢⎢⎢⎢⎢⎡θ1x11+θ2x21+...+θnxn1θ1x12+θ2x22+...+θnxn2θ1x13+θ2x23+...+θnxn3........θ1x1m+θ2x2m+...+θnxnm⎦⎥⎥⎥⎥⎥⎥⎤=X⋅θ
-
∂θi∂f⇒∇J(θ)=⎣⎢⎢⎢⎢⎢⎢⎢⎡∂θ1∂f∂θ2∂f∂θ3∂f..∂θn∂f⎦⎥⎥⎥⎥⎥⎥⎥⎤
2.变换流程
因为
∂θ1∂f=m1i=1∑m(hθ(xi)−yi)x1i∂θ2∂f=m1i=1∑m(hθ(xi)−yi)x2i......∂θn∂f=m1i=1∑m(hθ(xi)−yi)xni
所以
∇J(θ)=⎣⎢⎢⎢⎢⎢⎢⎢⎡∂θ1∂f∂θ2∂f∂θ3∂f..∂θn∂f⎦⎥⎥⎥⎥⎥⎥⎥⎤=⎣⎢⎢⎢⎢⎢⎢⎡x11(hθ(x1)−y1)+x12(hθ(x2)−y2)+...+x1m(hθ(xm)−ym)x21(hθ(x1)−y1)+x22(hθ(x2)−y2)+...+x2m(hθ(xm)−ym)x31(hθ(x1)−y1)+x32(hθ(x2)−y2)+...+x3m(hθ(xm)−ym)........xn1(hθ(x1)−y1)+xn2(hθ(x2)−y2)+...+xnm(hθ(xm)−ym)⎦⎥⎥⎥⎥⎥⎥⎤
经过奇妙变换得到
∇J(θ)=⎣⎢⎢⎢⎢⎢⎢⎢⎡∂θ1∂f∂θ2∂f∂θ3∂f..∂θn∂f⎦⎥⎥⎥⎥⎥⎥⎥⎤==⎣⎢⎢⎢⎢⎢⎢⎡x11x12x13..x1mx21...x22...x23...........x2m...xn1xn2xn3..xnm⎦⎥⎥⎥⎥⎥⎥⎤T⎣⎢⎢⎢⎢⎡hθ(x1)−y1hθ(x2)−y2hθ(x3−y3...hθ(xm)−ym⎦⎥⎥⎥⎥⎤
再变
∇J(θ)=⎣⎢⎢⎢⎢⎢⎢⎢⎡∂θ1∂f∂θ2∂f∂θ3∂f..∂θn∂f⎦⎥⎥⎥⎥⎥⎥⎥⎤==⎣⎢⎢⎢⎢⎢⎢⎡x11x12x13..x1mx21...x22...x23...........x2m...xn1xn2xn3..xnm⎦⎥⎥⎥⎥⎥⎥⎤T⎝⎜⎜⎜⎜⎛⎣⎢⎢⎢⎢⎡hθ(x1)hθ(x2)hθ(x3...hθ(xm)⎦⎥⎥⎥⎥⎤−⎣⎢⎢⎢⎢⎡y1y2y3...ym⎦⎥⎥⎥⎥⎤⎠⎟⎟⎟⎟⎞
代入子式们得到:
∇J(θ)=XT(Xθ−Y)
又因为
θ1=θ1−lR∂θ1∂fθ2=θ2−lR∂θ2∂fθ3=θ3−lR∂θ3∂f......θm=θm−lR∂θm1∂f
代入子式与∇J(θ)得到最终式子:
θ=θ−LR(∇J(θ))
-
式子里除LR外都是向量
重复上式足够次数,可得到距离代价函数取最小值时候的变量(ω1,ω2...ωn)极为接近的变量(θ1,θ2...θn)