Scikit-learn: sklearn.metrics.classification_report incorrecto?

Creado en 1 abr. 2020  ·  3Comentarios  ·  Fuente: scikit-learn/scikit-learn

Describe el error

sklearn.metrics.classification puede informar valores invertidos para precisión y recuperación?

Pasos / Código para reproducir

from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets

def calc_precision_recall(conf_matrix, class_labels):

    # for each class
    for i in range(len(class_labels)):

        # calculate true positives
        true_positives =(conf_matrix[i, i])

        # false positives
        false_positives = (conf_matrix[i, :].sum() - true_positives)

        # false negatives
        false_negatives = 0
        for j in range(len(class_labels)):
            false_negatives += conf_matrix[j, i]
        false_negatives -= true_positives

        # and finally true negatives
        true_negatives= (conf_matrix.sum() - false_positives - false_negatives - true_positives)

        # print calculated values
        print(
            "Class label", class_labels[i],
            "T_positive", true_positives,
            "F_positive", false_positives,
            "T_negative", true_negatives,
            "F_negative", false_negatives,
            "\nSensitivity/recall", true_positives / (true_positives + false_negatives),
            "Specificity", true_negatives / (true_negatives + false_positives),
            "Precision", true_positives/(true_positives+false_positives), "\n"
        )

    return

# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, 0:3]  # we only take the first two features.
y = iris.target

# Random_state parameter is just a random seed that can be used to reproduce these specific results.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=27)

# Instantiate a K-Nearest Neighbors Classifier:
KNN_model = KNeighborsClassifier(n_neighbors=2)

# Fit the classifiers:
KNN_model.fit(X_train, y_train)

# Predict and store the prediction:
KNN_prediction = KNN_model.predict(X_test)

# Generate the confusion matrix
conf_matrix = confusion_matrix(KNN_prediction, y_test)

# Print the classification report
print(classification_report(KNN_prediction, y_test))

# Dummy class labels for the three iris classes
class_labels = [0,1,2]

# Own function to calculate precision and recall from the confusion matrix
calc_precision_recall(conf_matrix, class_labels)

Resultados previstos

Mi función devuelve lo siguiente para cada clase:

Etiqueta de clase 0 T_positivo 7 F_positivo 0 T_negativo 23 F_negativo 0
Sensibilidad / recuperación 1.0 Especificidad 1.0 Precisión 1.0

Etiqueta de clase 1 T_positivo 11 F_positivo 1 T_negativo 18 F_negativo 0
Sensibilidad / recuperación 1.0 Especificidad 0.9473684210526315 Precisión 0.9166666666666666

Etiqueta de clase 2 T_positivo 11 F_positivo 0 T_negativo 18 F_negativo 1
Sensibilidad / recuperación 0,9166666666666666 Especificidad 1,0 Precisión 1,0

          precision    recall  

       0       1.00      1.00      
       1       0.92      1.00    
       2       1.00      0.92

Mi función asume que la matriz de confusión está estructurada con valores reales en el eje x superior y valores predichos en el eje y izquierdo. Esta es la misma estructura que se usa en Wikipedia y a la que se hace referencia en la documentación para la función de matriz de confusión.

Resultados actuales

En contraste, estos son los resultados reportados por sklearn.metrics import class_report

           precision    recall  f1-score   support

       0       1.00      1.00      1.00         7
       1       1.00      0.92      0.96        12
       2       0.92      1.00      0.96        11

Versiones

Sistema:
python: 3.8.1 (predeterminado, 8 de enero de 2020, 22:29:32) [GCC 7.3.0]
ejecutable: / home / will / anaconda3 / envs / ElStatLearn / bin / python
máquina: Linux-4.15.0-91-generic-x86_64-with-glibc2.10

Dependencias de Python:
pip: 20.0.2
herramientas de configuración: 38.2.5
sklearn: 0.22.1
numpy: 1.18.1
scipy: 1.4.1
Cython: Ninguno
pandas: 1.0.1
matplotlib: 3.1.3
joblib: 0.14.1

Construido con OpenMP: Verdadero

triage metrics

Comentario más útil

Creo que y_test debería ir primero en print(classification_report(KNN_prediction, y_test)) .

Entonces: print(classification_report(y_test, KNN_prediction)) .

La función sklearn.metrics.classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division='warn') tiene y_true como primer argumento. Esto cambiaría la precisión y la memoria.

Ver informe_clasificación .

Editar: su matriz de confusión también está al revés, pero funciona porque la matriz de confusión de sklearn está al revés de wikipedia.

>>> from sklearn.metrics import confusion_matrix
>>> y_true = [2, 0, 2, 2, 0, 1]
>>> y_pred = [0, 0, 2, 2, 0, 2]
>>> confusion_matrix(y_true, y_pred)
array([[2, 0, 0],
       [0, 0, 1],
       [1, 0, 2]])

Puede ver que hay 1 observación en la fila 1 y 0 en la columna 1, por lo que las filas son la verdad básica y las columnas son predicciones. Entonces puede usar la notación C[i, j] muestra en confusion_matrix

Todos 3 comentarios

Creo que y_test debería ir primero en print(classification_report(KNN_prediction, y_test)) .

Entonces: print(classification_report(y_test, KNN_prediction)) .

La función sklearn.metrics.classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division='warn') tiene y_true como primer argumento. Esto cambiaría la precisión y la memoria.

Ver informe_clasificación .

Editar: su matriz de confusión también está al revés, pero funciona porque la matriz de confusión de sklearn está al revés de wikipedia.

>>> from sklearn.metrics import confusion_matrix
>>> y_true = [2, 0, 2, 2, 0, 1]
>>> y_pred = [0, 0, 2, 2, 0, 2]
>>> confusion_matrix(y_true, y_pred)
array([[2, 0, 0],
       [0, 0, 1],
       [1, 0, 2]])

Puede ver que hay 1 observación en la fila 1 y 0 en la columna 1, por lo que las filas son la verdad básica y las columnas son predicciones. Entonces puede usar la notación C[i, j] muestra en confusion_matrix

Muchas gracias por aclarar eso: ¡la referencia de wikipedia me confundió!

No hay problema, probablemente debería hacer que Wikipedia cambie su ejemplo a la orientación sklearn.

¿Fue útil esta página
0 / 5 - 0 calificaciones