访问classification_report中的数字 - sklearn

Had*_*dij 11 python classification scikit-learn

这是一个简单的例子classification_reportsklearn

from sklearn.metrics import classification_report
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
target_names = ['class 0', 'class 1', 'class 2']
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
Run Code Online (Sandbox Code Playgroud)

我希望能够访问平均/总行数.例如,我想从报告中提取f1-score,即0.61.

我怎样才能访问该号码classification_report

小智 15

您可以使用以下命令将分类报告输出为 dict:

report = classification_report(y_true, y_pred, **output_dict=True** )
Run Code Online (Sandbox Code Playgroud)

然后像在普通python 字典中一样访问它的单个值。

例如,宏观指标:

macro_precision =  report['macro avg']['precision'] 
macro_recall = report['macro avg']['recall']    
macro_f1 = report['macro avg']['f1-score']
Run Code Online (Sandbox Code Playgroud)

或精度:

accuracy = report['accuracy']
Run Code Online (Sandbox Code Playgroud)


Pra*_*mar 11

你可以用来precision_recall_fscore_support一次性获得所有

from sklearn.metrics import precision_recall_fscore_support as score
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
precision,recall,fscore,support=score(y_true,y_pred,average='macro')
print 'Precision : {}'.format(precision)
print 'Recall    : {}'.format(recall)
print 'F-score   : {}'.format(fscore)
print 'Support   : {}'.format(support)
Run Code Online (Sandbox Code Playgroud)

这是模块的链接

  • 答案是正确的,但请注意您使用了错误的参数,因为第一个参数是`y_true`,第二个应该是`y_pred`。 (2认同)

Gam*_*ugo 9

您可以在内置的分类报告中使用 output_dict 参数来返回字典:

classification_report(y_true,y_pred,output_dict=True)


Aks*_*kar 5

classification_report 是字符串,所以我建议您使用 scikit-learn 中的 f1_score

from sklearn.metrics import f1_score
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
target_names = ['class 0', 'class 1', 'class 2']

print(f1_score(y_true, y_pred, average=None)
Run Code Online (Sandbox Code Playgroud)

输出