深入浅出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)。这个函数仅当模型中有Dropout和BatchNorm时才会有影响。

复制代码
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)
相关推荐
Flynn Liang7 小时前
RAG 检索性能提升:Redis 向量 + 全文 + 元数据过滤的混合检索实战
数据库·人工智能·redis·缓存·rag·ai agent·智能体
人人都是软件工程师7 小时前
前端接了 Agent,为什么还是满屏自定义代码?读懂 AG-UI 的 31 个事件
人工智能·github
掘金安东尼7 小时前
Claude 证明黎曼猜想了吗:1700 万行 Lean 代码、社区认证与数学界的保留
人工智能
延晗7 小时前
【从零开始 DeepSeek Harness 插件开发教程】三、从零开发 DeepSeek Harness 插件——完成第一个插件的挂载与运行
前端·人工智能
马吉哲7 小时前
《不会触发器也能改魔兽地图:用 AI 把“加个离谱英雄”翻译成 WE 能听懂的话》
人工智能
程序员cxuan8 小时前
上海团队开源了首个国产记忆模型,554B!这也太狠了
人工智能·后端·程序员
普密斯科技8 小时前
倾斜安装长工作距离:14X变倍镜头用于激光开封芯片腔体观测案例
人工智能·数码相机·计算机视觉
VIP_CQCRE8 小时前
GPT Image 2.6 动态表情交付别只发预览:GIF 文件校验、哈希清单与下载排错
图像处理·人工智能·python·gif
Sailing8 小时前
🤔🤔Dify 不必推倒重来,把重逻辑下沉到 LangGraph
人工智能·langchain·agent