问题
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.
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.
I use a custom Dataset:
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
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])
回答1:
I think you are using CrossEntropyLoss
incorrectly. See the documentation here.
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.
来源:https://stackoverflow.com/questions/56243672/expected-target-size-50-88-got-torch-size50-288-88