深入浅出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)
相关推荐
库拉大叔4 分钟前
从 0 到 1 做一部 AI 漫剧,知漫剧完整制作流程
人工智能·aigc
Omics Pro4 分钟前
之江实验室NAR|虚拟细胞3阶段训练范式
数据库·人工智能·算法·机器学习·自然语言处理
Thomas.Sir7 分钟前
第26课:工业零部件外观缺陷检测系统:从学术Demo到产线工程的重构实战
pytorch·ai
AIGC小尼17 分钟前
8G 显存零基础本地部署 AI 漫剧全流程|ComfyUI+Wan2.2+FFmpeg 离线成片完整方案(含代码 / 指令 / 排坑)
人工智能·ffmpeg·php·comfyui·ai漫剧
悟天特斯18 分钟前
AI驱动的楼宇节能:从“经验省电“到“算法能效“的进化之路
人工智能·物联网
破无差19 分钟前
人工智能训练师(三级)理论知识复习题-KimiK3的参考答案
人工智能
网络毒刘22 分钟前
AtomGit Actions + AI 评审草稿:PR 描述自动生成与安全敏感词门禁示例
人工智能·安全
ai_xiaogui22 分钟前
PanelAI 1.1.1重磅更新:秒级安装脚本优化 + 无公网IP算力节点组网,私有化AI管理平台全面升级
人工智能·网络协议·tcp/ip·api聚合管理·开发者ai一键部署·ai底层架构解析·ai应用快速变现
wflynn26 分钟前
语言判别增强多语言语音模型的语言学习能力
人工智能·ai
neocheng_52227 分钟前
自学、培训、项目还是认证?HR 学习 AI 的四种路径如何组合
人工智能