Cannot Unsqueeze Empty Tensor

When I load my data, I meet a problem:

Traceback (most recent call last):
  File "trainer.py", line 41, in <module>
    for i, (rmap, label) in enumerate(trainloader):
  File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 174, in __next__
    return self._process_next_batch(batch)
  File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 198, in _process_next_batch
    raise batch.exc_type(batch.exc_msg)
RuntimeError: Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 32, in _worker_loop
    samples = collate_fn([dataset[i] for i in batch_indices])
  File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 81, in default_collate
    return [default_collate(samples) for samples in transposed]
  File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 68, in default_collate
    return torch.stack(batch, 0)
  File "/usr/local/lib/python2.7/dist-packages/torch/functional.py", line 56, in stack
    return torch.cat(list(t.unsqueeze(dim) for t in sequence), dim)
  File "/usr/local/lib/python2.7/dist-packages/torch/functional.py", line 56, in <genexpr>
    return torch.cat(list(t.unsqueeze(dim) for t in sequence), dim)
RuntimeError: cannot unsqueeze empty tensor at /data/users/soumith/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensor.c:530

you need to give more context

I also came across the same issue when trying to build a custom dataset:

Here is the getitem method:

    def __getitem__(self, index):
            fname = self.train_filenames[index]
            image = Image.open(os.path.join(celeba_imgpath, fname))
            label = self.train_labels[index]
            return self.transform(image), torch.FloatTensor(label)

I think it was caused by the label given as a scalar value. I converted the label to a list, and then the problem was solved. Here is the corrected code:

    def __getitem__(self, index):
            fname = self.train_filenames[index]
            image = Image.open(os.path.join(celeba_imgpath, fname))
            label = [self.train_labels[index]]
            return self.transform(image), torch.FloatTensor(label)
7 Likes

I had the same issue this solution worked for me. Thanks

I also had the same issue and is resolved with your solution. This saved a lot of time! Thanks