深入浅出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)
相关推荐
2603_955279708 小时前
凝视与遗忘:AI如何定义记忆
人工智能
MartinYeung59 小时前
[论文学习] CAMIA:下文感知成员推理攻击
人工智能·深度学习·学习
IT_陈寒9 小时前
Python多线程的坑,我居然现在才踩到
前端·人工智能·后端
直接冲冲冲9 小时前
59-VGG
深度学习·神经网络·cnn
云边云科技_云网融合9 小时前
零信任安全:数字化时代的企业防护新范式
人工智能·安全·ai
万岳科技系统开发9 小时前
外卖跑腿配送系统如何借助AI提升配送效率?
大数据·人工智能·机器学习
thinking_talk9 小时前
腾讯云AI Agent安全中心综合评测
人工智能·安全·腾讯云
阿拉雷️9 小时前
Prompt工程设计实践:从基础模板到场景化策略
人工智能·语言模型·prompt
Kel10 小时前
MCP 传输链路全链路拆解:从字节流到协议栈的四层架构之旅
人工智能·设计模式·架构
2601_9628517410 小时前
计算机毕业设计之基于大数据的企业财务数据分析系统
大数据·人工智能·深度学习·信息可视化·课程设计