深入浅出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)
相关推荐
ACP广源盛139246256731 分钟前
M6/M5 Pro Mac mini 端侧 AI 新形态@ACP#GSV5800 Serdes 长距离视频传输在 AI 服务中的机会与落地场景
大数据·网络·数据库·人工智能·嵌入式硬件·macos·音视频
xian_wwq10 分钟前
【学习笔记】深度认知系列-第14讲 端侧AI崛起——为什么AI正在从云端走向本地
人工智能·笔记·学习
火山引擎开发者社区12 分钟前
火山引擎 Milvus Vector Lakebase 正式公测
人工智能
ocean210319 分钟前
2025-2026年AI部署与MLOps大厂面试高频问题
人工智能·面试·大模型推理·ai部署
嘿嘿-6633 分钟前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
冬奇Lab42 分钟前
Code Agent 解剖(22):从零扩展——用 Markdown 写一个 Skill
人工智能
小饕44 分钟前
llama.cpp 参数调优指南:Jetson 8GB 实战手记
人工智能·llama·大模型端侧部署
火山引擎开发者社区44 分钟前
Viking AI 搜索 × SearchCLI:搭建售后助手,让搜索能力参与售后回答
人工智能
冬奇Lab44 分钟前
一天一个开源项目(第210篇):herdr - AI 编程 Agent 的运行时底座
人工智能·开源·资讯
dadanhuang1 小时前
PyTorch深度学习与实践【04】【迭代周期、autograd、构建计算图、*params参数解包、.grad属性】
人工智能·pytorch·深度学习