Pytorch --- nn.Sequential()模块

简而言之,nn.Sequential()可以将一系列的操作打包,这些操作可以包括Conv2d()、ReLU()、Maxpool2d()等,打包后方便调用吧,就相当于是一个黑箱,forward()时调用这个黑箱就行了。

节选AlexNet代码的一部分来理解sequential:

class AlexNet(nn.Module):
    def __init__(self, num_classes=1000, init_weights=False):
        super(AlexNet, self).__init__()
        
        self.features = nn.Sequential(
            nn.Conv2d(3, 48, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2), 
            nn.Conv2d(48, 128, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(128, 192, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(192, 192, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(192, 128, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        ......
        
    def forward(self, x):
        x = self.features(x)
        ......
        return x

__init__中 self.features = nn.Sequential(…)

在forward()中只需要使用self.features(x)就可

你可能感兴趣的:(pytorch,pytorch,神经网络,机器学习,深度学习,python)