votes up 0

At least one label specified must be in y_true

Package:
Exception Class:
ValueError

Raise code

        labels = np.asarray(labels)
        n_labels = labels.size
        if n_labels == 0:
            raise ValueError("'labels' should contains at least one label.")
        elif y_true.size == 0:
            return np.zeros((n_labels, n_labels), dtype=int)
        elif len(np.intersect1d(y_true, labels)) == 0:
            raise ValueError("At least one label specified must be in y_true")

    if sample_weight is None:
        sample_weight = np.ones(y_true.shape[0], dtype=np.int64)
    else:
        sample_weight = np.asarray(sample_weight)

    check_consistent_length(y_true, y_pred, sample_weight)

Ways to fix

votes up 2 votes down

If the labels argument is given when calculating a confusion matrix then the label array or list should contain all the labels in y_true and y_pred .

e.g. If the labels = [1,0] then y_true shouldn't contain the label 2 i.e y_true = [2,0,1,1] .

This is what caused the error.

How to reproduce:

$ pipenv install numpy sklearn

  • sample code

import numpy as np
from sklearn.metrics import confusion_matrix
y_true = [2, 2, 2, 2, 2, 2]
y_pred = [0, 0, 0, 0, 0, 0]

cm = confusion_matrix(y_true, y_pred,labels=[1,0])
print(cm)

Fix: labels should contain all the labels in y_true. i.e labels = [0,1,2].

 
import numpy as np
from sklearn.metrics import confusion_matrix
y_true = [2, 2, 2, 2, 2, 2]
y_pred = [0, 0, 0, 0, 0, 0]

cm = confusion_matrix(y_true, y_pred,labels=[1,0,2])
print(cm)

Jun 10, 2021 kellemnegasi answer
kellemnegasi 2.7k

Add a possible fix

Please authorize to post fix