深入浅出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)
相关推荐
roman_日积跬步-终至千里6 小时前
【AI Engineering】Should I build this AI application?—AI应用决策框架与实践指南
大数据·人工智能
新智元6 小时前
谷歌 Nano Banana Pro 炸了!硅谷 AI 半壁江山同框,网友:PS 已死
人工智能·openai
m***D2866 小时前
机器学习总结
人工智能·机器学习
新智元6 小时前
51 岁周志华、53 岁刘云浩,当选中国科学院院士!
人工智能·openai
魁首7 小时前
初识 ACP (Agent Client Protocol)
人工智能·ai编程·mcp
周末程序猿7 小时前
开源项目|不一样的思维导图
人工智能·后端
Wgrape7 小时前
一文了解常见AI搜索方案的代码实现
人工智能·后端
中医正骨葛大夫7 小时前
一文解决如何在Pycharm中创建cuda深度学习环境?
pytorch·深度学习·pycharm·软件安装·cuda·anaconda·配置环境
Vadaski7 小时前
私有 Context 工程如何落地:从方法论到实战
人工智能·程序员
胖墩会武术7 小时前
【OpenCV图像处理】深度学习:cv2.dnn() —— 图像分类、人脸检测、目标检测
图像处理·pytorch·python·opencv