【问题标题】:Can my PyTorch forward function do additional operations?我的 PyTorch 转发功能可以做额外的操作吗?
【发布时间】:2020-06-16 19:16:02
【问题描述】:

通常是forward 函数将一堆层串在一起并返回最后一层的输出。在返回之前,我可以在最后一层之后做一些额外的处理吗?例如,通过.view进行一些标量乘法和整形?

我知道 autograd 会以某种方式计算渐变。所以我不知道我的额外处理是否会以某种方式搞砸。谢谢。

【问题讨论】:

    标签: python machine-learning pytorch autograd


    【解决方案1】:

    通过 张量computational graph 跟踪梯度,而不是通过函数。只要您的张量具有requires_grad=True 属性并且它们的grad 不是None,您就可以(几乎)做任何您喜欢的事情并且仍然能够反向传播。
    只要您使用 pytorch 的操作(例如,herehere 中列出的操作)就可以了。

    欲了解更多信息,请参阅this

    例如(取自torchvision's VGG implementation):

    class VGG(nn.Module):
    
        def __init__(self, features, num_classes=1000, init_weights=True):
            super(VGG, self).__init__()
            #  ...
    
        def forward(self, x):
            x = self.features(x)
            x = self.avgpool(x)
            x = torch.flatten(x, 1)  # <-- what you were asking about
            x = self.classifier(x)
            return x
    

    更复杂的例子可以看torchvision's implementation of ResNet

    class Bottleneck(nn.Module):
        def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
                     base_width=64, dilation=1, norm_layer=None):
            super(Bottleneck, self).__init__()
            # ...
    
        def forward(self, x):
            identity = x
    
            out = self.conv1(x)
            out = self.bn1(out)
            out = self.relu(out)
    
            out = self.conv2(out)
            out = self.bn2(out)
            out = self.relu(out)
    
            out = self.conv3(out)
            out = self.bn3(out)
    
            if self.downsample is not None:    # <-- conditional execution!
                identity = self.downsample(x)
    
            out += identity  # <-- inplace operations
            out = self.relu(out)
    
            return out
    

    【讨论】:

      猜你喜欢
      • 2015-03-08
      • 1970-01-01
      • 2011-07-15
      • 2013-07-13
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多