深入浅出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)
相关推荐
Mininglamp_27187 小时前
MCP和A2A之后,机器人网络里还缺一层开放通信协议
人工智能·agent·多智能体·具身智能
angered7 小时前
「AI 应用 / AI Agent」行业日报 · 2026-09-08
人工智能·ai编程
wxl7812277 小时前
深度解析:无本体VLA/WLA模型选型、数据采集与家用机器人产业终局
人工智能
羞儿7 小时前
AI Agent理论提升与体系构建
人工智能·智能体
2601_962218617 小时前
万象生鲜系统订单全生命周期状态同步技术实现业务可视
大数据·数据库·人工智能·python·算法
南京兴帝文化传媒有限公司7 小时前
实体理疗店地图优化实操:关键词布局+AI问答如何带来新客翻倍增长
大数据·人工智能·geo 优化·geo优化避坑·ai搜索获客·宣城企业数字化
richard_yuu8 小时前
AOI 实战第五篇:c_broken 漏检严重,V4 迭代背后的权衡
开发语言·深度学习·yolo
腾视科技-AIoT8 小时前
超低功耗 性能卓越|腾视科技重磅推出TS-SG-SM9系列AI算力模组,引领边缘智能计算新篇章
人工智能·科技·ai·算力模组·ai算力模组·ai模组·腾视科技