1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import numpy as np import torch
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]])
print("x:\n",x) print("y:\n",y) y.backward(gradient = gradient) x_grad = x.grad print("x_grad:\n",x_grad)
''' x: tensor([[0., 0.], [1., 2.]], requires_grad=True) y: tensor([[1., 1.], [0., 1.]], grad_fn=<AddBackward0>) x_grad: tensor([[-2., -2.], [ 0., 2.]]) '''
|