1. Pytorch模型定义的方式
- Module类时torch.nn模块里提供的一个模型构造类(nn.Module),是所有神经网络模块的基类,可以继承它来定义自己的模型
- Pytorch模型定义包括两个主要部分:各部分的初始化(
__init__
);数据流定义(forward
)
基于nn.Module,可以通过Sequential,ModuleList和ModuleDict三种方式定义Pytorch模型。
1.1 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):
for key, module in args[0].items():
self.add_module(key, module)
else:
for idx, module in enumerate(args):
self.add_modules(str(idx), module)
def forward(self, input):
# self._modules返回一个OrderedDict
for module in self._modules.values():
input = module(input)
return input
使用Sequential定义模型的两种方式:
- 直接排列
import torch.nn as nn
net = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10)
)
- 使用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))
]))
使用Sequential定义模型的好处在于简单、易读,但灵活性低,如需要在模型中间加入一个外部输入时则不适合用Seqential方式实现。
1.2 ModuleList
ModuleList接收一个子模块的列表作为输入,也可以类似List那样进行append和extend操作。
net = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
net.append(nn.Linear(256, 10))
print(net[-1])
nn.ModuleList
没有定义一个网络,只是将不同的模块储存在一起,需经过forward函数指定各个层的先后顺序才算完成模型的定义:
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
1.3 ModuleDict
与ModuleList类似,只是传入是字典类型
net = nn.ModuleDict({
'linear': nn.Linear(784, 256),
'act': nn.ReLU(),
})
net['output'] = nn.Linear(256, 10)
print(net['Linear'])
print(net.output)
1.4 三种方法的比较与适用场景
Sequential
适用于快速验证结果,明确使用哪些层;ModuleList和ModuleDict在某个完全相同的层需要重复出现多次时,非常方便实现。
2. 利用模型块快速搭建复杂网络
深度神经网络模型有很多层,其中可能有很多重复出现的结构,考虑到每层有其输入和输出,若干层串联成"模块"也有其输入和输出,将这些重复出现的层定义为"模块"。
2.1 U-Net模型
2.2 U-Net模型块
组成U-Net的模型块主要有如下几个部分:
1)每个子块内部的两次卷积(Double Convolution)
2)左侧模型块之间的下采样连接,即最大池化(Max pooling)
3)右侧模型块之间的上采样连接(Up sampling)
4)输出层的处理
根据功能可以定义四个模型块: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, bias=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=False):
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])
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)
2.3 组装U-Net
class UNet(nn.Module):
def __init__(self, n_channels, n_classes, bilinear=False):
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
3. PyTorch修改模型
以ResNet50为例,修改模型的某一层或几层,模型定义如下:
import torchvision.models as models
net = models.resnet50()
3.1 修改模型层
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 # 直接在net添加一个fc层
3.2 添加外部输入
基本思路是:将原模型添加输入位置前的部分作为一个整体,同时在forward中定义好原模型不变的部分、添加的输入和后续层之间的连接关系 .
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) # output层
return x
# 模型结构实例化
import torchvision.models as models
net = models.resnet50()
model = Model(net).cuda()
# 输入两个input
ouputs = model(inputs, add_var)
3.3 添加额外输出
场景是输出模型某一中间层的结果,添加额外的监督。基本思路是修改模型定义中forward函数的return变量。
在已经定义好的模型结构上,同时输出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) # 10维的output结果
return x10, x1000
# 实例化
import torchvision.models as models
net = models.resnet50()
model = Model(net).cuda()
out10, out1000 = model(inputs, add_var) # 输出结果
4. Pytorch模型保存和读取
PyTorch存储模型主要采用pkl,pt,pth三种格式。
4.1 模型的存储内容
存储与加载分整个模型保存+整个模型加载;保存+读取模型权重
from torchvision import models
model = models.resnet152(pretrained=True)
# 保存整个模型
torch.save(model, save_dir)
# 保存模型权重
torch.save(model.state_dict, save_dir)
4.2 单卡和多卡的区别
PyTorch中将模型和数据放到GPU上有两种方式——.cuda()和.to(device) 。 如果要使用多卡训练的话,需要对模型使用torch.nn.DataParallel。示例如下:
os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 如果是多卡改成类似0,1,2
model = model.cuda() # 单卡
model = torch.nn.DataParallel(model).cuda() # 多卡
存储时差别在于多卡并行的模型每层的名称前多了一个“module”
- 整个模型保存+读取
# 保存+读取整个模型
torch.save(model, save_dir) # save model
loaded_model = torch.load(save_dir)
# 单卡读取模型
loaded_model.cuda()
# 多卡读取模型
loaded_model = nn.DataParallel(loaded_model).cuda()
- 保存模型权重+加载
# 保存+读取模型权重
torch.save(model.state_dict(), save_dir) # 保存权重
loaded_dict = torch.load(save_dir)
loaded_model = models.resnet152() #定义模型结构
loaded_model.state_dict = loaded_dict # 更新模型权重
loaded_model.cuda()
4.3 情况分类
由于训练和测试所使用的硬件条件不同,在模型的保存和加载过程中可能因为单GPU和多GPU环境的不同带来模型不匹配等问题。
-
单卡保存+单卡加载
- 按照整个模型或模型权重保存、读取均可`
- 单卡+单卡示例
import os import torch from torchvision import models os.environ['CUDA_VISIBLE_DEVICES'] = '0' #这里替换成希望使用的GPU编号 model = models.resnet152(pretrained=True) model.cuda() # 保存+读取整个模型 torch.save(model, save_dir) loaded_model = torch.load(save_dir) loaded_model.cuda() # 保存+读取模型权重 torch.save(model.state_dict(), save_dir) loaded_dict = torch.load(save_dir) loaded_model = models.resnet152() #定义模型结构 loaded_model.state_dict = loaded_dict loaded_model.cuda()
-
单卡保存+多卡加载
- 以多卡读取方式加载
nn.DataParallel(loaded_model).cuda()
- 以多卡读取方式加载
-
多卡保存+单卡加载
- 单卡整个模型加载时需要读.module模块,加多
loaded_model = loaded_model.module
- 建议采样权重读取方式,用多卡方式
nn.DataParallel(loaded_model).cuda()
定义模型,再更新权重
- 单卡整个模型加载时需要读.module模块,加多
-
多卡+多卡
- 建议采用权重的方式存储和读取模型