当前位置: 首页 > news >正文

深度学习基础知识 nn.Sequential | nn.ModuleList | nn.ModuleDict

深度学习基础知识 nn.Sequential | nn.ModuleList | nn.ModuleDict

  • 1、nn.Sequential 、 nn.ModuleList 、 nn.ModuleDict 类都继承自 Module 类。
  • 2、nn.Sequential、nn.ModuleList 和 nn.ModuleDict语法
  • 3、Sequential 、ModuleDict、 ModuleList 的区别
  • 4、ModuleDict、 ModuleList 的区别
  • 5、nn.ModuleList 、 nn.ModuleDict 与 Python list、Dict 的区别

1、nn.Sequential 、 nn.ModuleList 、 nn.ModuleDict 类都继承自 Module 类。

2、nn.Sequential、nn.ModuleList 和 nn.ModuleDict语法

net = nn.Sequential(nn.Linear(32, 64), nn.ReLU()) →→只需要将定义的层按照顺序写入括号内就可以了

net = nn.ModuleList([nn.Linear(32, 6)4, nn.ReLU()]) →→在定义式需要加上中括号[],将定义的层写入到中括号内

net = nn.ModuleDict({‘linear’: nn.Linear(32, 64), ‘act’: nn.ReLU()}) →→需要大括号,将定义的层以键值对的形式写入

代码

import torch
import torch.nn as nnnet1 = nn.Sequential(nn.Linear(32, 64), nn.ReLU())
net2 = nn.ModuleList([nn.Linear(32, 64), nn.ReLU()])
net3 = nn.ModuleDict({'linear': nn.Linear(32, 64), 'act': nn.ReLU()})print(net1)
print(net2)
print(net3)

在这里插入图片描述

3、Sequential 、ModuleDict、 ModuleList 的区别

1、 ModuleList 仅仅是一个储存各种模块的列表,这些模块之间没有联系也没有顺序(所以不用保证相邻层的输入输出维度匹配),而且没有实现 forward 功能需要自己实现

2、和 ModuleList 一样, ModuleDict 实例仅仅是存放了一些模块的字典,并没有定义 forward 函数需要自己定义

3、而 Sequential 内的模块需要按照顺序排列,要保证相邻层的输入输出大小相匹配,内部 forward 功能已经实现,所以,直接如下写模型,是可以直接调用的,不再需要写forward,sequential 内部已经有 forward

代码:

import torch
import torch.nn as nnnet1 = nn.Sequential(nn.Linear(32, 64), nn.ReLU())
net2 = nn.ModuleList([nn.Linear(32, 64), nn.ReLU()])
net3 = nn.ModuleDict({'linear': nn.Linear(32, 64), 'act': nn.ReLU()})x = torch.randn(8, 3, 32)
print(net1(x).shape)    # 输出内容: torch.Size([8, 3, 64])
# print(net2(x).shape)  # 会报错,提示缺少forward
# print(net3(x).shape)   # 会报错,提示缺少forward

为 nn.ModuleList 写 forward 函数
代码:

import torch
import torch.nn as nnclass My_Model(nn.Module):def __init__(self):super(My_Model, self).__init__()self.layers = nn.ModuleList([nn.Linear(32, 64),nn.ReLU()])def forward(self, x):for layer in self.layers:x = layer(x)return xnet = My_Model()x = torch.randn(8, 3, 32)
out = net(x)
print(out.shape)

输出结果:
在这里插入图片描述
为 nn.ModuleDict 写 forward 函数

import torch
import torch.nn as nnclass My_Model(nn.Module):def __init__(self):super(My_Model, self).__init__()self.layers = nn.ModuleDict({'linear': nn.Linear(32, 64), 'act': nn.ReLU()})def forward(self, x):for layer in self.layers.values():x = layer(x)return xnet = My_Model()
x = torch.randn(8, 3, 32)
out = net(x)
print(out.shape)

将 nn.ModuleList 转换成 nn.Sequential

import torch
import torch.nn as nnmodule_list = nn.ModuleList([nn.Linear(32, 64), nn.ReLU()])
net = nn.Sequential(*module_list)
x = torch.randn(8, 3, 32)
print(net(x).shape)

输出如下:
在这里插入图片描述

将 nn.ModuleDict 转换成 nn.Sequential

import torch
import torch.nn as nnmodule_dict = nn.ModuleDict({'linear': nn.Linear(32, 64), 'act': nn.ReLU()})
net = nn.Sequential(*module_dict.values())
x = torch.randn(8, 3, 32)
print(net(x).shape)

输出如下:
在这里插入图片描述

4、ModuleDict、 ModuleList 的区别

1、ModuleDict 可以给每个层定义名字,ModuleList 不会
2、ModuleList 可以通过索引读取,并且使用 append 添加元素

import torch.nn as nnnet = nn.ModuleList([nn.Linear(32, 64), nn.ReLU()])
net.append(nn.Linear(64, 10))
print(net)

3、ModuleDict 可以通过 key 读取,并且可以像 字典一样添加元素

import torch.nn as nnnet = nn.ModuleDict({'linear1': nn.Linear(32, 64), 'act': nn.ReLU()})
net['linear2'] = nn.Linear(64, 128)
print(net)

5、nn.ModuleList 、 nn.ModuleDict 与 Python list、Dict 的区别

import torch.nn as nnnet = nn.ModuleList([nn.Linear(32, 64), nn.ReLU()])for name, param in net.named_parameters():print(name, param)print("-----------------------------")
for name, param in net.named_parameters():print(name, param.size())

显示结果如下:
在这里插入图片描述

import torch.nn as nnnet = nn.ModuleDict({'linear': nn.Linear(32, 64), 'act': nn.ReLU()})for name, param in net.named_parameters():print(name, param.size())
print("--------------------------")for name, param in net.named_parameters():print(name, param.size())

显示结果:
在这里插入图片描述

http://www.lryc.cn/news/186354.html

相关文章:

  • 【DevOps】搭建你的第一个 Docker 应用栈
  • 软件测试职业生涯需要编写的全套文档模板,收藏这一篇就够了 ~
  • 【Kubernetes】Pod——k8s中最重要的对象之一
  • vue-cli-service: command not found问题解决
  • 每日一练 | 华为认证真题练习Day117
  • 【JVM】垃圾回收(GC)详解
  • 阿里云服务器公网带宽多少钱1M?
  • 应用DeepSORT实现目标跟踪
  • Beyond Compare 4 30天评估到期 解决方法
  • 化妆品用乙基己基甘油全球市场总体规模2023-2029
  • springboot家政服务管理平台springboot29
  • 【网络安全】如何保护IP地址?
  • 2023年失业了,想学一门技术可以学什么?
  • MySQL-MVCC(Multi-Version Concurrency Control)
  • ArcGIS中的镶嵌数据集与接缝线
  • 网络安全工程师自主学习计划表(具体到阶段目标,保姆级安排,就怕你学不会!)
  • Linux 根据 PID 查看进程名称
  • Python二级 每周练习题21
  • 【算法训练-数组 三】【数组矩阵】螺旋矩阵、旋转图像、搜索二维矩阵
  • LED灯实验--汇编
  • Android多线程学习:线程池(一)
  • 网络安全(黑客技术)—小白自学笔记
  • 掌握核心技巧就能创建完美的目录!如何在Word中自动创建目录
  • 正则表达式中re.match、re.search、re.findall的用法和区别
  • 算法题:买卖股票的最佳时机含手续费(动态规划解法贪心解法-详解)
  • 【gcc】RtpTransportControllerSend学习笔记 4:码率分配
  • 「专题速递」AR协作、智能NPC、数字人的应用与未来
  • 什么是基于意图的网络(IBN)
  • 知识增强语言模型提示 零样本知识图谱问答10.8
  • 虚拟现实项目笔记:SDK、Assimp、DirectX Sample Browser、X86和X64