Pytorch --- nn.Sequential()模組

real小熊貓發表於2020-10-02

簡而言之,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)就可

相關文章