深入浅出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)
相关推荐
罗西的思考24 分钟前
【轻量化复现大模型 / KIMI K3】训练模块梳理 & Muon P2P 优化器
人工智能·深度学习·机器学习
lilihuigz32 分钟前
权限配置:WordPress 7.2 Abilities API 权限、输入验证与 JSON 输出指南
人工智能
杨凯凡37 分钟前
IT日报|2026-11-20:欧盟 AI 网络攻击、Valkey 9.2、GitHub 企业迁移
人工智能·github
鲁邦通物联网1 小时前
机器人梯控到站状态机设计:楼层匹配、事件时序与任务判断
人工智能·机器人·机器人梯控·agv梯控·非侵入式采集·机器人乘梯·机器人自主乘梯
静水深码2 小时前
文生图提示词的工程师写法:把玄学话术拆成结构化模板
人工智能·后端·代码规范
Seiran2 小时前
Claude Fable 5.1写技术方案,ZEEKEAI提效实录
人工智能
JonaHu2 小时前
GPT Image 2.6 多语言海报改版:保留商品细节,分离文案与图像验收
图像处理·人工智能·aigc
4cos902 小时前
pi学习笔记-BranchSummary
人工智能
程序员张富华2 小时前
一次发布拦住12个破坏性变更:我们给Agent工作流加了Schema门禁
人工智能·agent
伞伞悦读2 小时前
【第90期】KNN分类回归流水线与K值对照的实验与排查
大数据·人工智能·python·深度学习·机器学习