自学内容网 自学内容网

Pytorch中nn.Sequential()函数创建网络的几种方法

1. 创作灵感

在创建大型网络的时候,如果使用nn.Sequential()将几个有紧密联系的运算组成一个序列,可以使网络的结构更加清晰。

2.应用举例

为了记录nn.Sequential()的用法,搭建以下测试网络:

2.1 方法一

把网络分成3个Sequential序列,分别实现:第一个是卷积序列,第二个是铺平成一维的操作,第3个包含了两个线性层。


class TestNet(nn.Module):
    def __init__(self, in_channels, mid_channels):
        super(TestNet,self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(in_channels,in_channels*2,kernel_size=3,stride=2,padding=1),
            nn.BatchNorm2d(in_channels*2),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_channels*2,in_channels*4,kernel_size=3,stride=2,padding=1),
            nn.BatchNorm2d(in_channels*4),
            nn.ReLU(inplace=True)
        )
        self.flat = nn.Flatten()
        self.linaer = nn.Sequential(
            nn.Linear(49*4, 64),
            nn.Linear(64, 10),
            nn.Linear(10, 1)
        )

    def forward(self,x):
        x = self.conv(x)
        print(x.shape)
        x = self.flat(x)
        print(x.shape)
        x = self.linaer(x)
        print(x.shape)
        return x

运行结果:

从维度上判断,网络符合预期。

2.2  方法二

第二种方法,在网络结构比较复杂且重复的单元比较多,为了自动化生成网络,通常会先定义一个列表,在列表中添加网络,再使用nn.Sequential()。

使用方法二所需要的代码如下:

class TestNet2(nn.Module):
    def __init__(self, in_channels):
        super(TestNet2,self).__init__()
        layer1 = []
        layer2 = []
        layer1.append(nn.Conv2d(in_channels,in_channels*2,kernel_size=3,stride=2,padding=1))
        layer1.append(nn.BatchNorm2d(in_channels*2))
        layer1.append(nn.ReLU(inplace=True))
        layer1.append(nn.Conv2d(in_channels*2,in_channels*4,kernel_size=3,stride=2,padding=1))
        layer1.append(nn.BatchNorm2d(in_channels*4))
        layer1.append(nn.ReLU(inplace=True))
        self.conv = nn.Sequential(*layer1)
        self.flat = nn.Flatten()
        layer2.append(nn.Linear(49*4, 64))
        layer2.append(nn.Linear(64, 10))
        layer2.append(nn.Linear(10, 1))
        self.linaer = nn.Sequential(*layer2)

    def forward(self,x):
        x = self.conv(x)
        print(x.shape)
        x = self.flat(x)
        print(x.shape)
        x = self.linaer(x)
        print(x.shape)
        return x

运行结果如下:

与第一种方法的结果相同。

参考文献:

nn.Sequential、nn.ModuleList、nn.ModuleDict区别及使用技巧-CSDN博客


原文地址:https://blog.csdn.net/qq_42982824/article/details/140400443

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!