开始使用免费开始使用

优化阈值

您听说理论上默认值 0.5 能最大化准确率,但您想验证在实践中的表现。为此,您将尝试多个不同的阈值,查看各自得到的准确率,从而确定表现最好的阈值。然后对 F1 得分重复同样的实验。0.5 是最佳阈值吗?准确率与 F1 的最佳阈值是否相同?动手找出答案吧!您已有通过对测试数据打分得到的 scores 矩阵。测试数据的真实标签也以 y_test 提供。最后,已预加载两个 numpy 函数 argmin()argmax(),它们分别返回数组最小值与最大值的索引,同时还提供了评估指标 accuracy_score()f1_score()

本练习是课程的一部分

用 Python 设计机器学习工作流

查看课程

练习说明

  • 创建一组包含 0.0、0.25、0.5、0.75 和 1.0 的阈值。
  • 通过双重列表推导式,存储上述每个阈值对应的预测。回忆一下,若使用阈值 thr 从得分矩阵生成标签,可用 [s[1] > thr for s in scores]
  • 遍历该列表并计算每个阈值的准确率。对 F1 得分重复上述步骤。
  • 使用 argmin()argmax(),分别找出准确率与 F1 的最优阈值。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Create a range of equally spaced threshold values
t_range = ____

# Store the predicted labels for each value of the threshold
preds = [[____ > thr for s in scores] for ____ in ____]

# Compute the accuracy for each threshold
accuracies = [____(____, ____) for p in preds]

# Compute the F1 score for each threshold
f1_scores = [____(____, ____) for p in preds]

# Report the optimal threshold for accuracy, and for F1
print(t_range[____(accuracies)], t_range[____(f1_scores)])
编辑并运行代码