第五章:PyTorch模型定义

CNN模型解决了图视频处理问题,RNN/LSTM模型解决了序列数据处理问题,GNN在图模型上发挥了重要的作用

模型定义的方式

  • Module类是torch.nn模块里提供的一个模型构造类,是所有神经网络模块的基类,可以继承它来定义我们想要的模型
  • pytorch模型定义包括两个主要部分:各部分的初始化(init);数据流向定义(forward)
    基于nn.Module,可以通过Sequential,ModuleList和ModuleDict三种方式定义pytorch模型

Sequential

对应模块为nn.Sequential()
当模型的前向计算为串联各个层的计算时,Sequential类可以通过简单的方式定义模型

class MySequential(nn.Module):
    from collections import OrderedDict
    def __init__(self,*args):
        super(MySequential,self).__init__()
        if len(args)==1 and isinstance(args[0],OrderedDict):
            # 如果传入的是一个OrderedDict
            for key,module in args[0].items():
                self.add_module(key,module)
                #add_module方法会将moudle添加进self._modules
        else:
            for idx,module in enumerate(args):
                self.add_module(str(idx),module)
    def forward(self,input):
        for module in self._modules.values():
            input=module(input)
        return input

#直接排列
import torch.nn as nn
net=nn.Sequential(
    nn.Linear(784,256),
    nn.ReLU(),  #激活函数
    nn.Linear(256,10))
print(net)

#使用OrderedDict
import collections
import torch.nn as nn
net2=nn.Sequential(collections.OrderedDict([
    ('fc1',nn.Linear(784,256)),
    ('relu1',nn.ReLU()),
    ('fc2',nn.Linear(256,10))]))
print(net2)

注:使用Sequential定义模型的好处在于不用写forward,但是模型定义丧失灵活性,比如在模型中间加入一个外部输入就不适合用这种方法

ModuleList

对应模块为nn.ModuleList()

net=nn.ModuleList([nn.Linear(784,256),nn.ReLU()])
net.append(nn.Linear(256,10))   #类似list的append操作
print(net[-1])   #索引到最后一个
print(net)

nn.ModuleList并没有定义一个网络,它只是将不同的模块存储在一起,ModuleList元素的先后顺序并不代表在网络中的真实位置顺序,需要经过forward函数指定各个层的先后顺序才算完成了模型的定义,具体实现时用for循环即可完成:

class model(nn.Module):
    def __init__(self,...):
        super().__init__()
        self.modulelist=...
        ...
    def forward(self,x):
        for layer in self.modulelist:
            x=layer(x)
        return x

ModuleDict

对应模块为nn.ModuleDict()
ModuleList和ModuleDict的作用相似,只是ModuleDict能够为神经网络的层添加名称

net=nn.ModuleDict({
    'linear':nn.Linear(784,256),
    'act':nn.ReLU(),
    })
net['output']=nn.Linear(256,10)
print(net['linear'])
print(net.output)
print(net)

三种方法的比较和适用场景

Sequential适合于快速验证结果,明确了要使用哪些层,直接写,不需要同时写init和forward
ModuleList和ModuleDict在某个完全相同的层需要重复出现多次时,可以“一行顶多行”
当我们需要之前层的信息时候,比如ResNets中的残差计算,当前层的结果需要和之前层中的结果进行融合,一般使用ModuleList、ModuleDict

利用模块块快速搭建复杂网络

如果模型深度非常大时,使用Sequential定义模型结构需要向其中添加几百行代码
对于ResNet/DenseNet,模型有很多层,但是其中有很多重复出现的结构。考虑到每一层都有输入和输出,若干层串联成的模型也有输入与输出,如果我们能将这些重复出现的层定义为一个模块,每次只需要向网络中添加对应的模块来构建模型,这样会极大便利模块构建的过程。

U-Net模型块

以U-Net为例,如何构建模型块,以及如何利用模型块快速搭建复杂模型
U-Net通过残差连接结构解决了模型学习中的退化问题,使得神经网络的深度能够不断扩展

首先定义好模型块,再定义模型块之间的连接顺序计算方式
模型块是基础部件,根据功能将其命名为DoubleConv, Down, Up, OutConv.

import torch
import torch.nn as nn
import torch.nn functional as F
class DoubleConv(nn.Module):
     """(convolution => [BN] => ReLU) * 2"""
     def __init__(self,in_channels,out_channels, mid_channels=None):
         super().__init__()
         if not mid_channels:
             mid_channels=out_channels
            self.double_conv=nn.Sequential(
                nn.Conv2d(in_channels,mid_channels,kernel_size=3,padding=1,ias=False),
                nn.BatchNorm2d(mid_channels),
                nn.ReLU(inplace=True),
                nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),
                nn.BatchNorm2d(out_channels),
                nn.ReLU(inplace=True))
    def forward(self,x):
        return self.double_conv(x)
    
class Down(nn.Module):
    """Downscaling with maxpool then double conv"""
    def __init__(self,in_channels,out_channels):
        super().__init__()
        self.maxpool_conv=nn.Sequential(
            nn.MaxPool2d(2),
            DoubleConv(in_channels,out_channels))
    def forward(self,x):
        return self.maxpool_conv(x)
    
class Up(nn.Module):
    """Upscaling then double conv"""
    def __init__(self,in_channels,out_channels, bilinear=True):
        super().__init__()
        # if bilinear, use the normal convolutions to reduce the number of channels
       if bilinear:
           self.up=nn.Upsample(scale_factor=2,mode='bilinear',align_corners=True)
           self.conv=DoubleConv(in_channels, out_channels, in_channels // 2)
       else:
           self.up=nn.ConvTranspose2d(in_channels,in_channels//2,kernel_size=2, stride=2)
           self.conv = DoubleConv(in_channels, out_channels)
    def forward(self,x1,x2):
        x1=self.up(x1)
        #input is CHW
        diffY = x2.size()[2] - x1.size()[2]
        diffX = x2.size()[3] - x1.size()[3]
        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
                        diffY // 2, diffY - diffY // 2])
        # if you have padding issues, see
        # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a
        # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd
        x = torch.cat([x2, x1], dim=1)
        return self.conv(x)

class OutConv(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(OutConv, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
    def forward(self, x):
        return self.conv(x)

class UNet(nn.Module):
    def __init__(self,n_channels, n_classes, bilinear=True):
        super(UNet,self).__init__()
        self.n_channels=n_channels
        self.n_classes=n_classes
        self.bilinear=bilinear
        self.inc= DoubleConv(n_channels, 64)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        factor = 2 if bilinear else 1
        self.down4 = Down(512, 1024 // factor)
        self.up1 = Up(1024, 512 // factor, bilinear)
        self.up2 = Up(512, 256 // factor, bilinear)
        self.up3 = Up(256, 128 // factor, bilinear)
        self.up4 = Up(128, 64, bilinear)
        self.outc = OutConv(64, n_classes)
    def forward(self, x):
        x1 = self.inc(x)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        logits = self.outc(x)
        return logits

修改模型

如果现在有一个现成的模型,但模型的部分结构不符合我们的要求,需要对模型结构进行修改

1. 修改模型层

以torchvision预先定义好的ResNet50为例,如何修改模型的某一层或者某几层

import torchvision.models as models
net=models.resnet50()
print(net)
#最后全连接层的输出节点数是1000
#用这个resnet模型去做一个10分类的问题,就应该修改模型的fc层,将输出节点数替换为10
#如果觉得一层全连接层太少了,想再加一层
from collections import OrderedDict
classifier=nn.Sequential(OrderedDict([
    ('fc1',nn.Linear(2048,128)),
    ('relu1',nn.ReLU()),
    ('dropout1',nn.Dropout(0.5))),
    ('fc2',nn.Linear(128,10)),
    ('output',nn.Softmax(dim=1))]))
net.fc=classifier  #把fc层替换成了classifier结构
#Sequential+OrderedDict的模型定义方式

2. 添加外部输入

在模型训练中,除了已有模型的输入之外,还需要输入额外的信息。例如在CNN网络中,除了输入图像,同时还需要输入图像对应的其他信息,这时候就需要在已有的CNN网络中添加额外的输入变量
思路:将原模型添加输入位置前的一部分作为一个整体,同时在forward中定义好原模型不变的部分,添加的输入和后续层之间的连接关系,从而完成模型的修改
以torchvision的resnet50模型为基础,10分类任务,在已有模型结构上,在倒数第二层增加一个额外的输入变量add_variable来辅助预测

class Model(nn.Module):
    def __init__(self,net):
        super(Model,self).__init__()
        self.net=net
        self.relu=nn.ReLU()
        self.dropout=nn.Dropout(0.5)
        self.fc_add=nn.Linear(1001,10,bias=True)
        self.output=nn.Softmax(dim=1)
    def forward(self,x,add_variable):
        x=self.net(x)
        x=torch.cat((self.dropout(self.relu(x)),add_variable.unsqueeze(1)),1)
        x=self.fc_add(x)
        x=self.output(x)
        return x

先将原模型的1000维tensor通过激活函数层dropout层,再和外部输入变量add_variable拼接,最后通过全连接层映射到指定的输出维度10
对外部输入变量“add_variable”进行unsqueeze是为了和net输出的tensor保持维度一致,常用于add_variable是单一数值的情况,add_variable的维度是(batch_size,),需要在第一维补充维数1,从而可以和tensor进行torch.cat操作

import torchvision.models as models
net=models.resnet50()
model=Model(net).cuda()
#在训练中在输入数据的时候要给出两个inputs
outputs = model(inputs, add_var)

3. 添加额外输出

除了获得模型最后的输出外,有时候需要模型某一中间层的结果,基本的思路是修改模型定义中forward函数的return变量
依然以resnet50做10分类任务,在已经定义好的模型结构上,同时输出1000维的倒数第二层和10维的最后一层结果

class Model(nn.Module):
    def __init__(self,net):
        super(Model,self).__init__()
        self.net=net
        self.relu=nn.ReLU()
        self.dropout=nn.Dropout(0.5)
        self.fc1=nn.Linear(1000,10,bias=True)
        self.output=nn.Softmax(dim=1)
    def forward(self,x,add_variable):
        x1000=self.net(x)
        x10=self.dropout(self.relu(x1000))
        x10=self.fc1(x10)
        x10=self.output(x10)
        return x10,x1000

import torchvision.models as models
net = models.resnet50()
model = Model(net).cuda()
#训练中在输入数据后会有两个outputs
out10, out1000 = model(inputs, add_var)

你可能感兴趣的:(第五章:PyTorch模型定义)