自动求梯度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import torch from torch.autograd import Variable N, D = 3, 4 x = Variable(torch.randn(N, D)), requires_grad=True) y = Variable(torch.randn(N, D)), requires_grad=True) z = Variable(torch.randn(N, D)), requires_grad=True) a = x * y b = a + z c = torch.sum(b) c.backward() print(x.grad.data) # 求梯度 print(y.grad.data) print(z.grad.data) |