Machine
Learning
The foundational reference for classical machine learning — algorithms, evaluation metrics, model workflow, and the statistics and mathematics powering it all. From linear regression to eigenvalues, covered precisely.
Linear Regression
Linear regression models the relationship between a dependent variable y and one or more independent variables X by fitting a hyperplane that minimizes prediction error. It's the bedrock of supervised regression and the conceptual foundation for many advanced methods including neural networks.
Predicts a continuous output by learning the best-fit hyperplane through training data. "Best fit" is defined as minimizing the sum of squared residuals. The result is a weight vector — one coefficient per feature plus a bias term. Closed-form solution: β = (XᵀX)⁻¹Xᵀy.
- Ridge (L2): Adds λ·Σβ² penalty — shrinks all coefficients, none to exactly zero. Preferred when all features contribute.
- Lasso (L1): Adds λ·Σ|β| penalty — drives some to exactly zero. Built-in feature selection for sparse problems.
- ElasticNet: α·(L1) + (1−α)·(L2). Best for correlated features with sparsity.
- Choosing λ: Cross-validate. RidgeCV and LassoCV do this automatically.
- MSE: Mean Squared Error — penalizes large errors heavily. Scale-dependent.
- RMSE: √MSE — same units as target. Most interpretable.
- MAE: Mean Absolute Error — more robust to outliers than MSE.
- R²: Proportion of variance explained (0–1; 1 = perfect). Never use alone.
- Adj. R²: R² penalized for number of features. Use for model comparison.
Logistic Regression
Despite the name, logistic regression is a classification algorithm. It passes the linear combination of inputs through a sigmoid function to output a probability between 0 and 1. The decision boundary is a hyperplane, making it a linear classifier. Outputs are calibrated probabilities — unlike most other classifiers.
Two classes: output probability ≥ 0.5 → Class 1. Threshold is tunable — lower for higher recall (catching more positives), raise for higher precision. Coefficients as log-odds: exp(βᵢ) = odds ratio for feature i.
- One-vs-Rest (OvR): Train k binary classifiers, pick class with highest probability
- Softmax Regression: Generalizes using softmax activation — outputs sum to 1 across all k classes.
multi_class='multinomial' - Regularization: C parameter in sklearn = 1/λ. Smaller C = stronger regularization.
Decision Trees
Decision trees recursively partition the feature space. At each node, the best feature and threshold are chosen to maximally reduce impurity. The result is a flowchart — highly interpretable but prone to overfitting on deep, unconstrained trees. They are the base learner for Random Forests and Gradient Boosting.
G = 1 − Σ pᵢ². Measures misclassification probability. Ranges 0 (pure) to 0.5 (max impure binary). Default criterion in sklearn. Computationally cheaper than entropy.
H = −Σ pᵢ log₂(pᵢ). Information Gain = parent H − weighted child H. Splits that create pure children maximize gain. Equivalent to maximizing mutual information between feature and label.
Pre-pruning: max_depth, min_samples_split, min_samples_leaf — set before training. Post-pruning: cost-complexity pruning (ccp_alpha in sklearn) — remove branches that don't improve generalization.
max_depth or min_samples_leaf. Use CV to find optimal depth. The real value of trees is as interpretable baselines and building blocks for ensembles.Random Forests
Random Forests aggregate many decision trees trained on random data and feature subsets. By averaging diverse trees, they dramatically reduce variance while maintaining low bias. One of the most reliable off-the-shelf algorithms — high performance, robust to outliers, and provides feature importance out of the box.
- Bootstrap sampling: Each tree trains on a random sample with replacement (~63% unique samples)
- Feature randomness: At each split, only √p features (classification) or p/3 (regression) considered — forces diversity
- Aggregation: Classification → majority vote; Regression → mean prediction
- Out-of-bag (OOB): The ~37% unused samples form a free validation set.
oob_score=True
- MDI importance: Mean decrease in impurity across all trees. Fast but biased toward high-cardinality features.
- Permutation importance: Shuffle each feature, measure score drop. Slower but more reliable — use on val set.
- SHAP values: Tree-SHAP is exact and fast — gold standard for attribution.
- Key hyperparameters: n_estimators (≥100), max_features, max_depth, min_samples_leaf
K-Nearest Neighbors
KNN makes predictions by finding the k most similar training examples (by distance) and aggregating their labels. It's a lazy learner — no training step, no parameters to learn. All computation happens at prediction time. Simple, interpretable, and surprisingly effective on low-dimensional data with meaningful distance metrics.
- Classification: Majority vote of k nearest neighbors
- Regression: Mean (or weighted mean) of k nearest neighbor values
- Distance metric: Euclidean by default. Manhattan for high-dim; Cosine for text/sparse
- Weighting:
weights='distance'gives closer neighbors more influence — usually better
- Small k = low bias, high variance (can overfit)
- Large k = high bias, low variance (can underfit, ignores local structure)
- Rule of thumb: k = √n, then tune with CV
- Always use odd k for binary classification (avoids ties)
- Curse of dimensionality: Distance becomes meaningless in high-dim space. Use PCA or feature selection first.
StandardScaler or MinMaxScaler before KNN. Prediction complexity O(n·p) per query — slow for large datasets; use algorithm='ball_tree' or 'kd_tree' for speedup.Support Vector Machines
SVMs find the hyperplane that maximizes the margin between classes. Only the training points closest to the boundary — support vectors — determine the hyperplane. This makes SVMs robust to outliers far from the boundary. The kernel trick maps data to higher-dimensional spaces implicitly, enabling non-linear classification without computing the transformation.
- Maps data to higher-dimensional space implicitly — never computes the transformation
- Linear: Use for high-dim/text data where classes are linearly separable
- RBF (Gaussian): Default — works for most non-linear problems. Tune C and γ
- Polynomial: For polynomial feature interactions
- C (regularization): Low C = wide margin (may misclassify); High C = narrow margin (may overfit)
- γ (RBF bandwidth): High γ = tight fit (overfit); Low γ = smooth boundary (underfit)
- Search C in [0.001, 0.01, 0.1, 1, 10, 100]; γ in [0.001, 0.01, 0.1, 1]
- Use
GridSearchCVor Bayesian optimization
| Kernel | Formula | Use When |
|---|---|---|
| Linear | K(x,z) = xᵀz | High-dim, text/NLP, linearly separable |
| RBF / Gaussian | K(x,z) = exp(−γ‖x−z‖²) | General non-linear; most common default |
| Polynomial | K(x,z) = (γxᵀz + r)ᵈ | Known polynomial feature relationships |
| Sigmoid | K(x,z) = tanh(γxᵀz + r) | Rarely used; neural-net analogies |
Clustering — K-Means
K-Means partitions data into k clusters by iteratively assigning points to the nearest centroid and recomputing centroids as cluster means. It's unsupervised — no labels needed. Convergence is guaranteed but may find a local minimum. Always run multiple initializations (n_init=10+) and use k-means++ initialization.
- Elbow method: Plot inertia vs k — pick the "elbow" where adding clusters yields diminishing returns
- Silhouette score: How similar a point is to its own cluster vs neighboring clusters. Range −1 to 1; maximize this.
- Gap statistic: Compares inertia to a null reference distribution — statistically principled
- Domain knowledge: Often the best guide for k
- Assumes spherical, equal-sized clusters — fails on elongated or ring shapes
- Sensitive to outliers — consider removing before clustering
- Must specify k in advance
- DBSCAN: Density-based, arbitrary shapes, finds outliers automatically
- Gaussian Mixture Models: Soft probabilistic cluster assignments
- Hierarchical: No k needed; produces a dendrogram
Accuracy
Accuracy measures the fraction of predictions the model got right. It's the most intuitive metric but can be deeply misleading on imbalanced datasets. A model that always predicts "Not Fraud" on 99% non-fraud data achieves 99% accuracy while being completely useless.
Precision / Recall
Precision and Recall measure complementary aspects of a classifier and exist in a fundamental tradeoff. Adjusting the decision threshold moves you along the precision-recall curve. The business cost of FP vs FN determines which you prioritize.
- False alarms are expensive (irrelevant ads, spam blocking)
- Each positive action triggers significant cost
- Users trust is fragile (wrong email is never sent)
- Missing a positive is dangerous (disease, fraud, intrusion)
- Cost of false negative >> cost of false positive
- You can tolerate more false alarms to catch everything real
F1 Score
The F1 score is the harmonic mean of Precision and Recall. It rewards models that are good at both — penalizing heavily when either is low. It's the go-to metric for imbalanced classification when you want a single number.
Fβ weights recall β times more than precision. β=1 (standard F1), β=2 (recall matters more), β=0.5 (precision matters more). Use Fβ when the Precision-Recall tradeoff is asymmetric in business value.
- Macro: Average F1 per class — treats each class equally. Use when all classes matter equally.
- Weighted: Average weighted by class frequency. Use for imbalanced multi-class.
- Micro: Global TP/FP/FN across all classes. Equivalent to accuracy on balanced data.
f1_score(y, ŷ, average='weighted')
Confusion Matrix
The confusion matrix shows the complete breakdown of correct and incorrect predictions by class. It's the foundation for all classification metrics — precision, recall, F1, and specificity all derive from its four cells. Always examine the confusion matrix before reporting a single aggregate metric.
| Actual \ Predicted | Predicted Positive | Predicted Negative |
|---|---|---|
| Actual Positive | TP — True Positive ✓ | FN — False Negative ✗ |
| Actual Negative | FP — False Positive ✗ | TN — True Negative ✓ |
- Sensitivity/Recall: TP / (TP+FN) — "How many positives did we catch?"
- Specificity: TN / (TN+FP) — "How many negatives did we correctly reject?"
- FPR (Fall-out): FP / (FP+TN) — used for ROC curve x-axis
- MCC: Matthews Correlation Coefficient — robust for imbalanced classes. Range [−1, 1]; 1 = perfect.
- Diagonal cells = correct predictions — want high values
- Off-diagonal = misclassifications — inspect which classes confuse the model
- Row = actual class; Column = predicted class
- Normalize by row (
normalize='true') to see per-class recall rates regardless of class size
ROC-AUC
The ROC curve plots True Positive Rate vs False Positive Rate across all decision thresholds. The Area Under the Curve (AUC) summarizes this into a single number representing the probability that the model ranks a random positive example higher than a random negative one. It's threshold-independent — a measure of ranking quality, not absolute prediction.
- Binary classification with probabilistic output
- Comparing classifiers independent of threshold choice
- Dataset is balanced (or weights compensate)
- You care about ranking quality, not absolute predictions
- On severely imbalanced data, ROC-AUC can be optimistically misleading
- Precision-Recall AUC (Average Precision) is more informative when positives are rare
- PR curve: Precision (y) vs Recall (x) — area measures how well model ranks relevant items
average_precision_scorein sklearn
Training Pipeline
A production ML pipeline chains data preprocessing and modeling into a single estimator. This prevents data leakage, enables proper cross-validation, and makes deployment a single object — not a sequence of manual steps. Always use Pipelines in production code.
Validation Strategy
Validation is how you measure generalization. The test set must remain unseen until final evaluation — it's your one honest estimate. The validation (dev) set is used for model selection and hyperparameter tuning. Getting these boundaries wrong is the root cause of most "good in dev, bad in production" failures.
- High bias (underfitting): Model too simple — both train and val error are high. Fix: more features, more complex model, less regularization.
- High variance (overfitting): Train error low, val error high. Fix: more data, regularization, simpler model, dropout.
- Target: Low val error and small train/val gap. The Goldilocks zone.
- Total Error = Bias² + Variance + Irreducible Noise
- Temporal leakage: Future information in training data (e.g., next-day price predicting today)
- Target leakage: Features that are proxies for the target computed using test-set information
- Preprocessing leakage: Fitting StandardScaler on all data before splitting — test statistics bleed into training
- Fix: Always fit transformers on train set only. Use sklearn Pipelines inside cross-validation.
Hyperparameter Tuning
Hyperparameters control model structure and training — they're set before fitting, not learned from data. Tuning finds the combination that maximizes cross-validated score. The method you choose depends on the search space size and compute budget.
Tries all combinations in a defined grid. Guarantees finding the best within the grid. Exponentially expensive — only practical with 2-3 hyperparameters and narrow ranges. Use GridSearchCV.
Samples randomly from distributions over each hyperparameter. Often finds near-optimal configurations 5-10× faster than grid search. The standard approach for medium search spaces. Use RandomizedSearchCV with scipy distributions.
Builds a probabilistic surrogate model of the objective function and uses it to select the next most promising configuration. Significantly fewer evaluations needed. Use Optuna or scikit-optimize. Best for expensive-to-evaluate models.
Cross-Validation
Cross-validation provides a more reliable estimate of generalization than a single train/val split by rotating which data is used for validation. Every sample is validated exactly once. The result — mean ± standard deviation across folds — quantifies both performance and stability.
- k-Fold: k equal folds, rotate validation. k=5 or k=10 standard. General purpose.
- Stratified k-Fold: Preserves class proportions in each fold. Always use for classification.
- LOO: k=n. Lowest bias, highest variance, very slow. Only for tiny datasets.
- Time-Series CV: Train on past, validate on future. Never shuffle. Use
TimeSeriesSplit. - Group k-Fold: Ensures same patient/user/entity is not in both train and val — prevents leakage.
- Mean score: Expected performance on unseen data
- Std deviation: Model stability. High std = unstable; consider more data or simpler model
- Report: "F1 = 0.87 ± 0.03 (5-fold stratified CV)" — complete, honest result
- Nested CV: Outer loop evaluates generalization; inner loop selects hyperparameters — the only unbiased approach for combined selection + evaluation
- Final model: After CV, retrain on ALL training data. Evaluate once on held-out test set.
Statistics in Machine Learning
Machine learning is applied statistics at scale. Before you can understand why a model works — or why it fails — you need fluency in descriptive statistics, probability distributions, hypothesis testing, and Bayesian thinking. These aren't optional extras; they're the formal language of ML.
//Descriptive Statistics
Descriptive statistics summarize and describe a dataset's properties. Every EDA (Exploratory Data Analysis) begins here — before you feed data to any model, you must understand its shape, center, spread, and outliers.
//Probability Distributions
Distributions describe how data is generated. Knowing which distribution governs your data tells you which loss functions are appropriate, what assumptions a model is making, and how to interpret its outputs. Most ML algorithms implicitly assume a distribution — make that assumption explicit.
//Hypothesis Testing
Hypothesis testing is how you decide if a pattern in data is real or just noise. In ML: used for feature selection, A/B testing model changes, and statistical model comparison. The framework: formulate a null hypothesis H₀ (no effect), collect evidence, compute how surprised you would be under H₀.
- H₀ (null hypothesis): No effect, no difference — the default assumption
- H₁ (alternative): The effect you're trying to detect
- p-value: P(data this extreme | H₀ is true). Low p → evidence against H₀
- α (significance level): Threshold for "surprising enough" — typically 0.05. If p < α, reject H₀.
- Type I error (α): Rejecting H₀ when it's true (false positive)
- Type II error (β): Failing to reject H₀ when it's false (false negative)
- Power (1−β): Probability of detecting a real effect when it exists
- t-test: Compare means of two groups (e.g., A/B test on model accuracy). Assumes normality — robust for n>30 by CLT.
- Chi-squared (χ²): Independence of categorical features and target. Feature selection for text/categorical data.
- ANOVA / F-test: Compare means across 3+ groups. Used in sklearn's SelectKBest for regression features.
- Wilcoxon signed-rank: Non-parametric paired test. Better than t-test for CV score comparison.
- Kolmogorov-Smirnov: Test if two samples follow the same distribution. Data drift detection.
- McNemar's test: Compare two classifiers on the same test set — accounts for correlated errors.
//Bayesian Statistics & Correlation
- Prior P(H): Your belief before seeing data
- Likelihood P(D|H): How probable is this data given hypothesis H?
- Posterior P(H|D): Updated belief after seeing data
- MLE: Maximizes likelihood — ignores prior. Equivalent to Ridge/Lasso (MAP with Gaussian/Laplace prior)
- Naive Bayes: Assumes feature independence given class. Despite being "naive," highly effective for text.
- Covariance: Cov(X,Y) = E[(X−μₓ)(Y−μᵧ)]. Scale-dependent — hard to interpret directly.
- Pearson r: r = Cov(X,Y)/(σₓ·σᵧ). Range [−1,1]. Measures linear association. Sensitive to outliers.
- Spearman ρ: Rank correlation. Robust to outliers and non-linear monotone relationships.
- Point-Biserial: Correlation between a binary and continuous variable.
- Multicollinearity: High correlation between features (|r| > 0.9). Makes coefficients unstable in linear models. Detect via VIF (Variance Inflation Factor).
- Correlation ≠ Causation. Always.
//Central Limit Theorem & Confidence Intervals
- 95% CI: x̄ ± 1.96 · (σ/√n). Interpretation: if you repeated this experiment 100 times, 95 of the CIs would contain the true μ.
- Margin of error: Narrows with √n — double sample size, halve the CI width
- Standard Error: SE = σ/√n — std dev of the sampling distribution
- Bootstrap CI: Model-free. Resample with replacement 1000× and take percentiles. No distributional assumptions needed.
- CV uncertainty: Report mean ± 1.96·(std/√k) for a k-fold CI on model performance
- A/B test sample size: n = 2·(z_α/2 + z_β)² · p(1−p) / δ² where δ = minimum detectable effect
- Bootstrap importance: Bootstrap permutation importance distributions for feature significance
- Calibration: Well-calibrated model: 70% confidence predictions are correct 70% of the time
Mathematics in Machine Learning
Every ML algorithm is mathematics in disguise. Linear regression is matrix least squares. Neural networks are composed functions differentiated via the chain rule. PCA is eigendecomposition. Understanding the math tells you when an algorithm will fail, how to debug it, and how to adapt it for new problems.
//Linear Algebra
Linear algebra is the language of data. Features are vectors, datasets are matrices, transformations are matrix multiplications. Intuition about matrix operations is the single most important mathematical skill for ML practitioners.
- Vector: An ordered list of numbers — one data point in n-dimensional space. Notation: x ∈ ℝⁿ
- Dot product: x·y = Σxᵢyᵢ = ‖x‖‖y‖cos(θ). Measures similarity — the core operation of attention and KNN.
- Norms: L2: ‖x‖₂ = √(Σxᵢ²) — Euclidean length. L1: ‖x‖₁ = Σ|xᵢ| — Manhattan. L∞: max|xᵢ|
- Matrix multiply: (AB)ᵢⱼ = Σₖ Aᵢₖ Bₖⱼ. Only valid when inner dims match: (m×k)(k×n) → (m×n)
- Transpose: (Aᵀ)ᵢⱼ = Aⱼᵢ. Flips matrix. (AB)ᵀ = BᵀAᵀ.
- Inverse: A⁻¹A = I. Exists only for square, full-rank matrices. Used in OLS: β = (XᵀX)⁻¹Xᵀy
- Eigenvalue equation: Av = λv. Eigenvector v is unchanged in direction by A; scaled by λ.
- Covariance matrix: Σ = (1/n)XᵀX. Symmetric → always real eigenvalues, orthogonal eigenvectors.
- PCA: Eigenvectors of Σ are principal components (directions of max variance). Eigenvalues = variance explained.
- SVD: X = UΣVᵀ. U = left singular vectors, Σ = singular values, V = right singular vectors. Works on any matrix.
- Low-rank approximation: Keep top k singular values — compresses X while preserving most variance. Foundation for collaborative filtering, LSA, and matrix factorization.
//Calculus — Gradients & Chain Rule
Calculus powers model training. The gradient is the multi-dimensional derivative — it points uphill in parameter space. Minimizing a loss function means following the negative gradient. Backpropagation is the chain rule applied recursively through a computational graph.
- MSE Loss: ∂J/∂θ = (2/m)Xᵀ(Xθ − y) — linear in θ, one global minimum
- BCE Loss: ∂L/∂z = ŷ − y for logistic regression — gradient of log-loss w.r.t. linear output
- ReLU: ∂/∂x = 1 if x>0, else 0 — vanishes for negative inputs (dying ReLU)
- Sigmoid: dσ/dz = σ(z)(1−σ(z)) — self-referential, elegant, but saturates near 0 and 1
- Softmax: ∂S/∂zᵢ = Sᵢ(δᵢⱼ − Sⱼ) — used with cross-entropy in multi-class output
- Hessian H: Matrix of second partial derivatives. H_{ij} = ∂²J/∂θᵢ∂θⱼ
- Positive definite H: Local minimum (all eigenvalues > 0)
- Saddle point: Some eigenvalues positive, some negative — gradient = 0 but not a minimum. Common in deep networks.
- Newton's method: θ ← θ − H⁻¹∇J. Quadratic convergence but O(n³) per step — impractical for large models.
- L-BFGS: Approximate Hessian inverse. Used in LogisticRegression(solver='lbfgs').
//Gradient Descent Variants
Gradient descent is the core optimization algorithm for nearly every ML model. The variants differ in how much data they use per update and how they adapt the learning rate — each makes a different bias-variance-compute tradeoff.
| Variant | Update Rule | Pros | Cons |
|---|---|---|---|
| Batch GD | θ ← θ − α·(1/m)Xᵀ(Xθ−y) | Stable, exact gradient, convex → global min | O(m) per step — slow for large datasets |
| Stochastic GD (SGD) | θ ← θ − α·∇J(θ; xᵢ, yᵢ) for single sample | Very fast updates, escapes saddle points | Noisy — never fully converges; needs LR schedule |
| Mini-Batch GD | θ ← θ − α·∇J(θ; batch of m_b samples) | GPU parallelism, stable, best of both worlds | Requires batch size tuning (typically 32–512) |
| Momentum | v ← βv + α∇J; θ ← θ − v | Faster convergence, damps oscillations | Extra hyperparameter β (typically 0.9) |
| Adam | Adaptive per-parameter learning rates (m, v estimates) | Robust default — works well across tasks | May not generalize as well as SGD with LR schedule for large models |
//Information Theory
Information theory quantifies uncertainty, surprise, and information content. It connects directly to loss functions — cross-entropy loss, entropy-based splitting in decision trees, and KL divergence in variational autoencoders and KD. These concepts are not academic curiosities; they appear in the definition of most ML objectives.
- Measures how different Q is from P. Not symmetric: KL(P‖Q) ≠ KL(Q‖P)
- Always ≥ 0 (Gibbs' inequality); = 0 iff P = Q
- Used in: VAE regularization term (KL between posterior and prior), knowledge distillation, policy gradients (PPO, TRPO)
- Forward KL (P‖Q): mean-seeking — Q spreads to cover all of P
- Reverse KL (Q‖P): mode-seeking — Q collapses to a mode of P
- How much knowing Y reduces uncertainty about X. Always ≥ 0.
- Used in: feature selection (mutual_info_classif), causal discovery, representation learning
- Information Gain (decision trees) = I(Feature; Class label) at each split
- MINE estimator: Neural estimator for high-dimensional MI — used in contrastive learning
//Distance Metrics
Distance and similarity functions determine what "close" means for KNN, K-Means, SVMs, and embedding search. Choosing the right metric for your data type is as important as choosing the right algorithm — use the wrong metric and the model learns nothing meaningful.
| Metric | Formula | Best Used For | Notes |
|---|---|---|---|
| Euclidean | √Σ(xᵢ−yᵢ)² |
Low-dim continuous features; KNN, K-Means | Scale-sensitive — standardize features first. Suffers in high dimensions. |
| Manhattan (L1) | Σ|xᵢ−yᵢ| |
Grid-like spaces; sparse data; robust to outliers | Less affected by extreme values than L2. LASSO regularization uses L1 norm. |
| Cosine Similarity | x·y / (‖x‖‖y‖) |
Text, document embeddings, high-dim sparse vectors | Ignores magnitude — only direction matters. Range [−1, 1]. 1 = identical direction. |
| Minkowski (Lₚ) | (Σ|xᵢ−yᵢ|ᵖ)^(1/p) |
Generalization: p=1 is Manhattan, p=2 is Euclidean | p is a hyperparameter. Used in KNN as metric_params={'p': p}. |
| Mahalanobis | √((x−y)ᵀ Σ⁻¹ (x−y)) |
Correlated features; anomaly detection; accounts for feature scale and correlation | Equivalent to Euclidean after whitening transform. Requires invertible covariance matrix. |
| Hamming | Fraction of positions that differ |
Binary/categorical vectors; string comparison | Used for binary feature vectors, error detection, NLP tokenizer comparison. |
//Regularization as Math
Regularization prevents overfitting by adding a penalty term to the loss function. Understanding the math behind it reveals why L1 induces sparsity and L2 shrinks but doesn't zero out — and connects to Bayesian priors.