深入浅出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)。这个函数仅当模型中有Dropout和BatchNorm时才会有影响。

复制代码
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)
相关推荐
喵个咪6 小时前
补全如水,代理如刀:AI 编程的两本账与两种未来
人工智能·llm·mvp
如若1236 小时前
FIND:频域不变性解耦助力LiDAR 3D检测测试时自适应
人工智能·yolo·目标检测·计算机视觉·3d
织码weavecodes6 小时前
Spring Boot 接入 AI 图像生成:模型适配、图片转存与 Redis 清理
人工智能·spring boot·redis
Csvn7 小时前
WorkBuddy 使用指南:确实需要时再配 MCP
人工智能
Csvn7 小时前
重试到死不如快失败:熔断器三态状态机,让持续故障 1ms 拒绝(A02)
人工智能
陈嘿萌7 小时前
ACM MM 2026|厦门大学 Bio-PCNet:生物启发的复杂退化下多模态海事感知
人工智能·深度学习·计算机视觉·图像融合·学术研究与理论基础
数字供应链安全产品选型8 小时前
从 Skill 安全准入到 Agent 运行时防护,问境 AgentAI 打通企业智能体规模化落地的安全关卡
人工智能·安全
掘金安东尼8 小时前
任务成功率从 60% 做到 99%:Strands Evals 的运行框架优化
人工智能
Cosolar8 小时前
当 Harness 标准化后,工程师还剩什么?
人工智能·后端·agent
Wellijohn8 小时前
大模型推理为什么这么贵?从 KV Cache 到投机解码的一线优化实录
人工智能·性能优化·llm