深入浅出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)
相关推荐
般若-波罗蜜几秒前
MinerU高级用法,避坑指南(持续更新)
人工智能·python·语言模型·自然语言处理
安卓修改大师3 分钟前
安卓修改大师 vs MT管理器:反编译工具终极对决与全景解析
android·人工智能·机器翻译
A15362553 分钟前
国内好用的WMS仓储管理系统有哪些?万里牛WMS深度评测
大数据·数据库·人工智能
杀生丸学AI12 分钟前
【三维重建】ArtiFixer:自回归扩散增强与扩展3DGS(NVIDIA)
人工智能·3d·数据挖掘·aigc·三维重建·扩散模型·视觉大模型
爱勇宝29 分钟前
DeepSeek实习生日薪5500:真正恐怖的不是工资
人工智能·深度学习·面试
Feisy30 分钟前
出口锂电池-无人机等危险品的拍摄多张外包装申报照片的落地方案
深度学习·手机自动拍照·照片采集·电池外观拍摄·出口电池
ShareCreators37 分钟前
在华企业如何填补AI人才缺口数据基建:Share Creators 如何以 AI 驱动的数字资产管理重塑工业研发效能从人
人工智能·汽车·blueberry
中微极客37 分钟前
LangChain vs LlamaIndex:RAG框架选型深度对比
人工智能·langchain
糖果店的幽灵1 小时前
【langgraph 从入门到精通】全面实践项目:智能客服工单系统
人工智能·langgraph
卡卡罗特学AI1 小时前
曾经人手一个的Superpowers,为什么现在都在卸
人工智能·程序员