pytorch中文文档学习

1.自动求导

每个变量都有两个标志:requires_grad和volatile.

  • requires_grad: 只有所有输入都不需要梯度时,输出才不需要;如果有一个输入有梯度,它的输出也有梯度。

    >>> x = Variable(torch.randn(5, 5))
    >>> y = Variable(torch.randn(5, 5))
    >>> z = Variable(torch.randn(5, 5), requires_grad=True)
    >>> a = x + y
    >>> a.requires_grad
    False
    >>> b = a + z
    >>> b.requires_grad
    True
    
    
    # 如果想冻结部分模型时,只要切换冻结模型中的requires_grad标志就可以了
    model = torchvision.models.resnet18(pretrained=True)
    for param in model.parameters():
        param.requires_grad = False
    # Replace the last fully-connected layer
    # Parameters of newly constructed modules have requires_grad=True by default
    model.fc = nn.Linear(512, 100)
    
    # Optimize only the classifier
    optimizer = optim.SGD(model.fc.parameters(), lr=1e-2, momentum=0.9)
    
  • volatile

    纯粹的inference模式下推荐使用volatile,当你确定你甚至不用调用.backward()时,它比任何其他自动求导的设置更有效。--它将使用绝对最小的内存来评估模型。volatile也决定了require_grad is False。volatile不同于require_grad的传递。如果一个操作甚至只有一个volatile的输入,它的输出也将会是volatile.

    >>> regular_input = Variable(torch.randn(5, 5))
    >>> volatile_input = Variable(torch.randn(5, 5), volatile=True)
    >>> model = torchvision.models.resnet18(pretrained=True)
    >>> model(regular_input).requires_grad
    True
    >>> model(volatile_input).requires_grad
    False
    >>> model(volatile_input).volatile
    True
    >>> model(volatile_input).creator is None
    True
    

2.扩展torch

  • 扩展torch.autograd

    如果想添加一个新的operation到autograd的话,你的operation需要继承class Function。autograd使用Function计算结果和梯度,同时编码operation的历史。每个新的operation(function)都需要实现三个方法:

    • __ init __(optional)
    • forward()
    • backward()
  • 扩展torch.nn

    nn包含两种接口-modules和他们的functional版本。通过这两个接口,你都可以扩展nn。但是记忆扩展layer的时候,使用modules,因为modules保存着参数和buffer。如果不需要参数的话,那么建议使用functional(激活函数,pooling,这些都不需要参数。)