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

Ripley: <p>Hi, do anybody know why it will give this error? It points at  if (labels[i] == predicted[i]): .<br>
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.</p>
<p>‘’’   with torch.no_grad():<br>
# accuracy of each class<br>
n_classes_correct = [0 for i in range(self.numClass)]<br>
n_classes_samples = [0 for i in range(self.numClass)]<br>
cmatrix = np.zeros((self.numClass,self.numClass),np.int16)</p>
<pre><code>        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 x:x.to(device),[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

            print(images,labels,predicted)
            print('\n')
            print(type(predicted),type(labels))
            for i in range(labels.size(0)):
                print(i)
                print(labels[i], predicted[i])
                if (labels[i] == predicted[i]):
                    n_classes_correct[labels[i]] += 1
                n_classes_samples[labels[i]] += 1         '''
</code></pre>
<p>The error message</p>
<p>‘’’---------------------------------------------------------------------------<br>
RuntimeError                              Traceback (most recent call last)<br>
 in <br>
3 # classes = [“E_needleleaf”,“E_broadleaf”, “D_needleleaf”, “D_broadleaf”, “MixedForest”, “Closeshrublands”, “Openshrublands”, “WoodySavannas”, “Savannas”, “Grasslands”, “PermWetland”, “Cropland”, “Urban”, “VegeMosaics”, “Snow&amp;Ice”, “Barren”, “WaterBodies”]<br>
4 checkpoint = None<br>
----&gt; 5 train = trainer(imgdir= imgdir, classes = classes, reloadmode=‘same’, num_epochs = 5)<br>
6 train</p>
<p> in <strong>init</strong>(self, imgdir, classes, num_epochs, reloadmode, checkpoint, bs, report)<br>
158<br>
159             print(’\n’+’*‘<em>6+‘EVAL FOR ONE EPOCH’+’</em>’*6)<br>
–&gt; 160             overacc = self.evali()<br>
161<br>
162             if self.bestAccuracy is None or overacc &gt;= self.bestAccuracy or reloadmode == ‘different’:</p>
<p> in evali(self)<br>
334                     print(i)<br>
335                     print(labels[i], predicted[i])<br>
–&gt; 336                     if (labels[i] == predicted[i]):<br>
337                         n_classes_correct[labels[i]] += 1<br>
338                     n_classes_samples[labels[i]] += 1</p>
<p>RuntimeError: Boolean value of Tensor with more than one value is ambiguous ‘’’</p>

ptrblck: <p>This error is raised, if you are trying to compare more than a single value without calling <code>all()</code> or <code>any()</code> on the result.<br>
This comparison:</p>
<pre><code class="lang-python">labels[i] == predicted[i]
</code></pre>
<p>is apparently creating multiple result values so you could check the shape of <code>labels[i]</code> and <code>predicted[i]</code> and make sure to apply the right behavior.</p>

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

ptrblck: <p><code>(labels[i] == predicted[i]).all()</code> 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.</p>

Ripley: <p>Thanks for your advice! I will look into it!</p>