深入浅出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)
相关推荐
IT_陈寒1 小时前
Redis的持久化配置把我坑惨了:你以为数据安全了?
前端·人工智能·后端
miaowu3571 小时前
AI智能体推动数字化转型:从流程自动化到决策辅助的完整路线图
大数据·人工智能·自动化
阿里云大数据AI技术1 小时前
阿里云 Elasticsearch 日志采集与加工服务:让日志链路少一串组件,多一份稳定
人工智能·elasticsearch
ksueh1 小时前
AI写小说长篇创作中的上下文局限与外部记忆系统实践
人工智能
互联网江湖1 小时前
珞石机器人:向左科技股,向右零部件制造商?
大数据·人工智能
阿里云大数据AI技术2 小时前
从数据湖到多模态湖仓-基于阿里云EMR Serverless StarRocks与DLF Paimon构建AI时代的统一分析检索架构
人工智能
前端的阶梯2 小时前
浅谈Workflow和Agent的区别
人工智能
正在走向自律2 小时前
Deepseek V4 Flash 高效应用实战指南
人工智能·deepseek·deepseek v4·ai赋能中心
Xzaveir3 小时前
别把所有“认证”都塞进 AuthService:实名、一键登录与号码身份的领域拆分
android·人工智能
BerrySen1783 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
android·人工智能