利用sklearn對多分類的每個類別進行指標評價


  今天晚上,筆者接到客戶的一個需要,那就是:對多分類結果的每個類別進行指標評價,也就是需要輸出每個類型的精確率(precision),召回率(recall)以及F1值(F1-score)。
  對於這個需求,我們可以用sklearn來解決,方法並沒有難,筆者在此僅做記錄,供自己以后以及讀者參考。
  我們模擬的數據如下:

y_true = ['北京', '上海', '成都', '成都', '上海', '北京', '上海', '成都', '北京', '上海']
y_pred = ['北京', '上海', '成都', '上海', '成都', '成都', '上海', '成都', '北京', '上海']

其中y_true為真實數據,y_pred為多分類后的模擬數據。使用sklearn.metrics中的classification_report即可實現對多分類的每個類別進行指標評價。
  示例的Python代碼如下:

# -*- coding: utf-8 -*-
from sklearn.metrics import classification_report

y_true = ['北京', '上海', '成都', '成都', '上海', '北京', '上海', '成都', '北京', '上海']
y_pred = ['北京', '上海', '成都', '上海', '成都', '成都', '上海', '成都', '北京', '上海']

t = classification_report(y_true, y_pred, target_names=['北京', '上海', '成都'])

print(t)

輸出結果如下:

              precision    recall  f1-score   support

          北京       0.75      0.75      0.75         4
          上海       1.00      0.67      0.80         3
          成都       0.50      0.67      0.57         3

    accuracy                           0.70        10
   macro avg       0.75      0.69      0.71        10
weighted avg       0.75      0.70      0.71        10

需要注意的是,輸出的結果數據類型為str,如果需要使用該輸出結果,則可將該方法中的output_dict參數設置為True,此時輸出的結果如下:

{'北京': {'precision': 0.75, 'recall': 0.75, 'f1-score': 0.75, 'support': 4},
'上海': {'precision': 1.0, 'recall': 0.6666666666666666, 'f1-score': 0.8, 'support': 3},
'成都': {'precision': 0.5, 'recall': 0.6666666666666666, 'f1-score': 0.5714285714285715, 'support': 3},
'accuracy': 0.7,
'macro avg': {'precision': 0.75, 'recall': 0.6944444444444443, 'f1-score': 0.7071428571428572, 'support': 10},
'weighted avg': {'precision': 0.75, 'recall': 0.7, 'f1-score': 0.7114285714285715, 'support': 10}}

  使用confusion_matrix方法可以輸出該多分類問題的混淆矩陣,代碼如下:

from sklearn.metrics import confusion_matrix
y_true = ['北京', '上海', '成都', '成都', '上海', '北京', '上海', '成都', '北京', '上海']
y_pred = ['北京', '上海', '成都', '上海', '成都', '成都', '上海', '成都', '北京', '上海']
print(confusion_matrix(y_true, y_pred, labels = ['北京', '上海', '成都']))

輸出結果如下:

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

  為了將該混淆矩陣繪制成圖片,可使用如下的Python代碼:

# -*- coding: utf-8 -*-
# author: Jclian91
# place: Daxing Beijing
# time: 2019-11-14 21:52

from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import matplotlib as mpl

# 支持中文字體顯示, 使用於Mac系統
zhfont=mpl.font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")

y_true = ['北京', '上海', '成都', '成都', '上海', '北京', '上海', '成都', '北京', '上海']
y_pred = ['北京', '上海', '成都', '上海', '成都', '成都', '上海', '成都', '北京', '上海']


classes = ['北京', '上海', '成都']
confusion = confusion_matrix(y_true, y_pred)

# 繪制熱度圖
plt.imshow(confusion, cmap=plt.cm.Greens)
indices = range(len(confusion))
plt.xticks(indices, classes, fontproperties=zhfont)
plt.yticks(indices, classes, fontproperties=zhfont)
plt.colorbar()
plt.xlabel('y_pred')
plt.ylabel('y_true')

# 顯示數據
for first_index in range(len(confusion)):
    for second_index in range(len(confusion[first_index])):
        plt.text(first_index, second_index, confusion[first_index][second_index])

# 顯示圖片
plt.show()

生成的混淆矩陣圖片如下:

生成的混淆矩陣圖

  本次分享到此結束,感謝大家閱讀,也感謝在北京大興待的這段日子,當然還會再待一陣子~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM