您的位置:首页 > 编程语言 > Python开发

Python 批量梯度下降 BGD 代码实现 笔记

2019-01-27 17:27 405 查看

回顾梯度下降流程

#1 初始化 θ\thetaθ
#2 求 gradient
#3 θt+1=θt−α•g\theta^{t+1}=\theta^{t}-\alpha • gθt+1=θt−α•g
#4 ggg 收敛

批量梯度下降 BGD

批量:Batch
梯度:Gradient
下降:Descent
“Batch”: Each steep of gradient descent use all the training examples.
每一步下降都用到所有的数据样本

优点:全局最优解,精确
缺点:数据样本较大时耗费大量时间

θj:=θj−α∑i=1m(hθ(x(i))−y(i))xj(i)\theta_{j}:=\theta_{j}-\alpha\sum_{i=1}^{m}(h_{\theta}(x^{(i)})-y^{(i)})x_{j}^{(i)}θj​:=θj​−αi=1∑m​(hθ​(x(i))−y(i))xj(i)​

g(θ0...θm)=xj(x∗θ−y)g_{(\theta_{0}...\theta_{m})}=x_{j}(x*\theta-y)g(θ0​...θm​)​=xj​(x∗θ−y)
x为m行n列,θ\thetaθ为n行1列 相乘
⟹\Longrightarrow⟹m行1列−-−y为m行1列
⟹\Longrightarrow⟹m行1列
所以xjx_{j}xj​需要转置为n行m列 与 m行1列 相乘
⟹\Longrightarrow⟹n行1列
1/m 平均每个数据的权重;
gradients = 1/m * x_b.T.dot(x_b.dot(theta)-y)

import numpy as np
import matplotlib.pyplot as plt

# 随机X纬度x1,rand是随机均匀分布
x = 2 * np.random.rand(100,1)
# 人为设置真实的Y一列 np.random.randn(100,1) 设置误差遵循标准正态分布
y = 4 + 3 * x + np.random.randn(100,1)
# 整合 x0 和 x1 成矩阵
x_b = np.c_[np.ones((100,1)),x]

learning_rate = 0.01 # 学习率一般默认设置为0.01
n_iterations = 10000 # 迭代次数够多即可(不一定需要全局最优解)
m = 100 # 100 行

# #1 初始化theta,w0...wn
theta = np.random.randn(2,1) # x_b 中只有x0,x1,只需要两个theta

# #4 不设置阀值,直接设置超参数,迭代次数,迭代次数到了就认为收敛了
for iteration in range(n_iterations):
# #2 求梯度gradient
gradients = 1/m * x_b.T.dot(x_b.dot(theta)-y)
# #3 调整theta值
theta = theta - learning_rate * gradients

print(theta)

x_new = np.array([[0],[2]])
x_new_b = np.c_[(np.ones((2,1))),x_new]
y_predict = x_new_b.dot(theta)

# 绘制图形
plt.plot(x_new,y_predict,'r-')
plt.plot(x,y,'b.')
plt.axis([0,2,0,15])
plt.show()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: