牛顿法、梯度下降法原理及Python编程应用
一、使用梯度下降法实现求解多元线性回归方程
1. 梯度下降法原理
梯度下降法应用一阶泰勒展开,假设L(θ)代表损失函数,目标:最小化损失函数,θ是需要更新的模型参数。下面公式中alpha是步长(学习率),可以直接赋值一个小的数,也可以通过line search。
2.python实例
多元函数方程为z=x1 ^2 + 2 * x2 ^2 - 4 * x1- 2 * x1 * x2
使用梯度下降法实现求解多元线性回归方程
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def Fun(x,y): #原函数
return x*x+2*y*y+-4*x-2*x*y #方程为z=x1^2+2x2^2-4x1-2x1x2
def PxFun(x,y): #x偏导
return 2*x+4-2*y
def PyFun(x,y): #y偏导
return 4*y-2*x
#初始化
fig = plt.figure() #figure对象
ax = Axes3D(fig) #Axes3D对象
X,Y = np.mgrid[-2:2:40j,-2:2:40j] #取样并作满射联合
Z = Fun(X,Y) #取样点Z坐标打表
ax.plot_surface(X,Y,Z,rstride=1,cstride=1