深入浅出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)
相关推荐
巫山老妖1 小时前
置身AI内
人工智能
IT_陈寒3 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
vanuan4 小时前
两个AI智能体第一次对话-A2A双Agent协作实战
人工智能
kfaino6 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
雨落Re8 小时前
如何设计一个高质量Skill
人工智能
Token炼金师8 小时前
大模型权重文件全指南:从格式选择到优化实战
人工智能
阿牛哥_GX8 小时前
CDP 浏览器操控原理:让脚本接管你的浏览器
人工智能
ThreeS8 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
米小虾9 小时前
Loop Engineering —— 循环的设计与自主执行
人工智能·agent
米小虾10 小时前
Harness Engineering —— 系统的安全护栏
人工智能·agent