python 中召回率和精度为零时的 F1 分数计算方法?

A way around F1 score calculation when recall and precision is zero in python?

我正在尝试创建一个绘图图,用于绘制每个时期的 f1 分数。我有一个计算 F1 分数的函数,但有时,我的模型的召回率和精度会在随机时期达到零。这随后意味着整个 F1 分数变为零。我怎样才能避免这个问题?是否有我可以放下的占位符值,或者该图是否会变为零?我如何在 python 中编码?

代码:

precision_nums = [0.5146262049674988,
                  0.6140350699424744, 0.0, 0.6796116232872009, 0.5716332197189331, 0.7028985619544983,
                  0.7329059839248657, 0.7030965685844421, 0.709796667098999, 0.6807432174682617, 0.708791196346283,
                  0.7094972133636475, 0.7105262875556946, 0.7118958830833435, 0.7184466123580933, 0.7184466123580933,
                  0.7025089859962463]

recall_nums = [0.5146262049674988,
               0.6140350699424744, 0.0, 0.6796116232872009, 0.5716332197189331, 0.7028985619544983,
               0.7329059839248657, 0.7030965685844421, 0.709796667098999, 0.6807432174682617, 0.708791196346283,
               0.7094972133636475, 0.7105262875556946, 0.7118958830833435, 0.7184466123580933, 0.7184466123580933,
               0.7025089859962463]


def f1_score_computation(precision, recall):
    f1_score_list = []
    for (precision_score, recall_score) in zip(precision, recall):
        f1_score_list.append(2 * ((precision_score * recall_score) / (precision_score + recall_score)))
    return f1_score_list


f1_score_computation(precision_nums, recall_nums)

您可以自行处理异常。

def f1_score_computation(precision, recall):
    f1_score_list = []
    for (precision_score, recall_score) in zip(precision, recall):
        try:
            f1_score_list.append(2 * ((precision_score * recall_score) / (precision_score + recall_score)))
        except ZeroDivisionError:
            f1_score_list.append(np.nan)
    return f1_score_list

每当您除以零时,这将 return np.nan。绘图库可以很好地处理 nan