如何在 PyTorch 中计算梯度?

要计算梯度,张量必须具有它的参数requires_grad = true。梯度与偏导数相同。

例如,在函数y = 2*x + 1 中x是一个具有requires_grad = True的张量。我们可以使用函数计算梯度,并且可以使用x.grad访问梯度y.backward()

这里,x.gad的值与yx的偏导数相同。如果张量 x 没有requires_grad,则梯度为 None。我们可以定义一个多变量的函数。这里的变量是 PyTorch 张量。

步骤

我们可以使用以下步骤来计算梯度 -

  • 导入火炬库。确保您已经安装了它。

import torch

  • 使用requires_grad = True创建 PyTorch 张量并打印张量。

x = torch.tensor(2.0, requires_grad = True)
print("x:", x)

  • 为上述张量x定义一个函数y

y = x**2 + 1

  • 使用y后向函数计算梯度。

y.backward()

  • 使用x.grad访问并打印关于上面创建的张量x 的梯度

dx = x.grad
print("x.grad :", dx)

示例 1

以下示例显示了在 PyTorch 中计算梯度的详细过程。

# import torch library
import torch

# create tensors with requires_grad = true
x = torch.tensor(2.0, requires_grad = True)

# print the tensor
print("x:", x)

# define a function y for the tensor, x
y = x**2 + 1
print("y:", y)

# Compute gradients using backward function for y
y.backward()

# Access the gradients using x.grad
dx = x.grad
print("x.grad :", dx)
输出结果
x: tensor(2., requires_grad=True)
y: tensor(5., grad_fn=<AddBackward0>)
x.grad : tensor(4.)

示例 2

在下面的 Python 程序中,我们使用三个张量xwb作为函数y 的变量。张量x没有requires_grad并且wbrequires_grad = true

# import torch library
import torch

# create tensor without requires_grad = true
x = torch.tensor(3)

# create tensors with requires_grad = true
w = torch.tensor(2.0, requires_grad = True)
b = torch.tensor(5.0, requires_grad = True)

# print the tensors
print("x:", x)
print("w:", w)
print("b:", b)

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

# Compute gradients by calling backward function for y
y.backward()

# Access and print the gradients w.r.t x, w, and b
dx = x.grad
dw = w.grad
db = b.grad
print("x.grad :", dx)
print("w.grad :", dw)
print("b.grad :", db)
输出结果
x: tensor(3)
w: tensor(2., requires_grad=True)
b: tensor(5., requires_grad=True)
y: tensor(11., grad_fn=<AddBackward0>)
x.grad : None
w.grad : tensor(3.)
b.grad : tensor(1.)

请注意,x.grad是 None。这是因为 x 是在没有requires_grad = True 的情况下定义的。

示例 3

# import torch library
import torch

# create tensors with requires_grad = true
x = torch.tensor(3.0, requires_grad = True)
y = torch.tensor(4.0, requires_grad = True)

# print the tensors
print("x:", x)
print("y:", y)

# define a function z of above created tensors
z = x**y
print("z:", z)

# call backward function for z to compute the gradients
z.backward()

# Access and print the gradients w.r.t x, and y
dx = x.grad
dy = y.grad
print("x.grad :", dx)
print("y.grad :", dy)
输出结果
x: tensor(3., requires_grad=True)
y: tensor(4., requires_grad=True)
z: tensor(81., grad_fn=<PowBackward1>)
x.grad : tensor(108.)
y.grad : tensor(88.9876)