深入浅出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)
相关推荐
Jiamiren8 小时前
WEEX:长鑫科技上市大涨,宇树科技合约同步走高,传统资产交易迎来新路径
人工智能·科技·区块链
海兰9 小时前
mcporter — 安装部署及使用完全指南(二)
人工智能·agent
一拳不是超人9 小时前
LangChain 们的丧钟?DeepSeek 把 Agent 开发变成了拼乐高
人工智能·agent
麻雀飞吧9 小时前
零基础选量化工具,先把问题说清楚
人工智能·python
向成科技9 小时前
新品亮相|向成电子IPCA_3588H AI边缘网关重磅发布,算力下沉,自主可控
人工智能·边缘计算·国产化·硬件·边缘网关·主板·端侧ai
段一凡-华北理工大学9 小时前
AI推动工业智能化转型~系列文章20:工业 AI 平台架构:云-边-端协同的技术体系
人工智能·python·架构·工业平台·云-边协同
IT_陈寒9 小时前
Python线程池吞了异常还不告诉我,这谁顶得住啊
前端·人工智能·后端
CodeBlog-star9 小时前
Harness Engineering:Pi Agent 架构深度解析
人工智能·python·架构·harness工程
chen_zn959 小时前
《VLA 系列》Human-to-Robot Transfer | 人类视频共训练 | 跨本体涌现迁移 | 论文解析
人工智能·深度学习·transformer·具身智能·vla
CCC:CarCrazeCurator9 小时前
DeepSeek‑Harness Windows 本地快速上手
深度学习·数据挖掘