深入浅出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)
相关推荐
吴佳浩1 小时前
Hermes Agent 连环 400 真凶找到了:一个 call_id 让人炸毛
人工智能·llm·agent
程序员cxuan1 小时前
幽默,一个 Github 名字叫“马尾辫”,但是他给你省了 80% 的 token
人工智能·后端·程序员
宋哥转AI2 小时前
Agent记忆模块系列:03存储与检索链路实测验证
人工智能·agent
老金带你玩AI2 小时前
老金开源GoalPro,别让AI把目标越写越烂
人工智能
Bigfish_coding2 小时前
前端转agent-【python】-08 用 LangGraph 把 Agent 做成状态机:像写 Vue 3 状态管理一样编排 AI 流程
人工智能
刺猬的温驯3 小时前
语音克隆模型的难点之一:音素对齐及交叉注意力早期失效问题 (兼论旋转位置编码)——F5-TTS、SupertonicTTS、VoxFlash-TTS 对比
人工智能·语音合成·tts
道友可好3 小时前
AI 是最好的混乱放大器:代码熵管理实战
前端·人工智能·后端
不加辣椒5 小时前
第7章 边界与约束技术:确保输出的准确性与安全性
人工智能
AI悦创Python辅导5 小时前
Claude Code 越用越乱?Sub-Agents 才是上下文污染的解法
人工智能
Bigfish_coding5 小时前
前端转agent-【python】-07 长期记忆进阶:用 ChromaDB + 语义搜索给 Agent 装上真正的长期记忆
人工智能