深入浅出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)
相关推荐
ACP广源盛139246256731 分钟前
IX6012 PCIe 交换芯片@ACP#RTX Spark 入门级 12 口存储外设扩展方案(对比 ASM1812)
大数据·人工智能·分布式·嵌入式硬件·gpt·spark·电脑
丨白色风车丨3 分钟前
OpenCV 实战入门:轮廓检测、模板匹配与命令行参数解析
人工智能·opencv·计算机视觉
zhangfeng11336 分钟前
workbuddy 结合deepseekv4-flash 安装打印机 hp laster jet 3050
人工智能·workbuddy
爱看科技10 分钟前
三星提速开启AI转型,英伟达/WIMI微美全息推进AI算力建设需求持续旺盛
人工智能
dog25011 分钟前
信号权重和流分类的对数规律
人工智能·分类·数据挖掘
道一云黑板报13 分钟前
告别提示词工程:为什么“循环工程”才是 AI 编程的未来?
人工智能·驱动开发·软件工程·ai编程
实在智能RPA13 分钟前
大模型驱动航班规划实战:2026年企业级Agent重塑航空业调度逻辑
人工智能·ai
叫我:松哥14 分钟前
基于Python的共享单车租赁数据分析与预测系统,技术栈flask+boostrap+随机森林+XGBoost
人工智能·python·深度学习·算法·随机森林·数据分析·flask
米小虾25 分钟前
2026年6月AI大模型全景报告:GPT-5.6、Claude Opus 4.8、Gemini 3.5,中美AI三足鼎立谁主沉浮?
人工智能
米小虾27 分钟前
AI Agent从Demo到生产:2026年主流Agent开发框架全景对比与实战选型指南
人工智能·agent