深入浅出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)
相关推荐
领麦微红外3 分钟前
红外热电堆测温传感器:养生壶下的智能化控温
人工智能·产品经理·智能硬件
网络工程小王7 分钟前
【LLM开发实验】LLM推理基本介绍
人工智能·量化·推理
Bruce_Liuxiaowei12 分钟前
机器人的自由意志:约翰·麦卡锡《Free Will—Even for Robots》论文解读
人工智能·ai
阿里云大数据AI技术17 分钟前
使用 PAI ,一行命令跑起来云端 DeepSeek Agent
人工智能·agent·deepseek
hangzhouhuanyu19 分钟前
从培训到创业:AI工具在数字经济中的落地路径与避坑指南
大数据·人工智能
Lalolander21 分钟前
WorkBuddy App 怎么发起任务?输入栏与发送全流程
大数据·人工智能·金蝶erp·workbuddy
集芯微电科技有限公司25 分钟前
700V/17A高频开关低导通阻GaN HEMT驱动器适用于快充,LLC,PFC功率校正
人工智能·嵌入式硬件·深度学习·神经网络·机器学习·生成对抗网络·计算机外设
qq_252941316827 分钟前
窗户清洁检测数据集 | 窗户清洁检测 建筑运维 二分类任务 YOLO格式 深度学习数据集9019期
运维·人工智能·深度学习·yolo·目标检测·分类·窗户清晰度
落魄实习生30 分钟前
Spring AI Alibaba入门-生态集成
java·人工智能·spring
YOLO数据集集合30 分钟前
尼帕果实目标检测数据集 | 尼帕果实检测 农业视觉 热带作物 目标检测 YOLO格式9013期
人工智能·yolo·目标检测·机器学习·计算机视觉·农业果实