深入浅出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)
相关推荐
小婉5 分钟前
我用 Next.js + React Flow 从零搭建了一个可视化 AI 工作流编排平台
前端·人工智能·node.js
AI行业说6 分钟前
誉财自动化YC-18-M8045怎么选?2026中小服装工厂模板机选型指南
人工智能·机器人·自动化
Waiky10 分钟前
给 AI Agents 一双「眼睛」:CrawlEyes 开源了
人工智能
甲维斯35 分钟前
美版豆包又更新了!Gemini 3.8Flash是真Flash!
人工智能
云智慧AIOps社区36 分钟前
2026年智能巡检机器人行业格局:三类厂商阵营、选型维度与产品推荐
运维·人工智能·机器人·巡检机器人
微三云 - 廖会灵 (私域系统开发)36 分钟前
重资产的突围:当酒店遇上 RWA,用服务权益数字化重构产业供需关系
人工智能·重构
阿里云大数据AI技术40 分钟前
从“找得到”到“找得准”:用 Hologres 构建智能达人圈选系统
大数据·人工智能
2601_967659881 小时前
艾雨文承推出大头阿亮第五代智能养老机器人机构版,助力养老机构智慧巡护升级
人工智能·机器人
智兆APS1 小时前
价值测算与效益验证:缝制APS智能排产可量化收益评估、风险预判与价值闭环体系
人工智能·服装行业aps·缝制行业aps·包箱行业aps·鞋帽袜子行业aps
村口徐大爷1 小时前
电商新媒体通用!Lingko AI全套视觉素材自动化量产落地实操教程
人工智能·ai·ai工具·电商运营·lingnko ai