梯度下降算法

梯度下降法的简单介绍以及实现

梯度下降法的基本思想可以类比为一个下山的过程。假设这样一个场景:一个人被困在山上,需要从山上下来(i.e.找到山的最低点,也就是山谷)。但此时山上的浓雾很大,导致可视度很低。因此,下山的路径就无法确定,他必须利用自己周围的信息去找到下山的路径。这个时候,他就可以利用梯度下降算法来帮助自己下山。具体来说就是,以他当前的所处的位置为基准,寻找这个位置最陡峭的地方,然后朝着山的高度下降的地方走,同理,如果我们的目标是上山,也就是爬到山顶,那么此时应该是朝着最陡峭的方向往上走。然后每走一段距离,都反复采用同一个方法,最后就能成功的抵达山谷。

在这种就情况下,我们也可以假设此时周围的陡峭程度我们无法用肉眼来测量,需要一个复杂的工具来帮助我们测量,恰巧的是此人正好拥有测量最陡峭方向的能力。因此,这个人每走一段距离,都需要一段时间来测量所在位置最陡峭的方向,这是比较耗时的。那么为了在太阳下山之前到达山底,就要尽可能的减少测量方向的次数。这是一个两难的选择,如果测量的频繁,可以保证下山的方向是绝对正确的,但又非常耗时,如果测量的过少,又有偏离轨道的风险。所以需要找到一个合适的测量方向的频率,来确保下山的方向不错误,同时又不至于耗时太多!

梯度下降

梯度下降的过程就如同这个下山的场景一样
首先,我们有一个可微分的函数。这个函数就代表着一座山。我们的目标就是找到这个函数的最小值,也就是山底。根据之前的场景假设,最快的下山的方式就是找到当前位置最陡峭的方向,然后沿着此方向向下走,对应到函数中,就是找到给定点的梯度 ,然后朝着梯度相反的方向,就能让函数值下降的最快!因为梯度的方向就是函数之变化最快的方向(在后面会详细解释)
所以,我们重复利用这个方法,反复求取梯度,最后就能到达局部的最小值,这就类似于我们下山的过程。而求取梯度就确定了最陡峭的方向,也就是场景中测量方向的手段。

三种梯度算法的代码实现

导入函数包

import os
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
批量梯度下降求解线性回归

首先,我们需要定义数据集和学习率 接下来我们以矩阵向量的形式定义代价函数和代价函数的梯度 当循环次数超过1000次,这时候再继续迭代效果也不大了,所以这个时候可以退出循环!

eta = 0.1
n_iterations = 1000
m = 100
theta = np.random.randn(2, 1)

for iteration in range(n_iterations): # 限定迭代次数 
    gradients = 1/m * X_b.T.dot(X_b.dot(theta)-Y)  # 梯度
    theta = theta - eta * gradients  # 更新theta
theta_path_bgd = []

def plot_gradient_descent(theta, eta, theta_path = None):
    m = len(X_b)
    plt.plot(X, y, "b.")
    n_iterations = 1000
    for iteration in range(n_iterations):
        if iteration < 10: #取前十次
            y_predict = X_new_b.dot(theta)
            style = "b-"
            plt.plot(X_new,y_predict, style)
        gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
        theta = theta - eta*gradients
        if theta_path is not None:
            theta_path.append(theta)
    plt.xlabel("$x_1$", fontsize=18)
    plt.axis([0, 2, 0, 15])
    plt.title(r"$\eta = {}$".format(eta),fontsize=16)
np.random.seed(42) #随机数种子
theta = np.random.randn(2,1) #random initialization

plt.figure(figsize=(10,4))
plt.subplot(131);plot_gradient_descent(theta, eta=0.02) # 第一个,
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.subplot(132);plot_gradient_descent(theta, eta=0.1, theta_path=theta_path_bgd ) # 第二个,拟合最好,eta=0.1
plt.subplot(133);plot_gradient_descent(theta, eta=0.5) # 第三个

save_fig("gradient_descent_plot")

运行结果
在这里插入图片描述

随机梯度下降

随机梯度下降每次用一个样本来梯度下降,可能得到局部最小值。

theta_path_sgd = []
m = len(X_b)
np.random.seed(42)

n_epochs = 50

theta = np.random.randn(2,1) #随机初始化

for epoch in range(n_epochs):
    for i in range(m):
        if epoch == 0 and i < 10:
            y_predict = X_new_b.dot(theta)
            style = "b-"
            plt.plot(X_new,y_predict,style)
        random_index = np.random.randint(m)
        xi = X_b[random_index:random_index+1]
        yi = y[random_index:random_index+1]
        gradients = 2 * xi.T.dot(xi.dot(theta)-yi)
        eta = 0.1
        theta = theta - eta * gradients
        theta_path_sgd.append(theta)
        
plt.plot(x,y,"b.")
plt.xlabel("$x_1$",fontsize = 18)
plt.ylabel("$y$",rotation =0,fontsize = 18)
plt.axis([0,2,0,15])
save_fig("sgd_plot")
plt.show()

运行结果
在这里插入图片描述

小批量梯度下降

小批量梯度下降每次迭代使用一个以上又不是全部样本。

theta_path_mgd = []
n_iterations = 50
minibatch_size = 20

np.random.seed(42)
theta = np.random.randn(2,1)

for epoch in range(n_iterations):
    shuffled_indices = np.random.permutation(m)
    X_b_shuffled = X_b[shuffled_indices]
    y_shuffled = y[shuffled_indices]
    for i in range(0, m, minibatch_size):
        xi = X_b_shuffled[i:i+minibatch_size]
        yi = y_shuffled[i:i+minibatch_size]
        gradients = 2/minibatch_size * xi.T.dot(xi.dot(theta)-yi)
        eta = 0.1
        theta = theta-eta*gradients
        theta_path_mgd.append(theta)
三者的比较图像
theta_path_bgd = np.array(theta_path_bgd)
theta_path_sgd = np.array(theta_path_sgd)
theta_path_mgd = np.array(theta_path_mgd)

plt.figure(figsize=(7,4))
plt.plot(theta_path_sgd[:,0], theta_path_sgd[:,1], "r-s", linewidth = 1, label = "Stochastic")
plt.plot(theta_path_mgd[:,0], theta_path_mgd[:,1], "g-+", linewidth = 2, label = "Mini-batch")
plt.plot(theta_path_bgd[:,0], theta_path_bgd[:,1], "b-o", linewidth = 3, label = "Batch")
plt.legend(loc="upper left", fontsize = 16)
plt.xlabel(r"$\theta_0$", fontsize=20)
plt.ylabel(r"$\theta_1$", fontsize=20, rotation=0)
plt.axis([2.5,4.5,2.3,3.9])
save_fig("gradients_descent_paths_plot")
plt.show()

运行结果
在这里插入图片描述
总结:综合以上对比可以看出,批量梯度下降的准确度最好,其次是小批量梯度下降,最后是随机梯度下降。因为小批量梯度下降与随机梯度下降每次梯度估计的方向不确定,可能需要很长时间接近最小值点。对于训练速度来说,批量梯度下降在梯度下降的每一步中都用到了所有的训练样本,当样本量很大时,训练速度往往不能让人满意;随机梯度下降由于每次仅仅采用一个样本来迭代,所以训练速度很快;小批量梯度下降每次迭代使用一个以上又不是全部样本,因此训练速度介于两者之间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值