深入浅出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)
相关推荐
shengjk130 分钟前
AI最大的讽刺:你以为它能结束996,资本却可能用它开启997
人工智能
fanstuck42 分钟前
AI 回答得头头是道,怎么一查原文,条号就对不上了?
人工智能·aigc·agent
硅谷秋水1 小时前
BAAI的PhysCapBench分析
人工智能·机器学习·机器人
Dawson Zhu1 小时前
【多平台适配③】Ascend NPU昇腾适配:CANN软件栈与算子迁移实战
人工智能·语言模型·架构·aigc·agi
民乐团扒谱机1 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
SelectDB1 小时前
数据湖的数据怎么直接查?Apache Doris 免搬运查询 Iceberg、Paimon、Lance 与 AI 检索实战
人工智能
星恒随风2 小时前
从0实现C++ AI大模型接入SDK(四):大模型API接入、公共数据结构设计与日志库封装
linux·服务器·数据结构·c++·人工智能
SelectDB2 小时前
网易云音乐基于 Apache Doris 的 AI 数据统一查询与治理实践
人工智能
火山引擎开发者社区3 小时前
一个向量库,两种检索:VikingDB 关键词检索实践
人工智能
火山引擎开发者社区3 小时前
火山引擎携手南开大学:两个 AI 智能体,让美学研究走进日常对话
人工智能