深度学习基础知识 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

相关文章

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Python中文件读取操作漏洞深度解析与防护指南

《Python中文件读取操作漏洞深度解析与防护指南》在Web应用开发中,文件操作是最基础也最危险的功能之一,这篇文章将全面剖析Python环境中常见的文件读取漏洞类型,成因及防护方案,感兴趣的小伙伴可... 目录引言一、静态资源处理中的路径穿越漏洞1.1 典型漏洞场景1.2 os.path.join()的陷

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

Spring Boot拦截器Interceptor与过滤器Filter深度解析(区别、实现与实战指南)

《SpringBoot拦截器Interceptor与过滤器Filter深度解析(区别、实现与实战指南)》:本文主要介绍SpringBoot拦截器Interceptor与过滤器Filter深度解析... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实

MyBatis分页插件PageHelper深度解析与实践指南

《MyBatis分页插件PageHelper深度解析与实践指南》在数据库操作中,分页查询是最常见的需求之一,传统的分页方式通常有两种内存分页和SQL分页,MyBatis作为优秀的ORM框架,本身并未提... 目录1. 为什么需要分页插件?2. PageHelper简介3. PageHelper集成与配置3.

Maven 插件配置分层架构深度解析

《Maven插件配置分层架构深度解析》:本文主要介绍Maven插件配置分层架构深度解析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Maven 插件配置分层架构深度解析引言:当构建逻辑遇上复杂配置第一章 Maven插件配置的三重境界1.1 插件配置的拓扑

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

Python中__init__方法使用的深度解析

《Python中__init__方法使用的深度解析》在Python的面向对象编程(OOP)体系中,__init__方法如同建造房屋时的奠基仪式——它定义了对象诞生时的初始状态,下面我们就来深入了解下_... 目录一、__init__的基因图谱二、初始化过程的魔法时刻继承链中的初始化顺序self参数的奥秘默认

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

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