深入浅出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)
相关推荐
数据皮皮侠AI几秒前
上市公司数字供应链金融指数(2010-2024)
大数据·人工智能·算法
海兰14 分钟前
【思考】AI编码企业落地:从“通用生成”到“工程落地”的鸿沟与跨越
人工智能
白拾23 分钟前
【ICML 2026 (Oral)】RoboMME 论文解读:首个大规模具身记忆评测基准,系统评估 VLA 长程记忆
人工智能·机器人·具身智能·vla·icml·记忆·基准评测
word26 分钟前
用 AI 搭一条自动化热点监控流水线:RSS 聚合、智能筛选、定时推送一次跑通
人工智能
土星云SaturnCloud27 分钟前
智慧温室精准环控:土星云边缘计算设备实现温光水肥本地闭环调节
服务器·人工智能·ai·边缘计算
孙启超39 分钟前
【AI应用开发】LangChain 中 Chain 和 Agent 核心区别?
java·人工智能·langchain·llm·rag·ai应用开发·agent loop
别动我齐刘海41 分钟前
Day6 unitree_G1人形机器人GMR—— MotionInput
c语言·c++·人工智能·学习·机器学习·机器人·github
火山引擎开发者社区44 分钟前
基于 TLS 的 Coding Agent 全链路可观测体系:打破执行黑盒,实现全流程透明复盘
人工智能
ACP广源盛139246256731 小时前
DeepSeek‑V4‑Flash 公测@ACP#昇腾 950 国产算力组合落地,国产 PCIe 交换芯片 IX9104 有哪些硬件机会
大数据·数据库·人工智能·分布式·单片机·嵌入式硬件·microsoft
ZHOU_WUYI1 小时前
1. FastWAM 环境安装与初始化
pytorch·世界动作模型