pytorch中Sequential( )的使用

按照常规方法继承nn.Module来构建网络

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.conv1 = nn.Conv2d(3, 32, 5, padding=2)
        self.maxpool1 = nn.MaxPool2d(2)
        self.conv2 = nn.Conv2d(32, 32, 5, padding=2)
        self.maxpool2 = nn.MaxPool2d(2)
        self.conv3 = nn.Conv2d (32, 64, 5,padding=2)
        self.maxpool3 = nn.MaxPool2d(2)
        self.flatten = nn.Flatten() #展开
        self.linear1 = nn.Linear(1024, 64)
        self.linear2 = nn.Linear(64, 10)
        
    def forward(self,x):
        x = self.conv1(x)
        x = self.maxpool1(x)
        x = self.conv2(x)
        x = self.maxpool2(x)
        x = self.conv3(x)
        x = self.maxpool3(x)
        x = self.flatten(x)
        x = self.linear1(x)
        x = self.linear2(x)
        return x

net = Net()
print(net)

可以看到构建的网络

pytorch中Sequential( )的使用_第1张图片

当使用Sequential()构建时更加简单,forward函数也更加简洁

#sequential的使用
class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d (32, 64, 5,padding=2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(1024, 64),
            nn.Linear(64, 10),
        )
    
    def forward(self,x):
        x = self.model(x)
        return x      

net = Net()
print(net)

 pytorch中Sequential( )的使用_第2张图片

可以看到,Sequential把网络每一层按照顺序进行编号,在forward里面按照序号执行

你可能感兴趣的:(pytorch,深度学习,机器学习)