深入浅出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)
相关推荐
HcreateLabelView4 分钟前
引领RFID电子标签打印新时代,打造标识打印系统新标杆
大数据·人工智能
wjcroom7 分钟前
以太缄默-理论分析
人工智能·物理学
guslegend12 分钟前
4月5日(大语言模型训练原理)
人工智能·大模型
数智化管理手记19 分钟前
精益生产合理化建议核心解读:本质、价值与提报规范
大数据·网络·人工智能·低代码·制造
QfC92C02p19 分钟前
Hagicode 多 AI 提供者切换与互操作实现方案
人工智能
SUNNY_SHUN23 分钟前
VLM走进农田:AgriChat覆盖3000+作物品类,607K农业视觉问答基准开源
论文阅读·人工智能·算法·开源
黎阳之光26 分钟前
视频孪生赋能车路云一体化,领跑智慧高速新征程
人工智能·算法·安全·数字孪生
cxr82828 分钟前
GPU 加速声场求解器 CUDA Kernel 实现细节 —— 高频超声传播仿真并行计算引擎
人工智能·python·目标跟踪
空空潍31 分钟前
Spring AI 实战系列(十一):MCP实战 —— 接入第三方 MCP生态
人工智能·spring ai
赶路人儿31 分钟前
Claude Code 泄露源码 - 本地可运行版本
人工智能