深入浅出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)
相关推荐
AI_5678几秒前
Nmap端口扫描:SYN扫描+脚本绕过提升成功率
人工智能·nmap
人工智能培训3 分钟前
多模态大模型的统一表征与推理范式
人工智能·深度学习·ai大模型·多模态学习·具身智能·企业ai转型
szxinmai主板定制专家22 分钟前
RK3588 8个USB工控解决方案,适用于机器视觉,工业互联等
arm开发·人工智能·fpga开发
mao_feng23 分钟前
《AI智脉速递》2026 年 2月16日 - 2月23日
人工智能
2501_9436953329 分钟前
大专市场调查与统计分析专业,怎么学习市场调研问卷的设计?
人工智能·学习
阿甘编程点滴32 分钟前
人声伴奏分离工具5款实测精选
人工智能
小咖自动剪辑33 分钟前
豆包AI去水印插件:一键去除图片水印,网页/电脑/手机版通用教程
人工智能
qq_3903695335 分钟前
2025年国内互联网发展总结
人工智能
2501_9269783335 分钟前
概率分形理论对 LLM 大模型结构与类智能涌现的统一解释--及优化应用的方法--指数级规模的效率和体积提升。
人工智能·经验分享·agi
吾在学习路1 小时前
SAMCT: Segment Any CT Allowing Labor-Free Task-Indicator Prompts
深度学习·计算机视觉