蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行混淆矩阵、99:1 准确率陷阱、ROC/PR 曲线与多分类宏微平均实测

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-classification-metrics.py
explore-classification-metrics.py277 行
"""Independent scikit-learn classification metrics, confusion matrix, ROC/AUC, PR curve & multiclass averaging lab."""
import argparse
import hashlib
import json
import platform
from pathlib import Path

import numpy as np
import sklearn
from sklearn.datasets import load_iris, make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    accuracy_score,
    auc,
    average_precision_score,
    classification_report,
    confusion_matrix,
    f1_score,
    precision_recall_curve,
    precision_score,
    recall_score,
    roc_auc_score,
    roc_curve,
)
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def run_cases(fig_dir: Path | None):
    cases = []
    figures = {}

    # 1. Confusion matrix, core metrics, imbalanced accuracy trap & pos_label
    y_true_spam = [1, 0, 1, 1, 0, 0, 1, 0, 0, 1]
    y_pred_spam = [1, 0, 0, 1, 0, 0, 1, 1, 0, 1]
    cm = confusion_matrix(y_true_spam, y_pred_spam)
    tn, fp, fn, tp = [int(v) for v in cm.ravel()]
    acc = round(float(accuracy_score(y_true_spam, y_pred_spam)), 4)
    prec = round(float(precision_score(y_true_spam, y_pred_spam)), 4)
    rec = round(float(recall_score(y_true_spam, y_pred_spam)), 4)
    f1 = round(float(f1_score(y_true_spam, y_pred_spam)), 4)

    # 99% negative imbalanced trap
    y_true_imb = [0] * 99 + [1]
    y_pred_dummy = [0] * 100
    imb_acc = round(float(accuracy_score(y_true_imb, y_pred_dummy)), 4)
    imb_rec = round(float(recall_score(y_true_imb, y_pred_dummy, zero_division=0)), 4)
    imb_f1 = round(float(f1_score(y_true_imb, y_pred_dummy, zero_division=0)), 4)

    # Non-1 positive label with explicit pos_label
    y_true_str = ["spam" if v == 1 else "ham" for v in y_true_spam]
    y_pred_str = ["spam" if v == 1 else "ham" for v in y_pred_spam]
    prec_str = round(float(precision_score(y_true_str, y_pred_str, pos_label="spam")), 4)

    c1_ok = (
        cm.tolist() == [[4, 1], [1, 4]]
        and (acc, prec, rec, f1) == (0.8, 0.8, 0.8, 0.8)
        and (imb_acc, imb_rec, imb_f1) == (0.99, 0.0, 0.0)
        and prec_str == 0.8
    )
    cases.append(dict(
        name="confusion_matrix_and_core_metrics",
        inputs=dict(n_samples=10, imbalanced_ratio="99:1", string_pos_label="spam"),
        prerequisites="二分类混淆矩阵 TN/FP/FN/TP、四大基础指标、99:1 不平衡准确率陷阱与 pos_label 指定",
        action="验证混淆矩阵 [[4,1],[1,4]]、准确率/精确率/召回率/F1 均为 0.80,99:1 全负预测准确率 0.99 但召回率与 F1 为 0。",
        expected=dict(cm=[[4, 1], [1, 4]], core_all_08=True, imbalanced_trap_confirmed=True, pos_label_exact=True),
        actual=dict(
            cm=cm.tolist(),
            core_all_08=((acc, prec, rec, f1) == (0.8, 0.8, 0.8, 0.8)),
            imbalanced_trap_confirmed=((imb_acc, imb_rec, imb_f1) == (0.99, 0.0, 0.0)),
            pos_label_exact=(prec_str == 0.8),
        ),
        measurements=dict(
            tn=tn, fp=fp, fn=fn, tp=tp,
            accuracy=acc, precision=prec, recall=rec, f1=f1,
            imbalanced_dummy_acc=imb_acc, imbalanced_dummy_recall=imb_rec, imbalanced_dummy_f1=imb_f1,
        ),
        passed=c1_ok,
    ))

    # 2. ROC curve, AUC regimes & Precision-Recall curve
    y_true_roc = [1, 0, 1, 0, 1]
    y_scores_roc = [0.9, 0.4, 0.6, 0.3, 0.8]
    fpr_ex, tpr_ex, _ = roc_curve(y_true_roc, y_scores_roc)
    auc_ex = round(float(auc(fpr_ex, tpr_ex)), 4)

    # Realistic imbalanced binary classification for informative ROC & PR curves
    X_bin, y_bin = make_classification(
        n_samples=600, n_features=12, n_informative=5, weights=[0.85, 0.15],
        class_sep=1.1, random_state=42,
    )
    Xb_tr, Xb_te, yb_tr, yb_te = train_test_split(X_bin, y_bin, test_size=0.3, stratify=y_bin, random_state=42)
    lr_bin = LogisticRegression(max_iter=300).fit(Xb_tr, yb_tr)
    prob_pos = lr_bin.predict_proba(Xb_te)[:, 1]
    fpr_real, tpr_real, _ = roc_curve(yb_te, prob_pos)
    auc_real = round(float(auc(fpr_real, tpr_real)), 4)
    auc_inverted = round(float(roc_auc_score(yb_te, 1.0 - prob_pos)), 4)
    pr_prec, pr_rec, _ = precision_recall_curve(yb_te, prob_pos)
    pr_ap = round(float(average_precision_score(yb_te, prob_pos)), 4)

    c2_ok = auc_ex == 1.0 and 0.8 < auc_real < 1.0 and auc_inverted < 0.2 and abs(auc_real + auc_inverted - 1.0) < 1e-3 and pr_ap > 0.6
    cases.append(dict(
        name="roc_auc_thresholds_and_pr_curve",
        inputs=dict(example_n=5, realistic_test_n=int(len(yb_te)), positive_rate=round(float(yb_te.mean()), 4)),
        prerequisites="不同阈值下的 FPR/TPR、AUC 三区间与不平衡数据的 PR 曲线平均精确率",
        action="核对示例 5 样本 AUC=1.00、真实概率模型 0.5<AUC<1、反转分数 AUC<0.5 及 PR-AP。",
        expected=dict(example_auc_1=True, real_auc_informative=True, inverted_auc_complement=True, pr_ap_gt_06=True),
        actual=dict(
            example_auc_1=(auc_ex == 1.0),
            real_auc_informative=(0.8 < auc_real < 1.0),
            inverted_auc_complement=(auc_inverted < 0.2 and abs(auc_real + auc_inverted - 1.0) < 1e-3),
            pr_ap_gt_06=(pr_ap > 0.6),
        ),
        measurements=dict(
            example_auc=auc_ex,
            example_fpr=[round(float(v), 4) for v in fpr_ex],
            example_tpr=[round(float(v), 4) for v in tpr_ex],
            real_roc_auc=auc_real,
            inverted_roc_auc=auc_inverted,
            pr_average_precision=pr_ap,
        ),
        passed=c2_ok,
    ))

    # 3. Multiclass macro vs micro averaging
    y_true_mc = [0, 1, 2, 0, 1, 2, 0, 1, 2]
    y_pred_mc = [0, 2, 2, 0, 1, 1, 0, 0, 2]
    prec_macro = round(float(precision_score(y_true_mc, y_pred_mc, average="macro")), 4)
    prec_micro = round(float(precision_score(y_true_mc, y_pred_mc, average="micro")), 4)
    rec_macro = round(float(recall_score(y_true_mc, y_pred_mc, average="macro")), 4)
    f1_macro = round(float(f1_score(y_true_mc, y_pred_mc, average="macro")), 4)
    f1_micro = round(float(f1_score(y_true_mc, y_pred_mc, average="micro")), 4)
    # Class-wise precision: cls0=3/4=0.75, cls1=1/2=0.50, cls2=2/3=0.6667 -> macro=0.6389; micro=6/9=0.6667
    c3_ok = round(prec_macro, 2) == 0.64 and round(prec_micro, 2) == 0.67 and prec_macro < prec_micro and f1_micro == prec_micro
    cases.append(dict(
        name="multiclass_macro_vs_micro_averaging",
        inputs=dict(classes=3, n_samples=9),
        prerequisites="三分类宏平均(macro)与微平均(micro)精确率/召回率/F1 差异验证",
        action="验证三分类示例宏平均精确率 0.6389(约 0.64)低于微平均 0.6667(约 0.67)。",
        expected=dict(macro_rounded=0.64, micro_rounded=0.67, macro_lt_micro=True),
        actual=dict(macro_rounded=round(prec_macro, 2), micro_rounded=round(prec_micro, 2), macro_lt_micro=(prec_macro < prec_micro)),
        measurements=dict(
            precision_macro=prec_macro,
            precision_micro=prec_micro,
            recall_macro=rec_macro,
            f1_macro=f1_macro,
            f1_micro=f1_micro,
        ),
        passed=c3_ok,
    ))

    # 4. Comprehensive Iris evaluation (LogisticRegression vs DecisionTreeClassifier)
    iris = load_iris()
    Xi_tr, Xi_te, yi_tr, yi_te = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
    lr_iris = LogisticRegression(max_iter=200).fit(Xi_tr, yi_tr)
    yi_pred = lr_iris.predict(Xi_te)
    yi_proba = lr_iris.predict_proba(Xi_te)
    iris_cm = confusion_matrix(yi_te, yi_pred)
    iris_acc = round(float(accuracy_score(yi_te, yi_pred)), 4)
    iris_auc_ovr = round(float(roc_auc_score(yi_te, yi_proba, multi_class="ovr", average="macro")), 4)
    iris_rep = classification_report(yi_te, yi_pred, target_names=iris.target_names, output_dict=True)

    dt_iris = DecisionTreeClassifier(max_depth=2, random_state=42).fit(Xi_tr, yi_tr)
    dt_acc = round(float(accuracy_score(yi_te, dt_iris.predict(Xi_te))), 4)
    dt_auc_ovr = round(float(roc_auc_score(yi_te, dt_iris.predict_proba(Xi_te), multi_class="ovr", average="macro")), 4)

    c4_ok = iris_cm.tolist() == [[19, 0, 0], [0, 13, 0], [0, 0, 13]] and iris_acc == 1.0 and iris_auc_ovr == 1.0 and dt_acc >= 0.95
    cases.append(dict(
        name="iris_comprehensive_model_evaluation",
        inputs=dict(dataset="load_iris", test_size=0.3, models=["LogisticRegression(max_iter=200)", "DecisionTreeClassifier(max_depth=2)"]),
        prerequisites="鸢尾花多分类混淆矩阵、classification_report、准确率与 OvR 宏平均 AUC 综合评估",
        action="验证逻辑回归测试集对角混淆矩阵 [[19,0,0],[0,13,0],[0,0,13]]、准确率 1.0000 与 OvR 宏平均 AUC 1.0000,并对比浅层决策树。",
        expected=dict(lr_acc=1.0, lr_auc_ovr=1.0, cm_diagonal=True, dt_acc_ge_95=True),
        actual=dict(lr_acc=iris_acc, lr_auc_ovr=iris_auc_ovr, cm_diagonal=(iris_cm.tolist() == [[19, 0, 0], [0, 13, 0], [0, 0, 13]]), dt_acc_ge_95=(dt_acc >= 0.95)),
        measurements=dict(
            lr_cm=iris_cm.tolist(),
            lr_accuracy=iris_acc,
            lr_macro_f1=round(float(iris_rep["macro avg"]["f1-score"]), 4),
            lr_auc_ovr=iris_auc_ovr,
            dt_depth2_accuracy=dt_acc,
            dt_depth2_auc_ovr=dt_auc_ovr,
        ),
        passed=c4_ok,
    ))

    # 5. Matplotlib figure: Confusion Matrix Heatmap + ROC Curve + Precision-Recall Curve
    if fig_dir is not None:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        fig_dir.mkdir(parents=True, exist_ok=True)

        fig, axes = plt.subplots(1, 3, figsize=(12.2, 3.8), dpi=140)

        # Panel 1: Binary Confusion Matrix Heatmap (arranged as TP/FN, FP/TN or standard sklearn TN/FP, FN/TP)
        cm_disp = np.array([[tp, fn], [fp, tn]])
        im = axes[0].imshow(cm_disp, cmap="Blues", vmin=0, vmax=5)
        labels_txt = [[f"TP = {tp}", f"FN = {fn}"], [f"FP = {fp}", f"TN = {tn}"]]
        for r in range(2):
            for c in range(2):
                color = "white" if cm_disp[r, c] >= 3 else "#1b2a38"
                axes[0].text(c, r, labels_txt[r][c], ha="center", va="center", fontsize=11, fontweight="bold", color=color)
        axes[0].set_xticks([0, 1])
        axes[0].set_xticklabels(["Pred Pos", "Pred Neg"])
        axes[0].set_yticks([0, 1])
        axes[0].set_yticklabels(["True Pos", "True Neg"])
        axes[0].set_title("Confusion Matrix (Spam Demo)", fontsize=10)

        # Panel 2: ROC Curves (Example AUC=1.00 + Imbalanced Logistic Regression)
        axes[1].plot(fpr_ex, tpr_ex, color="#d95f02", lw=2.0, marker="o", ms=4, label=f"Demo (AUC={auc_ex:.2f})")
        axes[1].plot(fpr_real, tpr_real, color="#174d79", lw=2.0, label=f"LogReg (AUC={auc_real:.3f})")
        axes[1].fill_between(fpr_real, tpr_real, alpha=0.14, color="#174d79")
        axes[1].plot([0, 1], [0, 1], color="#666666", lw=1.2, linestyle="--", label="Random (0.50)")
        axes[1].set_xlim(-0.02, 1.02)
        axes[1].set_ylim(-0.02, 1.05)
        axes[1].set_xlabel("False Positive Rate (FPR)")
        axes[1].set_ylabel("True Positive Rate (TPR)")
        axes[1].set_title("ROC Curve & AUC", fontsize=10)
        axes[1].grid(True, alpha=0.3)
        axes[1].legend(loc="lower right", fontsize=8)

        # Panel 3: Precision-Recall Curve on Imbalanced Set
        baseline = float(yb_te.mean())
        axes[2].plot(pr_rec, pr_prec, color="#2b7a57", lw=2.0, label=f"LogReg (AP={pr_ap:.3f})")
        axes[2].fill_between(pr_rec, pr_prec, alpha=0.14, color="#2b7a57")
        axes[2].axhline(baseline, color="#666666", lw=1.2, linestyle="--", label=f"Baseline ({baseline:.2f})")
        axes[2].set_xlim(-0.02, 1.02)
        axes[2].set_ylim(-0.02, 1.05)
        axes[2].set_xlabel("Recall")
        axes[2].set_ylabel("Precision")
        axes[2].set_title("Precision-Recall Curve (85:15)", fontsize=10)
        axes[2].grid(True, alpha=0.3)
        axes[2].legend(loc="lower left", fontsize=8)

        fig.tight_layout()
        out_png = fig_dir / "classification-metrics-curves.png"
        fig.savefig(out_png)
        plt.close(fig)
        figures["classification-metrics-curves.png"] = sha(out_png)
        mpl_ver = matplotlib.__version__
    else:
        mpl_ver = None

    cases.append(dict(
        name="observed_metrics_plot",
        inputs=dict(panels=3, roc_points=int(len(fpr_real)), pr_points=int(len(pr_rec))),
        prerequisites="混淆矩阵热图、ROC/AUC 与不平衡数据 PR 曲线绘图输出",
        action="生成包含混淆矩阵、ROC 曲线与 Precision-Recall 曲线的三联实测图。",
        expected=dict(panels=3, curves_nonempty=True),
        actual=dict(panels=3, curves_nonempty=(len(fpr_real) > 2 and len(pr_rec) > 2)),
        measurements=dict(figure_generated="classification-metrics-curves.png" in figures),
        passed=(len(fpr_real) > 2 and len(pr_rec) > 2),
    ))

    payload = dict(
        version=platform.python_version(),
        sklearn=sklearn.__version__,
        numpy=np.__version__,
        system=platform.system(),
        cases=cases,
    )
    if mpl_ver:
        payload["matplotlib"] = mpl_ver
        payload["figures"] = figures
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--figures", type=Path, default=None)
    args = parser.parse_args()
    run_cases(args.figures)
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/ml-classification-metrics-lab/explore-classification-metrics.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-classification-metrics.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a452.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习