zoukankan      html  css  js  c++  java
  • Pytorch学习(一)—— 自动求导机制

      现在对 CNN 有了一定的了解,同时在 GitHub 上找了几个 examples 来学习,对网络的搭建有了笼统地认识,但是发现有好多基础 pytorch 的知识需要补习,所以慢慢从官网 API 进行学习吧。

    AUTOGRAD MECHANICS(自动求导机制)

      这一部分做了解处理,不需要完全理解的明明白白的。

    Excluding subgraphs from backward

      每一个 Tensor 变量都可以设置一个属性:requires_grad(默认参数 False),可以设置此参数排除向后梯度求导时排除子图,提高运行效率。

     1 import torch
     2 x = torch.randn(3, 3) # requires_grad=False by default
     3 y = torch.randn(3, 3)
     4 z = torch.randn(3, 3, requires_grad= True)
     5 
     6 a = x + y
     7 print(a.requires_grad) # False
     8 
     9 b = z + a
    10 print(b.requires_grad) # True

      这个设置在如下情况很好用:你提前知道你不需要某个参数的梯度。例如,你需要微调网络的时候,你只需要在最后一层将变量的 requires_grad 属性切换一下,因为仿射装换需要使用通过梯度调整的权重,而且输出结果也需要它。

    1 model = torchvision.models.resnet18(pretrained=True)
    2 for param in model.parameters():
    3     param.requires_grad = False  # 切换模式
    4 # Replace the last fully-connected layer
    5 # Parameters of newly constructed modules have requires_grad=True by default
    6 model.fc = nn.Linear(512, 100)
    7 
    8 # Optimize only the classifier
    9 optimizer = optim.SGD(model.fc.parameters(), lr=1e-2, momentum=0.9)

    How autograd encodes the history(自动求导如何编码历史信息)

      Autograd is reverse automatic (反向自动) differentiation system.....(这段话有点难翻译)。

      个人觉得关键是:When computing the forwards pass, autograd simultaneously performs the requested computations and builds up a graph representing the function that computes the gradient (the .grad_fn attribute of each torch.Tensor is an entry point into this graph)

      

    In-place operations with autograd(自动求导中使用 in-place)

      在自动求导中支持 in-place 是件困难的事,在多数场合下我们并不鼓励你使用。

    In-place correctness checks(in-place 的正确性检擦)

      每一个 tensor 变量都拥有版本计数器,每次被调用都会加一,当一个 Function 保留 tensor 用来向后计算时,也会保存这个版本计数器。当你访问 self.saved_tensors 的时候,就会检查版本计数器的值,如果大于计数器的值,就会报错。

      

  • 相关阅读:
    初始面向对象
    python之路——迭代器和生成器
    函数进阶
    python之路——初识函数
    实现css两端对齐
    http
    background-size
    call和apply的区别
    js兼容性
    面试题
  • 原文地址:https://www.cnblogs.com/KongHuZi/p/10960998.html
Copyright © 2011-2022 走看看