Autograd:自动微分

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.   
  7. x = Variable(t.ones(2,2),requires_grad = True)  
  8. print(x)  
  9. '''''tensor([[1., 1.], 
  10.         [1., 1.]], requires_grad=True)'''  
  11. y = x.sum()  
  12. print(y)  
  13. '''''tensor(4., grad_fn=<SumBackward0>)'''  
  14. print(y.grad_fn)    #指向一个Function对象,这个Function用来反向传播计算输入的梯度  
  15. '''''<SumBackward0 object at 0x000002D4240AB860>'''  
  16. y.backward()  
  17. print(x.grad)  
  18. '''''tensor([[1., 1.], 
  19.         [1., 1.]])'''  
  20. y.backward()  
  21. print(x.grad)  
  22. '''''tensor([[2., 2.], 
  23.         [2., 2.]])'''  
  24. y.backward()  
  25. print( x.grad )  
  26. '''''tensor([[3., 3.], 
  27.         [3., 3.]])'''  
  28. '''''grad在反向传播过程中时累加的(accumulated),这意味着运行 
  29. 反向传播,梯度都会累加之前的梯度,所以反向传播之前需要梯度清零'''  
  30. print( x.grad.data.zero_() )  
  31. '''''tensor([[0., 0.], 
  32.         [0., 0.]])'''  
  33.   
  34. y.backward()  
  35. print( x.grad )  
  36. '''''tensor([[1., 1.], 
  37.         [1., 1.]])'''  
  38.   
  39. m = Variable(t.ones(4,5))  
  40. n = t.cos(m)  
  41. print(m)  
  42. print(n)  
  43. '''''tensor([[1., 1., 1., 1., 1.], 
  44.         [1., 1., 1., 1., 1.], 
  45.         [1., 1., 1., 1., 1.], 
  46.         [1., 1., 1., 1., 1.]]) 
  47. tensor([[0.5403, 0.5403, 0.5403, 0.5403, 0.5403], 
  48.         [0.5403, 0.5403, 0.5403, 0.5403, 0.5403], 
  49.         [0.5403, 0.5403, 0.5403, 0.5403, 0.5403], 
  50.         [0.5403, 0.5403, 0.5403, 0.5403, 0.5403]])'''  
  51. m_tensor_cos = t.cos(m.data)  
  52. print(m_tensor_cos)  
  53. '''''ensor([[0.5403, 0.5403, 0.5403, 0.5403, 0.5403], 
  54.         [0.5403, 0.5403, 0.5403, 0.5403, 0.5403], 
  55.         [0.5403, 0.5403, 0.5403, 0.5403, 0.5403], 
  56.         [0.5403, 0.5403, 0.5403, 0.5403, 0.5403]])'''  

Monkey
原文地址:https://www.cnblogs.com/monkeyT/p/9751405.html