2.4

自动微分机制(Autograd)

什么是自动微分

自动微分(Automatic Differentiation)是 PyTorch 的核心特性,它可以自动计算梯度,这对于训练神经网络至关重要。

计算图的概念

当你执行张量操作时,PyTorch 会构建一个计算图,记录所有的操作。通过反向传播,可以自动计算梯度。

requires_grad 属性

import torch

# 创建需要梯度的张量
x = torch.tensor([2.0], requires_grad=True)
print(x.requires_grad)  # True

# 执行计算
y = x ** 2 + 3 * x + 1
print(y)  # tensor([11.], grad_fn=<AddBackward0>)

# grad_fn 表示创建该张量的操作

梯度计算

# 反向传播计算梯度
y.backward()

# 查看梯度
print(x.grad)  # tensor([7.])
# dy/dx = 2x + 3 = 2*2 + 3 = 7

梯度累积与清零

x = torch.tensor([2.0], requires_grad=True)

# 第一次计算
y = x ** 2
y.backward()
print(x.grad)  # tensor([4.])

# 第二次计算(梯度会累积)
y = x ** 3
y.backward()
print(x.grad)  # tensor([16.]) = 4 + 12

# 清零梯度
x.grad.zero_()
print(x.grad)  # tensor([0.])

实际应用:简单的梯度下降

import torch

# 目标:最小化 f(x) = (x - 3)^2
x = torch.tensor([0.0], requires_grad=True)
learning_rate = 0.1

for i in range(100):
    # 前向传播
    y = (x - 3) ** 2

    # 反向传播
    y.backward()

    # 更新参数
    with torch.no_grad():
        x -= learning_rate * x.grad

    # 清零梯度
    x.grad.zero_()

    if i % 10 == 0:
        print(f"Step {i}: x = {x.item():.4f}, y = {y.item():.4f}")

# 最终 x 应该接近 3

禁用梯度计算

# 方法1:torch.no_grad()
with torch.no_grad():
    y = x ** 2
    # y 不会追踪梯度

# 方法2:detach()
y = x ** 2
y_detached = y.detach()  # 从计算图中分离

# 方法3:@torch.no_grad() 装饰器
@torch.no_grad()
def predict(x):
    return x ** 2

✏️ 课堂练习

为什么在训练神经网络时需要在每次迭代后清零梯度?