pytorch:RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 1 a

1.pytorch报错

Namespace(batchSize=16, gpu='0,1', lr=0.001, nepoch=210, num_workers=8)

Epoch: 0
Epoch:0 [0|173089] loss:3.747539
Epoch:0 [1|173089] loss:3.629151
Epoch:0 [2|173089] loss:3.731266
Traceback (most recent call last):
  File "train.py", line 81, in 
    train(epoch)
  File "train.py", line 55, in train
    for batch_idx,(img,label) in enumerate(trainloader):
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 336, in __next__
    return self._process_next_batch(batch)
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 357, in _process_next_batch
    raise batch.exc_type(batch.exc_msg)
RuntimeError: Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 106, in _worker_loop
    samples = collate_fn([dataset[i] for i in batch_indices])
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 187, in default_collate
    return [default_collate(samples) for samples in transposed]
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 187, in 
    return [default_collate(samples) for samples in transposed]
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 164, in default_collate
    return torch.stack(batch, 0, out=out)
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 1 and 3 in dimension 1 at /pytorch/aten/src/TH/generic/THTensorMath.cpp:3616

2. 解决方案

dataloader

    def __getitem__(self,index):
        img_path=self.imgs[index]
        label=self.labels[index]
        data=Image.open(img_path)
#         data = data.convert('RGB')
        data=self.transform(data)
        return data,label

3.错误分析

使用DataLoader加载图像,这些图像中的一些具有3个通道(彩色图像),而其他图像可能具有单个通道(BW图像),由于dim1的尺寸不同,因此无法将它们连接成批次。
尝试将img = img.convert(‘RGB’)添加到数据集中的__getitem__中。

4.参考资料

https://discuss.pytorch.org/t/runtimeerror-invalid-argument-0/17919/5

你可能感兴趣的:(Debug)