深入浅出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)
相关推荐
Leiditech__几秒前
人工智能时代电子机器人静电问题及电路设计防范措施
人工智能·嵌入式硬件·机器人·硬件工程
谨慎谦虚42 分钟前
Trae 体验:探索被忽视的 Chat 模式
人工智能·trae
北极的树1 小时前
AI驱动的大前端开发工作流
人工智能
IT古董1 小时前
【漫话机器学习系列】100.L2 范数(L2 Norm,欧几里得范数)
人工智能·机器学习
小天努力学java1 小时前
【面试系列】Java开发--AI常见面试题
java·人工智能·面试
数造科技2 小时前
紧随“可信数据空间”政策风潮,数造科技正式加入开放数据空间联盟
大数据·人工智能·科技·安全·敏捷开发
@ V:ZwaitY092 小时前
如何打造TikTok矩阵:多账号管理与内容引流的高效策略
人工智能·矩阵·tiktok
lcw_lance2 小时前
人工智能(AI)的不同维度分类
人工智能·分类·数据挖掘
夏莉莉iy2 小时前
[MDM 2024]Spatial-Temporal Large Language Model for Traffic Prediction
人工智能·笔记·深度学习·机器学习·语言模型·自然语言处理·transformer
程序员古德2 小时前
《论软件的可靠性评价》审题技巧 - 系统架构设计师
人工智能·软件可靠性评价·考点概述·审题过程·可靠性模型·应用分析