深入浅出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不是事38 分钟前
用IndexedDB做AI对话离线缓存实战
人工智能
Asize1 小时前
多模态生图:从 Vite 工程化到前端调用 Qwen Image
javascript·人工智能·后端
MobotStone1 小时前
AI项目越多,为什么越容易失控
人工智能·aigc
十有八七1 小时前
AI时代的置身X内
前端·人工智能
Lkstar1 小时前
A2A协议深度解析|Agent2Agent通信标准,智能体互联网的"HTTP"
人工智能·llm
百度Geek说1 小时前
当代码越来越便宜,什么在变贵?
人工智能
橘子星1 小时前
LLM 无状态架构实践:从原理到代码落地
前端·javascript·人工智能
召钱熏2 小时前
裸聊可用 ≠ 工作流可用:Gemma4 12B 接入 Claude Code 的真实踩坑复盘
人工智能
黄敬峰2 小时前
从 Token 到向量:手把手带你通过代码读懂大模型(LLM)的“黑盒”原理
人工智能
魏祖潇2 小时前
别问哪个 AI 工具最好——我换了一圈才想明白的几件事
人工智能