分类评估指标完整指南从混淆矩阵到 Accuracy、Precision、Recall、F1-score 的全面解析
理解机器学习分类任务中四大核心评估指标的原理、公式、适用场景与权衡关系
目录
一、概述:为什么需要评估指标
在机器学习的分类任务中,模型预测的结果需要用客观、量化的指标来评估好坏。仅仅知道”模型预测了 95 个正确”是不够的——我们需要知道它在正类和负类上分别表现如何,是否偏向某一类,以及在特定业务场景下是否满足要求[1]。
1.1 四大核心指标速览
Accuracy
整体预测正确率。所有预测中正确的比例。直观但惧怕数据不均衡。Precision
查准率。预测为正的样本中,真正为正的比例。关注”预测的纯度”。Recall
查全率。实际为正的样本中,被正确预测的比例。关注”是否漏掉”。F1-score
精确率与召回率的调和平均。综合平衡两者的单一指标。二、混淆矩阵:一切的基础
混淆矩阵(Confusion Matrix)是一个 2×2 的表格,将模型预测结果与真实标签交叉对比,产生四个基本量。所有评估指标都从这四个量推导而来[2]。
2.1 四个基本量
| 符号 | 名称 | 含义 | 通俗理解 |
|---|---|---|---|
| TP | True Positive | 实际为正,预测为正 | 正确发现(命中) |
| TN | True Negative | 实际为负,预测为负 | 正确排除(正确拒绝) |
| FP | False Positive | 实际为负,预测为正 | 误报(假阳性 / Type I 错误) |
| FN | False Negative | 实际为正,预测为负 | 漏报(假阴性 / Type II 错误) |
2.2 记忆口诀
速记规则
T / F = 预测是否正确(True = 对了,False = 错了)
P / N = 模型的预测类别(Positive = 预测为正,Negative = 预测为负)
组合起来:TP = 预测正确且预测为正;FP = 预测错误且预测为正(实际上是负)。
三、Accuracy(准确率)
Accuracy(准确率)是最直观的评估指标,表示所有样本中模型预测正确的比例[3]。
3.1 直观理解
Accuracy 回答的问题是:“模型整体表现如何?” 它将正类和负类的正确预测一视同仁地计入分子,是唯一同时考虑 TN 的指标。
3.2 Accuracy 的致命陷阱
✅ 适用场景
各类别样本数量大致均衡
正类和负类的错误代价相近
需要快速了解整体表现
多分类任务的初始参考
❌ 不适用场景
数据严重不均衡(如欺诈检测、罕见病诊断)
正类极少但极重要(漏报代价高)
单独使用 Accuracy 作为唯一指标
需要区分不同类型错误的场景
四、Precision(精确率 / 查准率)
Precision(精确率,又称查准率)衡量的是:在所有被模型预测为正的样本中,实际为正的比例[1]。
4.1 直观理解
Precision 回答的问题是:“模型说’是’的时候,有多可信?” 它关注的是预测的纯度——预测为正的样本中,有多少是真正的正样本。
垃圾邮件过滤的例子
模型标记了 20 封邮件为”垃圾邮件”,其中 16 封确实是垃圾邮件,4 封是正常邮件被误判。则 Precision = 16 / 20 = 80%。
Precision 越高,意味着正常邮件被误判为垃圾邮件的可能性越低——用户不会因为重要邮件被误删而受损失。
4.2 Precision 的特性
| 维度 | 说明 |
|---|---|
| 关注焦点 | 预测为正的纯度(减少 FP) |
| 分子 | TP(正确预测的正样本) |
| 分母 | TP + FP(所有预测为正的样本) |
| 不含 TN | 不关心正确排除的负样本 |
| 极端值 | FP=0 时 Precision=1(宁可少报也不错报) |
| 提高方式 | 提高判断门槛,只对最有把握的样本预测为正 |
五、Recall(召回率 / 查全率)
Recall(召回率,又称查全率、灵敏度 Sensitivity、真阳性率 TPR)衡量的是:在所有实际为正的样本中,被模型正确预测为正的比例[4]。
5.1 直观理解
Recall 回答的问题是:“所有真正的正样本,模型找到了多少?” 它关注的是查全率——有没有漏掉应该被发现的正样本。
癌症检测的例子
100 个患癌病人中,模型正确识别了 85 个,漏掉了 15 个。则 Recall = 85 / 100 = 85%。
Recall 越高,意味着越少的病人被漏诊。在医疗场景中,漏诊(FN)的代价远高于误诊(FP)——宁可多做一次检查,也不能放过一个病人。
5.2 Recall 的特性
| 维度 | 说明 |
|---|---|
| 关注焦点 | 正样本的覆盖率(减少 FN) |
| 分子 | TP(被找到的正样本) |
| 分母 | TP + FN(所有实际为正的样本) |
| 不含 TN | 不关心正确排除的负样本 |
| 极端值 | FN=0 时 Recall=1(全部找到,宁可错报) |
| 提高方式 | 降低判断门槛,对所有可能为正的样本都预测为正 |
六、F1-score(F1 分数)
F1-score 是 Precision 和 Recall 的调和平均(Harmonic Mean),用于在两者之间取得平衡[5]。
等价形式:
F1 = 2 × TP / (2 × TP + FP + FN)
6.1 为什么用调和平均?
调和平均与算术平均的关键区别在于:它对极端值更敏感。如果 Precision=0.01 而 Recall=1.0,算术平均 = 0.505(看起来还行),但调和平均 F1 = 0.0198(暴露了 Precision 极低的问题)[5]。
| Precision | Recall | 算术平均 | F1(调和平均) |
|---|---|---|---|
| 0.80 | 0.80 | 0.80 | 0.80 |
| 0.90 | 0.50 | 0.70 | 0.643 |
| 1.00 | 0.50 | 0.75 | 0.667 |
| 0.01 | 1.00 | 0.505 | 0.0198 |
| 0.00 | 1.00 | 0.50 | 0.00 |
6.2 F-beta 推广
F1 是更一般的 F-β 指标的特例(β=1)。β 控制了 Recall 相对于 Precision 的权重:
F1 (β=1)
Precision 和 Recall 等权。最常用的综合指标。F2 (β=2)
Recall 权重更高。适用于漏报代价高的场景(如医疗)。F0.5 (β=0.5)
Precision 权重更高。适用于误报代价高的场景(如垃圾邮件)。七、指标间的关系与权衡
7.1 Precision-Recall 的跷跷板效应
Precision 和 Recall 之间存在天然的权衡关系(Trade-off)。通过调整分类阈值,可以提高一个指标但通常会降低另一个[4]。
7.2 四指标关系图
| 指标 | 公式 | 关注 | 不包含 | 最怕 |
|---|---|---|---|---|
| Accuracy | (TP+TN)/All | 整体正确率 | — | 数据不均衡 |
| Precision | TP/(TP+FP) | 预测纯度 | TN | FP 过多 |
| Recall | TP/(TP+FN) | 正类覆盖 | TN | FN 过多 |
| F1 | 2PR/(P+R) | P/R 平衡 | TN | P 或 R 极端 |
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%
八、不均衡数据集的挑战
当正负样本比例悬殊时(如欺诈检测 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 不均衡数据的应对策略
- 选择正确的指标 使用 Precision、Recall、F1 替代 Accuracy。考虑 PR-AUC(Precision-Recall 曲线下面积)。
- 重采样(Resampling) 过采样少数类(SMOTE)或欠采样多数类,使训练集更均衡。
- 类别权重(Class Weight) 在损失函数中给少数类更高权重,让模型更重视少数类的错误。
- 调整决策阈值 默认阈值 0.5 不一定最优,可根据业务需求调整以平衡 P/R。
- 使用适合的算法 集成方法(如 XGBoost)、异常检测方法对不均衡数据更鲁棒。
九、多分类场景扩展
在多分类任务中(如手写数字识别 0-9),混淆矩阵扩展为 N×N。如何将二分类指标扩展到多分类?有三种常见平均方式[7]:
9.1 三种平均策略
| 策略 | 计算方式 | 特点 | 适用场景 |
|---|---|---|---|
| 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 的加权本质)
9.3 One-vs-Rest 思路
多分类指标的底层计算通常采用 One-vs-Rest(OvR)策略:将每个类别依次视为”正类”,其余所有类别视为”负类”,计算该类的 Precision/Recall/F1,再按上述平均方式汇总。
十、实际应用指南与代码示例
10.1 场景-指标匹配指南
🏥 医疗诊断
优先指标:Recall / F2-score
漏诊(FN)代价远高于误诊(FP)。宁可多做检查,不可放过一个病人。
📧 垃圾邮件过滤
优先指标:Precision / F0.5
误删正常邮件(FP)代价远高于放过一封垃圾邮件(FN)。
💳 欺诈检测
优先指标:Recall / PR-AUC
漏掉一笔欺诈损失巨大,宁可多审核。数据极度不均衡。
🔍 搜索引擎
优先指标:Precision@K
用户只看前几条结果,返回的精确度比覆盖率更重要。
10.2 决策流程图
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 常见误区
| 误区 | 问题 | 纠正 |
|---|---|---|
| 只用 Accuracy | 不均衡数据下虚高 | 搭配 Precision/Recall/F1 使用 |
| 追求 F1 最高 | 可能不符合业务需求 | 根据 FP/FN 代价选择 Fβ |
| 忽略阈值调优 | 默认 0.5 阈值未必最优 | 用 PR 曲线选择业务最优阈值 |
| 测试集不均衡 | 指标有偏 | 分层抽样保持比例,或使用分层交叉验证 |
| 忽视 TN 影响 | F1 不含 TN,可能高估 | 极端不均衡时补充 MCC 指标 |
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
Contents
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].
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.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
| Symbol | Name | Meaning | Plain English |
|---|---|---|---|
| TP | True Positive | Actually positive, predicted positive | Correct hit |
| TN | True Negative | Actually negative, predicted negative | Correct rejection |
| FP | False Positive | Actually negative, predicted positive | False alarm (Type I error) |
| FN | False Negative | Actually positive, predicted negative | Miss (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).
3. Accuracy
Accuracy is the most intuitive evaluation metric—the proportion of all samples that the model predicted correctly[3].
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.
3.2 The Fatal Pitfall of Accuracy
✅ 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].
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
| Dimension | Description |
|---|---|
| Focus | Purity of positive predictions (minimize FP) |
| Numerator | TP (correctly predicted positives) |
| Denominator | TP + FP (all predicted positives) |
| Excludes TN | Doesn’t consider correctly rejected negatives |
| Extreme value | FP=0 → Precision=1 (better to miss than misfire) |
| How to improve | Raise threshold, predict positive only when most confident |
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].
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
| Dimension | Description |
|---|---|
| Focus | Coverage of positive class (minimize FN) |
| Numerator | TP (found positives) |
| Denominator | TP + FN (all actual positives) |
| Excludes TN | Doesn’t consider correctly rejected negatives |
| Extreme value | FN=0 → Recall=1 (find everything, even false alarms) |
| How to improve | Lower threshold, predict positive for any possibly positive sample |
6. F1-score
F1-score is the harmonic mean of Precision and Recall, designed to balance the two[5].
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].
| Precision | Recall | Arithmetic Mean | F1 (Harmonic) |
|---|---|---|---|
| 0.80 | 0.80 | 0.80 | 0.80 |
| 0.90 | 0.50 | 0.70 | 0.643 |
| 1.00 | 0.50 | 0.75 | 0.667 |
| 0.01 | 1.00 | 0.505 | 0.0198 |
| 0.00 | 1.00 | 0.50 | 0.00 |
6.2 F-beta Generalization
F1 is a special case of the more general F-β metric (β=1). β controls Recall’s weight relative to Precision:
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].
7.2 Four-Metric Comparison
| Metric | Formula | Focus | Excludes | Most afraid of |
|---|---|---|---|---|
| Accuracy | (TP+TN)/All | Overall correctness | — | Imbalanced data |
| Precision | TP/(TP+FP) | Prediction purity | TN | Too many FP |
| Recall | TP/(TP+FN) | Positive coverage | TN | Too many FN |
| F1 | 2PR/(P+R) | P/R balance | TN | Extreme P or R |
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%
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
- Choose the Right Metric Use Precision, Recall, F1 instead of Accuracy. Consider PR-AUC (area under Precision-Recall curve).
- Resampling Oversample minority class (SMOTE) or undersample majority class to balance training data.
- Class Weighting Assign higher weight to minority class in loss function to make the model care more about its errors.
- Threshold Tuning Default 0.5 threshold may not be optimal; adjust based on business needs to balance P/R.
- 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
| Strategy | Calculation | Characteristics | Use Case |
|---|---|---|---|
| Macro | Compute per-class metrics, then arithmetic mean | Equal weight per class; emphasizes rare classes | All classes equally important |
| Micro | Aggregate all TP/FP/FN, then compute global metric | Larger classes dominate | Overall performance |
| Weighted | Per-class metrics weighted by sample count | Accounts for class proportions | Imbalanced 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)
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.
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.
🔍 Search Engine
Priority Metric:Precision@K
Users only look at top results; precision of returned items matters more than coverage.
10.2 Decision Flowchart
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
| Pitfall | Problem | Correction |
|---|---|---|
| Using only Accuracy | Inflated on imbalanced data | Pair with Precision/Recall/F1 |
| Chasing highest F1 | May not match business needs | Choose Fβ based on FP/FN cost |
| Ignoring threshold tuning | Default 0.5 may not be optimal | Use PR curve to select optimal threshold |
| Imbalanced test set | Biased metrics | Use stratified sampling or stratified CV |
| Ignoring TN effect | F1 excludes TN, may overestimate | Add MCC for extreme imbalance |
