深入浅出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)
相关推荐
kaixin_啊啊1 分钟前
Micam 多容器太吃资源?用 Go2RTC + EasyNVR 给小米摄像头换一套轻量本地录像方案
图像处理·人工智能·摄像头
具身AGI4 分钟前
具身ICL走热,物理AI 自主学习能力 多一条轴
人工智能
雾屿_Mistisle5 分钟前
本地 AI 工作台的 Agent 化改造:从聊天转发到 22 个工具
人工智能
水如烟7 分钟前
孤能子视角:蓝星文明篇·异——正当性叙事的裂缝:负续指的聚合与相变
人工智能
美狐美颜SDK开放平台14 分钟前
直播APP源码与视频美颜sdk如何配合?一套完整开发思路
android·人工智能·计算机视觉·音视频·直播美颜sdk
不会写代码的女程序猿16 分钟前
商用 AI 四诊仪技术拆解|明理 AI 四诊仪多模态采集方案解析
大数据·人工智能·科技·ai·健康医疗
IT_陈寒26 分钟前
Redis大key删除引发的服务雪崩,这次我真记住了
前端·人工智能·后端
正经教主29 分钟前
【FDE系列】阶段2:Day 47:对接企业系统 — 飞书 / 钉钉 API
人工智能·docker·fde
Dawson Zhu36 分钟前
从 Jev 说起:快慢模型如何协同调度,以及这背后需要解决什么问题
人工智能·语言模型·架构·aigc·agi
小陈phd38 分钟前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法