深入浅出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)
相关推荐
生成论实验室16 小时前
《事件关系阴阳博弈动力学:识势应势之道》第八篇:认知与反思关系——探索、定位与延续
人工智能·算法·架构·知识图谱·创业创新
大树8816 小时前
液冷从“电老虎“变“热银行“:算力废热如何变成真金白银?
人工智能
E等于MC平方16 小时前
用 Next.js + Prisma + Gemini 打造 AI 替代风险追踪平台
人工智能·ai·职业·岗位·失业·替代
段一凡-华北理工大学16 小时前
【高炉炼铁领域炉温监测、预警、调控智能体设计与应用】~系列文章10:实时预警机制:跑在问题前面!
网络·人工智能·python·知识图谱·高炉炼铁·工业智能体
β添砖java16 小时前
深度学习(20)深度卷积神经网络AlexNet
人工智能·深度学习·cnn
weixin_4080996716 小时前
身份证OCR识别如何做到99.9%准确率?揭秘石榴智能六大核心技术(矫正/完整度/翻拍检测/头像提取)
图像处理·人工智能·ocr·api接口·身份证识别·石榴智能
林小卫很行16 小时前
Obsidian 入门39:怎么创建自己的 Skill?我把五步拆给你看
人工智能
Baihai_IDP16 小时前
为什么 AI Agent 重新爱上了文件系统(Filesystems)
人工智能·llm·agent
MATLAB代码顾问16 小时前
Transformer时序预测:PatchTST原理与PyTorch实现
pytorch·深度学习·transformer