dav*_*mes 3 python lstm pytorch
因此,我有一个包含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]]]
Run Code Online (Sandbox Code Playgroud)
我想做的是将这个列表转换为输入张量。据我了解,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)
Run Code Online (Sandbox Code Playgroud)
虽然这会产生以下错误ValueError: expected sequence of length 5 at dim 1 (got 3)
我猜这是因为第一个序列的长度为 5,第二个序列的长度为 3,这是不可转换的?
如何将给定列表转换为张量?或者我对训练 LSTM 的方式思考错误?
谢谢你的帮助!
正如您所说,序列长度可以不同。但因为我们使用批次,所以每个批次中的序列长度无论如何都必须相同。那是因为所有样本都是同时处理的。因此,您要做的就是通过取批次中长度最长的序列来将样本填充到相同的大小,并用零填充所有其他样本,以便它们具有相同的大小。为此,你必须使用 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)
Run Code Online (Sandbox Code Playgroud)
现在批次中的所有样本都应该具有该形状(5,2),因为最大样本的序列长度为 5。
如果您不知道如何使用 pytorch Dataloader 来实现这一点,您可以创建一个自定义 collate_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)
Run Code Online (Sandbox Code Playgroud)
现在您可以告诉 DataLoader 在返回批处理之前应用此函数:
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)
Run Code Online (Sandbox Code Playgroud)
现在 DataLoader 返回填充批次!
| 归档时间: |
|
| 查看次数: |
997 次 |
| 最近记录: |