当前位置: 首页 > 编程笔记 >

对Pytorch中nn.ModuleList 和 nn.Sequential详解

糜雪峰
2023-03-14
本文向大家介绍对Pytorch中nn.ModuleList 和 nn.Sequential详解,包括了对Pytorch中nn.ModuleList 和 nn.Sequential详解的使用技巧和注意事项,需要的朋友参考一下

简而言之就是,nn.Sequential类似于Keras中的贯序模型,它是Module的子类,在构建数个网络层之后会自动调用forward()方法,从而有网络模型生成。而nn.ModuleList仅仅类似于pytho中的list类型,只是将一系列层装入列表,并没有实现forward()方法,因此也不会有网络模型产生的副作用。

需要注意的是,nn.ModuleList接受的必须是subModule类型,例如:

nn.ModuleList(
      [nn.ModuleList([Conv(inp_dim + j * increase, oup_dim, 1, relu=False, bn=False) for j in range(5)]) for i in
       range(nstack)])

其中,二次嵌套的list内部也必须额外使用一个nn.ModuleList修饰实例化,否则会无法识别类型而报错!

摘录自

nn.ModuleList is just like a Python list. It was designed to store any desired number of nn.Module's. It may be useful, for instance, if you want to design a neural network whose number of layers is passed as input:

class LinearNet(nn.Module):
 def __init__(self, input_size, num_layers, layers_size, output_size):
   super(LinearNet, self).__init__()
 
   self.linears = nn.ModuleList([nn.Linear(input_size, layers_size)])
   self.linears.extend([nn.Linear(layers_size, layers_size) for i in range(1, self.num_layers-1)])
   self.linears.append(nn.Linear(layers_size, output_size)

nn.Sequential allows you to build a neural net by specifying sequentially the building blocks (nn.Module's) of that net. Here's an example:

class Flatten(nn.Module):
 def forward(self, x):
  N, C, H, W = x.size() # read in N, C, H, W
  return x.view(N, -1)
 
simple_cnn = nn.Sequential(
      nn.Conv2d(3, 32, kernel_size=7, stride=2),
      nn.ReLU(inplace=True),
      Flatten(), 
      nn.Linear(5408, 10),
     )

In nn.Sequential, the nn.Module's stored inside are connected in a cascaded way. For instance, in the example that I gave, I define a neural network that receives as input an image with 3 channels and outputs 10 neurons. That network is composed by the following blocks, in the following order: Conv2D -> ReLU -> Linear layer. Moreover, an object of type nn.Sequential has a forward() method, so if I have an input image x I can directly call y = simple_cnn(x) to obtain the scores for x. When you define an nn.Sequential you must be careful to make sure that the output size of a block matches the input size of the following block. Basically, it behaves just like a nn.Module

On the other hand, nn.ModuleList does not have a forward() method, because it does not define any neural network, that is, there is no connection between each of the nn.Module's that it stores. You may use it to store nn.Module's, just like you use Python lists to store other types of objects (integers, strings, etc). The advantage of using nn.ModuleList's instead of using conventional Python lists to store nn.Module's is that Pytorch is “aware” of the existence of the nn.Module's inside an nn.ModuleList, which is not the case for Python lists. If you want to understand exactly what I mean, just try to redefine my class LinearNet using a Python list instead of a nn.ModuleList and train it. When defining the optimizer() for that net, you'll get an error saying that your model has no parameters, because PyTorch does not see the parameters of the layers stored in a Python list. If you use a nn.ModuleList instead, you'll get no error.

以上这篇对Pytorch中nn.ModuleList 和 nn.Sequential详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持小牛知识库。

 类似资料:
  • 本文向大家介绍详解PyTorch中Tensor的高阶操作,包括了详解PyTorch中Tensor的高阶操作的使用技巧和注意事项,需要的朋友参考一下 条件选取:torch.where(condition, x, y) → Tensor 返回从 x 或 y 中选择元素的张量,取决于 condition 操作定义: 举个例子: 把张量中的每个数据都代入条件中,如果其大于 0 就得出 a,其它情况就得出

  • 本文向大家介绍对pytorch网络层结构的数组化详解,包括了对pytorch网络层结构的数组化详解的使用技巧和注意事项,需要的朋友参考一下 最近再写openpose,它的网络结构是多阶段的网络,所以写网络的时候很想用列表的方式,但是直接使用列表不能将网络中相应的部分放入到cuda中去。 其实这个问题很简单的,使用moduleList就好了。 1 我先是定义了一个函数,用来根据超参数,建立一个基础网

  • 本文向大家介绍PyTorch里面的torch.nn.Parameter()详解,包括了PyTorch里面的torch.nn.Parameter()详解的使用技巧和注意事项,需要的朋友参考一下 在看过很多博客的时候发现了一个用法self.v = torch.nn.Parameter(torch.FloatTensor(hidden_size)),首先可以把这个函数理解为类型转换函数,将一个不可训练的

  • 本文向大家介绍对Pytorch神经网络初始化kaiming分布详解,包括了对Pytorch神经网络初始化kaiming分布详解的使用技巧和注意事项,需要的朋友参考一下 函数的增益值 提供了对非线性函数增益值的计算。 增益值gain是一个比例值,来调控输入数量级和输出数量级之间的关系。 xavier分布 xavier分布解析:https://prateekvjoshi.com/2016/03/29/

  • 本文向大家介绍详解pytorch 0.4.0迁移指南,包括了详解pytorch 0.4.0迁移指南的使用技巧和注意事项,需要的朋友参考一下 总说 由于pytorch 0.4版本更新实在太大了, 以前版本的代码必须有一定程度的更新. 主要的更新在于 Variable和Tensor的合并., 当然还有Windows的支持, 其他一些就是支持scalar tensor以及修复bug和提升性能吧. Var

  • 本文向大家介绍pytorch对可变长度序列的处理方法详解,包括了pytorch对可变长度序列的处理方法详解的使用技巧和注意事项,需要的朋友参考一下 主要是用函数torch.nn.utils.rnn.PackedSequence()和torch.nn.utils.rnn.pack_padded_sequence()以及torch.nn.utils.rnn.pad_packed_sequence()来

  • 本文向大家介绍pytorch中的自定义数据处理详解,包括了pytorch中的自定义数据处理详解的使用技巧和注意事项,需要的朋友参考一下 pytorch在数据中采用Dataset的数据保存方式,需要继承data.Dataset类,如果需要自己处理数据的话,需要实现两个基本方法。 :.getitem:返回一条数据或者一个样本,obj[index] = obj.getitem(index). :.len

  • 本文向大家介绍pytorch 常用线性函数详解,包括了pytorch 常用线性函数详解的使用技巧和注意事项,需要的朋友参考一下 Pytorch的线性函数主要封装了Blas和Lapack,其用法和接口都与之类似。 常用的线性函数如下: 函数 功能 trace 对角线元素之和(矩阵的迹) diag 对角线元素 triu/tril 矩阵的上三角/下三角,可指定偏移量 mm/bmm 矩阵乘法,batch的