示例代码:
import torch
from torch import autograd
x = torch.tensor(1.) # 只有浮点型张量才可以求梯度(导数)
a = torch.tensor(1., requires_grad=True) # requires_grad=True 表示对其求导
b = torch.tensor(2., requires_grad=True)
c = torch.tensor(3., requires_grad=True)
y = a**2 * x + b * x + c # 要求导的公式
print('before:', a.grad, b.grad, c.grad)
grads = autograd.grad(y, [a, b, c]) # 进行求导计算
print('after:', grads[0], grads[1], grads[2])
运行结果:
before: None None None
after: tensor(2.) tensor(1.) tensor(1.)