深入浅出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)
相关推荐
ManageEngineITSM几秒前
CMDB 系统在云原生时代:当配置项每天变化几千次,传统 CMDB 还够用吗
人工智能·云原生·资产管理·itsm·工单系统
小沈跨境1 分钟前
Temu被罚2.32亿美元,CPSC认证批量上传合规指南
大数据·运维·网络·人工智能·temu·跨境
Elastic 中国社区官方博客2 分钟前
6个资源,1条命令:使用 Terraform 全自动化实现 Elastic 异常检测
大数据·人工智能·elasticsearch·搜索引擎·云原生·自动化·terraform
GlobalInfo6 分钟前
2026年!定制无人机市场正以17.1%增速狂飙
人工智能·无人机
captain_AIouo6 分钟前
深耕跨境赛道!autoAGC跨境AI,挖掘海外百亿增量红利
大数据·人工智能·经验分享·aigc
搬砖的前端7 分钟前
AI工具集:Git提交时使用AI进行CodeReview如何在前端应用构建NPM包
前端·人工智能·git·npm·codeview
Stick_ZYZ10 分钟前
从 Prompt 到 Context Engineering:Agent 真正稳定的关键
大数据·人工智能·算法·ai·prompt
shiyuankeyan10 分钟前
【AICsE 2026 Workshop 1 征稿】面向健康监测的多模态生物传感器——三位顶尖学者领衔,聚焦可穿戴医疗与边缘AI前沿
人工智能
码农小旋风10 分钟前
Codex中文网 | Codex CLI 中文指南
运维·服务器·ide·人工智能·chatgpt·claude
数学建模导师12 分钟前
2026第八届中青杯ABC题赛题分析【配套解题思路+代码】
大数据·人工智能·数学建模