如何在 PyTorch 中计算梯度?
要计算梯度,张量必须将其参数设置为 **requires_grad = True**。梯度与偏导数相同。
例如,在函数 **y = 2*x + 1** 中,**x** 是一个设置了 **requires_grad = True** 的张量。我们可以使用 **y.backward()** 函数计算梯度,并使用 **x.grad** 访问梯度。
这里,**x.grad** 的值与 **y** 关于 **x** 的偏导数相同。如果张量 x 没有设置 **requires_grad**,则梯度为 None。我们可以定义一个包含多个变量的函数。这里的变量是 PyTorch 张量。
步骤
我们可以使用以下步骤计算梯度:
导入 **torch** 库。确保你已经安装了它。
import torch
创建具有 **requires_grad = True** 的 PyTorch 张量并打印张量。
x = torch.tensor(2.0, requires_grad = True)
print("x:", x)为上述张量 **x** 定义函数 **y**。
y = x**2 + 1
使用 **y** 的 **backward** 函数计算梯度。
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 程序中,我们使用三个张量 **x**、**w** 和 **b** 作为函数 **y** 的变量。张量 **x** 没有设置 **requires_grad**,而 **w** 和 **b** 设置了 **requires_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)
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP