一、Pytorch对自定义表达式自动求导

例如:y = a²x + bx + c,分别对a,b,c求导

若当a=3,b=4,c=5,x=1时
在这里插入图片描述

import torch
from torch import autograd

x = torch.tensor(1.)
a = torch.tensor(3.,requires_grad=True)
b = torch.tensor(4.,requires_grad=True)
c = torch.tensor(5.,requires_grad=True)

y = a**2 * x + b * x + c

print("before:",a.grad,b.grad,c.grad)#before: None None None
grads = autograd.grad(y,[a,b,c])
print("after:",grads[0],grads[1],grads[2])#after: tensor(6.) tensor(1.) tensor(1.)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41264055/article/details/126558272