【问题标题】:Converting lists of uneven size into LSTM input tensor将大小不均匀的列表转换为 LSTM 输入张量
【发布时间】:2021-02-21 15:17:15
【问题描述】:

所以我有一个 1366 个样本的嵌套列表,每个样本具有 2 个特征,并且 可变序列 长度应该是输入数据一个 LSTM。标签应该是每个序列的一对值,即[-0.76797587, 0.0713816]。本质上,数据如下所示:

X = [[[-0.11675862, -0.5416186], [-0.76797587, 0.0713816]], [[-0.5115555, 0.25823522], [0.6099151999999999, 0.21718016], [-0.0022403747, 0.6470206999999999]]]

我想做的是将此列表转换为输入张量。据我了解,LSTM 接受不同长度的序列,因此在这种情况下,第一个样本的长度为 2,第二个样本的长度为 3。

目前我正在尝试通过以下方式转换列表:

train_data = TensorDataset(torch.tensor(X, dtype=torch.float32), torch.tensor(Y, dtype=torch.float32))
train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True)

虽然这会产生以下错误ValueError: expected sequence of length 5 at dim 1 (got 3)

我猜这是因为第一个序列的长度为 5,第二个序列的长度为 3,这是不可转换的?

如何将给定的列表转换为张量?还是我对训练 LSTM 的方式想错了?

感谢您的帮助!

【问题讨论】:

  • 你能把DataLoader函数发给我们吗?
  • 是 torch.utils.data DataLoader 函数。
  • 对不起,我的意思是 TensorDataset,但请看下面我的回答 :)

标签: python pytorch lstm


【解决方案1】:

所以正如你所说,序列长度可以不同。但是因为我们使用批次,所以在每个批次中,序列长度无论如何都必须相同。那是因为所有样品都是同时处理的。因此,您需要做的是通过取批次中长度最长的序列将样本填充到相同的大小,并用零填充所有其他样本,以使它们具有相同的大小。为此,您必须使用 pytorch 的 pad 功能,如下所示:

from torch.nn.utils.rnn import pad_sequence

# the batch must be a python list containing the tensor samples
sample_batch = [torch.tensor((4,2)), torch.tensor((2,2)), torch.tensor((5,2))]

# pad all samples in the batch to the length of the biggest sample
padded_batch = pad_sequence(sample_batch, batch_first=True)

# get the new size of the samples and reshape it to (BATCH_SIZE, SEQUENCE/PAD_SIZE. INPUT_SIZE)
padded_to = list(padded_batch.size())[1]
padded_batch = padded_batch.reshape(len(sample_batch), padded_to, 1)

现在批次中的所有样本都应该具有(5,2) 的形状,因为最大的样本的序列长度为 5。

如果您不知道如何使用 pytorch 数据加载器实现此功能,您可以创建自定义 collat​​e_fn:

def custom_collate(batch):
    batch_size = len(batch)

    sample_batch, target_batch = [], []
    for sample, target in batch:

        sample_batch.append(sample)
        target_batch.append(target)

    padded_batch = pad_sequence(sample_batch, batch_first=True)
    padded_to = list(padded_batch.size())[1]
    padded_batch = padded_batch.reshape(len(sample_batch), padded_to, 1)        

    return padded_batch, torch.cat(target_batch, dim=0).reshape(len(sample_batch)

现在您可以告诉 DataLoader 在返回之前将此函数应用于您的批次:

train_dataloader = DataLoader(
        train_data,
        batch_size=batch_size,
        num_workers=1,
        shuffle=True,
        collate_fn=custom_collate    # <-- NOTE THIS
    )

现在 DataLoader 返回填充批次!

【讨论】:

  • 非常感谢!提前思考我只是想知道,填充是否对模型的学习有任何影响,或者填充是否有效地被忽略了?
  • 我不这么认为,但我不确定。但是不使用填充但也不使用批次会降低性能
猜你喜欢
  • 1970-01-01
  • 2020-07-15
  • 2017-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2020-08-05
  • 2019-07-29
相关资源
最近更新 更多