深入浅出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)
相关推荐
miaowu3571 分钟前
企业 AI 智能体实施周期短吗?各阶段费用明细
人工智能
Xiaok10184 分钟前
NumPy 数组 vs PyTorch Tensor
人工智能·pytorch·numpy
卡梅德生物科技小能手13 分钟前
卡梅德生物科普 TSLP
经验分享·深度学习·生活
一只小菜鸡..16 分钟前
南京大学 操作系统 (JYY) 学习笔记:CPU 的局限、GPU 与 AI 时代的算力革命
人工智能·笔记·学习
AI创界者30 分钟前
开源硬核LTX-Video 本地部署整合包教程:超低显存生成高清AI视频,告别云端排队!
人工智能·aigc·音视频
Bruce_Liuxiaowei39 分钟前
当AI以可验证的方式攻克数学难题——它如何重写了“科研“的成本与门槛
人工智能·智能体
deepseek2344 分钟前
MiniMax H3 全模态模型拆解:2K 视频成本被腰斩背后,H3-VAE 和 In-context Regeneration 做了什么
人工智能·多模态·视频生成
智道天成1 小时前
杭州智道天成信息科技有限公司:助力浙江企业合规高效落地
大数据·人工智能·科技
董员外1 小时前
RAG 系统进化论(五):Corrective RAG 与 Self-RAG,让系统发现并纠正错误
人工智能·后端·设计模式
MistyStar1 小时前
Fast 模式为什么更快也更贵:从 Prefill/Decode 到 Batch 经济学
人工智能