深入浅出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)
相关推荐
m0_734571761 小时前
深入理解人工智能 chatGPT的软件架构
人工智能
飞塔老梅子1 小时前
09. Codex 节省Token ❀ 老梅子学AI
人工智能·ai·token·模型·codex
HyperAI超神经2 小时前
扰动实验+迁移学习,MIT团队推出IRIS,用「指纹」重建单细胞信号传导历史
人工智能·深度学习·机器学习·迁移学习
前沿在线2 小时前
启元机器人亮相外滩大会,探索个人机器人健康服务新场景
人工智能·ai·大模型
haishikeji696_2 小时前
现成无人机管理系统源码|支持私有化部署、二次开发、政企投标、自动机库对接
人工智能·无人机·低空经济·无人机管理系统·飞控管理系统
汇智信科2 小时前
煤矿视频智能分析系统:基于 AI 视觉实现井下安全隐患实时监测与闭环管控
人工智能
h78813942 小时前
录音容易纪要难?录音转文字 + AI 纪要实测,提升会议效率
人工智能·powerpoint
涛思数据(TDengine)2 小时前
从“极速算“到“知识沉淀“:工业 AI 实战直播(十三、十四期)
人工智能·时序数据库·tdengine·工业互联网·工业ai
Summer-Bright2 小时前
深度 | OpenAI 联合三星造芯:从模型层向底层算力延伸,AI 算力供应链开始重新洗牌
人工智能·ai·openai·芯片