深入浅出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)
相关推荐
麦豆GEO1 小时前
本地生活同城服务如何做好GEO优化
人工智能·生活
邂逅and回眸1 小时前
具身智能入门:机器人是怎么学会干活的
人工智能·机器人
阿里云大数据AI技术2 小时前
SENSER识季 × 阿里云OpenSearch:从时尚灵感到自我表达
人工智能
the3clipse2 小时前
Windows 11 26H2 AI 功能使用指南:回顾、单击以执行与实时字幕
人工智能·windows·copilot+ pc·recall 回顾·单击以执行·实时字幕翻译·windows studio
OpenPie丨拓数派3 小时前
拓数派以产品化FDE基座赋能某世界500强医疗科技企业,打造基于本体论的DRG检验医保合规AI原生服务
人工智能
阿里云大数据AI技术3 小时前
Hologres 数据沙箱:让 AI 在隔离环境中安全探索和验证
人工智能
程序员cxuan4 小时前
Running Hub 上线 Motion
人工智能·aigc
高洁014 小时前
具身智能的人机协作与物理空间安全
人工智能·python·深度学习·机器学习·django
赛博山人4 小时前
Sand.ai发布MAGI-2视频模型
人工智能·音视频
橙序员小站5 小时前
下次放假还有几天?AI开发微信小程序复盘
人工智能·微信小程序