Python利用Seaborn繪制多標(biāo)簽的混淆矩陣
Seaborn - 繪制多標(biāo)簽的混淆矩陣、召回、精準(zhǔn)、F1
導(dǎo)入seaborn\matplotlib\scipy\sklearn等包:
import seaborn as sns from matplotlib import pyplot as plt from scipy.special import softmax from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score sns.set_theme(color_codes=True)
從dataframe中,獲取y_true(真實(shí)標(biāo)簽)和y_pred(預(yù)測(cè)標(biāo)簽):
y_true = df["target"] y_pred = df['prediction']
計(jì)算驗(yàn)證數(shù)據(jù)整體的準(zhǔn)確率acc、精準(zhǔn)率precision、召回率recall、F1,使用加權(quán)模式average=‘weighted’:
# 準(zhǔn)確率acc,精準(zhǔn)precision,召回recall,F(xiàn)1
acc = accuracy_score(df["target"], df['prediction'])
precision = precision_score(y_true, y_pred, average='weighted')
recall = recall_score(y_true, y_pred, average='weighted')
f1 = f1_score(y_true, y_pred, average='weighted')
print(f'[Info] acc: {acc}, precision: {precision}, recall: {recall}, f1: {f1}')
計(jì)算混淆矩陣:
# 橫坐標(biāo)是真實(shí)類別數(shù),縱坐標(biāo)是預(yù)測(cè)類別數(shù) cf_matrix = confusion_matrix(y_true, y_pred)
5類矩陣的繪制方案,混淆矩陣、百分比的混淆矩陣、召回矩陣、精準(zhǔn)矩陣、F1矩陣:
- 混淆矩陣是計(jì)數(shù),百分比的混淆矩陣是占比
- 召回矩陣是,每行的和是1,每行代表真實(shí)類別數(shù),占比就是召回
- 精準(zhǔn)矩陣是,每列的和是1,每列代表預(yù)測(cè)列表數(shù),占比就是精準(zhǔn)
- F1矩陣是按照 2PR/(P+R),注意為0的情況,需要補(bǔ)0,使用np.divide(a, b, out=np.zeros_like(a), where=(b != 0))
代碼如下:
# 橫坐標(biāo)是真實(shí)類別數(shù),縱坐標(biāo)是預(yù)測(cè)類別數(shù)
cf_matrix = confusion_matrix(y_true, y_pred)
figure, axes = plt.subplots(2, 2, figsize=(16*1.25, 16))
# 混淆矩陣
ax = sns.heatmap(cf_matrix, annot=True, fmt='g', ax=axes[0][0], cmap='Blues')
ax.title.set_text("Confusion Matrix")
ax.set_xlabel("y_pred")
ax.set_ylabel("y_true")
# plt.savefig(csv_path.replace(".csv", "_cf_matrix.png"))
# plt.show()
# 混淆矩陣 - 百分比
cf_matrix = confusion_matrix(y_true, y_pred)
ax = sns.heatmap(cf_matrix / np.sum(cf_matrix), annot=True, ax=axes[0][1], fmt='.2%', cmap='Blues')
ax.title.set_text("Confusion Matrix (percent)")
ax.set_xlabel("y_pred")
ax.set_ylabel("y_true")
# plt.savefig(csv_path.replace(".csv", "_cf_matrix_p.png"))
# plt.show()
# 召回矩陣,行和為1
sum_true = np.expand_dims(np.sum(cf_matrix, axis=1), axis=1)
precision_matrix = cf_matrix / sum_true
ax = sns.heatmap(precision_matrix, annot=True, fmt='.2%', ax=axes[1][0], cmap='Blues')
ax.title.set_text("Precision Matrix")
ax.set_xlabel("y_pred")
ax.set_ylabel("y_true")
# plt.savefig(csv_path.replace(".csv", "_recall.png"))
# plt.show()
# 精準(zhǔn)矩陣,列和為1
sum_pred = np.expand_dims(np.sum(cf_matrix, axis=0), axis=0)
recall_matrix = cf_matrix / sum_pred
ax = sns.heatmap(recall_matrix, annot=True, fmt='.2%', ax=axes[1][1], cmap='Blues')
ax.title.set_text("Recall Matrix")
ax.set_xlabel("y_pred")
ax.set_ylabel("y_true")
# plt.savefig(csv_path.replace(".csv", "_precision.png"))
# plt.show()
# 繪制4張圖
plt.autoscale(enable=False)
plt.savefig(csv_path.replace(".csv", "_all.png"), bbox_inches='tight', pad_inches=0.2)
plt.show()
# F1矩陣
a = 2 * precision_matrix * recall_matrix
b = precision_matrix + recall_matrix
f1_matrix = np.divide(a, b, out=np.zeros_like(a), where=(b != 0))
ax = sns.heatmap(f1_matrix, annot=True, fmt='.2%', cmap='Blues')
ax.title.set_text("F1 Matrix")
ax.set_xlabel("y_pred")
ax.set_ylabel("y_true")
plt.savefig(csv_path.replace(".csv", "_f1.png"))
plt.show()
輸出混淆矩陣、混淆矩陣(百分比)、召回矩陣、精準(zhǔn)矩陣:

F1 Score:

到此這篇關(guān)于Python利用Seaborn繪制多標(biāo)簽的混淆矩陣的文章就介紹到這了,更多相關(guān)Python Seaborn混淆矩陣內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python機(jī)器學(xué)習(xí)利用鳶尾花數(shù)據(jù)繪制ROC和AUC曲線
這篇文章主要為大家介紹了Python機(jī)器學(xué)習(xí)利用鳶尾花數(shù)據(jù)繪制ROC和AUC曲線實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
Python 按比例獲取樣本數(shù)據(jù)或執(zhí)行任務(wù)的實(shí)現(xiàn)代碼
這篇文章主要介紹了Python 按比例獲取樣本數(shù)據(jù)或執(zhí)行任務(wù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
簡(jiǎn)單了解python 生成器 列表推導(dǎo)式 生成器表達(dá)式
這篇文章主要介紹了簡(jiǎn)單了解python 生成器 列表推導(dǎo)式 生成器表達(dá)式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Keras在mnist上的CNN實(shí)踐,并且自定義loss函數(shù)曲線圖操作
這篇文章主要介紹了Keras在mnist上的CNN實(shí)踐,并且自定義loss函數(shù)曲線圖操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2021-05-05
python+selenium 腳本實(shí)現(xiàn)每天自動(dòng)登記的思路詳解
這篇文章主要介紹了python+selenium 腳本實(shí)現(xiàn)每天自動(dòng)登記,本文你給大家分享基本的思路,通過(guò)實(shí)例代碼截圖的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03
使用python讀寫(xiě)txt和json(jsonl)大文件的方法步驟
在Python中讀取txt和json(jsonl)大文件并保存到字典是一項(xiàng)非常常見(jiàn)的操作,這篇文章主要給大家介紹了關(guān)于使用python讀寫(xiě)txt和json(jsonl)大文件的方法步驟,需要的朋友可以參考下2023-12-12
python實(shí)現(xiàn)用戶名密碼校驗(yàn)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)用戶名密碼校驗(yàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03

