首页 文章

Pytorch - 使用LSTM网络时尺寸不正确

提问于
浏览
1

我开始使用pytorch并使用一些转换来构建以下模型,使用其中一个教程作为参考:

model = torch.nn.Sequential( 
     torch.nn.Linear(D_in, H),
     torch.nn.ReLU(),
     torch.nn.Linear(H, D_out),
)

我想使用LSTM网络,所以我尝试执行以下操作:

model = torch.nn.Sequential(
      torch.nn.LSTM(D_in, H),
      torch.nn.Linear(H, D_out) 
)

这给了我这个错误:

RuntimeError:输入必须有3个维度,得2

为什么我看到这个错误?我预计在理解转换(网络?)如何在pytorch中链接时,有一些根本性的错误......

EDIT

按照@esBee的建议,我发现以下运行正确 . 这是因为LSTM期望输入具有以下维度:

形状输入(seq_len,batch,input_size):包含输入序列特征的张量 . 输入也可以是压缩变量长度序列

local_x = local_x.unsqueeze(0)
y_pred, (hn, cn) = layerA(local_x)
y_pred = y_pred.squeeze(0)
y_pred = layerB(y_pred)

但是,我的原始训练/测试数据集只是序列长度为1的事实让我觉得我做错了什么 . 在神经网络的上下文中该参数的目的是什么?

2 回答

  • 0

    错误消息告诉您输入需要三个维度 .

    看看pytorch documentation,他们提供的例子如下:

    lstm = nn.LSTM(3, 3)  # Input dim is 3, output dim is 3
    

    D_inH 没有三个维度 .

  • 1

    你需要注意的是,与 torch.nn.Linear 等线性层相反,对于重复出现的层,例如 torch.nn.LSTM ,有超过1个输出 .

    虽然 torch.nn.Linear 只返回 y = Ax + b 中的 ytorch.nn.LSTM 返回 output, (h_n, c_n) (更详细地解释in the docs),让您选择要处理的输出 . 所以在你的例子中发生的事情是你在LSTM层之后将所有这几种类型的输出提供给层(导致你看到的错误) . 您应该选择LSTM输出的特定部分,并仅将其输入下一层 .

    可悲的是我不知道如何在 Sequential 中选择LSTM的输出(建议欢迎),但你可以重写

    model = torch.nn.Sequential(
        torch.nn.LSTM(D_in, H),
        torch.nn.Linear(H, D_out) 
    )
    
    model(x)
    

    layerA = torch.nn.LSTM(D_in, H)
    layerB = torch.nn.Linear(H, D_out)
    
    x = layerA(x)
    x = layerB(x)
    

    然后通过写入选择LSTM最后一层的输出特征(h_n)来纠正它

    layerA = torch.nn.LSTM(D_in, H)
    layerB = torch.nn.Linear(H, D_out)
    
    x = layerA(x)[0]
    x = layerB(x)
    

相关问题