Machine Learning Notes

1 | Problem framing and experimental design

  • Specify prediction target, prediction time, decision threshold, intervention, utility and the cost of errors. Classify as regression, ranking, classification, forecasting, clustering, anomaly detection or causal estimation.

  • Choose a meaningful minimum baseline: majority class, mean/median, seasonal naive, last value, simple rule, or regularized linear model. Define the business metric separately from the surrogate training loss.

  • Create train/validation/test boundaries before looking at global statistics. Preserve the truly untouched final test; choose random stratified, grouped, chronological, purged/embargoed, or out-of-domain splits to match deployment.

  • Establish post-deployment realism: feature availability at prediction time, annotation lag, population shift, duplicate entities, treatment effects and feedback loops.

Further study — problem framing and experimental design

2 | Data preparation, feature engineering and leakage

Issue Preferred approach Watch-outs
Missing values Determine MCAR/MAR/MNAR; add indicators where useful; median/most-frequent/KNN/model-based imputation; native missing splits for capable trees. Imputers fit on training fold only; missingness may be informative or policy-driven.
Numerical scales / outliers StandardScaler for penalized linear, SVM, KNN and PCA; robust scaler/transform for heavy tails; quantile/power transform as justified. Do not scale entire dataset pre-split; tree models usually do not need scaling.
Categorical One-hot for low cardinality; explicit ordinal only if meaningful; native categorical boosting; cross-fitted target encoding; hashing for huge vocabularies. Rare/unseen categories; target leakage; uncontrolled cardinality and memory.
Time series / panel Lag and rolling-window features computed backward in time, entity-aware validation, known-future covariates only. Irregular sampling, label delays, horizon alignment, rolling aggregation leakage.
Imbalanced labels Appropriate ranking/PR metrics, class weights, threshold tuning, re/under-sampling inside folds only. SMOTE before split; accuracy as primary metric; probability distortion after resampling.
High-dimensional / collinear Regularization, feature filtering, embedded selection, PCA/SVD where suitable; stability analysis. Selection performed outside CV; PCA harms interpretability.
Data quality Schema contracts, ranges, duplicates, joins, units, class prevalence, label provenance, label noise audits. Silent schema changes, proxy attributes, broken as-of joins.
Further study — data preparation and feature engineering

3 | Core algorithm comparison

Default competition for structured tabular supervised learning: simple baseline → penalized generalized linear model → histogram-based gradient boosting / CatBoost or LightGBM or XGBoost → random forest; test a tabular foundation model where constraints and data size permit. Neural networks are stronger default choices for unstructured modalities than for ordinary medium-size tables.

Official estimator selection guide: https://scikit-learn.org/stable/machine_learning_map.html

Family Strengths / when to try Limitations / sensitive knobs
Linear / logistic / elastic net / GLM Fast, explainable, stable, sparse high-dimensional features; effective calibrated-ish starting point; useful with low signal. Linear additive boundaries absent features; scaling and nonlinear transformations; C/alpha, L1 ratio, interactions, regularization.
k-nearest neighbors (KNN) Simple nonparametric local structure; little fit time; good small low-dimensional smooth manifolds. Prediction/storage cost O(n); curse of dimensionality; metric and scaling critical; k, distance weighting, ANN indexing.
Single decision tree Human-readable rules, nonlinear splits, mixed features, monotone constraints in some implementations. High variance/instability, axis-aligned partition artifacts, depth and leaf-size tuning; probabilities often poor.
Random forest / ExtraTrees Low tuning burden; robust nonlinear baseline; variance reduction via bagging; permutation importance feasible. Larger models, weaker extrapolation, less sharp tabular accuracy than tuned boosting; leaf size/max_features/trees.
Gradient-boosted trees (GBDT) Often strongest general tabular baseline; flexible nonlinear interactions; native missing/categorical options; fast histogram engines. Sensitive to overfitting/noisy labels, tuning/early stopping, split artifacts, extrapolation; learning_rate, leaves/depth, iterations, regularization.
SVM / kernel methods Strong margins for medium data, sparse text via linear SVM, nonlinear RBF with good feature scale. Kernel fit roughly quadratic+ in samples; probabilities need calibration; C, gamma, kernel.
Naïve Bayes Very fast for sparse text/counts; low sample needs; robust baseline. Strong conditional-independence assumptions; poorly calibrated probabilities; smoothing alpha.
GAM / splines / Explainable Boosting Interpretable nonlinear main effects; often excellent regulated-domain accuracy/clarity compromise. Misses complex interactions unless added; binning/smoothing/interaction tuning.
MLP / tabular deep nets GPU-friendly, multitask embeddings, shared representations and huge training sets; combines modalities. Data hungry, more tuning, feature/scale sensitivity; may trail GBDT on modest heterogeneous tables.
Tabular foundation models (e.g., TabPFN) Fast task adaptation, compelling small-data accuracy, useful in an ensemble or fast benchmark. Memory/context/size/feature limits vary by version; licensing, OOD, calibration and independent evaluation concerns.
Gaussian processes Uncertainty-aware regression, strong small-data smooth-function prior; Bayesian optimization. Classic exact inference O(n³), kernel sensitivity; sparse approximations for scale.
Further study — supervised algorithm families

Each pair starts with a practical explanation and, where useful, a deeper implementation or research reference.

Linear regression, logistic regression, Ridge, Lasso, and Elastic Net

Read: scikit-learn: Generalized linear models · scikit-learn: Logistic regression. Focus: regularization geometry, collinearity, interactions, coefficient interpretation.

K-nearest neighbors (KNN)

Read: scikit-learn: Nearest Neighbors · NearestNeighbors API. Focus: distance metric, scaling, search complexity, dimensionality.

Decision trees

Read: scikit-learn: Decision trees · Plotting a decision tree. Focus: impurity, pruning, instability, depth/leaf-size effects.

Random forests and ExtraTrees

Read: scikit-learn: Ensemble methods · RandomForestClassifier. Focus: bootstrap variance reduction, decorrelation, out-of-bag scoring.

Gradient-boosted trees: XGBoost, LightGBM, CatBoost, HistGBDT

Read: XGBoost documentation · LightGBM documentation · CatBoost documentation · scikit-learn: Histogram boosting. Focus: sequential fitting, early stopping, regularization, native categoricals.

SVM and kernel methods

Read: scikit-learn: Support vector machines · RBF SVM parameter example. Focus: margins, kernels, C/gamma, complexity.

Naïve Bayes

Read: scikit-learn: Naïve Bayes · scikit-learn: Text classification. Focus: independence assumption, count features, smoothing, calibration.

GAMs and explainable boosting machines

Read: InterpretML: Explainable Boosting Machine · pyGAM documentation. Focus: smooth additive effects vs. explicitly modeled interactions.

Neural networks and MLPs

Read: PyTorch tutorials · scikit-learn: Neural network models. Focus: optimization, regularization, embeddings, when deep learning is competitive.

Tabular foundation models (TabPFN)

Read: TabPFN research paper (Nature, 2025) · TabPFN repository. Focus: pretrained priors, task limits, licensing, benchmark quality.

Gaussian processes

Read: scikit-learn: Gaussian processes · Gaussian Processes for Machine Learning (free book). Focus: kernels, posterior uncertainty, O(n³) exact inference.

Key algorithm mechanics and selection heuristics
  • Bias–variance: bagging averages unstable learners to reduce variance; boosting sequentially fits residuals/gradients to reduce bias (but can overfit); regularization constrains complexity. Early stopping is a form of regularization.

  • KNN: classification by neighborhood vote; regression by local mean. Crucial choices are k, distance metric, feature scaling, dimensionality reduction and approximate nearest-neighbor lookup. Do not confuse predictive KNN with embedding retrieval KNN.

  • Trees: recursive threshold partitions; impurity (Gini/entropy) for classification and squared error/other objectives for regression. Small leaves and deep trees make jagged high-variance functions.

  • Bagging versus boosting: random forests decorrelate trees using feature subsampling; GBDT adds trees stagewise with shrinkage. CatBoost emphasizes categorical handling and ordered boosting; LightGBM prioritizes histogram/leafwise speed; XGBoost offers strong regularization and engineering.

  • Logistic regression models log-odds, not probability linearly. Interpretation of coefficients depends on scaling, regularization, collinearity and feature coding.

  • Kernel SVM and RBF distinguish by pairwise similarity; useful at moderate n, but RBF scaling and calibration can dominate operational costs.

Further study — key algorithm mechanics
Unsupervised, representation, time-series and causal methods
Task Common methods / strengths Cautions
Clustering k-means (fast spherical groups); GMM (soft probabilistic); DBSCAN/HDBSCAN (arbitrary density clusters, noise); spectral (nonconvex geometry). Feature scaling, cluster stability, density heterogeneity; silhouette not equal business validity.
Dimensionality reduction PCA/SVD (variance and linear structure); UMAP/t-SNE (visual exploration); autoencoders (learned nonlinear embedding). UMAP/t-SNE distances and apparent clusters can mislead; fit embeddings on training data for prediction.
Anomaly detection Isolation forest (efficient), LOF (local density), one-class SVM, robust covariance; supervised detection if labels exist. Threshold depends on cost/prevalence; extreme class skew and unseen normal modes.
Forecasting Seasonal naïve, ETS/ARIMA/SARIMAX, pooled GBDT on lag features, deep global forecasting models. Rolling-origin evaluation, leakage from future regressors, hierarchy reconciliation, intermittent demand.
Causal inference RCT first; DAGs, backdoor adjustment, propensity weighting, doubly robust/AIPW, diff-in-diff, IV, synthetic controls, causal forests. Identification and overlap assumptions outweigh predictive accuracy; interference/hidden confounding.
Further study — unsupervised, representation, forecasting, causal methods

4 | Evaluation, calibration and reliable model selection

Scenario Use / interpretation Caveat
Balanced classification Log loss, ROC-AUC, balanced accuracy, F1, precision/recall as needed. AUC is threshold-free but not a business utility measure.
Rare positive events PR-AUC (average precision), recall@precision, precision@k, lift, expected utility. Always report prevalence; PR-AUC shifts with prevalence.
Regression MAE (robust), RMSE (penalizes large misses), pinball loss (quantiles), R² with context. MAPE unstable near zero; report strata and residual shape.
Forecasts MASE/RMSSE, horizon-weighted losses, quantile coverage/pinball score. Avoid random split of correlated time points.
Ranking / retrieval NDCG@k, MAP, MRR, recall@k; for RAG include answer faithfulness and task success. Negative sampling and leakage may inflate retrieval results.
Probabilistic predictions Brier/log loss, reliability diagrams, ECE with cautions, interval coverage. Calibrate on disjoint data using Platt, isotonic or temperature scaling as appropriate.
  • Cross-validation: use GroupKFold when entities repeat; TimeSeriesSplit / rolling-origin for temporal processes; nested CV if reporting the unbiased performance of a tuned model. Across repeated tuning, validation data gets implicitly overfit.

  • Report uncertainty: confidence intervals via grouped/blocked bootstrap where justified; compare on identical folds; show distribution across seeds and segments, not just a best-score leaderboard.

  • Optimize hyperparameters efficiently: random search or Bayesian optimization, successive halving, early stopping, sensible search spaces; keep a compute budget and track every experiment. Never choose test-set threshold or hyperparameters.

  • Interpretation: permutation importance on held-out data, SHAP for local explanations with background/dependence caveats, partial dependence/ALE, counterfactual checks; importance ≠ causality.

  • Decision threshold: select using operating costs and calibration on validation data. Model discrimination, calibration and policy utility are different properties.

Further study — evaluation, calibration, and model selection

5 | The state of the field

  • Tabular foundation models are a real alternative to test, not a blanket replacement for boosted trees. TabPFN reported major gains on small tabular tasks; 2026 surveys describe rapid scaling and new competitors, but model versions, claimed capacity and non-commercial weights vary. Evaluate against strong tuned GBDT on your exact split and compute budget. [2,3]

  • Histogram GBDT remains a production default for many tables. Modern scikit-learn HistGradientBoosting handles missing values and categorical dtypes natively; using it can simplify preprocessing, but high-cardinality categories and constraints still require design work. [1,4]

  • Foundation models / embeddings for text, vision, speech and mixed modalities shift the workflow from handcrafted inputs to pretrained representation + task-specific adaptation, retrieval or lightweight heads. Compare frozen embeddings with fine-tuning; check distribution shift, cost, privacy and evaluation contamination.

  • LLM applications: distinguish prompt-only, RAG, fine-tuning and agentic tool use. Evaluate retrieval recall, groundedness, task correctness, abstention, security, latency and cost; use golden sets and human adjudication. Beware prompt injection, poisoned retrieval and non-deterministic responses.

  • Evaluation contamination and data leakage are elevated concerns: recent research documents pervasive preprocessing leakage and shows that some tabular-language-model benchmarks overstate generalization. Require entity- and time-aware deduplication, exact label-time audits and independently held-out corpora. [5,6]

  • Causal and decision-focused DS are increasingly consequential: uplift and heterogeneous treatment-effect estimation are for interventions, while standard supervised learning predicts outcomes under observed policy. Counterfactual validity cannot be inferred from predictive AUC.

Further study — modern developments

6 | Deployment, MLOps, risk and monitoring

Phase Operational control
Reproducibility Version code/data/labels/features/models; log seeds, environment, split definitions, parameters and provenance; model registry and approvals.
Serving Batch versus synchronous latency; resource limits; schema validation, fallbacks, predictable missing/unseen values; shadow/canary or A/B rollouts.
Monitoring Input quality; missingness; numerical/categorical drift; label-delayed outcome and calibration drift; data slice parity; latency, costs, failure rate.
Drift response Distinguish covariate shift P(X), label shift P(Y), concept shift P(Y|X); alert thresholds anchored to action, not arbitrary PSI alone.
Governance Model cards, intended use, subgroup evaluation, explainability, privacy/security controls, human oversight, retention and rollback playbook.
Feedback Track how predictions alter labels, selection/observability, incentives and future data; reserve exploration/holdouts when appropriate.
Further study — production and monitoring

7 | References

scikit-learn, categorical support in HistGradientBoosting:** https://sklearn.org/1.8/auto_examples/ensemble/plot_gradient_boosting_categorical.html

Hollmann et al., Nature 2025, TabPFN:** https://doi.org/10.1038/s41586-024-08328-6

Current generation of tabular foundation models: critical review (2026):** https://www.mdpi.com/2504-4990/8/8/244

scikit-learn, choosing the right estimator:** https://scikit-learn.org/stable/machine_learning_map.html

Gorla & Puduppully, ICML 2026, tabular language models generalization:** https://proceedings.mlr.press/v306/gorla26a.html

Understanding data leakage in real-world ML notebooks (2026):** https://www.sciencedirect.com/science/article/pii/S0950584926003253

Normal equation

Ridge Regression

Stochastic gradient descent cost function

A Unified Data Infra

AI and ML Blueprint

ML lifecycle

A Unified Data Infra

Learning Curve example

validation curve example

Reinforcement learning

Correlation formula

Selecting statistical test. Source: Statistical Rethinking 2. Free Chapter 1