刘老师《Pytorch深度学习实践》第三讲:梯度下降

发布时间 2023-10-31 10:07:17作者: 亚1918

1.分治法不能用

局部点干扰性大

2.梯度下降

3. 随机梯度下降

随机梯度下降法(Stochastic Gradient Descent, SGD):由于批量梯度下降法在更新每一个参数时,都需要所有的训练样本,所以训练过程会随着样本数量的加大而变得异常的缓慢。随机梯度下降法正是为了解决批量梯度下降法这一弊端而提出的。随机梯度下降是通过每个样本来迭代更新一次。SGD伴随的一个问题是噪音较BGD要多,使得SGD并不是每次迭代都向着最优化方向进行。

4.Batch

批量梯度下降法(Batch Gradient Descent, BGD):是梯度下降法的最原始形式,每迭代一步或更新每一参数时,都要用到训练集中的所有样本数据,当样本数目很多时,训练过程会很慢。
小批量梯度下降(Mini-batch Gradient Descent,MBGD)
大多数用于深度学习的梯度下降算法介于以上两者之间,使用一个以上而又不是全部的训练样本。传统上,这些会被称为小批量(mini-batch)或小批量随机(mini-batch stochastic)方法,现在通常将它们简单地成为随机(stochastic)方法。对于深度学习模型而言,人们所说的“随机梯度下降, SGD”,其实就是基于小批量(mini-batch)的随机梯度下降。

5.鞍点

  • 鞍点的定义

    在学习最优化课程时,不时听到“鞍点”这个名词。老师很快提了这个词,但没有详细介绍鞍点的含义。
    鞍点 (saddle point)的数学含义是: 目标函数在此点上的梯度(一阶导数)值为 0, 但从该点出发的一个方向是函数的极大值点,而在另一个方向是函数的极小值点。
    判断鞍点的一个充分条件是:函数在一阶导数为零处(驻点)的黑塞矩阵为不定矩阵。
    半正定矩阵: 所有特征值为非负,或主子式全部非负。
    半负定矩阵:所有特征值为非正,或主子式负正相间。
    不定矩阵:特征值有正有负,或主子式不满足上面的两种情况。

6.代码

import matplotlib.pyplot as plt
 
# prepare the training set
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
 
# initial guess of weight 
w = 1.0
 
# define the model linear model y = w*x
def forward(x):
    return x*w
 
#define the cost function MSE 
def cost(xs, ys):
    cost = 0
    for x, y in zip(xs,ys):
        y_pred = forward(x)
        cost += (y_pred - y)**2
    return cost / len(xs)
 
# define the gradient function  gd
def gradient(xs,ys):
    grad = 0
    for x, y in zip(xs,ys):
        grad += 2*x*(x*w - y)
    return grad / len(xs)
 
epoch_list = []
cost_list = []
print('predict (before training)', 4, forward(4))
for epoch in range(100):
    cost_val = cost(x_data, y_data)
    grad_val = gradient(x_data, y_data)
    w-= 0.01 * grad_val  # 0.01 learning rate
    print('epoch:', epoch, 'w=', w, 'loss=', cost_val)
    epoch_list.append(epoch)
    cost_list.append(cost_val)
 
print('predict (after training)', 4, forward(4))
plt.plot(epoch_list,cost_list)
plt.ylabel('cost')
plt.xlabel('epoch')
plt.show() 

附图:


随机梯度下降算法

import matplotlib.pyplot as plt

x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

w = 1.0

def forward(x):
    return x * w

# calculate loss function
def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) ** 2

# define the gradient function  sgd
def gradient(x, y):
    return 2 * x * (x * w - y)
epoch_list = []
loss_list = []

print('predict (before training)', 4, forward(4))

for epoch in range(100):
    for x, y in zip(x_data, y_data):
        grad = gradient(x, y)
        w = w - 0.01 * grad  # update weight by every grad of sample of training set
        print("\tgrad:", x, y, grad)
        l = loss(x, y)
    print("progress:", epoch, "w=", w, "loss=", l)
    epoch_list.append(epoch)
    loss_list.append(l)

print('predict (after training)', 4, forward(4))
plt.plot(epoch_list, loss_list)
plt.ylabel('loss')
plt.xlabel('epoch')
plt.show()