深入浅出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)
相关推荐
一个被程序员耽误的厨师12 分钟前
04-实践篇-让AI生成可视化页面-ai-json-ui的落地实践
人工智能·ui·json
SilentSamsara16 分钟前
向量数据库实战:Chroma/Milvus/Qdrant 选型与语义搜索应用
开发语言·数据库·人工智能·python·青少年编程·milvus
Tardis117 分钟前
【无标题】
人工智能
Hello数据集22 分钟前
医疗AI实战:如何利用免疫与内分泌系统疾病数据集训练高精度预测模型?
人工智能·机器学习·数据挖掘·医疗ai
雪碧聊技术24 分钟前
什么是AI辅助编程?一文详解
人工智能·ai辅助编程
m0_图灵灵28 分钟前
吴恩达《深度学习》之看懂 ResNet
人工智能·深度学习·学习笔记
AI客栈31 分钟前
AI 大模型网关架构:动态限频与负载均衡设计实战
人工智能
暗黑小白35 分钟前
第二篇:不碰模型,意图识别快 9 倍 —— P0→P1→P2 流水线设计
人工智能·架构·ai agent
happyprince39 分钟前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
花骨朵轻创42 分钟前
基于WeChatBot框架 API 封装的 Python SDK,提供简洁易用的接口调用方式
人工智能