深入浅出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)
相关推荐
艾莉丝努力练剑2 小时前
【AI接入大模型SDK】ChatSDK示例验证
人工智能·学习·面试·大模型·sdk
wulitoud2 小时前
把 Claude、Codex、Gemini 的引擎换成本地模型:免费、离线、数据不出本机
人工智能·llama·claude·本地模型
火山引擎开发者社区5 小时前
TLS for DeepSeek Harness 可观测实践:从系统总览到会话复盘
人工智能
数字融合7 小时前
透明化地铁线视频孪生综合监控项目技术
大数据·人工智能·virtualenv
鼎艺创新科技8 小时前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
十三画者8 小时前
【文献分享】ConfRetro:融合3D构象信息的逆合成预测Transformer框架
人工智能·深度学习·数据挖掘·数据分析·transformer·数据可视化
前沿在线8 小时前
百度文心助手推出任务引擎 2.0,日活用户同比增长 83%,日均对话轮次增长超 2 倍
人工智能·ai·大模型
zandy10119 小时前
AI办公工具选哪个?千问办公、百度搭子、WorkBuddy三款高阶智能体深度拆解
人工智能·ai办公工具
mengpp_1234569 小时前
AIoT平台 vs 普通IoT平台 核心区别
人工智能
canonical_entropy9 小时前
可逆不是逆向运行:DeepSeek Harness 架构的数学本质
人工智能·架构·agent