深入浅出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)
相关推荐
Zzj_tju2 分钟前
大语言模型技术指南:Transformer 为什么能成为基础架构?核心模块与参数怎么理解
人工智能·语言模型·transformer
gorgeous(๑>؂<๑)9 分钟前
【CVPR26-韩国科学技术院】令牌扭曲技术助力多模态大语言模型从邻近视角观察场景
人工智能·语言模型·自然语言处理
AC赳赳老秦23 分钟前
OpenClaw email技能:批量发送邮件、自动回复,高效处理工作邮件
运维·人工智能·python·django·自动化·deepseek·openclaw
用户78245208077942 分钟前
一些容易混淆的点(个人记录)
人工智能
胡志辉44 分钟前
OpenClaw 教程:新 Mac 从 0 配到国产 AI、飞书微信和无人值守
人工智能·神经网络
机器之心1 小时前
全球第一,13个SOTA!我们找到了龙虾界掌管GUI的神
人工智能·openai
AI问答工程师1 小时前
Meta Muse Spark 的"思维压缩"到底是什么?我用 Python 复现了核心思路(附代码)
人工智能·python
机器之心1 小时前
大佬深度解析:Coding Agent的底层运行逻辑是什么?
人工智能·openai
爱吃的小肥羊1 小时前
Claude降智再被实锤!推理能力严重下滑,用户连夜跑路 Codex
人工智能·aigc·openai
Rabbit_QL1 小时前
【理论分析】信息熵的极值问题:什么时候最小?什么时候最大?
人工智能·深度学习