0
点赞
收藏
分享

微信扫一扫

无缝投屏技巧:怎样将Windows电脑屏幕共享到安卓手机?

you的日常 04-06 21:30 阅读 1

nn.ModuleList() 是 PyTorch 中的一个类,用于管理神经网络模型中的子模块列表。它允许将多个子模块组织在一起,并将它们作为整个模型的一部分进行管理和操作。

在神经网络模型的开发过程中,通常需要定义和使用多个子模块,例如不同的层、块或者其他组件。nn.ModuleList() 提供了一种方便的方式来管理这些子模块,并确保它们被正确地注册为模型的一部分。

使用 nn.ModuleList() 需要进行两个步骤:

在模型的 __init__ 方法中,定义一个 nn.ModuleList 实例,并将需要管理的子模块添加到该列表中。
在模型的 forward 方法中,使用 nn.ModuleList 实例来访问和操作子模块。

import torch
import torch.nn as nn

class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()

        self.module_list = nn.ModuleList([
            nn.Linear(3, 4),
            nn.ReLU(),
            nn.Linear(4, 3),
        ])

    def forward(self, x):
        for module in self.module_list:
            x = module(x)
            print(x)
        return x

model = MyModel()

input_tensor = torch.randn(5, 3)

output_tensor = model(input_tensor)

输出:
tensor([[ 0.4509,  0.3470, -0.0216, -0.5590],
        [-0.4539,  0.3508,  0.8228, -0.2100],
        [ 0.6888,  0.1177, -0.6534, -0.8283],
        [-1.3217,  0.5313,  2.0204,  0.4374],
        [ 0.3079,  0.5607,  0.3941, -0.5886]], grad_fn=<AddmmBackward>)

tensor([[0.4509, 0.3470, 0.0000, 0.0000],
        [0.0000, 0.3508, 0.8228, 0.0000],
        [0.6888, 0.1177, 0.0000, 0.0000],
        [0.0000, 0.5313, 2.0204, 0.4374],
        [0.3079, 0.5607, 0.3941, 0.0000]], grad_fn=<ReluBackward0>)

tensor([[-0.2666,  0.0640,  0.2471],
        [-0.6055, -0.0951,  0.0608],
        [-0.2297,  0.0512,  0.3325],
        [-1.4177, -0.6686, -0.4530],
        [-0.5100, -0.0886,  0.0436]], grad_fn=<AddmmBackward>)

在示例中,定义了一个名为 MyModel 的自定义模型类。在该类的 __init__ 方法中,创建了一个 该类nn.ModuleList的实例 module_list,并添加了三个子模块:一个线性层(nn.Linear)、一个 ReLU 激活函数(nn.ReLU)和另一个线性层(这是在初始化类时一次添加的模块),当然还可以调用module_list.append(layername)来添加子模块。这些子模块将作为整个模型的一部分。

在模型的 forward 方法中,通过迭代 module_list 中的子模块,依次将输入数据 x 传递给它们,并获取最终的输出。

通过使用 nn.ModuleList,我们可以方便地管理模型中的多个子模块,并确保它们被正确地注册为模型的一部分。这使得模型的结构清晰可见,同时也方便了模型的训练和参数优化。

举报

相关推荐

0 条评论