功能精确和召回

时间:2018-03-22 17:02:35

标签: function precision precision-recall

作为机器学习的初学者,我想编写一个precision_recall函数来计算精度和召回率。但是,我必须使用该函数的第三个参数,我不知道该怎么做。如何修复以下代码?

def precision_recall(y_true, y_pred, third):
    return precision_score(y_true, y_pred), recall_score(y_true, y_pred)

因此,我应该如何更改从数组中提取给定类的代码?

1 个答案:

答案 0 :(得分:2)

您可以这样做:

import numpy as np
from sklearn.metrics import precision_score, recall_score 

def precision_recall(y_true, y_pred, scalar):
    class_true = (y_true == scalar)
    class_pred = (y_pred == scalar)
    return precision_score(class_true, class_pred), recall_score(class_true, class_pred)

true = np.array(['red', 'green', 'blue', 'red', 'green'])
pred = np.array(['red', 'green', 'red', 'red', 'red'])

print(precision_recall(true, pred, 'red'))
print(precision_recall(true, pred, 'green'))

输出:

(0.5, 1.0)
(1.0, 0.5)