深入浅出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)
相关推荐
yosoar5 小时前
蔡司工业显微镜扫描电镜软件解决方案与材料应用
人工智能·扫描电子显微镜·昆山友硕·蔡司扫描电镜
Leo.yuan5 小时前
流批一体数据开发平台选型:除了Flink和Spark,还有哪些选择?
大数据·人工智能
浪兎兎5 小时前
【机器学习】朴素贝叶斯 贝叶斯回归
人工智能·机器学习·回归
乱世刀疤5 小时前
Claude Code提高工作效率案例:将视频培训转化为文本资料
人工智能·claude code
xcs194055 小时前
新版 IDEA(尤其是 2024/2025/2026)越来越臃肿
前端·人工智能·intellij-idea
万联WANFLOW5 小时前
AI Agent 落地新里程碑:Claude in Chrome 全面上线与安全架构解析
人工智能·chrome·安全架构
云边有话5 小时前
无锡芯健细胞:法国鹰演扫描的风险排查图谱
人工智能·精选
2601_950760795 小时前
聚焦 GUCY2C 受体:从肠道生理到结直肠癌免疫靶点及工具蛋白价值
人工智能·蛋白
会博通·代码搬运工5 小时前
双层PDF技术实现与档案数字化系统的API集成实践
数据库·人工智能·分布式·python·计算机视觉·api集成