【问题标题】:PyTorch LSTM: RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 1219 and 440 in dimension 1PyTorch LSTM:RuntimeError:无效参数 0:张量的大小必须匹配,但维度 0 除外。在维度 1 中得到 1219 和 440
【发布时间】:2020-05-26 00:04:41
【问题描述】:

我有一个基本的 PyTorch LSTM:

import torch.nn as nn
import torch.nn.functional as F

class BaselineLSTM(nn.Module):
    def __init__(self):
        super(BaselineLSTM, self).__init__()

        self.lstm = nn.LSTM(input_size=13, hidden_size=13)
        
    def forward(self, x):
        x = self.lstm(x)

        return x

对于我的数据,我有:

train_set = CorruptedAudioDataset(corrupted_path, train_set=True)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=128, shuffle=True, **kwargs)

我的CorruptedAudioDataset 有:

    def __getitem__(self, index):
        corrupted_sound_file = SoundFile(self.file_paths[index])
        corrupted_samplerate = corrupted_sound_file.samplerate
        corrupted_signal_audio_array = corrupted_sound_file.read()

        clean_path = self.file_paths[index].split('/')
        # print(self.file_paths[index], clean_path)
        clean_sound_file = SoundFile(self.file_paths[index])
        clean_samplerate = clean_sound_file.samplerate
        clean_signal_audio_array = clean_sound_file.read()


        corrupted_mfcc = mfcc(corrupted_signal_audio_array, samplerate=corrupted_samplerate)
        clean_mfcc = mfcc(clean_signal_audio_array, samplerate=clean_samplerate)

  
        print('return', corrupted_mfcc.shape, clean_mfcc.shape)
        return corrupted_mfcc, clean_mfcc

我的训练循环如下所示:

    model = BaselineLSTM()
    for epoch in range(300):
        for inputs, outputs in train_loader:
            print('inputs', inputs)

这就是我得到错误的那一行:

  File "train_lstm_baseline.py", line 47, in train
    for inputs, outputs in train_loader:
...
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 1219 and 440 in dimension 1 at ../aten/src/TH/generic/THTensor.cpp:612

【问题讨论】:

    标签: python pytorch lstm


    【解决方案1】:

    基本上是因为您正在加载具有不同形状的批次而引发此异常。由于它们存储在同一个张量中,因此所有样本必须具有相同的形状。在这种情况下,您在维度 0 中输入了 1219 和 440,这是不可能的。例如,你有类似的东西:

    torch.Size([1, 1219])
    torch.Size([1, 440])
    torch.Size([1, 550])
    ...
    

    你必须有:

    torch.Size([1, n])
    torch.Size([1, n])
    torch.Size([1, n])
    ...
    

    解决此问题的最简单方法是设置batch_size=1。但是,它可能会延迟您的代码。

    最好的方法是将数据设置为相同的形状。在这种情况下,您需要评估您的问题以检查是否可能。

    【讨论】:

      猜你喜欢
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2022-12-04
      • 2021-06-12
      • 2021-05-12
      • 1970-01-01
      相关资源
      最近更新 更多