使用 classification_report 输出每类 f1-score 并高亮低分

解读

面试官真正想看的是:

  1. 你是否熟悉 classification_report 的底层结构(返回的是可解析的 dict,而非仅打印字符串);
  2. 能否用 Pandas 快速对齐类别与指标,并用 style 或条件格式把低 f1-score 标红;
  3. 是否具备工程化思维:低分高亮不是“炫技”,而是快速定位业务痛点(如金融风控中的“违约”类、医疗中的“阳性”类),为后续样本重采样、阈值移动或代价敏感学习提供依据。
    国内面试节奏快,30 秒内给出可运行代码 + 1 句话说明业务含义即可拿到高分。

知识点

  • classification_report(y_true, y_pred, output_dict=True):返回嵌套 dict,键为类别标签,值为 precision/recall/f1/support。
  • f1-score 阈值设定:通常 <0.5 视为低分,但以业务指标为准(如金融场景 f1<0.6 即触发模型下线)。
  • Pandas Styler.applymap / style.highlight_min:在 Notebook 中零代码量即可高亮,比 print 后手动肉眼筛查效率提升 10 倍。
  • 中文对齐问题:国内数据标签常带中文,务必保证类别列 dtype=object,否则 Styler 会抛 KeyError。
  • 多分类 vs 多标签:classification_report 默认多分类,多标签需指定 target_names 防止标签错位。

答案

from sklearn.metrics import classification_report
import pandas as pd

def highlight_low_f1(report_dict, threshold=0.5):
    """
    返回一个已高亮低 f1-score 的 DataFrame,可直接在 Jupyter 展示。
    threshold 可按业务调整。
    """
    # 1. 转 DataFrame 并只保留 f1-score 列
    df = pd.DataFrame(report_dict).T
    f1_col = df['f1-score'].astype(float)
    
    # 2. 构造样式函数
    def color_below(val):
        color = 'red' if val < threshold else ''
        return f'color: {color}; font-weight: bold'
    
    # 3. 应用样式并隐藏 support 列,让面试官一眼看到重点
    styled = f1_col.to_frame().style.applymap(color_below)
    return styled

# ===== 使用示例 =====
y_true = [0, 1, 2, 2, 2, 0, 1, 1, 0, 2]
y_pred = [0, 0, 2, 1, 2, 0, 1, 0, 0, 2]

report = classification_report(y_true, y_pred, output_dict=True)
highlight_low_f1(report, threshold=0.5)

运行效果:f1-score 低于 0.5 的类别自动红色加粗,无需肉眼比对,直接定位到“类别 1”样本不足或特征区分度差的问题。

拓展思考

  1. 生产环境落地:把上述函数封装成 Airflow 任务,每日模型漂移检测后自动邮件推送“低 f1 类别”截图,实现 0 人工巡检。
  2. 阈值动态化:用验证集 f1 的 10% 分位数作为阈值,而非固定 0.5,防止类别极度不平衡时误报。
  3. 宏微观结合:除了按类 f1,同步输出 macro/weighted avg,当 macro f1 与 weighted f1 差距 >0.1 时,触发“少数类再采样”预警,这是国内大厂模型监控的通用红线指标。