首页 文章

将重复图层附加到具有不同隐藏大小的PyTorch LSTM模型

提问于
浏览
0

我正在使用PyTorch开发用于序列分析的BI-LSTM模型 . 我正在使用torch.nn.LSTM . 使用该模块,只需将参数 num_layers 传递给层数(例如, num_layers=2 )即可拥有多个图层 . 但是所有这些都有相同的 hidden_size ,这对我来说是部分罚款,我只想让它们全部相同 hidden_size but 最后一层具有不同的大小 . 基本示例如下:

rnn = nn.LSTM(input_size=10, hidden_size=20, num_layers=2)
inp = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 20)
c0 = torch.randn(2, 3, 20)
output, (hn, cn) = rnn(inp, (h0, c0))

输出暗淡是( 5, 3, 20

一个解决方案(但对我不利)是实现额外的模型,输出我需要的维度并从第一个模型中获取输入,例如:

rnn_two = nn.LSTM(input_size=20, hidden_size=2)
output2, _ = rnn_two(output)

但是,我不想这样做,因为我 parallelize 模型使用DataParallel,所以我需要所有的一个包 . 我希望找到类似于keras的东西,例如:

rnn.add(LSTM, hidden_size=2)

我检查了LSTM source code但找不到我需要的东西 .

有什么建议?

2 回答

  • 2

    如果我没有弄错,可以这样做:

    import torch.nn as nn
    import torch.nn.functional as F
    
    class RnnWith2HiddenSizesModel(nn.Module):
        def __init__(self):
            super(RnnWith2HiddenSizesModel, self).__init__()
            self.rnn = nn.LSTM(input_size=10, hidden_size=20, num_layers=2)
            self.rnn_two = nn.LSTM(input_size=20, hidden_size=2)
    
        def forward(self, inp, hc):
            output, _ = self.rnn(inp, hc)
            output2, _ = self.rnn_two(output)
            return output2
    
    
    inp = torch.randn(5, 3, 10)
    h0 = torch.randn(2, 3, 20)
    c0 = torch.randn(2, 3, 20)
    
    rnn = RnnWith2HiddenSizesModel()
    
    output = RnnWith2HiddenSizesModel()(inp, (h0, c0))
    
    
    tensor([[[-0.0305,  0.0327],
         [-0.1534, -0.1193],
         [-0.1393,  0.0474]],
    
        [[-0.0370,  0.0519],
         [-0.2081, -0.0693],
         [-0.1809,  0.0826]],
    
        [[-0.0561,  0.0731],
         [-0.2307, -0.0229],
         [-0.1780,  0.0901]],
    
        [[-0.0612,  0.0891],
         [-0.2378,  0.0164],
         [-0.1760,  0.0929]],
    
        [[-0.0660,  0.1023],
         [-0.2176,  0.0508],
         [-0.1611,  0.1053]]], grad_fn=<CatBackward>)
    
  • 0

    尽管@Mikhail Berlinkov的答案是按照需要运作的,但它并不是一般情况(在问题中甚至没有要求),我想提出第二个解决方案:

    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    from functools import reduce
    
    class RNNModel(nn.Module):
        def __init__(self, *models):
            super(RNNModel, self).__init__()
            self.models = models
    
        def forward(self, inp):
            return reduce(lambda arg, model: model(arg, None)[0], self.models, inp)
    

    可以称为:

    rnn = nn.LSTM(input_size=10, hidden_size=20, num_layers=2)
    rnn_two = nn.LSTM(input_size=20, hidden_size=2)
    inp = torch.randn(5, 3, 10)
    
    rnn_model = RNNModel(rnn, rnn_two)
    
    output = rnn_model(inp)
    

    output.shape 等于预期值(即 5,3,2

相关问题