深入浅出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)
相关推荐
新缸中之脑12 分钟前
为什么我选 Codex
人工智能
yumgpkpm14 分钟前
2026软件:白嫖,开源,外包,招标,晚进场(2025年下半年),数科,AI...中国的企业软件产业出路
大数据·人工智能·hadoop·算法·kafka·开源·cloudera
witAI20 分钟前
**AI漫剧制作工具2025推荐,零成本实现专业级动画创作*
人工智能·python
冬奇Lab25 分钟前
一天一个开源项目(第12篇):SoulX-Podcast - 多轮对话式播客生成,让AI语音更自然真实
人工智能·开源
风栖柳白杨31 分钟前
【语音识别】一些音频的使用方法
人工智能·音视频·语音识别
xixixi7777731 分钟前
今日 AI 、通信、安全行业前沿日报(2026 年 2 月 4 日,星期三)
大数据·人工智能·安全·ai·大模型·通信·卫星通信
LucDelton36 分钟前
模型微调思路
人工智能·深度学习·机器学习
寻道码路36 分钟前
【GitHub开源AI精选】WhisperX:70倍实时语音转录、革命性词级时间戳与多说话人分离技术
人工智能·开源·github
小王不爱笑1321 小时前
LangChain4J 整合多 AI 模型核心实现步骤
java·人工智能·spring boot
码农三叔1 小时前
(9-3)电源管理与能源系统:充电与扩展能源方案
人工智能·嵌入式硬件·机器人·能源·人形机器人