←Back to Science Coding Hub/Part J/J4
J4EasyPart J · RecSys & Search Metrics

Confusion Matrix, Precision, Recall & Macro/Micro F1

Industrial-grade implementation and mathematical foundations of Confusion Matrix, Precision, Recall & Macro/Micro F1.

⏱️ Time Complexity: O(N)
💾 Space Complexity: O(1)
💡

Core Mental Anchor / Mnemonic

Master Confusion Matrix, Precision, Recall & Macro/Micro F1: enforce numerical stability, check tensor shapes, and eliminate redundant memory allocations.

📐 Mathematical Derivation & Core Formula

Precision=TPTP+FP,Recall=TPTP+FN,F1=2⋅P⋅RP+R\mathrm{Precision} = \frac{\mathrm{TP}}{\mathrm{TP} + \mathrm{FP}}, \quad \mathrm{Recall} = \frac{\mathrm{TP}}{\mathrm{TP} + \mathrm{FN}}, \quad \mathrm{F1} = 2 \cdot \frac{P \cdot R}{P + R}
### Mathematical Derivation & Theoretical Principles
Detailed first-principles formulation and architectural mechanics for Confusion Matrix, Precision, Recall & Macro/Micro F1.

Refer to the LaTeX equation above for the core operator definition. The operator is designed to ensure strict numerical bounds, avoiding floating-point overflows and gradient anomalies.

🔄 Tensor Dimensions & Shape Flow

y_true, y_pred (N,) -> 逻辑与运算计数 TP,FP,FN,TN -> 闭式解算 P, R, F1

🛡️ Industrial Numerical Stability & Pitfalls

  • Ensure proper multi-dimensional tensor broadcasting and keepdims retention.
  • Enforce numerical guards (eps clamping and overflow thresholds) during exponentiation and division.
  • Verify train versus eval mode behavioral distinctions (e.g. frozen running statistics and dropout bypass).

💻 Industrial Code Implementation

import numpy as np

def compute_classification_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict:
    """手写二分类混淆矩阵与评估指标"""
    tp = int(np.sum((y_true == 1) & (y_pred == 1)))
    fp = int(np.sum((y_true == 0) & (y_pred == 1)))
    fn = int(np.sum((y_true == 1) & (y_pred == 0)))
    tn = int(np.sum((y_true == 0) & (y_pred == 0)))
    
    precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
    recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
    
    return {
        "tp": tp, "fp": fp, "fn": fn, "tn": tn,
        "precision": float(precision),
        "recall": float(recall),
        "f1": float(f1)
    }

🧪 Runnable Assertions & Validation

Copy and run directly in Python / Jupyter to verify correctness:

import numpy as np
yt = np.array([1, 1, 0, 0])
yp = np.array([1, 0, 1, 0])
m = compute_classification_metrics(yt, yp)
assert m["tp"] == 1 and m["fp"] == 1 and m["fn"] == 1 and m["tn"] == 1
assert np.isclose(m["precision"], 0.5)
assert np.isclose(m["recall"], 0.5)
assert np.isclose(m["f1"], 0.5)
print("✓ 混淆矩阵与 F1 综合指标自测通过")

🎯 Core Architecture Follow-up Q&A

Q1:What are the key trade-offs and memory bottlenecks when deploying Confusion Matrix, Precision, Recall & Macro/Micro F1 in high-throughput inference?
Memory bandwidth (HBM to SRAM I/O) is the primary latency factor. Fusing element-wise operations and avoiding intermediate tensor materialization significantly outperforms naive implementations.
Q2:How does Confusion Matrix, Precision, Recall & Macro/Micro F1 handle extreme numerical boundaries or precision reduction (FP16/BF16/INT8)?
Under low precision, operations must be upcasted to FP32 during accumulation to prevent underflow/overflow, followed by proper scaling and clamping before converting back to the target format.
←Prev: NDCG@K (Normalized Discounted Cumulative Gain)All 69 KernelsNext: Cosine Similarity & Vector Top-K Retrieval→