深入浅出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)
相关推荐
沸点小助手4 分钟前
「妈,我真不是修电脑的」获奖名单公示|本周互动话题上新🎊
前端·人工智能
nix.gnehc7 分钟前
LangX实战:从Spring生态理解LLM应用开发
人工智能·langchain·langgraph·langfuse
一马平川的大草原7 分钟前
报告笔记--AI工程的文化研读记录及感悟
人工智能·笔记·读书笔记
小锋java123415 分钟前
【技术专题】Spring AI 2.0 - Advisors —— 拦截器模式增强AI能力
java·人工智能
纽格立科技19 分钟前
AI让广播过时,还是让广播稀缺?
大数据·服务器·人工智能·车载系统·信息与通信·传媒
一切皆是因缘际会23 分钟前
AI工程化落地指南:
大数据·人工智能·机器学习·架构
东方佑25 分钟前
观测的连续性:从波粒二象性诠释生成式 AI 中音视频与图像的表征范式
人工智能·音视频
迁旭26 分钟前
Claude Code Skill(技能)系统机制与运行原理报告
人工智能·机器学习·gpt-3·文心一言
小程故事多_8034 分钟前
从零复刻Claude Code,深度拆解Agent Harness工程化落地全逻辑
人工智能
AIGC包拥它37 分钟前
RAG 项目实战进阶:基于 FastAPI + Vue3 前后端架构全面重构 LangChain 0.3 集成 Milvus 2.5 构建大模型智能应用
人工智能·python·重构·vue·fastapi·milvus·ai-native