深入浅出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)
相关推荐
MobotStone1 分钟前
生成代码一分钟,填坑一小时?问题不在 AI,而在用法
人工智能
ccice012 分钟前
硬核技术解析:运用Gemini多步推理链,攻克办公场景中的复杂决策与风险矩阵构建(国内免费镜像实操)
人工智能·线性代数·矩阵
2601_959477914 分钟前
Vatee:数字化能力升级的全面观察
大数据·人工智能
@蔓蔓喜欢你5 分钟前
Web Components:构建可复用组件的未来
人工智能·ai
JGHAI5 分钟前
GEO优化:AI搜索时代的底层逻辑重构与中小企业实践路径
人工智能
庚昀◟6 分钟前
ClaudeCode安装教程,基础使用、进阶推荐
人工智能·python·ai
Deep-w7 分钟前
【目标检测系统网页版】基于YOLOv8的淡水鱼检测系统
人工智能·yolo·目标检测
2501_931162437 分钟前
产业观察:AI民用化落地提速,优秘智能联合产业机构构建轻量化技术赋能体系
人工智能·ai技术·技术落地
赴山海bi8 分钟前
DeepBI赋能:家居类亚马逊Listing优化全攻略
大数据·人工智能
qq_3660327810 分钟前
Claude API中转怎么选?简易api下的国内接入与兼容 OpenAI 接口实践
大数据·运维·人工智能