【问题标题】:PyTorch : How to properly create a list of nn.Linear()PyTorch:如何正确创建 nn.Linear() 列表
【发布时间】:2018-11-01 00:04:40
【问题描述】:

我创建了一个以 nn.Module 作为子类的类。

在我的课堂上,我必须创建 N 个线性变换,其中 N 作为类参数给出。

因此,我按照以下方式进行:

    self.list_1 = []

    for i in range(N):
        self.list_1.append(nn.Linear(self.x, 1, bias=mlp_bias))

在 forward 方法中,我调用这些矩阵(使用 list_1[i])并连接结果。

两件事:

1)

即使我使用 model.cuda(),这些线性变换在 cpu 上使用,我得到以下错误:

RuntimeError: 预期变量类型为变量 [torch.cuda.FloatTensor] 的对象,但发现参数 #1 'mat2' 的变量类型 [torch.FloatTensor]

我必须这样做

self.list_1.append(nn.Linear(self.x, 1, bias=mlp_bias).cuda())

如果我这样做,则不需要这样做:

self.nn = nn.Linear(self.x, 1, bias=mlp_bias)

然后直接使用self.nn。

2)

出于更明显的原因,当我在 main 中打印(model) 时,我的列表中的线性矩阵没有打印。

还有其他方法吗。也许使用 bmm ?我发现它不太容易,我实际上想分别获得我的 N 个结果。

提前谢谢你,

M

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    您可以使用nn.ModuleList 包装线性层列表,如here 所述

    self.list_1 = nn.ModuleList(self.list_1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-11
      • 2019-04-27
      • 1970-01-01
      • 2020-11-09
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      相关资源
      最近更新 更多