【问题标题】:With a PyTorch LSTM, can I have a different hidden_size than input_size?使用 PyTorch LSTM,我的 hidden_​​size 可以与 input_size 不同吗?
【发布时间】:2020-06-14 21:45:55
【问题描述】:

我有:

    def __init__(self, feature_dim=15, hidden_size=5, num_layers=2):
        super(BaselineModel, self).__init__()
        self.num_layers = num_layers
        self.hidden_size = hidden_size

        self.lstm = nn.LSTM(input_size=feature_dim,
                            hidden_size=hidden_size, num_layers=num_layers)

然后我得到一个错误:

RuntimeError: The size of tensor a (5) must match the size of tensor b (15) at non-singleton dimension 2

如果我将两个尺寸设置为相同,那么错误就会消失。但是我想知道我的input_size 是否是一个很大的数字,比如 15,而我想将隐藏功能的数量减少到 5,为什么不能这样做?

【问题讨论】:

    标签: python pytorch lstm dimensionality-reduction


    【解决方案1】:

    它应该可以工作,错误可能来自其他地方。 例如这项工作:

            feature_dim = 15
            hidden_size = 5
            num_layers = 2
            seq_len = 5
            batch_size = 3
            lstm = nn.LSTM(input_size=feature_dim,
                                        hidden_size=hidden_size, num_layers=num_layers)
    
            t1 = torch.from_numpy(np.random.uniform(0,1,size=(seq_len, batch_size, feature_dim))).float()
            output, states = lstm.forward(t1)
            hidden_state, cell_state = states
            print("output: ",output.size())
            print("hidden_state: ",hidden_state.size())
            print("cell_state: ",cell_state.size())
    

    然后返回

        output:  torch.Size([5, 3, 5])
        hidden_state:  torch.Size([2, 3, 5])
        cell_state:  torch.Size([2, 3, 5])
    

    您是否在 lstm 之后的某处使用输出?您是否注意到它的大小等于隐藏的暗淡,即最后暗淡的 5?看起来你在使用它之后认为它的大小是 15

    【讨论】:

      【解决方案2】:

      简短的回答是:是的,input_size 可以不同于 hidden_size

      如需详细解答,请查看PyTorch documentations 中的 LSTM 公式,例如:

      这是计算 i_t 的公式,即一层在第 t 个时间步的输入激活。这里矩阵 W_ii 的形状为(hidden_size x input_size)。类似地,在其他公式中,矩阵 W_ifW_igW_io 都有相同的形状。这些矩阵将输入张量投影到与隐藏状态相同的空间中,以便它们可以相加。

      回到您的具体问题,正如另一个答案所指出的那样,这可能是您代码的另一部分的错误。如果不查看您的 forward 实现,很难说到底是什么问题。

      【讨论】:

        猜你喜欢
        • 2023-02-03
        • 2021-04-04
        • 1970-01-01
        • 2023-04-08
        • 2019-11-16
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多