深入浅出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)
相关推荐
cdut_suye6 分钟前
【Linux系统】从 C 语言文件操作到系统调用的核心原理
java·linux·数据结构·c++·人工智能·机器学习·云计算
梁下轻语的秋缘21 分钟前
前馈神经网络回归(ANN Regression)从原理到实战
人工智能·神经网络·回归
xu_wenming31 分钟前
华为Watch的ECG功能技术分析
人工智能·嵌入式硬件·算法
不吃香菜葱的程序猿42 分钟前
《Adversarial Sticker: A Stealthy Attack Method in the Physical World》论文分享(侵删)
深度学习·计算机视觉
meisongqing43 分钟前
【软件工程】机器学习多缺陷定位技术分析
人工智能·机器学习·软件工程·缺陷定位
高工智能汽车1 小时前
大模型浪潮下,黑芝麻智能高性能芯片助力汽车辅助驾驶变革
人工智能·汽车
带娃的IT创业者1 小时前
《AI大模型应知应会100篇》第62篇:TypeChat——类型安全的大模型编程框架
人工智能·安全
补三补四1 小时前
随机森林(Random Forest)
人工智能·科技·算法·随机森林·机器学习
dundunmm1 小时前
【每天一个知识点】Dip 检验(Dip test)
人工智能·机器学习
侃山2 小时前
pytorch nn.RNN demo
pytorch·rnn·深度学习