1. 程式人生 > >Autograd:自動微分

Autograd:自動微分

是個 形狀 func tensor requires comm 需要 data light

Autograd

1、深度學習的算法本質上是通過反向傳播求導數,Pytorch的Autograd模塊實現了此功能;在Tensor上的所有操作,Autograd都能為他們自動提供微分,避免手動計算導數的復雜過程。
2、autograd.Variable是Autograd中的核心類,它簡單的封裝了Tensor,並支持幾乎所有Tensor操作;Tensor被封裝為Variable之後,可以調用它的.backward()實現反向傳播,自動計算所有的梯度。
3、Variable主要包含三個屬性:
        data:保存Variable所包含的Tensor;
        grad:保存data對應的梯度,grad也是個Variable,而不是Tensor,它和data的形狀一樣;
        grad_fn:指向一個Function對象,這個Function用來反向傳播計算輸入的梯度。

具體代碼解析

  1. #_Author_:Monkey
  2. #!/usr/bin/env python
  3. #-*- coding:utf-8 -*-
  4. import torch as t
  5. from torch.autograd import Variable
  6. x = Variable(t.ones(2,2),requires_grad = True)
  7. print(x)
  8. ‘‘‘‘‘tensor([[1., 1.],
  9. [1., 1.]], requires_grad=True)‘‘‘
  10. y = x.sum()
  11. print(y)
  12. ‘‘‘‘‘tensor(4., grad_fn=<SumBackward0>)‘‘‘
  13. print(y.grad_fn) #指向一個Function對象,這個Function用來反向傳播計算輸入的梯度
  14. ‘‘‘‘‘<SumBackward0 object at 0x000002D4240AB860>‘‘‘
  15. y.backward()
  16. print(x.grad)
  17. ‘‘‘‘‘tensor([[1., 1.],
  18. [1., 1.]])‘‘‘
  19. y.backward()
  20. print(x.grad)
  21. ‘‘‘‘‘tensor([[2., 2.],
  22. [2., 2.]])‘‘‘
  23. y.backward()
  24. print( x.grad )
  25. ‘‘‘‘‘tensor([[3., 3.],
  26. [3., 3.]])‘‘‘
  27. ‘‘‘‘‘grad在反向傳播過程中時累加的(accumulated),這意味著運行
  28. 反向傳播,梯度都會累加之前的梯度,所以反向傳播之前需要梯度清零‘‘‘
  29. print( x.grad.data.zero_() )
  30. ‘‘‘‘‘tensor([[0., 0.],
  31. [0., 0.]])‘‘‘
  32. y.backward()
  33. print( x.grad )
  34. ‘‘‘‘‘tensor([[1., 1.],
  35. [1., 1.]])‘‘‘
  36. m = Variable(t.ones(4,5))
  37. n = t.cos(m)
  38. print(m)
  39. print(n)
  40. ‘‘‘‘‘tensor([[1., 1., 1., 1., 1.],
  41. [1., 1., 1., 1., 1.],
  42. [1., 1., 1., 1., 1.],
  43. [1., 1., 1., 1., 1.]])
  44. tensor([[0.5403, 0.5403, 0.5403, 0.5403, 0.5403],
  45. [0.5403, 0.5403, 0.5403, 0.5403, 0.5403],
  46. [0.5403, 0.5403, 0.5403, 0.5403, 0.5403],
  47. [0.5403, 0.5403, 0.5403, 0.5403, 0.5403]])‘‘‘
  48. m_tensor_cos = t.cos(m.data)
  49. print(m_tensor_cos)
  50. ‘‘‘‘‘ensor([[0.5403, 0.5403, 0.5403, 0.5403, 0.5403],
  51. [0.5403, 0.5403, 0.5403, 0.5403, 0.5403],
  52. [0.5403, 0.5403, 0.5403, 0.5403, 0.5403],
  53. [0.5403, 0.5403, 0.5403, 0.5403, 0.5403]])‘‘‘

Autograd:自動微分