深入浅出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)
相关推荐
谙弆悕博士3 分钟前
多智能体架构详解:黑板共享架构(共享存储交互型)
人工智能·架构·大模型·agent·多智能体·黑板架构·anggraph
AI创界者24 分钟前
Python 进阶实战(五十四章):大模型推理网关终极架构——分布式全局前缀 Trie 缓存同步与多网关高可用协同调度
人工智能·python·aigc
后端小肥肠40 分钟前
公众号里流量很夯的漫画赛道:趣味漫画创作全拆解
人工智能·aigc·agent
程序油菜花1 小时前
微软 ONNX Runtime 仓库突然 404:你的项目,可能并不真正属于你
人工智能
锋行天下1 小时前
LangGraph 对接 MCP 实战指南:从本地开发到线上部署与模型防坑
前端·人工智能·后端
汤姆宝库1 小时前
解码采样策略的实现:temperature、top-p、min-p与重复惩罚
人工智能
鶴哥只手遮天1 小时前
《WeKnora 深度技术解析》第 5 章 数据底座:多租户模型、仓储与迁移
人工智能
guuguo2 小时前
【做个开源软件】Mac 上 node 进程莫名吃掉 6G 内存?给 AI / MCP 做了个深度归因和安全回收工具
人工智能·开源·github
双鱼大猫3 小时前
opencode 吃掉 100G 空间:Agent 会话数据要分级清理
人工智能·agent·ai编程
用户5833339816683 小时前
RPA 流程的异常处理设计:重试、降级与告警,生产环境实战指南
人工智能