深入浅出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)
相关推荐
“AI国潮设计-小江”6 分钟前
【AIGC实战】Python+SDXL打造“潮汕英歌舞IP”万能立牌插件,批量生成“发财元宝蛋糕”视觉营销方案(附源码)
开发语言·人工智能·python·prompt·aigc
xsd2024111821 分钟前
Hy Image3.5:一张提示词,怎么撑起一整套品牌广告
人工智能
sbjdhjd30 分钟前
AI产业周度动态:从“更强模型”走向“可执行、可治理、可计价”的系统竞争 (2026年10月19日—10月25日)
人工智能·笔记·ai·开源·gemini·信息差·claude code
程序员cxuan33 分钟前
掀桌子了!Kimi K3.1 Pro 这效果也太离谱了。
人工智能·后端·程序员
AI技术新视界1 小时前
大模型推理延迟与吞吐量优化指南
人工智能·llm·推理引擎
武子康1 小时前
黑图、彩色噪声、NaN、偏色怎么排查
人工智能·后端·agent
hahaha60161 小时前
数字图像增强 & 锐化
人工智能
涤生大数据1 小时前
Doris Summit 2026 报名启动!议程全面公开,10 月 21-22 日敬请关注
人工智能
AICoder码农王2 小时前
如何写 Skill 第11课,实战工坊:痛点验出来,骨架偷出来
人工智能
feasibility.2 小时前
不装Claude Code,WorkBuddy也能做视频,Remotion skill告别抽卡(含安装与使用)
人工智能·aigc·音视频·agi·skill·remotion·workbuddy