深入浅出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)
相关推荐
TechEdu2026069 分钟前
[人工智能]AI芯片家族与产品目录指南
人工智能·ai
不会写代码的女程序猿9 分钟前
中小康养门店选型参考|明理 AI 四诊仪场景适配与投入回报分析
大数据·人工智能·科技·ai·健康医疗
机器人猎头David14 分钟前
VLA、世界模型、强化学习,在机器人里分别解决什么问题?
人工智能·机器人·机器人猎头·机器人猎头公司
dianziyao_15 分钟前
第 4.1 篇:让 Codex 理解你的双链——AI 辅助发现笔记间的关联
人工智能·笔记
围炉聊科技16 分钟前
网站把自己变成 MCP server:OpenAI 第一个用上 WebMCP
人工智能
葡萄城技术团队25 分钟前
一句话生成数据透视表?SpreadJS AI 如何把分析需求变成行、列和值
人工智能
米小虾27 分钟前
给 AI 生成的内容发一张身份证:C2PA 到底能证明什么,又证明不了什么
人工智能
芯片人00732 分钟前
纯硬件一键开关机ASIC芯片,为什么比 MCU 方案更适合更可靠
人工智能·单片机·嵌入式硬件·物联网·芯片
北岛贰1 小时前
迷茫焦虑期,我做了一个带支付带官网的 AI 聊天虚拟恋人 App
前端·人工智能·后端
冬奇Lab1 小时前
一天一个开源项目(第212篇):OpenMAIC —— 清华出品的多智能体交互式课堂
人工智能·开源·资讯