深入浅出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)
相关推荐
明志数科2 小时前
具身智能数据工程观察:“数据筑基“时代的数据底座建设路径
人工智能·机器人
m0_614523553 小时前
普通视频怎么做多场景一镜到底:路线设计、逐段衔接与整体验收
人工智能·音视频
海宇服务3 小时前
零信任架构实战:基于海宇对外投资历史查询服务构建自动化供应商准入网关
运维·人工智能·架构·自动化
东风破_3 小时前
别急着上 Agentic RAG:先用 LangGraph 把最小 RAG 跑明白
人工智能
LaughingZhu4 小时前
Product Hunt 每日热榜 | 2026-09-12
人工智能·深度学习·神经网络·搜索引擎·百度
天真小巫4 小时前
2026.9.13总结(工作量日益繁重的当下,AI如何提效)
人工智能
Zguigo4 小时前
【CUDA1】GPUvsCPU,CUDA Kernel
人工智能·pytorch·深度学习
thesky1234564 小时前
用 ONNX Runtime 把 PyTorch 模型变成跨平台极速推理引擎:导出、优化、量化完整实
人工智能·深度学习·模型部署
米小虾4 小时前
把 KV Cache 从 3514 字节压到 890 字节:DeepSeek V4.1-Flash 动了什么,又没动什么
人工智能
锋行天下4 小时前
LangGraph 进阶:Command + Send 动态控制流、并行 Map-Reduce 实战与踩坑
人工智能