深入浅出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)
相关推荐
智算菩萨2 分钟前
2026年春节后,AI大模型格局彻底变了——Claude 4.6、GPT-5.2与六大国产模型全面横评
人工智能·gpt·ai编程
DeepModel29 分钟前
【回归算法】Ridge回归详解
深度学习·机器学习·回归算法
狮子座明仔32 分钟前
Agent World Model:给智能体造一个“矩阵世界“——无限合成环境驱动的强化学习
人工智能·线性代数·语言模型·矩阵
OpenMiniServer36 分钟前
AI 大模型的本质:基于大数据的拟合,而非创造
大数据·人工智能
SmartBrain41 分钟前
FastAPI实战(第二部分):用户注册接口开发详解
数据库·人工智能·python·fastapi
星爷AG I41 分钟前
12-6 心理理论(AGI基础理论)
人工智能·agi
向哆哆1 小时前
102类农业害虫图像识别数据集:智慧农业与精准防控的高质量资源
人工智能
lisw051 小时前
云原生技术概述!
人工智能·机器学习·云原生
小程故事多_801 小时前
深度解析个人AI助手OpenClaw:从消息处理到定时任务的全流程架构
人工智能·架构
开发者导航1 小时前
【开发者导航】多功能生成模型开发工具:Diffusers 详细介绍
人工智能·python·学习·macos·信息可视化