Bool value of Tensor with more than one value is ambiguous in evaluation

Hi, do anybody know why it will give this error? It points at if (labels[i] == predicted[i]): .
The case I am working in is image segmentation with both my images and labels being .tiff files. And I have checked to ensure that my labels, and predicted are tensors. So I am confused as to why there is a boolean when both my labels and predicted are tensors.

‘’’ with torch.no_grad():
# accuracy of each class
n_classes_correct = [0 for i in range(self.numClass)]
n_classes_samples = [0 for i in range(self.numClass)]
cmatrix = np.zeros((self.numClass,self.numClass),np.int16)

        self.model = self.model.eval()
        eval_loss = 0
        itera = len(self.evalloader)
        for i, (images,labels) in tqdm(enumerate(self.evalloader), total=itera):
            images, labels = map(lambda,[images,labels])
            #The output of a label should be a tensor and not a tuple, if it is, look back at your y_label output of your dataset (make sure it is a tensor or a int to be able to convert into a tensor)
            outputs = self.model(images)

            # overall accuracy of model
            _, predicted = torch.max(outputs, 1)
            self.n_samples += labels.size(0)
            self.n_correct += (predicted == labels).sum().item()

            # loss = self.loss_function(outputs, labels,weight=torch.FloatTensor([0.2,1.0,0.4,0]).to(device))
            # eval_loss += loss.item()

            # for confusion matrix later
            for j, k in zip(labels.cpu().numpy().flatten(),predicted.cpu().numpy().flatten()):
                cmatrix[j,k] += 1

            for i in range(labels.size(0)):
                print(labels[i], predicted[i])
                if (labels[i] == predicted[i]):
                    n_classes_correct[labels[i]] += 1
                n_classes_samples[labels[i]] += 1         '''

The error message

RuntimeError Traceback (most recent call last)
3 # classes = [“E_needleleaf”,“E_broadleaf”, “D_needleleaf”, “D_broadleaf”, “MixedForest”, “Closeshrublands”, “Openshrublands”, “WoodySavannas”, “Savannas”, “Grasslands”, “PermWetland”, “Cropland”, “Urban”, “VegeMosaics”, “Snow&Ice”, “Barren”, “WaterBodies”]
4 checkpoint = None
----> 5 train = trainer(imgdir= imgdir, classes = classes, reloadmode=‘same’, num_epochs = 5)
6 train

in init(self, imgdir, classes, num_epochs, reloadmode, checkpoint, bs, report)
159 print(’\n’+’*‘6+‘EVAL FOR ONE EPOCH’+’’*6)
–> 160 overacc = self.evali()
162 if self.bestAccuracy is None or overacc >= self.bestAccuracy or reloadmode == ‘different’:

in evali(self)
334 print(i)
335 print(labels[i], predicted[i])
–> 336 if (labels[i] == predicted[i]):
337 n_classes_correct[labels[i]] += 1
338 n_classes_samples[labels[i]] += 1

RuntimeError: Boolean value of Tensor with more than one value is ambiguous ‘’’

This error is raised, if you are trying to compare more than a single value without calling all() or any() on the result.
This comparison:

labels[i] == predicted[i]

is apparently creating multiple result values so you could check the shape of labels[i] and predicted[i] and make sure to apply the right behavior.

hmm would it be possible to give an example of how i can implement the torch.all() function? Thanks alot!

(labels[i] == predicted[i]).all() should work. However, I don’t think this will yield your desired result as it seems you expect to compare scalar values instead of tensors, so I would still recommend to check the shape and make sure the indexing works as expected.

1 Like

Thanks for your advice! I will look into it!