要计算梯度,张量必须具有它的参数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)以下示例显示了在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.)在下面的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的情况下定义的。