深入浅出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)。这个函数仅当模型中有Dropout和BatchNorm时才会有影响。

复制代码
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)
相关推荐
柯南46683 分钟前
【AI工程师精讲】KV Cache 精讲:为什么 AI 越聊越慢,以及长上下文真正的成本在哪
人工智能·ai编程
QCoding6 分钟前
Spring AI Alibaba Graph实战:从ReAct Agent到Workflow,企业AI复杂流程该如何编排?
java·人工智能
小蒋观天下13 分钟前
端侧大模型在安防摄像头部署实操(上)|行业痛点、架构选型、落地思路解析
大数据·人工智能·安全·计算机视觉·ai大模型
hzxxxz34 分钟前
端到端测速数据采集实战:从节点部署到指标口径的完整链路
人工智能
林伽一36 分钟前
能力趋同、账单分化,技术选型正在从榜单转向负载|2026年10月06日
人工智能·科技·安全·ai
Jooolin42 分钟前
把 GitHub Issue 的第一轮脏活交给 AI:做一个 Issue 分诊助手
人工智能·github
具身AGI1 小时前
物理AI 空间理解:空间物理 信息的三条注入路线
人工智能·深度学习
飘尘1 小时前
从"算子"到"AI Infra":大模型背后看不见的那群人在忙什么
人工智能·算法·面试
AOI小白新手上路2 小时前
anomalib 缺陷检测复现笔记:从跑通库到 EfficientAD 落地
人工智能·笔记·机器学习
中伟视界2 小时前
危化罐区“双预警“方案解析:AI气体监测布控球+AI布控球,罐区作业怎么管?
人工智能