Files
obsidian_sycn/编程经验/Pytorch/网页剪辑/理解Pytorch的loss.backward()和optimizer.step().md
T
2026-07-31 15:28:08 +08:00

37 lines
1.7 KiB
Markdown
Raw 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'
---
## Metadata
- Reference: https://zhuanlan.zhihu.com/p/445009191
- Tags:
## Highlights
- loss.backward()故名思义,就是将损失loss 向输入侧进行反向传播,同时对于需要进行梯度计算的所有变量 xxx (requires_grad=True),计算梯度 $\frac{d}{dx}loss$,并将其累积到梯度 $x.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=xlr∗x.gradx$,减号是由于要沿着梯度的反方向调整变量值以减少Cost。
```python
x = torch.tensor([1., 2.], requires_grad=True)
# x: tensor([1., 2.], requires_grad=True)
y = 100*x
# y: tensor([100., 200.], grad_fn=<MulBackward0>)
loss = y.sum(). # tensor(300., grad_fn=<SumBackward0>)
# Compute gradients of the parameters respect to the loss
print(x.grad) # None, 反向传播前,梯度不存在
loss.backward()
print(x.grad) # tensor([100., 100.]) loss对y的梯度为1 对x的梯度为100
optim = torch.optim.SGD([x], lr=0.001) # 随机梯度下降, 学习率0.001
print(x) # tensor([1., 2.], requires_grad=True)
optim.step() # 更新x
print(x) # tensor([0.9000, 1.9000], requires_grad=True) 变化量=梯度X学习率 0.1=100*0.001
```
- optimizer.zero_grad()清除了优化器中所有 xxx 的 $x.grad$ ,在每次loss.backward()之前,不要忘记使用,否则之前的梯度将会累积,这通常不是我们所期望的( 也不排除也有人需要利用这个功能)。