深入浅出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)
相关推荐
Tbisnic几秒前
AI大模型学习第十二天:Coze工作流与智能体开发
人工智能·python·ai·大模型·智能体·coze
m0_737302582 分钟前
OpenClaw:从对话到执行,开启行动型 AI 智能体新时代
人工智能
X54先生(人文科技)6 分钟前
《元创力》纪实录·卷宗2.2署名权、龙标悖论与社会人格的剥夺
人工智能·开源·ai写作·零知识证明
上海全爱科技11 分钟前
80℃高温+多路4K解码实测报告-全爱科技后羿智盒QA500A2-B
人工智能
abcy07121312 分钟前
python Statsmodels实例详解
人工智能
sunshine88513 分钟前
ISO 27001与PCI-DSS认证:财务数据安全如何反哺业财一体化落地?
大数据·人工智能
金融RPA机器人丨实在智能17 分钟前
跨境库存Agent测评:开源产品无法动态备货?实在Agent以ISSUT技术重塑跨境电商供需链
人工智能·ai·开源
程序员佳佳18 分钟前
四个月长期实测:自建 Milvus、FAISS、原生向量 API 和向量引擎中转方案,到底怎么选?
人工智能·windows·python·gpt·milvus·faiss
kyle~25 分钟前
推理部署---CUDA 执行模型(SM、Block、Warp 与 SIMT)
人工智能·nvidia·cuda
淮南颂恩少儿编程C++26 分钟前
在淮南:编程信息学培训与 C++ 信奥赛:从 CSP 到 NOI 的进阶之路
人工智能·学习·青少年编程