x = torch.tensor(0.0,requires_grad = True) # x需要被求导 a = torch.tensor(1.0) b = torch.tensor(-2.0) c = torch.tensor(1.0) y = a*torch.pow(x,2) + b*x + c
y.backward() dy_dx = x.grad print(dy_dx)
# 非标量的反向传播
x = torch.tensor([[0.0,0.0],[1.0,2.0]],requires_grad = True) a = torch.tensor(1.0) b = torch.tensor(-2.0) c = torch.tensor(1.0) y = a*torch.pow(x,2) + b*x + c
x = torch.tensor([[0.0,0.0],[1.0,2.0]],requires_grad = True) a = torch.tensor(1.0) b = torch.tensor(-2.0) c = torch.tensor(1.0) y = a*torch.pow(x,2) + b*x + c
gradient = torch.tensor([[1.0,1.0],[1.0,1.0]]) z = torch.sum(y*gradient)