在 PyTorch 中向后()做什么?

该方法用于计算神经网络中反向传播期间的梯度。 backward()

  • 执行此方法时会计算梯度。

  • 这些梯度存储在各自的变量中。

  • 梯度是根据这些变量计算的,梯度是使用.grad访问的。

  • 如果我们不调用backward()计算梯度的方法,则不会计算梯度。

  • 而且,如果我们使用.grad访问梯度,结果是None

让我们举几个例子来演示它是如何工作的。

示例 1

在这个例子中,我们尝试在不调用backward()方法的情况下访问梯度。我们注意到所有的梯度都是None

# import torch library
import torch

# define three tensor
x = torch.tensor(2., requires_grad = False)
w = torch.tensor(3., requires_grad = True)
b = torch.tensor(1., requires_grad = True)
print("x:", x)
print("w:", w)
print("b:", b)

# define a function of the above defined tensors
y = w * x + b
print("y:", y)

# print the gradient w.r.t above tensors
print("x.grad:", x.grad)
print("w.grad:", w.grad)
print("b.grad:", b.grad)
输出结果
x: tensor(2.)
w: tensor(3., requires_grad=True)
b: tensor(1., requires_grad=True)
y: tensor(7., grad_fn=<AddBackward0>)
x.grad: None
w.grad: None
b.grad: None

示例 2

在第二个示例中,backward()为函数y调用该方法。然后,访问梯度。不需要grad的张量的梯度再次为None。关于具有梯度的张量的梯度不是无。

# import torch library
import torch

# define three tensors
x = torch.tensor(2., requires_grad = False)
w = torch.tensor(3., requires_grad = True)
b = torch.tensor(1., requires_grad = True)
print("x:", x)
print("w:", w)
print("b:", b)

# define a function y
y = w * x + b
print("y:", y)

# take the backward() for y
y.backward()
# print the gradients w.r.t. above x, w, and b
print("x.grad:", x.grad)
print("w.grad:", w.grad)
print("b.grad:", b.grad)
输出结果
x: tensor(2.)
w: tensor(3., requires_grad=True)
b: tensor(1., requires_grad=True)
y: tensor(7., grad_fn=<AddBackward0>)
x.grad: None
w.grad: tensor(2.)
b.grad: tensor(1.)