pytorch模型相关知识点
之前的笔记略
模型的定义
基于nn.Module
,可以通过Sequential
,ModuleList
和ModuleDict
三种方式定义PyTorch模型
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方法会将module添加进self._modules(一个OrderedDict)
else: # 传入的是一些Module
for idx, module in enumerate(args):
self.add_module(str(idx), module)
def forward(self, input):
# self._modules返回一个 OrderedDict,保证会按照成员添加时的顺序遍历成
for module in self._modules.values():
input = module(input)
return input
Sequential
类:接收一系列子模块或者一个子模块的有序字典(OrderedDict)作为参数来逐一添加Module
的实例,模型的前向计算就是将这些实例按添加的顺序逐⼀计算
- 优点:可以通过简单的方式定义模型,不需要再写forward,因为顺序已经定义好了
- 缺点:会使得模型定义丧失灵活性,比如需要在模型中间加入一个外部输入时就不适合了
# 方式1
net = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10),
)
print('net:', net)
# 方式2,好处是可以给里面的层进行命名
net2 = nn.Sequential(collections.OrderedDict([
('fc1', nn.Linear(784, 256)),
('relu1', nn.ReLU()),
('fc2', nn.Linear(256, 10))
]))
print('net2:', net2)
ModuleList
ModuleList 接收一个属于nn.Module类的子模块(或层)的列表作为输入,然后也可以类似List
那样进行append
和extend
操作。同时,子模块或层的权重也会自动添加到网络中来
class net1(nn.Module):
def __init__(self):
super(net1, self).__init__()
self.linears = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
def append(self, module):
self.linears = self.linears.append(module)
return self.linears
def forward(self, x):
for m in self.linears:
x = m(x)
return x
net = net1()
print(net)
net.append(nn.Linear(256, 10)) # 类似List的append操作
# net1类本身没有append方法,自己写了一个以便能给ModuleList完成append操作
# print(net[-1]) # 模型没有类似List的索引访问
for name in net.state_dict():
print(name) # 获得每层的参数名
# print(net.state_dict()[name]) # 填该层参数名, 打印网络中指定的一层的参数
# for name, parameters in net.named_parameters(): # 打印整个网络每一层的名称和参数值
# print(name, ':', parameters)
print(net)
nn.ModuleList
只是将不同的模块储存在一起,并没有定义一个网络。ModuleList
中元素的先后顺序并不代表其在网络中的真实位置顺序,需要定义forward函数,指定各个层的先后顺序。
class model(nn.Module):
# ......
def forward(self, x):
for layer in self.modulelist:
x = layer(x)
return x
类似这样用for
循环写一个forward
就好了
ModuleDict
和ModuleList
类似,但是接受一个模型字典作为输入,模型字典的键为该子模块(层)的名称,值为子模块(层)本身
但是python3.6之前的字典是无序的?前向的传播顺序能保证和模块字典中的一样吗?
总结
- Sequential适用于明确了要用哪些层,快速搭建模型的情况,不需要写
__init__
和forward
; - ModuleList和ModuleDict在适合某个完全相同的层需要重复出现多次,以及前层的结果需要和之前层中的结果进行融合(需要之前层的信息,如ResNets中的残差计算)时;
利用模型块快速搭建复杂网络
当模型的深度非常大时候,使用Sequential定义模型结构需要向其中添加几百行代码,使用起来不甚方便
对于大部分模型结构(比如ResNet、DenseNet等),我们仔细观察就会发现,虽然模型有很多层, 但是其中有很多重复出现的结构。考虑到每一层有其输入和输出,若干层串联成的”模块“也有其输入和输出,如果我们能将这些重复出现的层定义为一个"模块",每次只需要向网络中添加对应的模块来构建模型,这样将会极大便利模型构建的过程。
搞清楚了U-Net的架构,卷积和池化、上采样分别是什么意思,初步学习了U-Net的搭建方法
组成U-Net的模型块主要有如下几个部分:
- 每个子块内部的两次卷积(Double Convolution)
- 左侧模型块之间的下采样连接,即最大池化(Max pooling)
- 右侧模型块之间的上采样连接(Up sampling)
- 输出层的处理
- 除模型块外,还有模型块之间的横向连接,输入和U-Net底部的连接等计算
# e.g. U-Net
# 两次卷积
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=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
修改模型
假设我们想用原本用于ImageNet的resnet模型去做一个10分类的问题;同时我们又觉得一层全连接层可能太少了,想再加一层。这个时候应该怎么操作呢?
- 修改模型的fc层,将其输出节点数替换为10
- 将模型(net)最后名称为"fc"的层进行替换
# 首先查看resnet50的结构
net = models.resnet50()
print(net)
# 进行修改
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
如果我们希望利用已有的模型结构,在倒数第二层增加一个额外的输入变量add_variable来辅助预测(监督),这时候应该怎么做呢?
这一块和上一块没有细究,以后用到了再说,主要是下一块:输出模型某一中间层的结果,以施加额外的监督,获得更好的中间层结果,以便我们进行攻击
以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):
x1000 = self.net(x)
x10 = self.dropout(self.relu(x1000))
x10 = self.fc1(x10)
x10 = self.output(x10)
return x10, x1000
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):
x1000 = self.net(x)
x10 = self.dropout(self.relu(x1000))
x10 = self.fc1(x10)
x10 = self.output(x10)
return x10, x1000
原生模型获取中间结果
temp = None
for name, value in net._modules.items():
# 一种获取模型名字的方法
print('name:', name)
print('value:', value)
# x = value(x)
# if name=='0':
# temp = value[0](x)
import random
net = models.resnet18()
for param in net.named_parameters():
# nn.Module里面关于参数有两个很重要的属性named_parameters()和parameters()
# 前者给出网络层的名字[0]和参数数值[1]的迭代器,而后者仅仅是参数的迭代器
print(param[0])
x = torch.randn(1,3,224,224)
# 使用pytorch中nn.module里的register_forward_hook()来获取网络forward时的feature
def hook(module, inputdata, output):
print(output.data)
handle = net.conv1.register_forward_hook(hook)
handle0 = net.maxpool.register_forward_hook(hook)
handle1 = net.layer1[0].conv1.register_forward_hook(hook)
handle2 = net.layer1[0].conv2.register_forward_hook(hook)
handle3 = net.layer1[1].conv1.register_forward_hook(hook)
handle4 = net.layer1[1].conv2.register_forward_hook(hook)
y = net(x)
handle.remove()
handle0.remove()
handle1.remove()
handle2.remove()
handle3.remove()
handle4.remove()
# 获取网络不同层的feature并传到hook函数中打印feature的形状,记得把钩子删掉
模型的训练与保存
一个PyTorch模型主要包含两个部分:模型结构和权重。其中模型是继承nn.Module的类,权重的数据结构是一个字典(key是层名,value是权重向量)。存储也由此分为两种形式:存储整个模型(包括结构和权重),和只存储模型权重。
而PyTorch存储模型主要采用pkl,pt,pth三种格式,这三种格式均支持只保留权重,或模型结构和权重一起保存。
由于目前都是单卡训练,因此只需要简单的下面的代码就可以了
# 保存模型
model = models.resnet152(pretrained=True)
# 保存整个模型
torch.save(model, save_dir)
# 只保存模型权重
torch.save(model.state_dict, save_dir)
os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 这里替换成希望使用的GPU编号
model = models.resnet152(pretrained=True)
model.cuda()
# 读取整个模型
loaded_model = torch.load(save_dir)
loaded_model.cuda()
# 读取模型权重
loaded_dict = torch.load(save_dir)
loaded_model = models.resnet152() # 注意这里需要对模型结构有定义
loaded_model.state_dict = loaded_dict
loaded_model.cuda()
参考资料
- https://blog.csdn.net/qq_45589658/article/details/112335626
- https://zhuanlan.zhihu.com/p/53927068
- https://github.com/datawhalechina/thorough-pytorch/tree/main/%E7%AC%AC%E4%BA%94%E7%AB%A0%20PyTorch%E6%A8%A1%E5%9E%8B%E5%AE%9A%E4%B9%89
- https://zhuanlan.zhihu.com/p/64990232
- https://www.zhihu.com/question/49376084/answer/338145504
- https://blog.csdn.net/hxxjxw/article/details/107734140
- https://www.freesion.com/article/97611099115/
- https://blog.csdn.net/weixin_41866216/article/details/107933311?utm_source=app&app_version=5.1.1&code=app_1562916241&uLinkId=usr1mkqgl919blen
- https://blog.csdn.net/qq_42278791/article/details/90690747