DAY08:【pytorch】模型容器

打印 上一主题 下一主题

主题 1751|帖子 1751|积分 5253

1、三大容器



  • nn.Sequential:按次序包装多个网络层
  • nn.ModuleList:像 Python 中的 list 一样包装多个网络层
  • nn.ModuleDict:像 Python 中的 dict 一样包装多个网络层
1.1 Sequential


1.1.1 概念

nn.Sequential 是 nn.Module 的容器,用于按次序包装一组网络层
1.1.2 特征



  • 次序性:各网络层之间严格按次序构建
  • 自带 forward():自带的 forward 里,通过 for 循环依次执行向前传播运算
1.3 代码框架



  • LeNetSequential()
  1. class LeNetSequential(nn.Module):
  2.     def __init__(self, classes):
  3.         super(LeNetSequential, self).__init__()
  4.         self.features = nn.Sequential(
  5.             nn.Conv2d(3, 6, 5),
  6.             nn.ReLU(),
  7.             nn.MaxPool2d(kernel_size=2, stride=2),
  8.             nn.Conv2d(6, 16, 5),
  9.             nn.ReLU(),
  10.             nn.MaxPool2d(kernel_size=2, stride=2),)
  11.         self.classifier = nn.Sequential(
  12.             nn.Linear(16*5*5, 120),
  13.             nn.ReLU(),
  14.             nn.Linear(120, 84),
  15.             nn.ReLU(),
  16.             nn.Linear(84, classes),)
  17.     def forward(self, x):
  18.         x = self.features(x)
  19.         x = x.view(x.size()[0], -1)
  20.         x = self.classifier(x)
  21.         return x
复制代码


  • LeNetSequentialOrderDict()
  1. class LeNetSequentialOrderDict(nn.Module):
  2.     def __init__(self, classes):
  3.         super(LeNetSequentialOrderDict, self).__init__()
  4.         self.features = nn.Sequential(OrderedDict({
  5.             'conv1': nn.Conv2d(3, 6, 5),
  6.             'relu1': nn.ReLU(inplace=True),
  7.             'pool1': nn.MaxPool2d(kernel_size=2, stride=2),
  8.             'conv2': nn.Conv2d(6, 16, 5),
  9.             'relu2': nn.ReLU(inplace=True),
  10.             'pool2': nn.MaxPool2d(kernel_size=2, stride=2),
  11.         }))
  12.         self.classifier = nn.Sequential(OrderedDict({
  13.             'fc1': nn.Linear(16*5*5, 120),
  14.             'relu3': nn.ReLU(),
  15.             'fc2': nn.Linear(120, 84),
  16.             'relu4': nn.ReLU(inplace=True),
  17.             'fc3': nn.Linear(84, classes),
  18.         }))
  19.     def forward(self, x):
  20.         x = self.features(x)
  21.         x = x.view(x.size()[0], -1)
  22.         x = self.classifier(x)
  23.         return x
复制代码
1.2 ModuleList

1.2.1 概念

nn.ModuleList 是 nn.module 的容器,用于包装一组网络层,以索引方式调用网络层
1.2.2 重要方法



  • append():在 ModuleList 背面添加网络层
  • extend():拼接两个 ModuleList
  • insert():指定在 ModuleList 中某个位置插入网络层
1.2.3 代码框架

  1. class ModuleList(nn.Module):
  2.     def __init__(self):
  3.         super(ModuleList, self).__init__()
  4.         self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(20)])
  5.     def forward(self, x):
  6.         for i, linear in enumerate(self.linears):
  7.             x = linear(x)
  8.         return x
复制代码
1.3 ModuleDict

1.3.1 概念

nn.ModuleDict 是 nn.module 的容器,用于包装一组网络层,以索引方式调用网络层
1.3.2 重要方法



  • clear():清空 ModuleDict
  • items():返回可迭代的键值对(key-value pairs)
  • keys():返回字典的键(key)
  • values():返回字典的值(value)
  • pop():返回一组键值对并从字典中删除
1.3.3 代码框架

  1. class ModuleDict(nn.Module):
  2.     def __init__(self):
  3.         super(ModuleDict, self).__init__()
  4.         self.choices = nn.ModuleDict({
  5.             'conv': nn.Conv2d(10, 10, 3),
  6.             'pool': nn.MaxPool2d(3)
  7.         })
  8.         self.activations = nn.ModuleDict({
  9.             'relu': nn.ReLU(),
  10.             'prelu': nn.PReLU()
  11.         })
  12.     def forward(self, x, choice, act):
  13.         x = self.choices[choice](x)
  14.         x = self.activations[act](x)
  15.         return x
复制代码
1.4 小结



  • nn.Sequential:次序性,各网络层之间严格按照次序执行,常用于 block 构建
  • nn.ModuleList:迭代性,常用于大量重复网络构建,通过 for 循环实现重复构建
  • nn.ModuleDict:字典性,冲用于可选择的网络层构建
2、AlexNet


2.1 配景介绍

2021年 AlextNet 以高出第二名10多个百分点的准确率得到 ImageNet 分类任务冠军,开创了卷积神经网络的新时代
2.2 特征


  • 接纳 ReLU 激活函数:替换了 sigmoid 函数,减轻梯度消散的问题
  • 接纳 LRN(Local Response Normalization):对数据进行归一化,抑制其对输出的影响,减轻梯度消散的问题
  • 接纳 Dropout:提高全毗连层的鲁棒性,增加网络的泛化本领
  • 接纳 Data Augmentation:TenCrop 策略,色彩修改
2.3 代码框架

  1. class AlexNet(nn.Module):
  2.     def __init__(self, num_classes: int = 1000, dropout: float = 0.5) -> None:
  3.         super().__init__()
  4.         _log_api_usage_once(self)
  5.         self.features = nn.Sequential(
  6.             nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
  7.             nn.ReLU(inplace=True),
  8.             nn.MaxPool2d(kernel_size=3, stride=2),
  9.             nn.Conv2d(64, 192, kernel_size=5, padding=2),
  10.             nn.ReLU(inplace=True),
  11.             nn.MaxPool2d(kernel_size=3, stride=2),
  12.             nn.Conv2d(192, 384, kernel_size=3, padding=1),
  13.             nn.ReLU(inplace=True),
  14.             nn.Conv2d(384, 256, kernel_size=3, padding=1),
  15.             nn.ReLU(inplace=True),
  16.             nn.Conv2d(256, 256, kernel_size=3, padding=1),
  17.             nn.ReLU(inplace=True),
  18.             nn.MaxPool2d(kernel_size=3, stride=2),
  19.         )
  20.         self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
  21.         self.classifier = nn.Sequential(
  22.             nn.Dropout(p=dropout),
  23.             nn.Linear(256 * 6 * 6, 4096),
  24.             nn.ReLU(inplace=True),
  25.             nn.Dropout(p=dropout),
  26.             nn.Linear(4096, 4096),
  27.             nn.ReLU(inplace=True),
  28.             nn.Linear(4096, num_classes),
  29.         )
  30.     def forward(self, x: torch.Tensor) -> torch.Tensor:
  31.         x = self.features(x)
  32.         x = self.avgpool(x)
  33.         x = torch.flatten(x, 1)
  34.         x = self.classifier(x)
  35.         return x
复制代码

微语录:熬过无人问津的日子,才能拥抱诗和远方。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

兜兜零元

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表