TypeError: default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found

参考资料

  1. issue

问题描述

原始网络用来训练一个表情分类的网络,对输入的图像进行了变换;我将其换成了一个图像分割的网络,目标值从原来的表情标签变成了01概率图的ground truth,此时不能再对输入图像进行变换,因为ground truth不能随之变换。所以我将transform赋值为None,再次训练网络时,出现了错误TypeError: default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found

问题解决

查阅相关问题的回答。

The error states that the DataLoader receives a PIL image. This is because there are no transforms made (transform=None) on the image. The getitem method of MyDataset passes an unprocessed PIL image to the DataLoader, whereas it should receive a tensor. You can add a transform that creates a tensor from the PIL image by adding transform:

PIL image交给DataLoader,必须要将PIL image先进行处理,即将其转为tensor,所以对图片仍需进行transform,将其它随机裁剪注释掉,仅保留PIP image转为tensor的代码。

1
2
3
4
5
6
7
8
9
10
transform_train = transforms.Compose([
#transforms.RandomCrop(44),
#transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
])

transform_test = transforms.Compose([
#transforms.TenCrop(cut_size),
transforms.Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])),
])