torch_auto_grad.py 434 B

12345678910111213141516171819202122232425262728293031
  1. import torch
  2. from torch.autograd import Variable
  3. # 变量
  4. x = Variable(torch.ones(2, 2), requires_grad=True)
  5. print(x)
  6. y = x + 2
  7. print(y)
  8. z = y * y * 3
  9. out = z.mean()
  10. print(z)
  11. print(out)
  12. # 梯度
  13. out.backward()
  14. print(x.grad)
  15. a = torch.randn(3)
  16. a = Variable(a, requires_grad=True)
  17. b = a * 2
  18. while b.data.norm() < 1000:
  19. b = b * 2
  20. print(b)
  21. gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
  22. b.backward(gradients)
  23. print(a.grad)