Как построить матрицу путаницы 2×2 с предсказаниями в строках и реальными значениями в столбцах?

#python #machine-learning #scikit-learn #confusion-matrix

Вопрос:

Я знаю, что мы можем построить матрицу путаницы с помощью sklearn, используя следующий пример кода.

 from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay import matplotlib.pyplot as plt  y_true = [1, 0, 1, 1, 0, 1] y_pred = [0, 0, 1, 1, 0, 1]  print(f'y_true: {y_true}') print(f'y_pred: {y_pred}n')  cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) print(cm) disp = ConfusionMatrixDisplay(confusion_matrix=cm) disp.plot() plt.show()  

введите описание изображения здесь

Что у нас есть:

 TN | FP FN | TP  

Но я хочу, чтобы метка прогноза была размещена в строке или по оси y, а метка истинного или реального значения-в столбце или по оси x. Как я могу построить это с помощью Python?

Чего я хочу:

 TP | FP FN | TN  

Ответ №1:

Не уверен, что вы подразумеваете под «Построить это», но если вы просто пытаетесь переместить элементы данных, вы можете сделать это с iloc[] помощью и назначения

 df   0 1 0 TN FP 1 FN TP   df.iloc[0,0], df.iloc[1,1]=df.iloc[1,1],df.iloc[0,0]  df  0 1 0 TP FP 1 FN TN  

Комментарии:

1. «построить это» означает матрицу путаницы с предсказаниями в строках и реальными значениями в столбцах как реальный график, а не как текстовый вывод

2. @Zion в вашем вопросе нет никакого сюжета (реального или нет), только текстовый вывод. Сообщение здесь ответило на вопрос точно так, как было задано.

Ответ №2:

(1) Вот один из способов обратить вспять TP/TN.

Код

 """ Reverse True and Prediction labels  References:  https://github.com/scikit-learn/scikit-learn/blob/0d378913b/sklearn/metrics/_plot/confusion_matrix.py  https://scikit-learn.org/stable/modules/generated/sklearn.metrics.ConfusionMatrixDisplay.html """  from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay import matplotlib.pyplot as plt  y_true = [1, 0, 1, 1, 0, 1] y_pred = [0, 0, 1, 1, 0, 1]  print(f'y_true: {y_true}') print(f'y_pred: {y_pred}n')  # Normal print('Normal') cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) print(cm) disp = ConfusionMatrixDisplay(confusion_matrix=cm) disp.plot()  plt.savefig('normal.png') plt.show()  # Reverse TP and TN print('Reverse TP and TN') cm = confusion_matrix(y_pred, y_true, labels=[1, 0]) # reverse true/pred and label values print(cm) disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[1, 0]) # reverse display labels dp = disp.plot() dp.ax_.set(ylabel="My Prediction Label") # modify ylabel of ax_ attribute of plot dp.ax_.set(xlabel="My True Label") # modify xlabel of ax_ attribute of plot  plt.savefig('reverse.png') plt.show()  

Выход

 y_true: [1, 0, 1, 1, 0, 1] y_pred: [0, 0, 1, 1, 0, 1]  Normal [[2 0]  [1 3]]  

введите описание изображения здесь

 Reverse TP and TN [[3 0]  [1 2]]  

введите описание изображения здесь

(2) Другой способ-поменять местами значения и построить их с помощью sns/matplotlib.

Код

 import seaborn as sns from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt   y_true = [1, 0, 1, 1, 0, 1] y_pred = [0, 0, 1, 1, 0, 1]  cm = confusion_matrix(y_true, y_pred) print(cm) cm_11 = cm[1][1] # backup value in cm[1][1] cm[1][1] = cm[0][0] # swap cm[0][0] = cm_11 # swap print(cm)  ax = sns.heatmap(cm, annot=True)  plt.yticks([1.5, 0.5], ['0', '1'], ha='right') plt.xticks([1.5, 0.5], ['0', '1'], ha='right')  ax.set(xlabel='True Label', ylabel='Prediction Label') plt.savefig('reverse_tp_tn.png') plt.show()  

Выход

 [[2 0]  [1 3]] [[3 0]  [1 2]]  

введите описание изображения здесь