I have the same issue. I tried with nn.CrossEntropyLoss and then BCELoss and got errors in both case. Just tried nn.NLLLoss and got this error:
“bool value of Tensor with more than one value is ambiguous”
I cannot understand what is the problem. My images are read in as PIL images in RGB mode and then transformed this way:
data_transforms = {
‘train’: transforms.Compose([
transforms.RandomResizedCrop(input_size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
‘val’: transforms.Compose([
transforms.Resize(input_size),
transforms.CenterCrop(input_size),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
Masks are .PNG images and read with PIL library and the mode is L (black and white images). I applied these transformations:
class Train_Dataset(Dataset):
def __init__(self, imgarray, maskarray, transform=None):

    
    self.images = imgarray
    self.masks = maskarray
    self.transform = transform

    
def __getitem__(self, index):
    
    img = self.images[index]
    if self.transform is not None:
        img = self.transform(img)  
    
    #label = torch.from_numpy(self.masks[index])
    trnsf1 = transforms.RandomResizedCrop(input_size)
    trnsf2 = transforms.ToTensor()
    label = trnsf2(trnsf1(self.masks[index]))
    
   
    return img, label

def __len__(self):
    return len(self.images) 

##-----------------------------------------------------------------------------------
class val_Dataset(Dataset):
def __init__(self, imgarray_val, maskarray_val, transform=None):

    
    self.images = imgarray_val
    self.masks = maskarray_val
    self.transform = transform

    
def __getitem__(self, index):
   
    img = self.images[index]
    if self.transform is not None:
        img = self.transform(img)
        
    #label = torch.from_numpy(self.masks[index])
    trnsf1 = transforms.RandomResizedCrop(input_size)
    trnsf2 = transforms.ToTensor()
    label = trnsf2(trnsf1(self.masks[index]))
  
    return img, label

def __len__(self):
    return len(self.images)

So basically resizing the image and then converting it into a tensor.
I am not certain if converting a mask image into a tensor is reasonable as my mask label contains class indexes (each pixel gets discrete values between 0 and 3). When I transform this image into a tensor, the values will be between 0 and 1. I wonder how the computations will take place?
Also, My mask tensors get the shape [N, C, W, H]=[2, 1, 224,224] and the output of the model has the shape of [2, 4, 224, 224]. When using CrossEntropy, I get an error telling me that the dimension of my target should be of 3 and not 4. How should I change this? should I drop the C  value and create a tensor of shape [N, W, H].