《动手学深度学习 PyTorch版》学习笔记(二):自动求梯度

    科技2026-04-16  3

    一、自动求梯度

    1、requires_grad_(), detach(), torch.no_grad()的区别 参考博客:https://www.jianshu.com/p/ff74ccae25f3

    2、.grad_fn 每个Tensor都有一个.grad_fn属性,该属性即创建该Tensor的Function, 就是说该Tensor是不是通过某些运算得到的,若是,则grad_fn返回一个与这些运算相关的对象,否则是None。

    3、梯度

    grad在反向传播过程中是累加的(accumulated),这意味着每一次运行反向传播,梯度都会累加之前的梯度,所以一般在反向传播之前需把梯度清零 .grad.data.zero_()在y.backward()时,如果y是标量,则不需要为backward()传入任何参数;否则,需要传入一个与y同形的Tensor x = torch.tensor([1.0, 2.0, 3.0, 4.0], requires_grad=True) y = 2 * x z = y.view(2, 2) print(z)

    输出

    tensor([[2., 4.], [6., 8.]], grad_fn=<ViewBackward>)

    现在 z 不是一个标量,所以在调用backward时需要传入一个和z同形的权重向量进行加权求和得到一个标量。

    v = torch.tensor([[1.0, 0.1], [0.01, 0.001]], dtype=torch.float) z.backward(v) print(x.grad)

    输出

    tensor([2.0000, 0.2000, 0.0200, 0.0020])

    4、中断梯度

    x = torch.tensor(1.0, requires_grad=True) y1 = x ** 2 with torch.no_grad(): y2 = x ** 3 y3 = y1 + y2 print(x.requires_grad) print(y1, y1.requires_grad) # True print(y2, y2.requires_grad) # False print(y3, y3.requires_grad) # True y3.backward() print(x.grad)

    Processed: 0.016, SQL: 9