深入浅出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服务老曹2 分钟前
模型版本管理完整流程:景区文旅项目从0到1怎么做
大数据·人工智能
冬奇Lab3 分钟前
Code Agent 解剖(21):从零扩展——接入新的 LLM Provider
人工智能
那个松鼠很眼熟w5 分钟前
4.Spring-Ai入门案例
java·人工智能·spring
巫山老妖9 分钟前
讲不清楚,是因为你还没想清楚
人工智能·程序员
职场的momo14 分钟前
字节生活服务海量内推,挑战亿级订单与AI交易中台
人工智能·程序人生·面试·职场和发展·跳槽·生活·业界资讯
Dawson Zhu14 分钟前
知识图谱与 Palantir Ontology:同一套「实体—关系」表象下,两种截然不同的工程范式
人工智能·语言模型·架构·aigc·agi
YOLO数据集集合28 分钟前
无人机高分辨率多树种单木分割数据集 | 单木分割 无人机林业 树种识别 实例分割 点云 遥感数据集 深度学习 精准林业9047期
人工智能·深度学习·数据集·无人机·遥感数据集·点云数据集·树木分割
科技看点30 分钟前
小机身里的Windows+AI,Windows原生OpenClaw离线AI盒子实测
人工智能
GEO实战经验分享32 分钟前
跨平台GEO度量框架:从多源数据整合到效果评估的系统化指南
人工智能
2601_9668631939 分钟前
扩音器哪个牌子性价比高?哪个牌子适合教师?开学季扩音器推荐
人工智能