深入浅出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)
相关推荐
数据治理自习室2 分钟前
AI 应用评测体系(GraphRAG)
android·大数据·人工智能·kotlin
真空回流焊炉9 分钟前
高密封性真空回流炉应用指南与关键注意事项
人工智能
清华kenny14 分钟前
养生馆AI体质辨识品牌参考:从采集效率到报告生成维度的多维评估
大数据·人工智能·安徽晓得养
码视野20 分钟前
基于 Spring Boot + Vue3 的【智慧公厕微负压排风除臭与客流人感空间占用导引中台】设计与实现(含PRD/三端高保真源码/大屏)
前端·vue.js·人工智能·spring boot·后端
MartinYeung523 分钟前
[论文分析]大规模模型成员推理攻击综述的深度分析
人工智能
Web3&Basketball23 分钟前
从0到1落地多模态表格/发票结构化识别:踩坑全记录
深度学习·大模型·ai技术
fengyangaiGEO25 分钟前
GEO 如何分析竞品的 AI 引用情况?
人工智能·python·信息可视化
段一凡-华北理工大学28 分钟前
高炉炉况智能诊断与预警实战~系列文章18:预警提前量问题:过程滞后与预测窗口的权衡
服务器·网络·人工智能·机器学习·高炉智能化·炉况预警·工业预警滞后
新知图书1 小时前
16.3 基于MCP的多Agent旅行规划助手项目结构
人工智能·agent·ai agent·智能体
龍德明宇1 小时前
专栏导读:关注龍德明宇,读点AI哲学
人工智能·大语言模型llm·负主体性·ai存在论