![](/img/trans.png)
[英]Could not calculate accuracy, sensitivity and specificity of segmented image
[英]How to calculate Sensitivity, specificity and pos predictivity for each class in multi class classficaition
我檢查了所有生成混淆矩陣並計算 TP、TN、FP、FN 的 SO 問題。
Scikit-learn:如何獲得真陽性、真陰性、假陽性和假陰性
主要是它的用法
from sklearn.metrics import confusion_matrix
對於兩節課,這很容易
從 sklearn.metrics 導入 confusion_matrix
y_true = [1, 1, 0, 0]
y_pred = [1, 0, 1, 0]
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
對於 multiclass 有一個解決方案,但它只適用於頭等艙。 不是全班
def perf_measure(y_actual, y_pred):
class_id = set(y_actual).union(set(y_pred))
TP = []
FP = []
TN = []
FN = []
for index ,_id in enumerate(class_id):
TP.append(0)
FP.append(0)
TN.append(0)
FN.append(0)
for i in range(len(y_pred)):
if y_actual[i] == y_pred[i] == _id:
TP[index] += 1
if y_pred[i] == _id and y_actual[i] != y_pred[i]:
FP[index] += 1
if y_actual[i] == y_pred[i] != _id:
TN[index] += 1
if y_pred[i] != _id and y_actual[i] != y_pred[i]:
FN[index] += 1
return class_id,TP, FP, TN, FN
但這默認只計算一個類。
但是我想計算給定 4 類的每個類的值。 對於https://extendsclass.com/csv-editor.html#0697f61
我已經用這樣的excel完成了。
然后計算每個結果
我已經在 Excel 工作表中對其進行了自動化處理,但是在 python 或 sklearn 中是否有任何編程解決方案可以做到這一點?
使用multilabel_confusion_matrix
更容易。 對於您的示例,您還可以將labels=["A", "N", "O", "~"]
作為參數傳遞,以按首選順序獲取標簽。
from sklearn.metrics import multilabel_confusion_matrix
import numpy as np
mcm = multilabel_confusion_matrix(y_true, y_pred)
tps = mcm[:, 1, 1]
tns = mcm[:, 0, 0]
recall = tps / (tps + mcm[:, 1, 0]) # Sensitivity
specificity = tns / (tns + mcm[:, 0, 1]) # Specificity
precision = tps / (tps + mcm[:, 0, 1]) # PPV
這會為每個指標生成一個數組:
[[0.83333333 0.94285714 0.64 0.25 ] # Sensitivity / Recall
[0.99029126 0.74509804 0.91666667 1. ] # Specificity
[0.9375 0.83544304 0.66666667 1. ]] # Precision / PPV
或者,您可以在classification_report
中查看依賴於類的精度和召回率。 您可以使用output_dict=True
和每個類標簽獲得相同的列表。
>>> print(classification_report(y_true, y_pred))
precision recall f1-score support
A 0.94 0.83 0.88 18
N 0.84 0.94 0.89 70
O 0.67 0.64 0.65 25
~ 1.00 0.25 0.40 8
accuracy 0.82 121
macro avg 0.86 0.67 0.71 121
weighted avg 0.83 0.82 0.81 121
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.