深入浅出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)
相关推荐
阳光是sunny1 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
冬奇Lab2 小时前
每日一个开源项目(第148篇):obsidian-skills - Obsidian CEO 亲写的 AI Agent 格式规范,让 Agent 不再破坏你的 Vault
人工智能·开源·资讯
ethantan2 小时前
AI Agent 组成:像人一样思考的智能体
人工智能·程序员·架构
冬奇Lab2 小时前
Workflow 系列(05):评测体系——三层测试结构与 Trace 追踪
人工智能·工作流引擎
ethantan3 小时前
一篇讲解AI Agent 组成:像人一样思考的智能体
人工智能·后端·程序员
Cosolar5 小时前
vLLM 生产级部署完全指南
人工智能·后端·架构
CodePlayer竟然被占用了5 小时前
被美国政府封杀18天,Claude Fable 5 回来了——但代价是什么?
人工智能
IT_陈寒6 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
smartpi6 小时前
SmartPi GPIO 脉冲与回复语执行时序指南
人工智能
阿里云大数据AI技术6 小时前
PAI支持一键部署GLM-5.2,Coding能力比肩Claude Opus 4.8
人工智能