sklearn.metrics.classification pode relatar valores invertidos para precisão e recuperação?
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)
Minha função retorna o seguinte para cada classe:
Rótulo de classe 0 T_positivo 7 F_positivo 0 T_negativo 23 F_negativo 0
Sensibilidade / recall 1.0 Especificidade 1.0 Precisão 1.0
Rótulo de classe 1 T_positivo 11 F_positivo 1 T_negativo 18 F_negativo 0
Sensibilidade / recall 1.0 Especificidade 0,9473684210526315 Precisão 0,9166666666666666
Rótulo de classe 2 T_positivo 11 F_positivo 0 T_negativo 18 F_negativo 1
Sensibilidade / recall 0,9166666666666666 Especificidade 1.0 Precisão 1.0
precision recall
0 1.00 1.00
1 0.92 1.00
2 1.00 0.92
Minha função assume que a matriz de confusão está estruturada com valores reais no eixo x superior e valores previstos no eixo y esquerdo. Esta é a mesma estrutura usada na Wikipedia e referenciada na documentação para a função de matriz de confusão.
Em contraste, esses são os resultados relatados por sklearn.metrics import classificação_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
Sistema:
python: 3.8.1 (padrão, 8 de janeiro de 2020, 22:29:32) [GCC 7.3.0]
executável: / home / will / anaconda3 / envs / ElStatLearn / bin / python
máquina: Linux-4.15.0-91-generic-x86_64-with-glibc2.10
Dependências do Python:
pip: 20.0.2
ferramentas de configuração: 38.2.5
sklearn: 0.22.1
numpy: 1.18.1
scipy: 1.4.1
Cython: Nenhum
pandas: 1.0.1
matplotlib: 3.1.3
joblib: 0.14.1
Construído com OpenMP: True
Acho que y_test
deve vir primeiro em print(classification_report(KNN_prediction, y_test))
.
Portanto: print(classification_report(y_test, KNN_prediction))
.
A função sklearn.metrics.classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division='warn')
tem y_true
como o primeiro argumento. Isso mudaria a precisão e a recuperação.
Veja classificação_report .
Edit: sua matriz de confusão está invertida também, mas funciona porque a matriz de confusão do sklearn está invertida da 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]])
Você pode ver que há 1 observação na linha 1 e 0 na coluna 1, então as linhas são verdadeiras e as colunas são previsões. Portanto, você pode usar a notação C[i, j]
mostrada em confused_matrix
Muito obrigado por esclarecer isso - a referência da Wikipedia me deixou confuso!
Não tem problema, provavelmente deveria fazer a Wikipedia mudar seu exemplo para a orientação sklearn.
Comentários muito úteis
Acho que
y_test
deve vir primeiro emprint(classification_report(KNN_prediction, y_test))
.Portanto:
print(classification_report(y_test, KNN_prediction))
.A função
sklearn.metrics.classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division='warn')
temy_true
como o primeiro argumento. Isso mudaria a precisão e a recuperação.Veja classificação_report .
Edit: sua matriz de confusão está invertida também, mas funciona porque a matriz de confusão do sklearn está invertida da wikipedia.
Você pode ver que há 1 observação na linha 1 e 0 na coluna 1, então as linhas são verdadeiras e as colunas são previsões. Portanto, você pode usar a notação
C[i, j]
mostrada em confused_matrix