• 深入浅出PyTorch——模型定义


    1. PyTorch模型定义的方式

    1.1 知识回顾

            在上节主要模块和基础实战中学习到了PyTorch在进行模型定义时所需要的必要知识。

    1.1.1 Module 类

            Module 类是 torch.nn 模块里提供的一个模型构造类 (nn.Module),是所有神经⽹网络模块的基类,我们可以继承它来定义我们想要的模型。

    1.1.2 定义模型的两个主要部分

            (1)各个部分的初始化(__init__);

            (2)数据流向定义(forward)(正向传播)。

    1.2 模型定义的三种方式

    1.2.1 Sequential

            (1)对应模块:nn.Sequential()

            (2)传入方式:

                    一系列子模块

    1. import torch.nn as nn
    2. net = nn.Sequential(
    3. nn.Linear(784, 256),
    4. nn.ReLU(),
    5. nn.Linear(256, 10),
    6. )
    7. print(net)

                    子模块的有序字典(OrderedDict)        

    1. import collections
    2. import torch.nn as nn
    3. net2 = nn.Sequential(collections.OrderedDict([
    4. ('fc1', nn.Linear(784, 256)),
    5. ('relu1', nn.ReLU()),
    6. ('fc2', nn.Linear(256, 10))
    7. ]))
    8. print(net2)

            (3)nn.Sequential()底层代码理解:

    1. class MySequential(nn.Module):
    2. from collections import OrderedDict
    3. # 初始化定义
    4. def __init__(self, *args):
    5. super(MySequential, self).__init__()
    6. # 如果传入的是一个OrderedDict
    7. if len(args) == 1 and isinstance(args[0], OrderedDict):
    8. for key, module in args[0].items():
    9. self.add_module(key, module)
    10. # add_module方法会将module添加进self._modules(一个OrderedDict)
    11. # 传入的是一些Module
    12. else:
    13. for idx, module in enumerate(args):
    14. self.add_module(str(idx), module)
    15. # 正向传播
    16. def forward(self, input):
    17. # self._modules返回一个 OrderedDict,保证会按照成员添加时的顺序遍历成
    18. for module in self._modules.values():
    19. input = module(input)
    20. return input

            (4)优点:简单、易读,顺序已经定义好不需要再写forawrd

            (5)缺点:丧失灵活性

    1.2.2 ModuleList

            (1)对应模块:nn.ModuleList()

            (2)传入方式:ModuleList 接收一个子模块(或层,需属于nn.Module类)的列表作为输入,可以类似List那样进行append和extend操作。

            (3)nn.ModuleList()底层代码理解:

    1. net = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
    2. net.append(nn.Linear(256, 10)) # # 类似List的append操作
    3. print(net[-1]) # 类似List的索引访问
    4. print(net)

            (4)在forward中调用方式(列表中定义的网络顺序并不是真实的顺序,需要在forward函数中进行指定):

    1. class model(nn.Module):
    2. def __init__(self, ...):
    3. super().__init__()
    4. self.modulelist = ...
    5. ...
    6. def forward(self, x):
    7. for layer in self.modulelist:
    8. x = layer(x)
    9. return x

    1.2.3 ModuleDict

            (1)对应模块:nn.ModuleDict()

            (2)传入方式:通过定义字典型的网络传入

            (3)nn.ModuleDict()底层代码理解:

    1. net = nn.ModuleDict({
    2. 'linear': nn.Linear(784, 256),
    3. 'act': nn.ReLU(),
    4. })
    5. net['output'] = nn.Linear(256, 10) # 添加
    6. print(net['linear']) # 访问
    7. print(net.output)
    8. print(net)

    1.3 三种方法的比较

            (1)Sequential适用于快速验证结果 

            (2)ModuleList和ModuleDict在某个完全相同的层需要重复出现多次时,可以”一行顶多行“

    2. 利用模型块快速搭建复杂网络——U-Net

    2.1 U-Net模型架构图

    2.2 U-Net模型块分析和模型块实现

    2.2.1 Double Convolution

            每个子块内部的两次卷积

    1. class DoubleConv(nn.Module):
    2. """(convolution => [BN] => ReLU) * 2"""
    3. def __init__(self, in_channels, out_channels, mid_channels=None):
    4. super().__init__()
    5. if not mid_channels:
    6. mid_channels = out_channels
    7. self.double_conv = nn.Sequential(
    8. nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),
    9. nn.BatchNorm2d(mid_channels),
    10. nn.ReLU(inplace=True),
    11. nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),
    12. nn.BatchNorm2d(out_channels),
    13. nn.ReLU(inplace=True)
    14. )
    15. def forward(self, x):
    16. return self.double_conv(x)

    2.2.2 Down

            左侧模型块之间的下采样连接

    1. class Down(nn.Module):
    2. """Downscaling with maxpool then double conv"""
    3. def __init__(self, in_channels, out_channels):
    4. super().__init__()
    5. self.maxpool_conv = nn.Sequential(
    6. nn.MaxPool2d(2),
    7. DoubleConv(in_channels, out_channels)
    8. )
    9. def forward(self, x):
    10. return self.maxpool_conv(x)

    2.2.3 Up

            右侧模型块之间的上采样连接

    1. class Up(nn.Module):
    2. """Upscaling then double conv"""
    3. def __init__(self, in_channels, out_channels, bilinear=False):
    4. super().__init__()
    5. # if bilinear, use the normal convolutions to reduce the number of channels
    6. if bilinear:
    7. self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
    8. self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)
    9. else:
    10. self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
    11. self.conv = DoubleConv(in_channels, out_channels)
    12. def forward(self, x1, x2):
    13. x1 = self.up(x1)
    14. # input is CHW
    15. diffY = x2.size()[2] - x1.size()[2]
    16. diffX = x2.size()[3] - x1.size()[3]
    17. x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
    18. diffY // 2, diffY - diffY // 2])
    19. x = torch.cat([x2, x1], dim=1)
    20. return self.conv(x)

    2.2.4 OutConv

            输出层的处理

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

    2.3  模型块组装U-Net

    1. class UNet(nn.Module):
    2. def __init__(self, n_channels, n_classes, bilinear=False):
    3. super(UNet, self).__init__()
    4. self.n_channels = n_channels
    5. self.n_classes = n_classes
    6. self.bilinear = bilinear
    7. self.inc = DoubleConv(n_channels, 64)
    8. self.down1 = Down(64, 128)
    9. self.down2 = Down(128, 256)
    10. self.down3 = Down(256, 512)
    11. factor = 2 if bilinear else 1
    12. self.down4 = Down(512, 1024 // factor)
    13. self.up1 = Up(1024, 512 // factor, bilinear)
    14. self.up2 = Up(512, 256 // factor, bilinear)
    15. self.up3 = Up(256, 128 // factor, bilinear)
    16. self.up4 = Up(128, 64, bilinear)
    17. self.outc = OutConv(64, n_classes)
    18. def forward(self, x):
    19. x1 = self.inc(x)
    20. x2 = self.down1(x1)
    21. x3 = self.down2(x2)
    22. x4 = self.down3(x3)
    23. x5 = self.down4(x4)
    24. x = self.up1(x5, x4)
    25. x = self.up2(x, x3)
    26. x = self.up3(x, x2)
    27. x = self.up4(x, x1)
    28. logits = self.outc(x)
    29. return logits

    3. PyTorch修改模型

            下面是以模型ResNet50为基础,进行模型的修改展示,这里先对该模型结构进行查看。

    1. import torchvision.models as models
    2. net = models.resnet50()
    3. print(net)
    4. ResNet(
    5. (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
    6. (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    7. (relu): ReLU(inplace=True)
    8. (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
    9. (layer1): Sequential(
    10. (0): Bottleneck(
    11. (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
    12. (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    13. (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
    14. (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    15. (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
    16. (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    17. (relu): ReLU(inplace=True)
    18. (downsample): Sequential(
    19. (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
    20. (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    21. )
    22. )
    23. ..............
    24. (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
    25. (fc): Linear(in_features=2048, out_features=1000, bias=True)
    26. )

    3.1 修改模型层

    3.1.1 修改方式

            对模型的输出进行修改,将输出节点1000改为10,并添加多层网络层。

    3.1.2 修改代码

    1. from collections import OrderedDict
    2. classifier = nn.Sequential(OrderedDict([('fc1', nn.Linear(2048, 128)),
    3. ('relu1', nn.ReLU()),
    4. ('dropout1',nn.Dropout(0.5)),
    5. ('fc2', nn.Linear(128, 10)),
    6. ('output', nn.Softmax(dim=1))
    7. ]))
    8. net.fc = classifier

    3.2 添加外部输入

    3.2.1 添加方式

            利用resnet50模型结构,在倒数第二层增加一个额外的输入变量add_variable来辅助预测。

    3.2.2 修改代码

    1. class Model(nn.Module):
    2. def __init__(self, net):
    3. super(Model, self).__init__()
    4. self.net = net
    5. self.relu = nn.ReLU()
    6. self.dropout = nn.Dropout(0.5)
    7. self.fc_add = nn.Linear(1001, 10, bias=True)
    8. self.output = nn.Softmax(dim=1)
    9. def forward(self, x, add_variable):
    10. x = self.net(x)
    11. x = torch.cat((self.dropout(self.relu(x)), add_variable.unsqueeze(1)),1)
    12. x = self.fc_add(x)
    13. x = self.output(x)
    14. return x
    15. import torchvision.models as models
    16. net = models.resnet50()
    17. model = Model(net).cuda()
    18. outputs = model(inputs, add_var)

    3.3 添加额外输出

    3.3.1 添加方式

            输出1000维的倒数第二层和10维的最后一层结果

    3.3.2 修改代码

    1. class Model(nn.Module):
    2. def __init__(self, net):
    3. super(Model, self).__init__()
    4. self.net = net
    5. self.relu = nn.ReLU()
    6. self.dropout = nn.Dropout(0.5)
    7. self.fc1 = nn.Linear(1000, 10, bias=True)
    8. self.output = nn.Softmax(dim=1)
    9. def forward(self, x, add_variable):
    10. x1000 = self.net(x)
    11. x10 = self.dropout(self.relu(x1000))
    12. x10 = self.fc1(x10)
    13. x10 = self.output(x10)
    14. return x10, x1000
    15. import torchvision.models as models
    16. net = models.resnet50()
    17. model = Model(net).cuda()
    18. out10, out1000 = model(inputs, add_var)

    4. PyTorch模型保存与读取

    4.1 模型存储格式

            PyTorch存储模型主要采用pkl,pt,pth三种格式

    4.2 模型存储内容

            模型结构和权重

    1. from torchvision import models
    2. model = models.resnet152(pretrained=True)
    3. # 保存整个模型
    4. torch.save(model, save_dir)
    5. # 保存模型权重
    6. torch.save(model.state_dict, save_dir)

    4.3  单卡和多卡模型存储的区别

    1. os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 如果是多卡改成类似0,1,2
    2. model = model.cuda() # 单卡
    3. model = torch.nn.DataParallel(model).cuda() # 多卡

            差别在于多卡并行的模型每层的名称前多了一个“module”

    4.4 情况分类讨论

    4.4.1 单卡保存+单卡加载

    1. import os
    2. import torch
    3. from torchvision import models
    4. os.environ['CUDA_VISIBLE_DEVICES'] = '0' #这里替换成希望使用的GPU编号
    5. model = models.resnet152(pretrained=True)
    6. model.cuda()
    7. # 保存+读取整个模型
    8. torch.save(model, save_dir)
    9. loaded_model = torch.load(save_dir)
    10. loaded_model.cuda()
    11. # 保存+读取模型权重
    12. torch.save(model.state_dict(), save_dir)
    13. loaded_dict = torch.load(save_dir)
    14. loaded_model = models.resnet152() #注意这里需要对模型结构有定义
    15. loaded_model.state_dict = loaded_dict
    16. loaded_model.cuda()

    4.4.2 单卡保存+多卡加载

    1. import os
    2. import torch
    3. from torchvision import models
    4. os.environ['CUDA_VISIBLE_DEVICES'] = '0' #这里替换成希望使用的GPU编号
    5. model = models.resnet152(pretrained=True)
    6. model.cuda()
    7. # 保存+读取整个模型
    8. torch.save(model, save_dir)
    9. os.environ['CUDA_VISIBLE_DEVICES'] = '1,2' #这里替换成希望使用的GPU编号
    10. loaded_model = torch.load(save_dir)
    11. loaded_model = nn.DataParallel(loaded_model).cuda()
    12. # 保存+读取模型权重
    13. torch.save(model.state_dict(), save_dir)
    14. os.environ['CUDA_VISIBLE_DEVICES'] = '1,2' #这里替换成希望使用的GPU编号
    15. loaded_dict = torch.load(save_dir)
    16. loaded_model = models.resnet152() #注意这里需要对模型结构有定义
    17. loaded_model.state_dict = loaded_dict
    18. loaded_model = nn.DataParallel(loaded_model).cuda()

    4.4.3 多卡保存+单卡加载

    1. import os
    2. import torch
    3. from torchvision import models
    4. os.environ['CUDA_VISIBLE_DEVICES'] = '1,2' #这里替换成希望使用的GPU编号
    5. model = models.resnet152(pretrained=True)
    6. model = nn.DataParallel(model).cuda()
    7. # 保存+读取整个模型
    8. torch.save(model, save_dir)
    9. os.environ['CUDA_VISIBLE_DEVICES'] = '0' #这里替换成希望使用的GPU编号
    10. loaded_model = torch.load(save_dir)
    11. loaded_model = loaded_model.module

    4.4.4  多卡保存+多卡加载

            多卡模式下建议使用权重的方式存储和读取模型

    1. import os
    2. import torch
    3. from torchvision import models
    4. os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2' #这里替换成希望使用的GPU编号
    5. model = models.resnet152(pretrained=True)
    6. model = nn.DataParallel(model).cuda()
    7. # 保存+读取模型权重,强烈建议!!
    8. torch.save(model.state_dict(), save_dir)
    9. loaded_dict = torch.load(save_dir)
    10. loaded_model = models.resnet152() #注意这里需要对模型结构有定义
    11. loaded_model = nn.DataParallel(loaded_model).cuda()
    12. loaded_model.state_dict = loaded_dict

    深入浅出PyTroch 

  • 相关阅读:
    # Spring MVC与RESTful API:如何设计高效的Web接口
    HTML做一个简单漂亮的旅游网页(纯html代码)重庆旅游 7页
    软件工程理论与实践 (吕云翔) 第八章 软件体系结构与设计模式课后习题及其答案解析
    16.0、C语言——指针详解(2)
    C++--map和set--1027
    Jenkins 配置邮件通知(腾讯企业邮箱)
    接口测试-笔记
    pytest的内置插件盘点9. debugging
    Java面试八股文之暑假合集
    『Java安全』利用反射调用MimeLauncher.run()触发RCE
  • 原文地址:https://blog.csdn.net/qq_51167531/article/details/127948187