F-Score是一种衡量分类模型性能的指标,常用于二分类问题。其计算公式为:

其中,Precision是精确率,Recall是召回率,是权重因子。 Precision是预测为正的样本中实际为正的比例,Recall是实际为正的样本中预测为正的比例。

标准代码如下

def f_score(y_true, y_pred, beta):
    tp = np.sum((y_true == 1) & (y_pred == 1))
    fn = np.sum((y_true == 1) & (y_pred == 0))
    fp = np.sum((y_true == 0) & (y_pred == 1))

    recall = tp / (tp + fn) if (tp + fn) > 0 else 0
    precision = tp / (tp + fp) if (tp + fp) > 0 else 0

    op = precision * recall
    div = ((beta**2) * precision) + recall

    if div == 0 or op == 0:
        return 0.0

    score = (1 + (beta ** 2)) * op / div
    return round(score, 3)

该分数是一个常见的分类模型评价指标,也可以使用sklearn库中的fbeta_score函数来实现F-Score的计算。

def f_score(y_true, y_pred, beta):
    from sklearn.metrics import fbeta_score
    return round(fbeta_score(y_true, y_pred, beta=beta),3)