【翻译】class torch.nn.Sequential(*args)

参考链接: class torch.nn.Sequential(*args)

在这里插入图片描述

原文及翻译:

Sequential   Sequential部分
class torch.nn.Sequential(*args)
类型 torch.nn.Sequential(*args)
    A sequential container. Modules will be added to it in the order they are passed in 
    the constructor. Alternatively, an ordered dict of modules can also be passed in.
   这是一个序列化容器. 按照传递到构造器内的先后顺序,模块将被依次添加到这个序列化容器. 同样,你可以
   给构造器传递一个由模块构成的有序字典.

    To make it easier to understand, here is a small example:
    以下是一个小例子,方便理解:

    # Example of using Sequential
    # 使用Sequential的例子
    model = nn.Sequential(
              nn.Conv2d(1,20,5),
              nn.ReLU(),
              nn.Conv2d(20,64,5),
              nn.ReLU()
            )

    # Example of using Sequential with OrderedDict
    # Sequential使用有序字典的例子
    model = nn.Sequential(OrderedDict([
              ('conv1', nn.Conv2d(1,20,5)),
              ('relu1', nn.ReLU()),
              ('conv2', nn.Conv2d(20,64,5)),
              ('relu2', nn.ReLU())
            ]))

代码实验:

Microsoft Windows [版本 10.0.18363.1316]
(c) 2019 Microsoft Corporation。保留所有权利。

C:\Users\chenxuqi>conda activate ssd4pytorch1_2_0

(ssd4pytorch1_2_0) C:\Users\chenxuqi>python
Python 3.7.7 (default, May  6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.manual_seed(seed=20200910)
<torch._C.Generator object at 0x0000026E386DD330>
>>> import torch.nn as nn
>>> from collections import OrderedDict
>>>
>>> # Example of using Sequential
>>>
>>> model = nn.Sequential(
...           nn.Conv2d(1,20,5),
...           nn.ReLU(),
...           nn.Conv2d(20,64,5),
...           nn.ReLU()
...         )
>>> model
Sequential(
  (0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
  (1): ReLU()
  (2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
  (3): ReLU()
)
>>> model[0]
Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
>>> model[1]
ReLU()
>>> model[2]
Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
>>> model[3]
ReLU()
>>> model[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Anaconda3\envs\ssd4pytorch1_2_0\lib\site-packages\torch\nn\modules\container.py", line 68, in __getitem__
    return self._get_item_by_idx(self._modules.values(), idx)
  File "D:\Anaconda3\envs\ssd4pytorch1_2_0\lib\site-packages\torch\nn\modules\container.py", line 60, in _get_item_by_idx
    raise IndexError('index {} is out of range'.format(idx))
IndexError: index 4 is out of range
>>> model[-1]
ReLU()
>>> model[-2]
Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
>>> model[-4]
Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
>>> model[-5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Anaconda3\envs\ssd4pytorch1_2_0\lib\site-packages\torch\nn\modules\container.py", line 68, in __getitem__
    return self._get_item_by_idx(self._modules.values(), idx)
  File "D:\Anaconda3\envs\ssd4pytorch1_2_0\lib\site-packages\torch\nn\modules\container.py", line 60, in _get_item_by_idx
    raise IndexError('index {} is out of range'.format(idx))
IndexError: index -5 is out of range
>>>
>>> len(model)
4
>>>
>>> for m in model:
...     print(m)
...
Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
ReLU()
Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
ReLU()
>>>
>>>
>>> # Example of using Sequential with OrderedDict
>>> model = nn.Sequential(OrderedDict([
...           ('conv1', nn.Conv2d(1,20,5)),
...           ('relu1', nn.ReLU()),
...           ('conv2', nn.Conv2d(20,64,5)),
...           ('relu2', nn.ReLU())
...         ]))
>>> model
Sequential(
  (conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
  (relu1): ReLU()
  (conv2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
  (relu2): ReLU()
)
>>> model[0]
Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
>>> for m in model:
...     print(m)
...
Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
ReLU()
Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
ReLU()
>>>
>>> model['conv1']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Anaconda3\envs\ssd4pytorch1_2_0\lib\site-packages\torch\nn\modules\container.py", line 68, in __getitem__
    return self._get_item_by_idx(self._modules.values(), idx)
  File "D:\Anaconda3\envs\ssd4pytorch1_2_0\lib\site-packages\torch\nn\modules\container.py", line 58, in _get_item_by_idx
    idx = operator.index(idx)
TypeError: 'str' object cannot be interpreted as an integer
>>> model.conv1
Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
>>> model.relu1
ReLU()
>>> model.conv2
Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
>>> model.relu2
ReLU()
>>>
>>>

代码实验:

Microsoft Windows [版本 10.0.18363.1440]
(c) 2019 Microsoft Corporation。保留所有权利。

C:\Users\chenxuqi>conda activate pytorch_1.7.1_cu102

(pytorch_1.7.1_cu102) C:\Users\chenxuqi>python
Python 3.7.9 (default, Aug 31 2020, 17:10:11) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> from torch import nn
>>> model = nn.Sequential(nn.Conv2d(1,20,5),nn.ReLU(),nn.Conv2d(20,64,5),nn.ReLU())
>>> model
Sequential(
  (0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
  (1): ReLU()
  (2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
  (3): ReLU()
)
>>> model[2]
Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
>>> type(model)
<class 'torch.nn.modules.container.Sequential'>
>>> type(model[2])
<class 'torch.nn.modules.conv.Conv2d'>
>>> type(model[0:2])
<class 'torch.nn.modules.container.Sequential'>
>>> model[0:2]
Sequential(
  (0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
  (1): ReLU()
)
>>> model[-1:]
Sequential(
  (3): ReLU()
)
>>>
>>> type(model[-1:])
<class 'torch.nn.modules.container.Sequential'>
>>>
>>>
>>>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
from collections import OrderedDict import torch import torch.nn.functional as F import torchvision from torch import nn import models.vgg_ as models class BackboneBase_VGG(nn.Module): def __init__(self, backbone: nn.Module, num_channels: int, name: str, return_interm_layers: bool): super().__init__() features = list(backbone.features.children()) if return_interm_layers: if name == 'vgg16_bn': self.body1 = nn.Sequential(*features[:13]) self.body2 = nn.Sequential(*features[13:23]) self.body3 = nn.Sequential(*features[23:33]) self.body4 = nn.Sequential(*features[33:43]) else: self.body1 = nn.Sequential(*features[:9]) self.body2 = nn.Sequential(*features[9:16]) self.body3 = nn.Sequential(*features[16:23]) self.body4 = nn.Sequential(*features[23:30]) else: if name == 'vgg16_bn': self.body = nn.Sequential(*features[:44]) # 16x down-sample elif name == 'vgg16': self.body = nn.Sequential(*features[:30]) # 16x down-sample self.num_channels = num_channels self.return_interm_layers = return_interm_layers def forward(self, tensor_list): out = [] if self.return_interm_layers: xs = tensor_list for _, layer in enumerate([self.body1, self.body2, self.body3, self.body4]): xs = layer(xs) out.append(xs) else: xs = self.body(tensor_list) out.append(xs) return out class Backbone_VGG(BackboneBase_VGG): """ResNet backbone with frozen BatchNorm.""" def __init__(self, name: str, return_interm_layers: bool): if name == 'vgg16_bn': backbone = models.vgg16_bn(pretrained=True) elif name == 'vgg16': backbone = models.vgg16(pretrained=True) num_channels = 256 super().__init__(backbone, num_channels, name, return_interm_layers) def build_backbone(args): backbone = Backbone_VGG(args.backbone, True) return backbone if __name__ == '__main__': Backbone_VGG('vgg16', True)
最新发布
06-02

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值