Pytorch深度学习实践3-梯度下降

本笔记来源于b站刘二大人:《PyTorch深度学习实践》3.梯度下降

一、代码

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() 

二、何为梯度

首选明确梯度是什么:梯度的本意是一个向量(矢量),表示某一函数在该点处的方向导数沿着该方向取得最大值,即函数在该点处沿着该方向变化最快,变化率最大。

既然是函数,那么就会有一元与多元的区分

一元函数:

如上图,对于cost和w组成的函数上的任一点就是这一点的切线向量:Gradient=\frac{\partial cost}{\partial w}\overrightarrow{i}

二元函数:

 在一元上进行推导,对多元函数而言这一点的梯度就是由这一点所有自变量的偏导数组成的向量。如对cost = f(w1,w2,w3),

Gradient=\frac{\partial cost}{\partial w1}\overrightarrow{i}+\frac{\partial cost}{\partial w2}\overrightarrow{j}+\frac{\partial cost}{\partial w3}\overrightarrow{z}

三、再来理解梯度下降算法

上面说了函数在该点处沿着梯度变化最快,变化率最大。那么对于我们的损失函数cost和权重w而言,深度学习需要让cost随着w的变化尽快的下降到最小,直到无限趋近于0或者等于0。

既然函数在该点处沿着梯度上升变化最快,那么沿着梯度反方向就是下降最快,也就是我们需要的情况,这就是梯度下降算法。

表现在数学上就是w = w - \alpha |Gradient|,其中\alpha就是学习率,也就是我们沿着梯度这根线下降一次多少,\alpha要取合适值,太大太小都不好

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值