深入浅出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)。这个函数仅当模型中有Dropout和BatchNorm时才会有影响。

复制代码
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)
相关推荐
锋行天下9 分钟前
Langgraph HITL 中断运行,用户输入后输出打字效果
人工智能·python
ZhengEnCi13 分钟前
agent 为什么需要自进化:从静态模型到经验驱动的持续成长
人工智能
QXWZ_IA21 分钟前
RTK平面很准、高程总飘,问题出在哪
人工智能
Ferries29 分钟前
用 WorkBuddy+DeepSeek 跑了30天自动矩阵,事情没那么简单
人工智能·aigc·vibecoding
用户8371332007640 分钟前
AI总是会忘记细节咋办?我用GitHub实现外部记忆管理
人工智能·github
谁在黄金彼岸40 分钟前
OCR 方案对比:本地多模态可行吗?
人工智能
IT_陈寒1 小时前
React的useEffect依赖数组把我坑惨了
前端·人工智能·后端
大模型真好玩1 小时前
DeepSeek Harness 插件的服务与事件监听详解
人工智能·agent·deepseek
迪菲赫尔曼1 小时前
【基础篇 11】把官方源码放到服务器:版本、解压层级和安装位置,一次弄清楚
运维·服务器·开发语言·人工智能·python·yolo·目标检测
阿里云大数据AI技术1 小时前
阿里云DLF年度发布:Agentic Lake全模态 AI 数据湖底座
人工智能