RuntimeError: 1only batches of spatial targets supported (non-empty 3D tensors) but got targets of size

原因:这个原因是因为在使用Crossentropyloss作为损失函数时,output=net(input)的output应该是[batchsize, n_class, height, weight],而label则是[batchsize, height, weight],label是单通道灰度图;BCELoss与CrossEntropyLoss都是用于分类问题。BCELoss是CrossEntropyLoss的一个特例,只用于二分类问题,而CrossEntropyLoss可以用于二分类,也可以用于多分类。

(1)If logit.shape is torch.Size ([4, 31, 256, 256])  and target.shape is [4, 256, 256, 1], where 4 is the batchSize and 31 is the number of categories.

Solution:维度压缩

loss = criterion(logit, torch.squeeze(target).long())

to change the target to [4, 256, 256].

(2)1only batches of spatial targets supported (non-empty 3D tensors) but got targets of size: : [2, 321, 321, 4]

Solution:使用BCELoss

# criterion = nn.CrossEntropyLoss(weight=self.weight, ignore_index=self.ignore_index, reduction='mean')
criterion = nn.BCELoss(weight=self.weight,reduction='mean')

在BCELoss中,logit.size和target.size()都是[batchsize, n_class, height, weight].

猜你喜欢

转载自www.cnblogs.com/dyc99/p/12665778.html
今日推荐