深入浅出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)
相关推荐
Blossom.11822 分钟前
AI Agent智能办公助手:从ChatGPT到真正“干活“的系统
人工智能·分布式·python·深度学习·神经网络·chatgpt·迁移学习
应用市场23 分钟前
Adam优化器深度解析:从数学原理到PyTorch源码实
人工智能·pytorch·python
a努力。25 分钟前
2026 AI 编程终极套装:Claude Code + Codex + Gemini CLI + Antigravity,四位一体实战指南!
java·开发语言·人工智能·分布式·python·面试
qwerasda12385226 分钟前
基于cornernet_hourglass104的纸杯检测与识别模型训练与优化详解
人工智能·计算机视觉·目标跟踪
抠头专注python环境配置39 分钟前
解决“No module named ‘tensorflow‘”报错:从导入失败到环境配置成功
人工智能·windows·python·tensorflow·neo4j
好奇龙猫1 小时前
【AI学习-comfyUI学习-三十六节-黑森林-融合+扩图工作流-各个部分学习】
人工智能·学习
卡尔AI工坊1 小时前
Andrej Karpathy:过去一年大模型的六个关键转折
人工智能·经验分享·深度学习·机器学习·ai编程
:mnong1 小时前
通过手写识别数字可视化学习卷积神经网络原理
人工智能·学习·cnn
俊哥V2 小时前
[本周看点]AI算力扩张的“隐形瓶颈”——电网接入为何成为最大制约?
人工智能·ai
X54先生(人文科技)2 小时前
碳硅协同对位法:从对抗博弈到共生协奏的元协议
人工智能·架构·零知识证明