深入浅出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)
相关推荐
xierui1231232 分钟前
NotionAgent 新增建议修改:如何用Patch、Diff 与人工确认设计 AI 改稿工作流
人工智能·ai·自然语言处理
国科安芯5 分钟前
星载CAN总线通信网络中抗辐射MCU的通信可靠性设计分析
网络·人工智能·分布式·单片机·嵌入式硬件·架构
AI程序员25 分钟前
MCP Apps 能直接返回 HTML,为什么还需要 A2UI?
人工智能·agent·mcp
思考着亮26 分钟前
1.MCP
人工智能
MindUp30 分钟前
企业私有化文件管理系统选型实录:从部署架构到AI能力的技术调研笔记
人工智能·笔记·架构
长江后浪博客32 分钟前
无人机AI识虫:用“空中巡检 + GIS地图 + AI识别”解决大规模种植虫害问题
人工智能·无人机·智慧农业·植保无人机·无人机ai识虫·空中巡检·gis地图
ITresearchGuest38 分钟前
AI 是怎么操作浏览器的——browser use 实现原理
人工智能
悟天特斯39 分钟前
智慧楼宇楼宇自控系统:从孤立控制到协同优化的BAS架构演进
人工智能·物联网·架构
法狗狗技术团队44 分钟前
万息投标标书审查功能介绍:AI如何辅助检查投标文件?
人工智能·招标·投标·标书·标书检查·标书审查·标书检查工具
wangchunyu1141 小时前
Cursor介绍和安装说明
人工智能