深入浅出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)
相关推荐
MSTcheng.27 分钟前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
世冠科技39 分钟前
世冠科技GCEAgent重磅发布,开启复杂装备AI原生智能研发新范式
人工智能·科技·ai-native
轻松,带微笑1 小时前
AI竞争进入下半场:微软押注专业模型,通用大模型不再是唯一答案
人工智能·microsoft
哈尔滨张谦蛋1 小时前
兰州大学 · 甘肃省可穿戴装备重点实验室 · 2027年博士招生
人工智能·深度学习
MysTic_Zhong1 小时前
【3】核心引擎:LangGraph 编排与多路召回重排
人工智能·agent
vivo互联网技术1 小时前
研发数字人 Agent:从 0 到 1 的架构与实践
人工智能·agent·mcp
练习两年半的攻城狮1 小时前
企业级 AI Agent 架构知识点讲解(一):从知识型到业务型,从 LangGraph 到生产落地
人工智能·架构
Cosolar2 小时前
从 50ms 到 3 分钟:淘特动线 Agent 如何把 LLM 塞进一个有预算约束的实时系统
人工智能·后端·agent
Cosolar2 小时前
拆开「研发数字人」:一个 Agent 系统真正的护城河,是被结构化的判断力
人工智能·后端·架构