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

回顾梯度下降流程

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

批量梯度下降 BGD

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

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

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

g ( θ 0 . . . θ m ) = x j ( 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列
所以 x j x_{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()

你可能感兴趣的:(代码,机器学习,批量梯度下降,机器学习,代码实现,python)