深入浅出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)
相关推荐
Mike_666几秒前
摩尔线程AB100安装torch环境
人工智能·深度学习·ffmpeg·aarch64·摩尔线程·musa
无心水几秒前
【Hermes:进阶调优与性能优化】41、模型选择策略:OpenRouter 多模型切换与成本优化
人工智能·性能优化·mcp协议·openclaw·养龙虾·hermes·honcho
子午2 分钟前
道路车辆检测与计数系统~Python+YOLOV8算法+深度学习+人工智能+Web可视化界面
人工智能·python·yolo
周有贵4 分钟前
AI视角下广电转型新探索:GEO技术与金鹰卡通初步接洽,解锁传媒AI融合新可能
大数据·人工智能·传媒
2601_9577867711 分钟前
AI 原生营销矩阵系统:底层安全架构与多模态内容生产技术实现
人工智能·矩阵·安全架构
沪漂阿龙11 分钟前
字节跳动大模型面试题深度拆解:项目深挖、SFT 与 RLHF、Claude Code、记忆机制、并发锁与手撕题全攻略
人工智能·面试
Jurio.18 分钟前
当 AI 不再只是对话:Codex app 的自动化功能
运维·人工智能·ai·自动化·codex
财经资讯数据_灵砚智能26 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月14日
人工智能·python·信息可视化·自然语言处理·ai编程
跨境卫士—小依26 分钟前
低值包裹全面计税之后跨境卖家如何重做小额订单承接逻辑
大数据·人工智能·跨境电商·亚马逊·营销策略
沪漂阿龙31 分钟前
AI大模型面试题:大模型训练优化全解析——AdamW、Warmup、Annealing、Scaling Law、SFT、RLHF、拒绝采样、PPO 一文讲透
人工智能