深入浅出Pytorch函数——torch.nn.Module

分类目录:《深入浅出Pytorch函数》总目录


torch.nn.Module是所有Pytorch中所有神经网络模型的基类,我们的神经网络模型也应该继承这个类。Modules可以包含其它Modules,也允许使用树结构嵌入他们,还可以将子模块赋值给模型属性。

实例

复制代码
import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)       # submodule: Conv2d
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
       x = F.relu(self.conv1(x))
       return F.relu(self.conv2(x))

通过上面方式赋值的submodule会被注册。当调用.cuda()的时候,submodule的参数也会转换为cuda Tensor

函数

eval()

将模块设置为evaluation模式,相当于self.train(False)。这个函数仅当模型中有DropoutBatchNorm时才会有影响。

复制代码
def eval(self: T) -> T:
        r"""Sets the module in evaluation mode.

        This has any effect only on certain modules. See documentations of
        particular modules for details of their behaviors in training/evaluation
        mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
        etc.

        This is equivalent with :meth:`self.train(False) <torch.nn.Module.train>`.

        See :ref:`locally-disable-grad-doc` for a comparison between
        `.eval()` and several similar mechanisms that may be confused with it.

        Returns:
            Module: self
        """
        return self.train(False)
相关推荐
电子科技圈8 小时前
SmartDV展示完整的边缘与连接IP解决方案,以高速和低功耗特性赋能移动、物联网和媒体处理设备创新
人工智能·嵌入式硬件·mcu·物联网·智能家居·智能硬件·iot
Rubin智造社8 小时前
04月17日AI每日参考:Claude Opus 4.7正式发布,智元机器人大会今日开幕
大数据·人工智能·机器学习·claude code·智元机器人·deepseek v4·claude opus 4.7
Raink老师15 小时前
【AI面试临阵磨枪】详细解释 Transformer 架构的核心组件与工作流程。
人工智能·深度学习·transformer·ai 面试·ai 应用开发
qcx2316 小时前
【AI Agent实战】OpenClaw 安全加固完全指南:安全攻击手段与五步防护实践(2026最新)
人工智能·安全
AnnyYoung16 小时前
单细胞转录组+空间转录组+深度学习的意义
深度学习·数据分析
码农小白AI16 小时前
AI报告审核进入技术驱动时代:IACheck如何从规则引擎走向深度学习,构建检测报告审核“技术矩阵”
人工智能·深度学习
song1502653729816 小时前
视觉检测设备:自动识别缺陷、尺寸、瑕疵、装配错误,一键全检
人工智能·计算机视觉·视觉检测
智能化咨询16 小时前
(163页PPT)某著名企业K3生产制造售前营销指导方案P164(附下载方式)
大数据·人工智能
Zzj_tju16 小时前
大语言模型技术指南:SFT、RLHF、DPO 怎么串起来?对齐训练与关键参数详解
人工智能·深度学习·语言模型
金智维科技官方16 小时前
RPA技术赋能电信运营商话单稽核:金智维如何驱动高精度自动化转型
人工智能·自动化·数字化·rpa·智能体·电信