分类评估指标完整指南

分类评估指标完整指南 · Classification Metrics Guide

分类评估指标完整指南从混淆矩阵到 Accuracy、Precision、Recall、F1-score 的全面解析

理解机器学习分类任务中四大核心评估指标的原理、公式、适用场景与权衡关系

一、概述:为什么需要评估指标

在机器学习的分类任务中,模型预测的结果需要用客观、量化的指标来评估好坏。仅仅知道”模型预测了 95 个正确”是不够的——我们需要知道它在正类负类上分别表现如何,是否偏向某一类,以及在特定业务场景下是否满足要求[1]

核心问题:不同指标衡量的是模型性能的不同维度。没有”万能指标”——选择哪个指标取决于具体的业务场景、数据分布和代价权衡。理解每个指标的定义、适用条件和局限性是正确评估模型的前提。

1.1 四大核心指标速览

Accuracy

整体预测正确率。所有预测中正确的比例。直观但惧怕数据不均衡。

Precision

查准率。预测为正的样本中,真正为正的比例。关注”预测的纯度”。

Recall

查全率。实际为正的样本中,被正确预测的比例。关注”是否漏掉”。

F1-score

精确率与召回率的调和平均。综合平衡两者的单一指标。
混淆矩阵 TP / TN / FP / FN
Accuracy · Precision · Recall · F1
图 1 四大评估指标均由混淆矩阵中的四个基本量推导而来

二、混淆矩阵:一切的基础

混淆矩阵(Confusion Matrix)是一个 2×2 的表格,将模型预测结果与真实标签交叉对比,产生四个基本量。所有评估指标都从这四个量推导而来[2]

2.1 四个基本量

预测为正
预测为负
实际为正
TPTrue Positive
FNFalse Negative
实际为负
FPFalse Positive
TNTrue Negative
表 1 混淆矩阵四个基本量的含义
符号名称含义通俗理解
TPTrue Positive实际为正,预测为正正确发现(命中)
TNTrue Negative实际为负,预测为负正确排除(正确拒绝)
FPFalse Positive实际为负,预测为正误报(假阳性 / Type I 错误)
FNFalse Negative实际为正,预测为负漏报(假阴性 / Type II 错误)

2.2 记忆口诀

速记规则

T / F = 预测是否正确(True = 对了,False = 错了)

P / N = 模型的预测类别(Positive = 预测为正,Negative = 预测为负)

组合起来:TP = 预测正确且预测为正;FP = 预测错误且预测为正(实际上是负)。

关键关系:样本总数 = TP + TN + FP + FN。其中 TP + FN = 实际正类总数,TP + FP = 预测正类总数。这两个关系是推导所有指标的基石。

三、Accuracy(准确率)

Accuracy(准确率)是最直观的评估指标,表示所有样本中模型预测正确的比例[3]

Accuracy 公式
Accuracy = (TP + TN) / (TP + TN + FP + FN)

3.1 直观理解

Accuracy 回答的问题是:“模型整体表现如何?” 它将正类和负类的正确预测一视同仁地计入分子,是唯一同时考虑 TN 的指标。

TP (60)
命中
60
TN (30)
正确排除
30
FP (5)
误报
5
FN (5)
漏报
5
Accuracy
90 / 100
90%
图 2 Accuracy 示例:100 个样本中 90 个预测正确(TP=60 + TN=30),准确率 = 90%

3.2 Accuracy 的致命陷阱

不均衡数据的陷阱:当数据严重不均衡时,Accuracy 会产生误导。例如,1000 封邮件中 950 封是正常邮件、50 封是垃圾邮件。一个什么都不做的分类器(全部判为”正常”)的 Accuracy = 950/1000 = 95%,但它完全没有识别出任何垃圾邮件[3]

✅ 适用场景

各类别样本数量大致均衡

正类和负类的错误代价相近

需要快速了解整体表现

多分类任务的初始参考

❌ 不适用场景

数据严重不均衡(如欺诈检测、罕见病诊断)

正类极少但极重要(漏报代价高)

单独使用 Accuracy 作为唯一指标

需要区分不同类型错误的场景

四、Precision(精确率 / 查准率)

Precision(精确率,又称查准率)衡量的是:在所有被模型预测为正的样本中,实际为正的比例[1]

Precision 公式
Precision = TP / (TP + FP)

4.1 直观理解

Precision 回答的问题是:“模型说’是’的时候,有多可信?” 它关注的是预测的纯度——预测为正的样本中,有多少是真正的正样本。

垃圾邮件过滤的例子

模型标记了 20 封邮件为”垃圾邮件”,其中 16 封确实是垃圾邮件,4 封是正常邮件被误判。则 Precision = 16 / 20 = 80%

Precision 越高,意味着正常邮件被误判为垃圾邮件的可能性越低——用户不会因为重要邮件被误删而受损失。

4.2 Precision 的特性

表 2 Precision 指标特性分析
维度说明
关注焦点预测为正的纯度(减少 FP)
分子TP(正确预测的正样本)
分母TP + FP(所有预测为正的样本)
不含 TN不关心正确排除的负样本
极端值FP=0 时 Precision=1(宁可少报也不错报)
提高方式提高判断门槛,只对最有把握的样本预测为正
Precision 的局限:高 Precision 不一定代表好模型。如果模型极度保守,只对 1 个最确信的样本预测为正(且确实为正),Precision = 1/1 = 100%,但它可能漏掉了 999 个正样本。高 Precision 可能以牺牲 Recall 为代价。

五、Recall(召回率 / 查全率)

Recall(召回率,又称查全率、灵敏度 Sensitivity、真阳性率 TPR)衡量的是:在所有实际为正的样本中,被模型正确预测为正的比例[4]

Recall 公式
Recall = TP / (TP + FN)

5.1 直观理解

Recall 回答的问题是:“所有真正的正样本,模型找到了多少?” 它关注的是查全率——有没有漏掉应该被发现的正样本。

癌症检测的例子

100 个患癌病人中,模型正确识别了 85 个,漏掉了 15 个。则 Recall = 85 / 100 = 85%

Recall 越高,意味着越少的病人被漏诊。在医疗场景中,漏诊(FN)的代价远高于误诊(FP)——宁可多做一次检查,也不能放过一个病人。

5.2 Recall 的特性

表 3 Recall 指标特性分析
维度说明
关注焦点正样本的覆盖率(减少 FN)
分子TP(被找到的正样本)
分母TP + FN(所有实际为正的样本)
不含 TN不关心正确排除的负样本
极端值FN=0 时 Recall=1(全部找到,宁可错报)
提高方式降低判断门槛,对所有可能为正的样本都预测为正
Recall 的局限:高 Recall 不一定代表好模型。如果模型对所有样本都预测为正,则 FN=0,Recall=100%,但它产生了大量 FP。高 Recall 可能以牺牲 Precision 为代价。

六、F1-score(F1 分数)

F1-score 是 Precision 和 Recall 的调和平均(Harmonic Mean),用于在两者之间取得平衡[5]

F1-score 公式
F1 = 2 × (Precision × Recall) / (Precision + Recall)

等价形式:

F1 = 2 × TP / (2 × TP + FP + FN)

6.1 为什么用调和平均?

调和平均与算术平均的关键区别在于:它对极端值更敏感。如果 Precision=0.01 而 Recall=1.0,算术平均 = 0.505(看起来还行),但调和平均 F1 = 0.0198(暴露了 Precision 极低的问题)[5]

表 4 不同平均方式对比
PrecisionRecall算术平均F1(调和平均)
0.800.800.800.80
0.900.500.700.643
1.000.500.750.667
0.011.000.5050.0198
0.001.000.500.00
调和平均的惩罚性:当 Precision 或 Recall 任一为 0 时,F1 一定为 0。这意味着 F1 要求模型在两个维度上都表现不错,不允许”一条腿走路”。而算术平均会掩盖一个极端低值的问题。

6.2 F-beta 推广

F1 是更一般的 F-β 指标的特例(β=1)。β 控制了 Recall 相对于 Precision 的权重:

F-β 公式
Fβ = (1 + β²) × (Precision × Recall) / (β² × Precision + Recall)

F1 (β=1)

Precision 和 Recall 等权。最常用的综合指标。

F2 (β=2)

Recall 权重更高。适用于漏报代价高的场景(如医疗)。

F0.5 (β=0.5)

Precision 权重更高。适用于误报代价高的场景(如垃圾邮件)。

七、指标间的关系与权衡

7.1 Precision-Recall 的跷跷板效应

Precision 和 Recall 之间存在天然的权衡关系(Trade-off)。通过调整分类阈值,可以提高一个指标但通常会降低另一个[4]

降低阈值 预测更多正样本 Recall ↑ + FP ↑ Precision ↓
提高阈值 预测更少正样本 Precision ↑ + FN ↑ Recall ↓
图 3 Precision-Recall 权衡:调整阈值如踩跷跷板,一端上升则另一端下降

7.2 四指标关系图

表 5 四大指标的核心对比
指标公式关注不包含最怕
Accuracy(TP+TN)/All整体正确率数据不均衡
PrecisionTP/(TP+FP)预测纯度TNFP 过多
RecallTP/(TP+FN)正类覆盖TNFN 过多
F12PR/(P+R)P/R 平衡TNP 或 R 极端
关键洞察:Precision、Recall、F1 三个指标都不包含 TN。这意味着在负样本极多的场景下(如欺诈检测,99.9% 是正常交易),TN 虽然巨大但不参与这三个指标的计算,因此它们不受数据不均衡的直接影响——这是它们比 Accuracy 更适合不均衡数据的原因。

7.3 数值示例:同一模型的多维评估

场景:疾病筛查

1000 人中实际 100 人患病。模型预测 120 人为”患病”(其中 80 人确实患病,40 人误报),其余 880 人为”健康”(其中 20 人漏诊,860 人正确排除)。

  • TP=80, FP=40, FN=20, TN=860
  • Accuracy = (80+860)/1000 = 94%(看似不错)
  • Precision = 80/(80+40) = 66.7%(每 3 个诊断中 1 个误报)
  • Recall = 80/(80+20) = 80%(100 个患者找到 80 个)
  • F1 = 2×(0.667×0.80)/(0.667+0.80) = 72.7%
Accuracy
94%
94%
Precision
66.7%
66.7%
Recall
80%
80%
F1
72.7%
72.7%
图 4 同一模型在四个指标上的表现差异:Accuracy 虚高,F1 反映真实综合水平

八、不均衡数据集的挑战

当正负样本比例悬殊时(如欺诈检测 1:1000、罕见病 1:10000),Accuracy 会失效,需要依赖 Precision、Recall 和 F1[6]

8.1 Accuracy 失效演示

❌ 仅看 Accuracy

10000 笔交易中 10 笔是欺诈。模型全部预测为”正常”。

TP=0, FP=0, FN=10, TN=9990

Accuracy = 9990/10000 = 99.9%

看起来非常好——但一个欺诈都没抓到。

✅ 看 Precision/Recall/F1

同一模型:

Precision = 0/(0+0) = 未定义(无预测正样本)

Recall = 0/(0+10) = 0%

F1 = 0%(或未定义)

立刻暴露了模型完全无效。

8.2 不均衡数据的应对策略

  1. 选择正确的指标 使用 Precision、Recall、F1 替代 Accuracy。考虑 PR-AUC(Precision-Recall 曲线下面积)。
  2. 重采样(Resampling) 过采样少数类(SMOTE)或欠采样多数类,使训练集更均衡。
  3. 类别权重(Class Weight) 在损失函数中给少数类更高权重,让模型更重视少数类的错误。
  4. 调整决策阈值 默认阈值 0.5 不一定最优,可根据业务需求调整以平衡 P/R。
  5. 使用适合的算法 集成方法(如 XGBoost)、异常检测方法对不均衡数据更鲁棒。

九、多分类场景扩展

在多分类任务中(如手写数字识别 0-9),混淆矩阵扩展为 N×N。如何将二分类指标扩展到多分类?有三种常见平均方式[7]

9.1 三种平均策略

表 6 多分类平均策略对比
策略计算方式特点适用场景
Macro各类别指标分别计算后取算术平均各类别等权,重视少数类各类别同等重要
Micro所有类别 TP/FP/FN 汇总后计算全局指标样本多的类权重更大整体性能评估
Weighted各类别指标按样本量加权平均兼顾类别比例不均衡多分类

9.2 Macro vs Micro 示例

三分类示例

3 个类别 A、B、C,样本数分别为 100、50、10。

各类别的 Recall:
  类别 A (100样本): Recall = 90/100 = 0.90
  类别 B ( 50样本): Recall = 40/50  = 0.80
  类别 C ( 10样本): Recall = 5/10   = 0.50

Macro-Recall = (0.90 + 0.80 + 0.50) / 3 = 0.733
  → 每个类别同等重要,C 的低 Recall 拉低了均值

Micro-Recall = (90+40+5) / (100+50+10) = 135/160 = 0.844
  → 按样本加权,A 的高占比推高了均值

Weighted-Recall = (0.90×100 + 0.80×50 + 0.50×10) / 160 = 0.844
  → 与 Micro 相同(因为 Recall 的加权本质)
选择建议:如果少数类的表现同样重要(如各疾病诊断),用 Macro-F1;如果关注整体预测准确度,用 Micro-F1;如果类别间不均衡且需兼顾比例,用 Weighted-F1

9.3 One-vs-Rest 思路

多分类指标的底层计算通常采用 One-vs-Rest(OvR)策略:将每个类别依次视为”正类”,其余所有类别视为”负类”,计算该类的 Precision/Recall/F1,再按上述平均方式汇总。

类别 A 为正 P/R/F1 (A)
类别 B 为正 P/R/F1 (B) Macro/Micro/Weighted 平均
类别 C 为正 P/R/F1 (C)
图 5 One-vs-Rest 策略:将 N 分类转化为 N 个二分类问题

十、实际应用指南与代码示例

10.1 场景-指标匹配指南

🏥 医疗诊断

优先指标:Recall / F2-score

漏诊(FN)代价远高于误诊(FP)。宁可多做检查,不可放过一个病人。

📧 垃圾邮件过滤

优先指标:Precision / F0.5

误删正常邮件(FP)代价远高于放过一封垃圾邮件(FN)。

💳 欺诈检测

优先指标:Recall / PR-AUC

漏掉一笔欺诈损失巨大,宁可多审核。数据极度不均衡。

10.2 决策流程图

数据是否均衡?
是 → Accuracy | 否 → 继续
FP 和 FN 哪个代价高?
FP 高 → Precision | FN 高 → Recall | 相当 → F1
图 6 指标选择决策流程

10.3 Python 代码示例

# 使用 scikit-learn 计算分类评估指标
from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score,
    classification_report,
    confusion_matrix
)
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

# 1. 生成不均衡数据(正负比 1:9)
X, y = make_classification(
    n_samples=1000,
    weights=[0.1],
    random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# 2. 训练模型
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

# 3. 混淆矩阵
cm = confusion_matrix(y_test, y_pred)
print(f"Confusion Matrix:\n{cm}")
# [[256  11]
#  [  13  20]]

tn, fp, fn, tp = cm.ravel()
print(f"TP={tp}, TN={tn}, FP={fp}, FN={fn}")
# TP=20, TN=256, FP=11, FN=13

# 4. 四大指标
print(f"Accuracy:  {accuracy_score(y_test, y_pred):.4f}")
# Accuracy:  0.9200

print(f"Precision: {precision_score(y_test, y_pred):.4f}")
# Precision: 0.6452

print(f"Recall:    {recall_score(y_test, y_pred):.4f}")
# Recall:    0.6061

print(f"F1-score:  {f1_score(y_test, y_pred):.4f}")
# F1-score:  0.6250

# 5. 多分类报告(含 Macro/Micro/Weighted)
print(classification_report(y_test, y_pred, target_names=["Negative", "Positive"]))
#               precision  recall  f1-score  support
#     Negative       0.95     0.96      0.95      267
#     Positive       0.65     0.61      0.63       33
#    accuracy                           0.92      300
#   macro avg       0.80     0.78      0.79      300
# weighted avg       0.92     0.92      0.92      300

# 6. 交叉验证中指定 average 策略
from sklearn.model_selection import cross_val_score

macro_f1 = cross_val_score(model, X, y, cv=5, scoring="f1_macro")
weighted_f1 = cross_val_score(model, X, y, cv=5, scoring="f1_weighted")
print(f"Macro F1 CV:    {macro_f1.mean():.4f}")
print(f"Weighted F1 CV:{weighted_f1.mean():.4f}")

10.4 常见误区

表 7 常见误区与纠正
误区问题纠正
只用 Accuracy不均衡数据下虚高搭配 Precision/Recall/F1 使用
追求 F1 最高可能不符合业务需求根据 FP/FN 代价选择 Fβ
忽略阈值调优默认 0.5 阈值未必最优用 PR 曲线选择业务最优阈值
测试集不均衡指标有偏分层抽样保持比例,或使用分层交叉验证
忽视 TN 影响F1 不含 TN,可能高估极端不均衡时补充 MCC 指标
总结:Accuracy、Precision、Recall、F1-score 是分类评估的基石。它们各有适用场景,不存在”最好的指标”——只有”最适合当前业务场景的指标”。理解混淆矩阵是掌握一切的前提,而根据数据均衡性、FP/FN 代价权衡选择合适的指标组合,是每个机器学习从业者的必备能力。

Complete Guide to Classification MetricsFrom Confusion Matrix to Accuracy, Precision, Recall & F1-score

Understand the four core evaluation metrics in ML classification: principles, formulas, use cases, and trade-offs

1. Overview: Why Evaluation Metrics Matter

In machine learning classification tasks, model predictions need objective, quantifiable metrics to assess quality. Knowing “the model got 95 correct” is insufficient—we need to understand its performance on positive and negative classes separately, whether it’s biased, and whether it meets specific business requirements[1].

Core Problem: Different metrics measure different dimensions of model performance. There is no “universal metric”—the choice depends on the specific business scenario, data distribution, and cost trade-offs. Understanding each metric’s definition, applicability, and limitations is the prerequisite for proper model evaluation.

1.1 Four Core Metrics at a Glance

Accuracy

Overall correctness. Proportion of all predictions that are correct. Intuitive but vulnerable to imbalance.

Precision

Of predicted positives, how many are actually positive. Focus: “purity of predictions.”

Recall

Of actual positives, how many were correctly found. Focus: “did we miss any?”

F1-score

Harmonic mean of precision and recall. A single balanced metric combining both.
Confusion Matrix TP / TN / FP / FN
Accuracy · Precision · Recall · F1
Figure 1 All four metrics derive from the four quantities in the confusion matrix

2. Confusion Matrix: The Foundation

The Confusion Matrix is a 2×2 table that cross-tabulates model predictions against ground truth labels, producing four fundamental quantities. All evaluation metrics are derived from these four[2].

2.1 The Four Basic Quantities

Predicted Positive
Predicted Negative
Actual Positive
TPTrue Positive
FNFalse Negative
Actual Negative
FPFalse Positive
TNTrue Negative
Table 1 Meaning of the four confusion matrix quantities
SymbolNameMeaningPlain English
TPTrue PositiveActually positive, predicted positiveCorrect hit
TNTrue NegativeActually negative, predicted negativeCorrect rejection
FPFalse PositiveActually negative, predicted positiveFalse alarm (Type I error)
FNFalse NegativeActually positive, predicted negativeMiss (Type II error)

2.2 Memory Aid

Quick Rule

T / F = whether the prediction is correct (True = correct, False = wrong)

P / N = the model’s predicted class (Positive = predicted positive, Negative = predicted negative)

Combined: TP = correct prediction of positive; FP = wrong prediction of positive (actually negative).

Key Relationship: Total samples = TP + TN + FP + FN. Where TP + FN = total actual positives, and TP + FP = total predicted positives. These two relationships are the foundation for deriving all metrics.

3. Accuracy

Accuracy is the most intuitive evaluation metric—the proportion of all samples that the model predicted correctly[3].

Accuracy Formula
Accuracy = (TP + TN) / (TP + TN + FP + FN)

3.1 Intuitive Understanding

Accuracy answers: “How does the model perform overall?” It treats correct predictions of positive and negative classes equally in the numerator, and is the only metric that considers TN.

TP (60)
Hits
60
TN (30)
Correct rejects
30
FP (5)
False alarm
5
FN (5)
Miss
5
Accuracy
90 / 100
90%
Figure 2 Accuracy example: 90 of 100 predictions correct (TP=60 + TN=30), accuracy = 90%

3.2 The Fatal Pitfall of Accuracy

Imbalanced Data Trap: When data is severely imbalanced, Accuracy becomes misleading. For example, of 1000 emails, 950 are normal and 50 are spam. A classifier that does nothing (labels everything as “normal”) achieves Accuracy = 950/1000 = 95%, yet it catches zero spam[3].

✅ When to Use

Classes are roughly balanced

FP and FN costs are similar

Quick overall performance check needed

Initial reference for multi-class tasks

❌ When NOT to Use

Severely imbalanced data (fraud, rare disease)

Positive class is rare but critical (high FN cost)

Using Accuracy as the sole metric

Need to distinguish different error types

4. Precision

Precision measures: of all samples predicted as positive, what fraction is actually positive[1].

Precision Formula
Precision = TP / (TP + FP)

4.1 Intuitive Understanding

Precision answers: “When the model says ‘yes’, how trustworthy is it?” It focuses on the purity of positive predictions.

Spam Filter Example

The model flags 20 emails as “spam”—16 are actually spam, 4 are normal emails misclassified. Precision = 16 / 20 = 80%.

Higher Precision means fewer normal emails are wrongly flagged as spam—users won’t lose important emails.

4.2 Precision Characteristics

Table 2 Precision metric characteristics
DimensionDescription
FocusPurity of positive predictions (minimize FP)
NumeratorTP (correctly predicted positives)
DenominatorTP + FP (all predicted positives)
Excludes TNDoesn’t consider correctly rejected negatives
Extreme valueFP=0 → Precision=1 (better to miss than misfire)
How to improveRaise threshold, predict positive only when most confident
Precision’s Limitation: High Precision doesn’t necessarily mean a good model. If the model is extremely conservative—predicting positive for only 1 sample it’s most sure about (and it’s correct)—Precision = 1/1 = 100%, but it may have missed 999 actual positives. High Precision often comes at the cost of Recall.

5. Recall

Recall (also known as Sensitivity, Hit Rate, or True Positive Rate) measures: of all actual positive samples, what fraction was correctly predicted as positive[4].

Recall Formula
Recall = TP / (TP + FN)

5.1 Intuitive Understanding

Recall answers: “Of all actual positives, how many did the model find?” It focuses on coverage—did we miss any positives?

Cancer Detection Example

Of 100 cancer patients, the model correctly identifies 85 and misses 15. Recall = 85 / 100 = 85%.

Higher Recall means fewer missed diagnoses. In medical settings, the cost of missing a patient (FN) is far higher than a false alarm (FP)—better to run one more test than miss a patient.

5.2 Recall Characteristics

Table 3 Recall metric characteristics
DimensionDescription
FocusCoverage of positive class (minimize FN)
NumeratorTP (found positives)
DenominatorTP + FN (all actual positives)
Excludes TNDoesn’t consider correctly rejected negatives
Extreme valueFN=0 → Recall=1 (find everything, even false alarms)
How to improveLower threshold, predict positive for any possibly positive sample
Recall’s Limitation: High Recall doesn’t necessarily mean a good model. If the model predicts positive for all samples, FN=0, Recall=100%, but it generates massive FP. High Recall often comes at the cost of Precision.

6. F1-score

F1-score is the harmonic mean of Precision and Recall, designed to balance the two[5].

F1-score Formula
F1 = 2 × (Precision × Recall) / (Precision + Recall)

Equivalent form:

F1 = 2 × TP / (2 × TP + FP + FN)

6.1 Why Harmonic Mean?

The key difference between harmonic and arithmetic mean: harmonic mean is more sensitive to extreme values. If Precision=0.01 and Recall=1.0, the arithmetic mean = 0.505 (looks okay), but the harmonic mean F1 = 0.0198 (exposes the low Precision)[5].

Table 4 Comparison of averaging methods
PrecisionRecallArithmetic MeanF1 (Harmonic)
0.800.800.800.80
0.900.500.700.643
1.000.500.750.667
0.011.000.5050.0198
0.001.000.500.00
Harmonic Mean’s Punishment: When either Precision or Recall is 0, F1 must be 0. This means F1 requires the model to perform decently on both dimensions—no “one-legged” walking. The arithmetic mean would mask an extreme low value.

6.2 F-beta Generalization

F1 is a special case of the more general F-β metric (β=1). β controls Recall’s weight relative to Precision:

F-β Formula
Fβ = (1 + β²) × (Precision × Recall) / (β² × Precision + Recall)

F1 (β=1)

Equal weight to Precision and Recall. Most common composite metric.

F2 (β=2)

Recall weighted higher. For high FN-cost scenarios (e.g., medical).

F0.5 (β=0.5)

Precision weighted higher. For high FP-cost scenarios (e.g., spam).

7. Relationships and Trade-offs

7.1 The Precision-Recall Seesaw

There is a natural trade-off between Precision and Recall. By adjusting the classification threshold, you can improve one metric but typically at the expense of the other[4].

Lower threshold More positive predictions Recall ↑ + FP ↑ Precision ↓
Raise threshold Fewer positive predictions Precision ↑ + FN ↑ Recall ↓
Figure 3 Precision-Recall trade-off: adjusting threshold is like a seesaw

7.2 Four-Metric Comparison

Table 5 Core comparison of the four metrics
MetricFormulaFocusExcludesMost afraid of
Accuracy(TP+TN)/AllOverall correctnessImbalanced data
PrecisionTP/(TP+FP)Prediction purityTNToo many FP
RecallTP/(TP+FN)Positive coverageTNToo many FN
F12PR/(P+R)P/R balanceTNExtreme P or R
Key Insight: Precision, Recall, and F1 all exclude TN. This means in scenarios with abundant negative samples (e.g., fraud detection where 99.9% are normal), TN is huge but doesn’t participate in these three metrics—so they are not directly affected by data imbalance. This is why they’re preferred over Accuracy for imbalanced data.

7.3 Numerical Example: Multi-dimensional Evaluation

Scenario: Disease Screening

Of 1000 people, 100 are actually sick. The model predicts 120 as “sick” (80 correctly, 40 false alarms), the remaining 880 as “healthy” (20 missed, 860 correctly excluded).

  • TP=80, FP=40, FN=20, TN=860
  • Accuracy = (80+860)/1000 = 94% (looks good)
  • Precision = 80/(80+40) = 66.7% (1 in 3 diagnoses is false alarm)
  • Recall = 80/(80+20) = 80% (found 80 of 100 patients)
  • F1 = 2×(0.667×0.80)/(0.667+0.80) = 72.7%
Accuracy
94%
94%
Precision
66.7%
66.7%
Recall
80%
80%
F1
72.7%
72.7%
Figure 4 Same model across four metrics: Accuracy is inflated, F1 reflects true composite performance

8. Imbalanced Dataset Challenges

When positive/negative ratios are extreme (fraud 1:1000, rare disease 1:10000), Accuracy fails. We need Precision, Recall, and F1[6].

8.1 Accuracy Failure Demo

❌ Looking at Accuracy Only

Of 10000 transactions, 10 are fraud. Model predicts all as “normal.”

TP=0, FP=0, FN=10, TN=9990

Accuracy = 9990/10000 = 99.9%

Looks great—but caught zero fraud.

✅ Looking at P/R/F1

Same model:

Precision = 0/(0+0) = undefined

Recall = 0/(0+10) = 0%

F1 = 0% (or undefined)

Immediately exposes model is useless.

8.2 Strategies for Imbalanced Data

  1. Choose the Right Metric Use Precision, Recall, F1 instead of Accuracy. Consider PR-AUC (area under Precision-Recall curve).
  2. Resampling Oversample minority class (SMOTE) or undersample majority class to balance training data.
  3. Class Weighting Assign higher weight to minority class in loss function to make the model care more about its errors.
  4. Threshold Tuning Default 0.5 threshold may not be optimal; adjust based on business needs to balance P/R.
  5. Use Appropriate Algorithms Ensemble methods (XGBoost) and anomaly detection approaches are more robust to imbalance.

9. Multi-class Extensions

In multi-class tasks (e.g., digit recognition 0-9), the confusion matrix expands to N×N. How do we extend binary metrics to multi-class? Three common averaging strategies[7]:

9.1 Three Averaging Strategies

Table 6 Multi-class averaging strategies compared
StrategyCalculationCharacteristicsUse Case
MacroCompute per-class metrics, then arithmetic meanEqual weight per class; emphasizes rare classesAll classes equally important
MicroAggregate all TP/FP/FN, then compute global metricLarger classes dominateOverall performance
WeightedPer-class metrics weighted by sample countAccounts for class proportionsImbalanced multi-class

9.2 Macro vs Micro Example

Three-class Example

3 classes A, B, C with 100, 50, 10 samples respectively.

Per-class Recall:
  Class A (100 samples): Recall = 90/100 = 0.90
  Class B ( 50 samples): Recall = 40/50  = 0.80
  Class C ( 10 samples): Recall = 5/10   = 0.50

Macro-Recall = (0.90 + 0.80 + 0.50) / 3 = 0.733
  → Each class equally important; C's low Recall drags down average

Micro-Recall = (90+40+5) / (100+50+10) = 135/160 = 0.844
  → Sample-weighted; A's high proportion boosts the average

Weighted-Recall = (0.90×100 + 0.80×50 + 0.50×10) / 160 = 0.844
  → Same as Micro (because of Recall's weighted nature)
Selection Guide: If minority class performance matters equally (e.g., disease diagnosis), use Macro-F1; if overall prediction accuracy is the focus, use Micro-F1; if classes are imbalanced and proportions matter, use Weighted-F1.

9.3 One-vs-Rest Approach

Multi-class metrics are typically computed using the One-vs-Rest (OvR) strategy: treat each class as “positive” in turn, all others as “negative,” compute that class’s P/R/F1, then aggregate using one of the averaging strategies above.

Class A as positive P/R/F1 (A)
Class B as positive P/R/F1 (B) Macro/Micro/Weighted
Class C as positive P/R/F1 (C)
Figure 5 One-vs-Rest strategy: converts N-class into N binary problems

10. Practical Guide & Code Examples

10.1 Scenario-Metric Matching Guide

🏥 Medical Diagnosis

Priority Metric:Recall / F2-score

Missing a diagnosis (FN) is far costlier than a false alarm (FP). Better to run extra tests than miss a patient.

📧 Spam Filter

Priority Metric:Precision / F0.5

Deleting a normal email (FP) is far costlier than letting spam through (FN).

💳 Fraud Detection

Priority Metric:Recall / PR-AUC

Missing fraud is hugely expensive; better to over-review. Extremely imbalanced data.

10.2 Decision Flowchart

Is data balanced?
Yes → Accuracy | No → continue
Which costs more: FP or FN?
FP high → Precision | FN high → Recall | Equal → F1
Figure 6 Metric selection decision flow

10.3 Python Code Example

# Computing classification metrics with scikit-learn
from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score,
    classification_report,
    confusion_matrix
)
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

# 1. Generate imbalanced data (1:9 ratio)
X, y = make_classification(
    n_samples=1000,
    weights=[0.1],
    random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# 2. Train model
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

# 3. Confusion matrix
cm = confusion_matrix(y_test, y_pred)
print(f"Confusion Matrix:\n{cm}")
# [[256  11]
#  [  13  20]]

tn, fp, fn, tp = cm.ravel()
print(f"TP={tp}, TN={tn}, FP={fp}, FN={fn}")
# TP=20, TN=256, FP=11, FN=13

# 4. Four core metrics
print(f"Accuracy:  {accuracy_score(y_test, y_pred):.4f}")
# Accuracy:  0.9200

print(f"Precision: {precision_score(y_test, y_pred):.4f}")
# Precision: 0.6452

print(f"Recall:    {recall_score(y_test, y_pred):.4f}")
# Recall:    0.6061

print(f"F1-score:  {f1_score(y_test, y_pred):.4f}")
# F1-score:  0.6250

# 5. Full classification report (with Macro/Micro/Weighted)
print(classification_report(y_test, y_pred, target_names=["Negative", "Positive"]))
#               precision  recall  f1-score  support
#     Negative       0.95     0.96      0.95      267
#     Positive       0.65     0.61      0.63       33
#    accuracy                           0.92      300
#   macro avg       0.80     0.78      0.79      300
# weighted avg       0.92     0.92      0.92      300

# 6. Cross-validation with average strategy
from sklearn.model_selection import cross_val_score

macro_f1 = cross_val_score(model, X, y, cv=5, scoring="f1_macro")
weighted_f1 = cross_val_score(model, X, y, cv=5, scoring="f1_weighted")
print(f"Macro F1 CV:    {macro_f1.mean():.4f}")
print(f"Weighted F1 CV:{weighted_f1.mean():.4f}")

10.4 Common Pitfalls

Table 7 Common pitfalls and corrections
PitfallProblemCorrection
Using only AccuracyInflated on imbalanced dataPair with Precision/Recall/F1
Chasing highest F1May not match business needsChoose Fβ based on FP/FN cost
Ignoring threshold tuningDefault 0.5 may not be optimalUse PR curve to select optimal threshold
Imbalanced test setBiased metricsUse stratified sampling or stratified CV
Ignoring TN effectF1 excludes TN, may overestimateAdd MCC for extreme imbalance
Summary: Accuracy, Precision, Recall, and F1-score are the cornerstones of classification evaluation. Each has its applicable scenario—there is no “best metric,” only the “most appropriate metric for the current business context.” Understanding the confusion matrix is the prerequisite for mastering all of them. Choosing the right metric combination based on data balance and FP/FN cost trade-offs is an essential skill for every ML practitioner.