深入浅出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)
相关推荐
腾讯云开发者25 分钟前
腾讯云TVP走进美的,共探智能制造新范式
人工智能
一水鉴天26 分钟前
整体设计 逻辑系统程序 之34七层网络的中台架构设计及链路对应讨论(含 CFR 规则与理 / 事代理界定)
人工智能·算法·公共逻辑
我星期八休息32 分钟前
C++智能指针全面解析:原理、使用场景与最佳实践
java·大数据·开发语言·jvm·c++·人工智能·python
ECT-OS-JiuHuaShan37 分钟前
《元推理框架技术白皮书》,人工智能领域的“杂交水稻“
人工智能·aigc·学习方法·量子计算·空间计算
minhuan41 分钟前
构建AI智能体:六十八、集成学习:从三个臭皮匠到AI集体智慧的深度解析
人工智能·机器学习·adaboost·集成学习·bagging
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - 循环神经网络(SimpleRNN)示例
python·深度学习·tensorflow·tensorflow2
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - 通俗理解池化层,卷积层以及全连接层
python·深度学习·tensorflow·tensorflow2
ssshooter1 小时前
MCP 服务 Streamable HTTP 和 SSE 的区别
人工智能·面试·程序员
rengang661 小时前
软件工程新纪元:AI协同编程架构师的修养与使命
人工智能·软件工程·ai编程·ai协同编程架构师
IT_陈寒1 小时前
Python+AI实战:用LangChain构建智能问答系统的5个核心技巧
前端·人工智能·后端