深入浅出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)
相关推荐
jinanwuhuaguo21 分钟前
人工智能的进化阶梯:AI、ANI、AGI与ASI的核心区别与深度剖析
开发语言·人工智能·agi·openclaw
程序员Shawn40 分钟前
【深度学习 | 第三篇】-卷积神经网络
人工智能·深度学习·cnn
vkv55881 小时前
我做了一个自媒体多平台发布工具:支持 AI 生成、账号管理、自动登录与批量发布
人工智能·媒体
IT_陈寒1 小时前
React hooks依赖数组这个坑差点把我埋了
前端·人工智能·后端
我科绝伦(Huanhuan Zhou)1 小时前
分享一个服务故障自愈系统
运维·人工智能·自动化
做个文艺程序员1 小时前
Spring AI + Qwen3.5 实现多步 Agent:从工具调用到自主任务拆解的踩坑全记录
java·人工智能·spring
光电的一只菜鸡1 小时前
《PyTorch深度学习建模与应用(参考用书)》(三)——深度神经网络
pytorch·深度学习·dnn
波动几何2 小时前
极简万能通用AI Agent:universal-agent
人工智能
行者-全栈开发2 小时前
腾讯地图 Map Skills 快速入门:从零搭建 AI 智能行程规划应用
人工智能·typescript·腾讯地图·ai agent·mcp 协议·map skills·智能行程规划
彩虹编程2 小时前
通俗讲解LTN中的非逻辑符号、连接词、量词
人工智能·神经符号