预期目标大小(50,88),得到了火炬.大小([50,288,88]) [英] Expected target size (50, 88), got torch.Size([50, 288, 88])

查看:216
本文介绍了预期目标大小(50,88),得到了火炬.大小([50,288,88])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试训练我的神经网络.模型中的训练是正确的,但我无法计算损失.输出和目标具有相同的尺寸.

I am trying to train my neuronal network. Train in the model is correct, but I can't calculate loss. The output and the target have the same dimension.

我曾经尝试过使用torch.stack,但是我不能这样做,因为每个输入的大小为(252,x),其中252个元素中的x相同,而其他输入则不同.

I had tried to use torch.stack, but I can't because the size of the each input is (252, x) where x is the same in the 252 elements, but is different for the others inputs.

我使用自定义数据集:

class MusicDataSet(Dataset):
def __init__(self, transform=None):
    self.ms, self.target, self.tam = sd.cargarDatos()  
    self.mean, self.std = self.NormalizationValues()                    
def __len__(self):
    return self.tam

def __getitem__(self, idx):
    #Normalize
    inp = (self.ms[idx]-self.mean)/self.std
    inp = torch.from_numpy(inp).float()    
    inp = inp.t()
    inp = inp.to('cuda')

    target= torch.from_numpy(self.target[idx])
    target = target.long()
    target = target.t()
    target = target.to('cuda')

    return inp, target

我必须说列表不能用类似以下的内容强制转换:target = torch.Tensor()或torch.stack(),因为正如我已经说过的那样,它是(252,x).

I must say that list can't be cast with something like: target = torch.Tensor() or torch.stack() because this (252, x), as I have already said.

def music_collate_fn(batch):
    data = [item[0] for item in batch]
    data = pad_sequence(data, batch_first=True)
    target = [item[0] for item in batch]
    target = pad_sequence(target, batch_first=True)
    return data, target


musicSet = mds.MusicDataSet()
train_loader = torch.utils.data.DataLoader(musicSet,batch_size=50, collate_fn = music_collate_fn, shuffle=False)

input_dim = 252
hidden_dim = (512,1024,512)
output_dim = 88
mlp = rn.MLP(input_dim, hidden_dim, output_dim).to(device)

optimizer = torch.optim.RMSprop(mlp.parameters(), lr = learning_rate)
criterion = nn.CrossEntropyLoss()
for batch_idx, (x,y) in enumerate(train_loader):
    outputs = mlp(x.to(device))
    loss = criterion(outputs, y)
    optimizer.zero_grad()           
    loss.backward()                 
    optimizer.step()

输出和目标的大小相同,

The size of output and target is the same,

output: torch.Size([50, 288, 88])
target:  torch.Size([50, 288, 88])

但是当我尝试计算损失时,下一个错误消失了:

But the next error apears when I try to calculate loss:

  File "<ipython-input-205-3c47d7aa11a4>", line 32, in <module>
    loss = criterion(outputs, y)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 489, in __call__
    result = self.forward(*input, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\loss.py", line 904, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\functional.py", line 1970, in cross_entropy
    return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch
\nn\functional.py", line 1800, in nll_loss
    out_size, target.size()))

ValueError: Expected target size (50, 88), got torch.Size([50, 288, 88])

推荐答案

我认为您使用的CrossEntropyLoss错误.请参阅文档此处.

I think you are using CrossEntropyLoss incorrectly. See the documentation here.

尤其是,如果输入的形状为[NxCxd],则目标的形状应为[Nxd],并且target中的值是0到C-1之间的整数,即,您可以只提供类标签,而不必一键编码目标变量.错误消息也指出相同.

In particular, if the input is of shape [NxCxd] then target should be of shape [Nxd], and value in target are integer between 0 and C-1 i.e you can just provide the class labels and it is not required to one-hot encode the target variable. Error message also states that same.

这篇关于预期目标大小(50,88),得到了火炬.大小([50,288,88])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆