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

2023-10-09 18:15

本文主要是介绍深度学习基础知识 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())

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

这篇关于深度学习基础知识 nn.Sequential | nn.ModuleList | nn.ModuleDict的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/174664

相关文章

pytorch之torch.flatten()和torch.nn.Flatten()的用法

《pytorch之torch.flatten()和torch.nn.Flatten()的用法》:本文主要介绍pytorch之torch.flatten()和torch.nn.Flatten()的用... 目录torch.flatten()和torch.nn.Flatten()的用法下面举例说明总结torch

SpringCloud动态配置注解@RefreshScope与@Component的深度解析

《SpringCloud动态配置注解@RefreshScope与@Component的深度解析》在现代微服务架构中,动态配置管理是一个关键需求,本文将为大家介绍SpringCloud中相关的注解@Re... 目录引言1. @RefreshScope 的作用与原理1.1 什么是 @RefreshScope1.

Python 中的异步与同步深度解析(实践记录)

《Python中的异步与同步深度解析(实践记录)》在Python编程世界里,异步和同步的概念是理解程序执行流程和性能优化的关键,这篇文章将带你深入了解它们的差异,以及阻塞和非阻塞的特性,同时通过实际... 目录python中的异步与同步:深度解析与实践异步与同步的定义异步同步阻塞与非阻塞的概念阻塞非阻塞同步

Redis中高并发读写性能的深度解析与优化

《Redis中高并发读写性能的深度解析与优化》Redis作为一款高性能的内存数据库,广泛应用于缓存、消息队列、实时统计等场景,本文将深入探讨Redis的读写并发能力,感兴趣的小伙伴可以了解下... 目录引言一、Redis 并发能力概述1.1 Redis 的读写性能1.2 影响 Redis 并发能力的因素二、

最新Spring Security实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)

《最新SpringSecurity实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)》本章节介绍了如何通过SpringSecurity实现从配置自定义登录页面、表单登录处理逻辑的配置,并简单模拟... 目录前言改造准备开始登录页改造自定义用户名密码登陆成功失败跳转问题自定义登出前后端分离适配方案结语前言

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx

Redis 内存淘汰策略深度解析(最新推荐)

《Redis内存淘汰策略深度解析(最新推荐)》本文详细探讨了Redis的内存淘汰策略、实现原理、适用场景及最佳实践,介绍了八种内存淘汰策略,包括noeviction、LRU、LFU、TTL、Rand... 目录一、 内存淘汰策略概述二、内存淘汰策略详解2.1 ​noeviction(不淘汰)​2.2 ​LR

Python与DeepSeek的深度融合实战

《Python与DeepSeek的深度融合实战》Python作为最受欢迎的编程语言之一,以其简洁易读的语法、丰富的库和广泛的应用场景,成为了无数开发者的首选,而DeepSeek,作为人工智能领域的新星... 目录一、python与DeepSeek的结合优势二、模型训练1. 数据准备2. 模型架构与参数设置3

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动