深入浅出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)
相关推荐
杨杨杨大侠7 小时前
Agent 的上下文和记忆怎么管?从 Harness 到 AgentScope 实现
人工智能·agent
lll23526917797 小时前
法律咨询过程中的重要信息如何保存?
深度学习·智能手机
小王2047 小时前
Day 41:模型注意力机制 — SE / CBAM / ECA
python·深度学习·机器学习
OceanBase数据库官方博客7 小时前
被 VLDB 2027接收OceanBase 最新论文让数据库基(技术解析与实践)
数据库·人工智能·oceanbase
朝朝辞暮i7 小时前
第 22 课:Conditional 1D U-Net——Diffusion Policy 怎样理解一整段未来动作?
人工智能·pytorch·深度学习·transformer·vla
别动我齐刘海8 小时前
Linux 系统调试学习2
linux·运维·c++·人工智能·学习·机器学习·机器人
Dawson Zhu8 小时前
《Agentic Design Patterns》第 18 章导读:Guardrails 安全模式
人工智能·语言模型·架构·aigc·agi
探客木木夕8 小时前
结构超图重构神经网络模型:脉冲权重节点与四阶段闭环框架
人工智能·深度学习·神经网络
地理探险家8 小时前
从零实现图片自动分类:数据准备、模型训练与单图预测
人工智能·深度学习·机器学习·分类·数据挖掘·数据集