如何在 PyTorch 中计算梯度?
要计算梯度,张量必须具有它的参数requires_grad=true。梯度与偏导数相同。
例如,在函数y=2*x+1中,x是一个具有requires_grad=True的张量。我们可以使用函数计算梯度,并且可以使用x.grad访问梯度。y.backward()
这里,x.gad的值与y对x的偏导数相同。如果张量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程序中,我们使用三个张量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)