深入浅出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)
相关推荐
minhuan28 分钟前
大模型应用:AI智能体高并发实战:Redis缓存+负载均衡协同解决推理超时难题.133
人工智能·redis·智能体推理缓存·智能体负载均衡·大模型集群应用
圣殿骑士-Khtangc1 小时前
Windsurf AI IDE 超详细使用教程:从安装到实战,一站式上手
人工智能·ai编程·编程助手·windsurf
dazzle1 小时前
机器学习算法原理与实践-入门(十一):基于PyTorch的房价预测实战
pytorch·算法·机器学习
weixin_505154466 小时前
打破传统界限:Bowell Studio引领3D作业指导新纪元
人工智能·3d·制造·数据安全·数字孪生·数据可视化
ModelHub XC信创模盒8 小时前
中国信创AI生态下 “信创模盒”社区战略招募种子用户
人工智能·大模型·开发者·信创·算力
袋鼠云数栈9 小时前
集团数字化统战实战:统一数据门户与全业态监管体系构建
大数据·数据结构·人工智能·多模态
廋到被风吹走9 小时前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python
cskywit9 小时前
【IEEE TNNLS 2025】赋予大模型“跨院行医”的能力:基于全局与局部提示的医学图像泛化框架 (GLP) 解析
人工智能
2501_948114249 小时前
AI API Gateway 选型指南:2026 年生产环境下的聚合平台深度对比
人工智能·gateway
实在智能RPA9 小时前
Agent 在物流行业能实现哪些自动化?——深度拆解 AI Agent 驱动的智慧物流新范式
运维·人工智能·ai·自动化