深入浅出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)
相关推荐
东离与糖宝8 小时前
拆解编码Agent内核:所谓AI修bug,本质只是while循环
人工智能
半个布点8 小时前
传统自动驾驶模块化流水线 vs VLA 视觉 - 语言 - 动作端到端架构
人工智能·架构·自动驾驶
小和尚同志9 小时前
我也来试试已经 202k star 的 Ponytail 马尾辫
人工智能·aigc·ai编程
AAA修煤气灶刘哥9 小时前
11 月编程 Agent 排名:Arena 第一是 Claude,而另一张榜第一是 Gemini
人工智能·llm·agent
不得了zz9 小时前
11-Agent 可观测与评估:Spring AI Alibaba Admin Studio 到底解决了什么
java·人工智能·后端·spring·ai编程·springaialibaba
掘金安东尼9 小时前
智能体运行框架图解:Pi、OpenCode、Hermes 和 OpenClaw
人工智能·开源·agent
iiiiii1110 小时前
从最大熵到 SAC:Soft Q-Learning 与 Soft Actor-Critic 公式推导笔记
人工智能·笔记·算法·机器学习·强化学习
JonaHu10 小时前
GPT Image 2.6 商品换台面不悬浮:倒影、接触阴影与材质验收
图像处理·人工智能·aigc
AI创界者11 小时前
2026 全平台 AI 视频换脸工作流实战:一套方案打通 N 卡、A 卡、I 卡与 Win / Mac
人工智能·python·aigc·音视频
always202211 小时前
AI运行时 · 附录3 - GPU 设备插件与 MIG:K8s 上的 AI 加速器编排
人工智能·容器·kubernetes