RuntimeError: 1D target tensor expected, multi-target not supported

I am a beginner, and I am experimenting in PyTorch.
I am trying to learn Custom Datasets with a toy example.
Here is my script:

import torch
import torch.nn as nn
import torch.utils.data as data
import torchvision.datasets as datasets
device=torch.device('cuda:0');
class CustomDataset(data.Dataset):
 def __init__(self,high):
  self.src=list(range(high));
  self.trgt=list(iter*1 for iter in range(high));
  self.allItems=self.src;
 def inttoTensor(self,integer):
  tensor=torch.zeros(len(self.src));
  index=0;
  for item in self.allItems:
   if item==integer:
    index=self.allItems.index(item);
  print(index);
  tensor[index]=1;
  return tensor;
 def __len__(self):
  return len(self.src);
 def __getitem__(self,idx):
  number=self.src[idx];
  numbert=self.trgt[idx];
  numtensor=self.inttoTensor(number);
  numberttensor=self.inttoTensor(numbert);
  return numtensor,numberttensor;
dset=CustomDataset(50);
dataloader=data.DataLoader(dset,batch_size=1);
model=nn.Linear(50,50);
loss=nn.CrossEntropyLoss();
optimizer=torch.optim.SGD(model.parameters(),lr=0.05);
for batch,(X,y) in enumerate(dataloader):
 pred=model(X);
 lossv=loss(pred,y);
 optimizer.zero_grad();
 loss.backward();
 optimizer.step();

I have looked at a lot of tutorials and some problems like this on this forum, though I am not able to fix it. When I run the script: This is the output I get:

0
0
Traceback (most recent call last):
  File "cust.py", line 35, in <module>
    lossv=loss(pred,y);
  File "/home/samarth/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/samarth/.local/lib/python3.6/site-packages/torch/nn/modules/loss.py", line 1121, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)
  File "/home/samarth/.local/lib/python3.6/site-packages/torch/nn/functional.py", line 2824, in cross_entropy
    return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: 1D target tensor expected, multi-target not supported

Can anyone help me?
Thank you.

Hi @NeuralFoX

Seems like you have the sequence of ascending numbers in

self.trgt=list(iter*1 for iter in range(high));

The cross_entropy_loss treats it like multi-class labels. Probably you have a buggy code in the snippet above

Thank you. I will try this out. So you are saying that there is something wrong with the list comprehension? Thanks again.

Sorry. I figured out my problem. I had written


self.trgt=list(iter*1 for iter in range(high));

I meant it to be iter*2 instead of iter*1. Thanks a lot for helping me.