[英]how to score precision, recall and f1-score in a multi-class dataset using cross-validate?
[英]F1-score per class for multi-class classification
我正在使用 python 和 scikit-learn 處理多類分類問題。 目前,我正在使用classification_report
函數來評估classification_report
的性能,獲得如下報告:
>>> print(classification_report(y_true, y_pred, target_names=target_names))
precision recall f1-score support
class 0 0.50 1.00 0.67 1
class 1 0.00 0.00 0.00 1
class 2 1.00 0.67 0.80 3
avg / total 0.70 0.60 0.61 5
為了做進一步的分析,我對獲得每個可用類的每類 f1 分數很感興趣。 也許是這樣的:
>>> print(calculate_f1_score(y_true, y_pred, target_class='class 0'))
0.67
scikit-learn 上有類似的東西嗎?
取自f1_score
文檔。
from sklearn.metrics import f1_score
y_true = [0, 1, 2, 0, 1, 2]
y_pred = [0, 2, 1, 0, 0, 1]
f1_score(y_true, y_pred, average=None)
輸出:
array([ 0.8, 0. , 0. ])
這是每個班級的分數。
如果您只有混淆矩陣C
,行對應於預測,列對應於事實,則可以使用以下函數計算 F1 分數:
def f1(C):
num_classes = np.shape(C)[0]
f1_score = np.zeros(shape=(num_classes,), dtype='float32')
weights = np.sum(C, axis=0)/np.sum(C)
for j in range(num_classes):
tp = np.sum(C[j, j])
fp = np.sum(C[j, np.concatenate((np.arange(0, j), np.arange(j+1, num_classes)))])
fn = np.sum(C[np.concatenate((np.arange(0, j), np.arange(j+1, num_classes))), j])
# tn = np.sum(C[np.concatenate((np.arange(0, j), np.arange(j+1, num_classes))), np.concatenate((np.arange(0, j), np.arange(j+1, num_classes)))])
precision = tp/(tp+fp) if (tp+fp) > 0 else 0
recall = tp/(tp+fn) if (tp+fn) > 0 else 0
f1_score[j] = 2*precision*recall/(precision + recall)*weights[j] if (precision + recall) > 0 else 0
f1_score = np.sum(f1_score)
return f1_score
您只需要使用 pos_label 作為參數並分配要打印的類值。
f1_score(ytest, ypred_prob, pos_label=0)# default is pos_label=1
我會使用f1_score
和labels
參數
from sklearn.metrics import f1_score
y_true = [0, 1, 2, 0, 1, 2]
y_pred = [0, 2, 1, 0, 0, 1]
labels = [0, 1, 2]
f1_scores = f1_score(y_true, y_pred, average=None, labels=labels)
f1_scores_with_labels = {label:score for label,score in zip(labels, f1_scores)}
輸出:
{0: 0.8, 1: 0.0, 2: 0.0}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.