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

时间:2018-05-27 22:21:11

标签: deep-learning lstm pytorch

我开始使用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中链接时,存在根本性的错误......

修改

按照@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 :(得分:1)

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

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

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

D_inH没有三个维度。

答案 1 :(得分:1)

这里需要注意的是,与torch.nn.Linear等线性图层相比,torch.nn.LSTM等重复图层的输出多于1个。

虽然torch.nn.Linear只返回y中的y = Ax + b,但torch.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)