深入浅出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)
相关推荐
英辰朗迪AI获客18 分钟前
英辰朗迪GEO知识库第188期:动态渲染站点在AI搜索里成了隐形人
人工智能
硅谷秋水29 分钟前
MorphMimic 方法分析
人工智能·机器学习·计算机视觉·机器人
MobotStone1 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法
jay神1 小时前
基于 YOLOv8 的传送带异物检测系统(Web 版)
前端·人工智能·深度学习·yolo·计算机视觉·计算机毕业设计
复杂网络与机器学习1 小时前
Meta 重写 K-Means:25 轮压成 2 轮,GPU 快 45 倍
人工智能·算法·数据挖掘
ONEYAC唯样2 小时前
YXC扬兴科技小型化有源晶振OT4JI-111-24M,提升红外热成像稳定性
人工智能·python·pygame
小宋10212 小时前
AI 爬虫把大学图书馆站点拖垮:按行为指纹给爬虫分类、按类发配额、用边缘缓存分层,以带宽成本结构和真实用户 P95 延迟定档
人工智能·爬虫·分类
碧海银沙音频科技研究院2 小时前
BP寻呼机原理
人工智能·嵌入式硬件
万俟淋曦2 小时前
[ROS 系列学习教程] 建模与仿真 - 使用 ros_control 控制六轴串联机械臂
人工智能·ai·机器人·ros·机械臂·robotics·具身智能
IT_陈寒2 小时前
Vue开发者必知:5个让你效率翻倍的隐藏技巧
前端·人工智能·后端