深入浅出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)
相关推荐
jinanwuhuaguo3 小时前
OpenClaw深度沟通渠道-全景深度解构
大数据·开发语言·人工智能·openclaw
软件资深者3 小时前
OpenClaw 本地安装 vs 网页版龙虾:全方位对比 + 2026 最新一键安装客户端(新手零门槛搭建专属 AI 助理)
运维·人工智能·自动化·飞书·数字员工·openclaw·龙虾
北鸟南游4 小时前
使用AI智能体的MCP和SKILL
人工智能·程序员·前端框架
cxr8284 小时前
OpenClaw Node 技术架构与核心概念
人工智能·架构·ai智能体·openclaw
1941s4 小时前
OpenClaw 每日新玩法 | 多 Agent 协作系统 - 让 AI 员工 24小时自主工作
人工智能·agent·openclaw
步步为营DotNet4 小时前
深入剖析.NET 11 中 Microsoft.Extensions.AI 在 AI 驱动后端开发的进阶应用
人工智能·microsoft·.net
空空潍4 小时前
Spring AI 实战系列(三):多模型共存+双版本流式输出
java·人工智能·spring
gaozhiyong08134 小时前
提示词的解剖学:Gemini 3.1 Pro 提示工程高级策略与国内实战
人工智能·算法·机器学习
Langchain4 小时前
2026 年 AI 最值得关注的方向:上下文工程!
人工智能·python·自然语言处理·llm·agent·大模型开发·rag
学习者0074 小时前
大模型之VLLMA
人工智能