深入浅出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)
相关推荐
circuitsosk4 分钟前
大模型驱动的AI产品后端架构设计与实践
人工智能·python
飞凌嵌入式5 分钟前
性能翻倍·功耗减半!RK3572八核核心板,重构嵌入式计算新标杆
人工智能·嵌入式硬件·飞凌嵌入式
gnhpc16 分钟前
深耕工业智造!飞腾主板,让智慧城市发展更高效
人工智能·智慧城市
人工智能AI技术14 分钟前
从Prompt到Graph Engineering:企业多Agent五层AI工程演进全解析
人工智能
西西弗Sisyphus15 分钟前
部署模型的优化:图像标准化预处理从三步到一步乘加(2)
人工智能·机器学习·分类·训练·推理·imagenet
zandy101128 分钟前
2026年,AI Agent搜索Skill推荐已经离不开底层架构
大数据·人工智能·架构
小弥儿39 分钟前
GitHub今日热榜 | 2026-07-31:AI Agent工作流共享赛道升温
人工智能·学习·github
想你依然心痛43 分钟前
HarmonyOS 5.0智慧农业开发实战:构建分布式农业物联网与区块链农产品溯源系统
人工智能·分布式·物联网·区块链·智慧农业·harmonyos·开发实战
Kevin Wang72744 分钟前
华为昇腾910B部署手册——课堂质量诊断
人工智能·华为
徐礼昭|商派软件市场负责人1 小时前
腾讯云企业版WorkBuddy官方代理商“商派”ShopeX:零售数智化进入”对话即操作”时代
人工智能·腾讯云·零售·workbuddy