PyTorch深度学习实践 Lecture03 梯度下降


🤵 AuthorHorizon John

编程技巧篇各种操作小结

🎇 机器视觉篇会变魔术 OpenCV

💥 深度学习篇简单入门 PyTorch

🏆 神经网络篇经典网络模型

💻 算法篇再忙也别忘了 LeetCode


视频链接:Lecture 03 Gradient_Descent
文档资料:

//Here is the link:
课件链接:https://pan.baidu.com/s/1vZ27gKp8Pl-qICn_p2PaSw
提取码:cxe4

Gradient Descent(梯度下降)

概述

在这里插入图片描述
我们前面说到利用 穷举法 找到一个合适的 W 值,

使得拟合出来的直线尽可能多的 穿过或者接近 给定的3组数据,

在这里我们一般都会 随机初始化 一个 W 值,

然后利用 穷举法不断的更新迭代 直到找到一个 最优 的拟合(直线)曲线;


在这里插入图片描述

假设给定的随机初始值 W 为:Initial Guess

cost-W 曲线存在一个 最优点(损失值最小点):Global cost minimum

那么下一次 W值 更新迭代的时候是往 or 呢 ?

这就涉及到 梯度下降 的问题了,

在机器学习中,最小化损失函数时,通过 梯度下降法 来一步步的迭代求解,得到最小化的损失函数和模型参数值。



我们可以对 W0 点进行 求导 得到该处的导数,偏导数以向量的形式就是 梯度(具有方向)

W ’ > 0 ,单调递增;    W ’ < 0 ,单调递减;

这里我们建立了一个 Update 函数,使得每次的更新都 往梯度下降的方向 进行,

式中 α学习率,即更新迭代的速率,决定了下一次更新 W(n+1) - W(n) 之间距离。


在这里插入图片描述

Code

# Here is the code :

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

运行结果

在这里插入图片描述


附录:相关文档资料

PyTorch 官方文档: PyTorch Documentation
PyTorch 中文手册: PyTorch Handbook


《PyTorch深度学习实践》系列链接:

  Lecture01 Overview
  Lecture02 Linear_Model
  Lecture03 Gradient_Descent
  Lecture04 Back_Propagation
  Lecture05 Linear_Regression_with_PyTorch
  Lecture06 Logistic_Regression
  Lecture07 Multiple_Dimension_Input
  Lecture08 Dataset_and_Dataloader
  Lecture09 Softmax_Classifier
  Lecture10 Basic_CNN
  Lecture11 Advanced_CNN
  Lecture12 Basic_RNN
  Lecture13 RNN_Classifier

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Horizon John

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值