深入浅出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)
相关推荐
高洁015 小时前
多源数据融合:把零散信号拼成一致图景
人工智能·python·机器学习·transformer·迁移学习
美团技术团队5 小时前
从模仿到自我纠错:Keeta客服模型的RSI实践
人工智能
郝学胜-神的一滴5 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
星恒随风6 小时前
从0实现C++ AI大模型接入SDK(五):DeepSeekProvider的实现——策略模式、HTTP请求与SSE流式响应
linux·开发语言·c++·人工智能
yz_aiks7 小时前
Claude Code Skills 团队怎么共享:.claude/skills 提交 git 还是建私有插件市场(2.1.299 实测 5 个坑)
人工智能·ai编程·开发工具·团队协作·claude code
指掀涛澜天下惊7 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo
AAA修煤气灶刘哥7 小时前
GLM-5.4 到了什么水平?和 Kimi、DeepSeek、GPT 放在一起看
人工智能·llm
小虎AI生活8 小时前
朋友圈发了没人理?这个AI技能一句话甩你4个版本,做私域的都能用
人工智能·超级个体·青玥ai
龙腾AI白云8 小时前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
aimartec8 小时前
不动老旧 ERP 核心总账,如何以高性价比方案落地外勤与车间移动协同?
人工智能