Files
obsidian_sycn/网页剪辑/zhuanlan.zhihu.com/理解Pytorch的loss.backward()和optimizer.step().md
2026-07-31 15:28:08 +08:00

21 lines
1.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
doc_type: hypothesis-highlights
url: 'https://zhuanlan.zhihu.com/p/445009191'
---
# 理解Pytorch的loss.backward()和optimizer.step()
## Metadata
- Author: [zhuanlan.zhihu.com]()
- Title: 理解Pytorch的loss.backward()和optimizer.step()
- Reference: https://zhuanlan.zhihu.com/p/445009191
- Category: #source/article🗞
- Tags:
## Highlights
- loss.backward()故名思义,就是将损失loss 向输入侧进行反向传播,同时对于需要进行梯度计算的所有变量 xxx (requires_grad=True),计算梯度 ddxloss\frac{d}{dx}loss\frac{d}{dx}loss ,并将其累积到梯度 x.gradx.gradx.grad 中备用,即: x.grad=x.grad+ddxlossx.grad =x.grad +\frac{d}{dx}lossx.grad =x.grad +\frac{d}{dx}loss
- optimizer.step()是优化器对 xxx 的值进行更新,以随机梯度下降SGD为例:学习率(learning rate, lr)来控制步幅,即:x=xlrx.gradx = x - lr * x.gradx = x - lr * x.grad ,减号是由于要沿着梯度的反方向调整变量值以减少Cost。
- optimizer.zero_grad()清除了优化器中所有 xxx 的 x.gradx.gradx.grad ,在每次loss.backward()之前,不要忘记使用,否则之前的梯度将会累积,这通常不是我们所期望的( 也不排除也有人需要利用这个功能)。