首页 文章

Pytorch中LSTM的可变大小输入

提问于
浏览
0

我正在使用可变长度视频的功能来训练一层LSTM . 视频大小从10帧变为35帧 . 我使用的批处理大小为1.我有以下代码:

lstm_model = LSTMModel(4096, 4096, 1, 64)
for step, (video_features, label) in enumerate(data_loader):
    bx = Variable(score.view(-1, len(video_features), len(video_features[0]))) #examples = 1x12x4096, 1x5x4096
    output = lstm_model(bx)

Lstm模型是;

class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
    super(LSTMModel, self).__init__()
    self.l1 = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)
    self.out = nn.Linear(hidden_size, num_classes)
def forward(self, x):
    r_out, (h_n, h_c) = self.l1(x, None) #None represents zero initial hidden state
    out = self.out(r_out[:, -1, :])
    return out

我只是想问;我是否有权利用可变大小的输入训练LSTM . 代码工作正常,损失减少,但我不确定我做的是否正确 . 因为我之前没有在Pytorch中使用过LSTM .

1 回答

  • 1

    是的,您的代码是正确的,并且总是适用于批量大小1.但是,如果您想使用1以外的批量大小,则需要将可变大小的输入打包到序列中,然后在LSTM之后解压缩 . 您可以在my answer to a similar question中找到更多详细信息 .

    附: - 你应该将这些问题发布到codereview

相关问题