深入浅出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)
相关推荐
DS随心转插件几秒前
DeepSeek 代码手机端导出与 AI 辅助方案实测
android·人工智能·chatgpt·智能手机·deepseek·ai导出鸭
He少年几秒前
【实践AI 编程规则引擎深度解读:从零理解工程化设计】
人工智能
hero827482741 分钟前
公司武装AI
人工智能
阿文的代码库5 分钟前
机器学习任务二分类的应用案例
人工智能·机器学习·分类
hixiong1237 分钟前
C# LLamaSharp部署大语言模型实例
人工智能·语言模型·自然语言处理
morning_judger12 分钟前
Agent开发系列(八)-组织知识库建设
人工智能
HERR_QQ13 分钟前
端到端课程自用 8 规划 端到端与VLA 世界模型 RL的关系
人工智能·深度学习·自动驾驶·transformer
小江的记录本13 分钟前
【Spring全家桶】Spring AI核心原理、大模型集成、Prompt工程、RAG实现、AI Agent开发(附《思维导图》+《面试高频考点清单》)
java·人工智能·spring boot·后端·spring·面试·prompt
jiayong2318 分钟前
AI工作流实现原理深度解析
人工智能·comfyui·工作流·coze
用户51914958484518 分钟前
Nortek Linear eMerge E3 预认证远程代码执行漏洞利用工具
人工智能·aigc