深入浅出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)
相关推荐
时序之心几秒前
ICLR 2026两篇时间序列论文新思路:都用Patch作为建模基础单元
人工智能·iclr·时间序列
天天进步20152 分钟前
实时通信的艺术:OpenWork 中 SSE 与事件流驱动的 UI 交互实现
人工智能
AI_paid_community5 分钟前
我花了一晚上把 Claude Code 彻底"薅羊毛"了——free-claude-code 项目深度实测
人工智能·claude
猫头虎7 分钟前
如何搭建 24 小时 AI 直播平台:魔珐星云数字人打造无人值守 “AI 销冠” 全流程实战教程
人工智能·langchain·开源·prompt·aigc·embedding·agi
zandy10118 分钟前
HENGSHI SENSE 6.2 架构全景解析:Data Agent、指标引擎与Headless语义层的工程实现
大数据·人工智能·架构
经济元宇宙10 分钟前
全场景 AI 智能交互 专业级语音机器人推荐什么?
人工智能·机器人·语音识别
我是发哥哈19 分钟前
主流AI框架生产环境性能对比:5大关键维度深度评测
大数据·人工智能·学习·机器学习·ai·chatgpt·ai-native
隔壁大炮19 分钟前
Day07-RNN介绍
人工智能·pytorch·rnn·深度学习·神经网络·算法·numpy
羑悻的小杀马特25 分钟前
零成本搞定!异地访问 OpenClaw 最简方案:SSH 端口映射组网!
运维·服务器·人工智能·docker·自动化·ssh·openclaw
雷帝木木26 分钟前
Python 并发编程的高级技巧与性能优化
人工智能·python·深度学习·机器学习