深入浅出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)
相关推荐
继续商行几秒前
探秘 Go 动态数组:pprof 排查大数据切片 GC 停顿
人工智能
OBiO20131 分钟前
如何利用AAV精准靶向血管平滑肌细胞(VSMCs)?
人工智能
lwyingdao1 分钟前
Codex接入国产大模型,三步配置,无需OpenAI账号
人工智能·ai编程·ai工具
团象科技3 分钟前
出海企业算力适配调研:深度学习模型云端搭建的落地观察
人工智能·深度学习
kft13145 分钟前
04 — AI 测试用例生成与评审实战
人工智能·测试用例
无心水5 分钟前
【Harness:落地实战】24、Harness CI/CD+GitOps深度实战:智能交付与渐进发布——企业级云原生DevOps全解析
人工智能·ci/cd·云原生·openclaw·harness·hermes·honcho
AI学长6 分钟前
数据集|二维码目标检测QRCodeDetection
人工智能·目标检测·计算机视觉·二维码目标检测
IT_陈寒7 分钟前
React开发实战:从入门到精通
前端·人工智能·后端
古道青阳9 分钟前
AI编码智能体横向评测Cursor、OpenAI Codex 与 Claude Code
人工智能
kft131410 分钟前
测试深度洞察 | 2026年6月:测试工具迭代背后的行业信号
人工智能·测试用例