Quick reference

Supervised Learning Algorithms Cheat Sheet: Concepts, 10 Core Models, Metrics & Model Selection

A production-grade reference guide to supervised learning: covering end-to-end ML workflows, 10 core algorithm mechanics and hyperparameter tuning, comprehensive classification and regression metrics, industrial model selection matrix, and 7 engineering best practices.

· Published

Supervised Learning is the most widely adopted and production-mature paradigm in machine learning. It fits models on ground-truth labeled training data to learn an optimal mapping function ( f: X \to y ) between input features ( X ) and target labels ( y ), delivering accurate predictions on unseen data.

This cheat sheet provides a high-density, production-tested reference covering the end-to-end machine learning lifecycle, 10 foundational and state-of-the-art algorithms, comprehensive evaluation metrics, and a practical model selection matrix.

🔗 Related Cheat Sheets: Core AI Algorithms · Scikit-Learn Cheat Sheet · Keras Cheat Sheet · Algorithm Complexity (Big-O) · Vector Databases & Retrieval Architecture · Python Cheat Sheet


1. Core Framework & Two Primary Task Paradigms

1.1 End-to-End Production Workflow

[Labeled Data (X, y)] ──> [Feature Eng & Cleaning] ──> [Data Split (Train/Val/Test)]
                                                                   │
                                                                   ▼
[Production Inference] <── [Metric Eval & Tuning] <── [Model Training & HPO]
  1. Data Collection & Annotation: Assemble feature matrices ( X \in \mathbb{R}^{n \times d} ) with high signal-to-noise ratios and ground-truth targets ( y ).
  2. Feature Engineering & Preprocessing: Impute missing values, clip outliers, encode categorical features (One-Hot, Target Encoding), and scale numerical features (StandardScaler, MinMaxScaler).
  3. Data Splitting & Cross-Validation: Partition data into Train, Validation, and Test sets using stratified or temporal splitting to strictly prevent data leakage.
  4. Model Training & Hyperparameter Tuning: Train baseline models via gradient-based or closed-form optimization, tuning hyperparameters with K-Fold Cross-Validation.
  5. Model Evaluation & Validation: Benchmark models against business-aligned metrics across multiple calibration and threshold boundaries.
  6. Inference & Monitoring: Export optimized artifacts (ONNX, TensorRT), deploy batch or real-time scoring, and monitor feature drift and concept drift over time.

1.2 Classification vs. Regression

Task Type Target Label Space Standard Loss Functions Primary Output Typical Industrial Use Cases
Classification Discrete categories (Binary, Multi-class, Multi-label) Cross-Entropy, Log Loss, Hinge Loss, Focal Loss Calibrated probabilities ( P(y=c \mid X) ) or class decisions Spam filtering, CTR prediction, credit card fraud detection, medical triage diagnosis
Regression Continuous numeric values (Scalars or Vectors) Mean Squared Error (MSE), Mean Absolute Error (MAE), Huber, Smooth L1 Continuous scalar estimates ( \hat{y} \in \mathbb{R} ) Asset valuation, demand & sales forecasting, weather modeling, Loss Given Default (LGD)

2. Master Table: 10 Core Supervised Learning Algorithms

# Algorithm (Abbr.) Task Type Core Mathematical Foundation Time Complexity (Train / Predict) Key Hyperparameters Production Characteristics & Boundary
01 Linear Regression Regression Ordinary Least Squares (OLS); Regularized into Ridge (L2) / Lasso (L1) Train: ( O(d^3 + nd^2) )
Predict: ( O(d) )
alpha (L1/L2 penalty), l1_ratio High explainability; coefficients directly reflect impact; sensitive to outliers and multicollinearity.
02 Logistic Regression Classification Sigmoid/Softmax maps linear projections to posterior probabilities; minimizes Log Loss Train: ( O(nd) )
Predict: ( O(d) )
C (inverse penalty), class_weight, penalty Generalized linear model with calibrated probabilities; linear decision boundary cannot capture non-linear interactions.
03 Decision Tree (CART) Both Greedy recursive binary partitioning maximizing Gini gain or variance reduction Train: ( O(n \cdot d \log n) )
Predict: ( O(\text{depth}) )
max_depth, min_samples_split, min_samples_leaf White-box If-Else rules; invariant to feature scale; handles missing data natively; high variance and prone to overfitting.
04 Random Forest Both Bagging: row bootstrapping + random column subspace sampling; tree voting/averaging Train: ( O(M \cdot n \cdot d \log n) )
Predict: ( O(M \cdot \text{depth}) )
n_estimators, max_features, max_depth Drastically reduces variance; excellent out-of-the-box performance; robust against overfitting; provides feature importance.
05 Support Vector Machine (SVM) Both Convex quadratic programming maximizing margins; soft margins and Kernel Trick Train: ( O(n^2 \cdot d) \sim O(n^3) )
Predict: ( O(N_{\text{sv}} \cdot d) )
C (penalty), kernel, gamma (RBF width) Strong theoretical generalization bounds; excels in high-dimensional small samples; strictly requires scaling; slow on ( n > 10^5 ).
06 K-Nearest Neighbors (KNN) Both Instance-based lazy learning: computes metric distance to ( K ) nearest neighbors Train: ( O(1) )
Predict: ( O(n \cdot d) ) or KD-Tree ( O(d \log n) )
n_neighbors, metric, weights Simple and intuitive; no explicit training stage; suffers from curse of dimensionality; high memory and inference latency.
07 Naive Bayes Classification Bayes Theorem with class-conditional feature independence assumption (MAP) Train: ( O(nd) )
Predict: ( O(cd) )
alpha (Laplace smoothing parameter) Extremely fast training/inference; excels in sparse text classification; independence assumption fails on correlated features.
08 Gradient Boosted Trees (GBDT) Both Boosting: sequentially fits shallow regression trees to negative gradients of loss Train: ( O(M \cdot n \cdot d \log n) )
Predict: ( O(M \cdot \text{depth}) )
learning_rate, n_estimators, max_depth, subsample Sequentially minimizes bias; captures complex non-linear interactions; strictly serial training; sensitive to hyperparameter tuning.
09 XGBoost Both 2nd-order Taylor loss expansion, structural tree regularization, quantile sketch Train: Optimized multi-core / GPU
Predict: ( O(M \cdot \text{depth}) )
eta, max_depth, lambda (L2), gamma (min split loss) SOTA standard for tabular benchmarks; native handling of missing values; hardware-level cache awareness and GPU acceleration.
10 Neural Networks (MLP) Both Affine matrix transformations with non-linear activations; Backpropagation (BP) Scales with layers, hidden units, and batch sizes hidden_layer_sizes, activation, learning_rate_init, alpha Arbitrary non-linear representation power; excels on unstructured data (vision, audio, NLP); black-box nature; compute-heavy.

3. Deep Dive: Mechanics, Formulas & Production Pitfalls

01. Linear Regression

  • Core Formulation: $$ \hat{y} = \mathbf{w}^T \mathbf{x} + b, \quad \mathcal{L}{\text{MSE}}(\mathbf{w}, b) = \frac{1}{2n} \sum{i=1}^n \left( y^{(i)} - (\mathbf{w}^T \mathbf{x}^{(i)} + b) \right)^2 $$
  • Regularization Variants:
    • Ridge (L2): ( \mathcal{L} + \lambda |\mathbf{w}|_2^2 ), shrinks weights to prevent ill-conditioned inversion in collinear features.
    • Lasso (L1): ( \mathcal{L} + \lambda |\mathbf{w}|_1 ), drives redundant coefficients to zero for automatic sparse feature selection.
    • ElasticNet: Combines L1 and L2 penalties to retain group selection effects under correlation.
  • Production Pitfalls: Extreme outliers exert quadratic leverage on the regression line; apply Huber loss or RANSAC when data contains severe noise.

02. Logistic Regression

  • Core Formulation: $$ P(y=1 \mid \mathbf{x}) = \sigma(\mathbf{w}^T \mathbf{x} + b) = \frac{1}{1 + e^{-(\mathbf{w}^T \mathbf{x} + b)}} $$ $$ \mathcal{L}{\text{LogLoss}} = -\frac{1}{n}\sum{i=1}^n \left[ y^{(i)}\ln(\hat{p}^{(i)}) + (1 - y^{(i)})\ln(1 - \hat{p}^{(i)}) \right] $$
  • Key Insight: Maps linear predictions to the ((0, 1)) probability interval. Log-odds are linear: ( \ln\frac{p}{1-p} = \mathbf{w}^T \mathbf{x} + b ).
  • Production Pitfalls: Cannot learn feature interactions directly without manual feature crosses or polynomial expansions. Use Softmax for multi-class classification.

03. Decision Tree (CART)

  • Splitting Criteria:
    • Classification (Gini Impurity): $$ \text{Gini}(D) = 1 - \sum_{k=1}^K p_k^2, \quad \Delta \text{Gini} = \text{Gini}(D) - \frac{|D_L|}{|D|}\text{Gini}(D_L) - \frac{|D_R|}{|D|}\text{Gini}(D_R) $$
    • Regression (Variance Reduction): $$ \mathcal{L}(D) = \sum_{i \in D_L} (y^{(i)} - \bar{y}L)^2 + \sum{j \in D_R} (y^{(j)} - \bar{y}_R)^2 $$
  • Key Insight: Hierarchical axis-aligned partitioning. Non-parametric, highly interpretable, and invariant to monotonic feature scaling.
  • Production Pitfalls: Unconstrained trees overfit aggressively. Always constrain max_depth, min_samples_leaf, or apply cost-complexity pruning (ccp_alpha).

04. Random Forest

  • Core Mechanisms:
    • Row Perturbation: Bootstrap sampling with replacement leaves (\approx 36.8%) of data out-of-bag (OOB) for unbiased zero-cost validation.
    • Column Perturbation: At each split, selects from a random subset of features (( \sqrt{d} ) for classification, ( d/3 ) for regression).
  • Variance Reduction: For ( M ) trees with variance ( \sigma^2 ) and pairwise correlation ( \rho ), ensemble variance is ( \rho \sigma^2 + \frac{1-\rho}{M}\sigma^2 ). Feature random subspace sampling lowers ( \rho ), driving down total model variance.
  • Tuning Strategy: More trees monotonically improve stability until returns plateau (usually 100–500). Focus tuning on max_features and min_samples_leaf.

05. Support Vector Machine (SVM)

  • Dual Formulation (Soft Margin): $$ \max_{\boldsymbol{\alpha}} \sum_{i=1}^n \alpha_i - \frac{1}{2}\sum_{i=1}^n \sum_{j=1}^n \alpha_i \alpha_j y^{(i)} y^{(j)} K(\mathbf{x}^{(i)}, \mathbf{x}^{(j)}) \quad \text{s.t.} \quad 0 \le \alpha_i \le C, \sum_{i=1}^n \alpha_i y^{(i)} = 0 $$
  • Primary Kernels:
    • Linear Kernel: ( K(\mathbf{x}_i, \mathbf{x}_j) = \mathbf{x}_i^T \mathbf{x}_j ) (optimal for high-dimensional text).
    • RBF Gaussian Kernel: ( K(\mathbf{x}_i, \mathbf{x}_j) = \exp(-\gamma |\mathbf{x}_i - \mathbf{x}_j|^2) ) (general non-linear boundaries).
  • Production Pitfalls: Requires standardized inputs; scaling differences distort margins. Training scaling of ( O(n^2 \sim n^3) ) makes non-linear SVM intractable for large datasets (( n > 100\text{k} )).

06. K-Nearest Neighbors (KNN)

  • Prediction Rule: $$ \hat{y}(\mathbf{x}) = \text{Mode}\left( { y^{(i)} \mid \mathbf{x}^{(i)} \in \mathcal{N}_k(\mathbf{x}) } \right) $$
  • Distance Metrics: Minkowski distance ( D(\mathbf{x}, \mathbf{z}) = \left(\sum |x_j - z_j|^p\right)^{1/p} ) (( p=1 ) Manhattan, ( p=2 ) Euclidean).
  • Production Pitfalls: Inference requires scanning all training points. Suffers severely from the curse of dimensionality; distances become equidistant in high dimensions. Always apply dimensionality reduction (PCA) beforehand.

07. Naive Bayes

  • Bayes Formulation: $$ P(C_k \mid \mathbf{x}) = \frac{P(C_k) \prod_{j=1}^d P(x_j \mid C_k)}{\sum_{r} P(C_r) \prod_{j=1}^d P(x_j \mid C_r)} \propto P(C_k) \prod_{j=1}^d P(x_j \mid C_k) $$
  • Common Distributions:
    • GaussianNB: Continuous features assuming normal distributions per class.
    • MultinomialNB: Discrete word counts and TF-IDF term frequencies.
    • BernoulliNB: Binary indicator vectors (word presence / absence).
  • Production Pitfalls: Zero-probability collapse occurs for unseen tokens; always enforce Laplace smoothing (( \alpha = 1 )).

08. Gradient Boosted Decision Trees (GBDT)

  • Additive Model & Gradient Fitting: $$ F_m(\mathbf{x}) = F_{m-1}(\mathbf{x}) + \eta \cdot h_m(\mathbf{x}) $$ where each new weak regression tree ( h_m(\mathbf{x}) ) fits the negative gradient (pseudo-residuals) of the loss function: $$ r_{im} = -\left[ \frac{\partial \mathcal{L}(y_i, F(\mathbf{x}i))}{\partial F(\mathbf{x}i)} \right]{F(\mathbf{x}) = F{m-1}(\mathbf{x})} $$
  • Tuning Strategy: Unlike Random Forests (which reduce variance), GBDT sequentially reduces bias. Use small learning rates (( \eta \le 0.05 )) paired with early stopping to prevent aggressive overfitting.

09. XGBoost (Extreme Gradient Boosting)

  • Objective Function (2nd-Order Taylor + Explicit Regularization): $$ \text{Obj}^{(t)} \approx \sum_{i=1}^n \left[ g_i f_t(\mathbf{x}i) + \frac{1}{2} h_i f_t^2(\mathbf{x}i) \right] + \gamma T + \frac{1}{2}\lambda \sum{j=1}^T w_j^2 $$ where ( g_i = \partial{\hat{y}^{(t-1)}} \mathcal{L} ) and ( h_i = \partial^2_{\hat{y}^{(t-1)}} \mathcal{L} ), ( T ) is the number of leaves, and ( w_j ) are leaf weights.
  • Engineering Innovations:
    • Second-order derivatives provide exact curvature information;
    • Explicit leaf penalties limit model complexity;
    • Sparsity-aware split finding handles missing values automatically;
    • Approximate histogram sketches enable distributed multi-threaded and GPU execution.

10. Neural Networks (Multilayer Perceptron / MLP)

  • Forward & Backward Propagation: $$ \mathbf{a}^{(l)} = \sigma\left( \mathbf{W}^{(l)} \mathbf{a}^{(l-1)} + \mathbf{b}^{(l)} \right), \quad \mathbf{W} \leftarrow \mathbf{W} - \eta \frac{\partial \mathcal{L}}{\partial \mathbf{W}} $$
  • Key Insight: Alternates affine projections with non-linear activation functions (ReLU, GELU, Swish), leveraging the chain rule for end-to-end backpropagation.
  • Production Boundary: Gradient boosted trees (XGBoost/LightGBM) typically outperform MLPs on structured tabular data in speed and sample efficiency; neural networks dominate unstructured data (images, speech, natural language).

4. Evaluation Metrics Reference Matrix

               ┌─────────────────────── Actual Ground Truth ───────────────────┐
               │              Positive (+)             Negative (-)            │
┌──────────────┼───────────────────────────────────────────────────────────────┤
│ Positive (+) │           True Positive (TP)           False Positive (FP)    │
│ Predicted    │                                        (Type I Error)         │
│ Negative (-) │           False Negative (FN)          True Negative (TN)     │
│              │           (Type II Error)                                     │
└──────────────┴───────────────────────────────────────────────────────────────┘

4.1 Classification Evaluation Metrics

Metric Mathematical Formula Core Interpretation Best Use Cases & Pitfalls
Accuracy ( \frac{\text{TP} + \text{TN}}{\text{TP} + \text{TN} + \text{FP} + \text{FN}} ) Ratio of correct predictions over total samples Valid only on balanced datasets; completely misleading on imbalanced data (e.g., 99% accuracy by predicting all negatives on a 1% fraud dataset).
Precision (Positive Predictive Value) ( \frac{\text{TP}}{\text{TP} + \text{FP}} ) Proportion of true positives among all predicted positives Critical when False Positives carry high cost (e.g., spam false alarms, fraud false freezes).
Recall (Sensitivity / TPR) ( \frac{\text{TP}}{\text{TP} + \text{FN}} ) Proportion of true positives identified among all actual positives Critical when False Negatives carry fatal cost (e.g., tumor cancer screening, security breach detection).
F1-Score ( 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}} ) Harmonic mean of Precision and Recall Standard balanced metric; use Macro-F1 for equal class weighting or Weighted-F1 for size-proportional evaluation.
ROC-AUC Area under ROC Curve (FPR vs. TPR across all thresholds) Probability that a random positive is ranked higher than a random negative Evaluates overall ranking capability independently of operational classification threshold; robust when class balance is moderate.
PR-AUC Area under Precision-Recall Curve Precision behavior integrated across all recall thresholds Gold standard for severe class imbalance (e.g., 0.01% ad conversion rate, rare financial defaults).
Log Loss (Cross-Entropy) ( -\frac{1}{n} \sum [y \ln \hat{p} + (1-y)\ln(1-\hat{p})] ) Logarithmic penalty on predicted probability deviation Evaluates probabilistic calibration; vital for auction bidding and risk scoring where probability magnitudes matter.

4.2 Regression Evaluation Metrics

Metric Mathematical Formula Core Interpretation Best Use Cases & Pitfalls
Mean Absolute Error (MAE) ( \frac{1}{n}\sum_{i=1}^n |y^{(i)} - \hat{y}^{(i)}| ) Mean magnitude of prediction errors Retains original target units; penalizes errors linearly; highly robust to extreme outliers.
Mean Squared Error (MSE) ( \frac{1}{n}\sum_{i=1}^n (y^{(i)} - \hat{y}^{(i)})^2 ) Mean of squared prediction errors Penalizes large errors heavily; smoothly differentiable for gradient optimization; non-intuitive squared units.
Root Mean Squared Error (RMSE) ( \sqrt{\frac{1}{n}\sum_{i=1}^n (y^{(i)} - \hat{y}^{(i)})^2} ) Square root of MSE Standard engineering metric returning error to original units while preserving quadratic sensitivity to outliers.
Coefficient of Determination (( R^2 )) ( 1 - \frac{\sum (y^{(i)} - \hat{y}^{(i)})^2}{\sum (y^{(i)} - \bar{y})^2} ) Proportion of variance explained by model (best = 1, can be ( < 0 )) Dimensionless benchmark metric across datasets; values below 0 indicate predictions worse than the mean baseline.
Mean Absolute Percentage Error (MAPE) ( \frac{100%}{n}\sum_{i=1}^n \left|\frac{y^{(i)} - \hat{y}^{(i)}}{y^{(i)}}\right| ) Average relative percentage error Intuitive for executive communication; explodes or becomes undefined when ground truth ( y = 0 ).

5. Industrial Model Selection Decision Matrix

Under the No Free Lunch Theorem, no single model uniformly outperforms all alternatives. Model selection must balance dataset topology, latency budgets, feature dimensionality, and explainability requirements:

Scenario / Data Topology Recommended First-Line Model Advanced / Alternative Model Architectural Justification
Strong linear trends, strict compliance / regulatory auditing Linear / Ridge Regression Shallow Decision Trees Direct white-box coefficient auditing; ultra-low CPU footprint.
Binary classification needing calibrated probabilities Logistic Regression GBDT leaf embeddings + LR Stable monotonic probability outputs with natural odds ratio interpretation.
Explainable If-Else business rule extraction Decision Tree (CART) RuleFit / Linear Baselines Directly maps to human-readable business decision policies; scale-invariant.
Medium-sized tabular data, zero-tuning baseline Random Forest Extremely Randomized Trees Dual randomization suppresses variance out-of-the-box with minimal tuning.
Small-scale low-dimensional data, localized cluster topology KNN Naive Bayes Non-parametric instance lookup; ideal for fast cold-start baselines.
High-dimensional sparse text classification (TF-IDF / Bag of Words) Naive Bayes Linear SVM (LinearSVC) Conditional independence holds well in sparse text; converges almost instantly.
High-dimensional small samples, complex non-linear boundary Support Vector Machine (RBF) Random Forest Maximum margin theory guarantees robust generalization bounds on small datasets.
Large-scale structured tabular data, competitive SOTA accuracy XGBoost / LightGBM CatBoost (categorical heavy) 2nd-order gradients, histogram acceleration, and missing-value handling make boosted trees the tabular benchmark.
Unstructured multimodal inputs (CV, NLP, Speech, Time Series) Deep Neural Networks (CNN/Transformer) Pretrained Model Fine-tuning End-to-end representation learning breaks manual feature extraction ceilings at scale.

6. 7 Production Best Practices for Supervised Learning

  1. Features Define the Ceiling; Models Only Approximate It
    • Dedicate 70% of engineering bandwidth to data hygiene, feature crosses, aggregations, and target encoding before cycling through complex model architectures.
  2. Always Standardize for Distance and Gradient Models
    • Algorithms relying on Euclidean distances (KNN), hyperplanes (SVM), or gradient descent (Logistic Regression, Neural Networks) strictly require feature scaling (StandardScaler). Tree-based models are scale-invariant.
  3. Strictly Guard Against Data Leakage
    • Compute scaling statistics, imputation values, and encodings exclusively on the training fold. Never fit scalers on the full dataset before cross-validation splitting.
  4. Counteract Class Imbalance Systematically
    • On severe skew (( > 1:100 )), abandon raw Accuracy. Optimize for PR-AUC or Balanced Accuracy, configure cost-sensitive loss (class_weight='balanced', scale_pos_weight), or apply SMOTE / downsampling.
  5. Regularization Is the First Line of Defense
    • Apply L1/L2 penalties to linear models, restrict max_depth and min_samples_leaf on trees, utilize early stopping on boosting rounds, and inject Dropout / Weight Decay into deep networks.
  6. Tier Hyperparameter Tuning
    • Start with domain-informed defaults; run RandomizedSearchCV to identify sensitive hyperparameter subspaces; proceed to Bayesian Optimization (Optuna) over stratified K-folds.
  7. Adhere to Occam’s Razor: Simple First
    • Benchmark against simple interpretable baselines (Logistic Regression or single trees). Validate that complex ensemble or neural pipelines justify their latency, compute, and maintenance overheads in production.

Related topics