ML Fundamentals

Mathematical intuition behind algorithms, hyperparameter tradeoffs, and diagnosing model behavior.

Key Takeaways

  • High bias (underfitting): both train and val errors are high → model too simple.
  • High variance (overfitting): low train error, high val error → model too complex.
  • L1 (Lasso) promotes sparsity (feature selection); L2 (Ridge) handles multicollinearity by shrinking large weights smoothly.
  • Gradient boosting builds trees sequentially (each corrects the residuals of the last). Random Forest builds trees in parallel (bagging). GBM typically outperforms RF on tabular data but is more prone to overfit.
  • Gini impurity: $1 - \sum p_i^2$; Entropy: $-\sum p_i \log_2 p_i$. Both minimize impurity at splits. Gini is faster (no log).
  • XGBoost uses second-order Taylor expansion of the loss + L1/L2 regularization on leaf weights — more principled than vanilla GBM.
  • For tabular data, gradient boosted trees (LightGBM, XGBoost) usually beat neural networks; NNs dominate on unstructured data (images, text, audio).

1. Algorithm Mechanics

Linear & Logistic Regression

Linear Regression assumptions (LINE): Linearity, Independence of errors, Normality of errors, Equal variance (Homoscedasticity).

Logistic Regression models the log-odds of the outcome:

$$\log\frac{p}{1-p} = \beta_0 + \beta_1 x_1 + \cdots + \beta_n x_n$$

A coefficient $\beta_i = 0.5$ means a 1-unit increase in $x_i$ multiplies the odds by $e^{0.5} \approx 1.65$. Logistic regression is the regulatory gold standard for credit scoring because it is fully explainable.

Tree-Based Models

Model How Trees Are Built Reduces Key Hyperparameters
Random Forest Parallel (bagging + random feature subsets) Variance n_estimators, max_features, max_depth
GBM Sequential (fit residuals) Bias learning_rate, n_estimators, max_depth
XGBoost Sequential + 2nd-order Taylor + regularization Bias + Variance Same as GBM + reg_alpha, reg_lambda, subsample

Splitting criterion: Gini Impurity = $1 - \sum_i p_i^2$. Information Gain uses Entropy = $-\sum_i p_i \log_2 p_i$. Both produce similar results in practice.

Clustering

  • K-Means: Minimizes within-cluster variance. Requires scaling. Assumes spherical clusters. Choose $k$ with elbow method (inertia) or silhouette score.
  • DBSCAN: Density-based. No need to specify $k$. Handles non-spherical clusters and identifies outliers as noise. Sensitive to eps and min_samples.

2. The Bias-Variance Tradeoff

$$\text{Expected Error} = \text{Bias}^2 + \text{Variance} + \text{Irreducible Noise}$$

Symptom Problem Fix
High train error, high val error High Bias (underfitting) More complex model, more features, less regularization
Low train error, high val error High Variance (overfitting) More data, simpler model, more regularization, dropout

3. Regularization & Optimization

L1 vs. L2

L1 (Lasso) L2 (Ridge)
Penalty $\lambda \sum |\beta_i|$ $\lambda \sum \beta_i^2$
Effect Drives weights to exactly 0 (feature selection) Shrinks weights smoothly, never to 0
Use when Many irrelevant features Correlated features (multicollinearity)

Elastic Net combines both: $\lambda_1 \sum |\beta_i| + \lambda_2 \sum \beta_i^2$.

Gradient Descent

Variant Update Uses Pros/Cons
Batch Full dataset Stable, slow for large data
Stochastic (SGD) 1 sample Fast, noisy — can escape local minima
Mini-batch Batch of n samples Best of both; standard in deep learning

4. Neural Networks

Neural networks are function approximators composed of layers of learnable linear transformations followed by non-linear activations. They excel when feature interactions are complex and unstructured data (images, text, audio) is involved.

Architecture Fundamentals

  • Neuron: computes $z = \mathbf{w}^T\mathbf{x} + b$, then applies activation $a = f(z)$
  • Layer: a set of neurons applied in parallel to the same input
  • Depth (layers) vs. Width (neurons per layer): depth captures hierarchical features; width captures breadth at each level
  • Universal approximation theorem: a single hidden layer with enough neurons can approximate any continuous function — but depth is more parameter-efficient for complex functions

Activation Functions

Activation Formula Use Case Problem
ReLU $\max(0, z)$ Default for hidden layers Dying ReLU (neurons output 0 permanently)
Leaky ReLU $\max(0.01z, z)$ When dying ReLU is a concern Hyperparameter (slope)
Sigmoid $\frac{1}{1+e^{-z}}$ Binary output layer Vanishing gradient for deep networks
Softmax $\frac{e^{z_i}}{\sum_j e^{z_j}}$ Multi-class output layer Sensitive to large logits
Tanh $\frac{e^z - e^{-z}}{e^z + e^{-z}}$ RNNs, some hidden layers Vanishing gradient

Backpropagation

Backpropagation is the chain rule of calculus applied to compute gradients of the loss with respect to every weight. Forward pass: compute predictions and loss. Backward pass: propagate gradients layer by layer from output to input.

$$\frac{\partial L}{\partial \mathbf{w}^{(l)}} = \frac{\partial L}{\partial \mathbf{a}^{(l)}} \cdot \frac{\partial \mathbf{a}^{(l)}}{\partial z^{(l)}} \cdot \frac{\partial z^{(l)}}{\partial \mathbf{w}^{(l)}}$$

Vanishing gradients: early layers receive near-zero gradients when sigmoid/tanh is used in deep networks. Solutions: ReLU activations, batch normalization, residual connections (skip connections in ResNets).

Key Regularization Techniques

  • Dropout: randomly zero out neurons during training with probability $p$. Forces the network to learn redundant representations. At inference, scale weights by $(1-p)$.
  • Batch Normalization: normalize activations within each mini-batch; reduces internal covariate shift; allows higher learning rates; acts as mild regularizer.
  • Weight Decay (L2): add $\lambda \|\mathbf{w}\|^2$ to loss; equivalent to L2 regularization on weights.
  • Early stopping: stop training when validation loss stops improving; simple and effective.

Weight Initialization

  • Xavier/Glorot: $W \sim \mathcal{U}\!\left(-\sqrt{\frac{6}{n_{in}+n_{out}}}, \sqrt{\frac{6}{n_{in}+n_{out}}}\right)$ — for sigmoid/tanh activations
  • He initialization: $W \sim \mathcal{N}\!\left(0, \sqrt{\frac{2}{n_{in}}}\right)$ — for ReLU activations (default in PyTorch)

Neural Networks vs. Gradient Boosted Trees

Neural Networks GBTs (XGBoost/LightGBM)
Tabular data Often underperforms GBTs without careful tuning Usually wins; handles heterogeneous features natively
Unstructured data Dominant (images, text, audio) Not applicable
Training data needed Typically 10K+ Effective with hundreds of rows
Hyperparameter sensitivity High (architecture, lr, batch size, init) Moderate (n_estimators, max_depth, lr)
Training time Slow for large networks Fast (parallelized on CPU)
Interpretability Low (SHAP applicable) Moderate (feature importance, SHAP)
import torch
import torch.nn as nn

class FeedForwardNet(nn.Module):
    def __init__(self, input_dim, hidden_dims, output_dim, dropout=0.3):
        super().__init__()
        layers = []
        prev_dim = input_dim
        for h in hidden_dims:
            layers += [nn.Linear(prev_dim, h), nn.BatchNorm1d(h), nn.ReLU(), nn.Dropout(dropout)]
            prev_dim = h
        layers.append(nn.Linear(prev_dim, output_dim))
        self.net = nn.Sequential(*layers)

    def forward(self, x):
        return self.net(x)

model = FeedForwardNet(input_dim=20, hidden_dims=[128, 64], output_dim=1)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-4)
criterion = nn.BCEWithLogitsLoss()

5. Advanced Boosting: LightGBM, CatBoost, and Stacking

LightGBM

LightGBM grows trees leaf-wise (best-first) rather than level-wise, achieving lower loss with fewer leaves. Key optimizations: Gradient-based One-Side Sampling (GOSS) ignores small-gradient instances; Exclusive Feature Bundling (EFB) merges mutually exclusive features. Result: typically 5–10× faster than XGBoost with comparable or better accuracy.

import lightgbm as lgb

model = lgb.LGBMClassifier(
    n_estimators=1000,
    learning_rate=0.05,
    num_leaves=63,          # 2^max_depth - 1; key LightGBM parameter
    min_child_samples=20,   # regularization: min samples per leaf
    subsample=0.8,
    colsample_bytree=0.8,
    reg_alpha=0.1,          # L1
    reg_lambda=0.1,         # L2
    early_stopping_rounds=50
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], callbacks=[lgb.log_evaluation(100)])

CatBoost

Handles categorical features natively using ordered target encoding — avoids target leakage by encoding each sample using only prior samples in the permuted order. Also uses symmetric trees for fast inference. Best choice when the dataset has many high-cardinality categorical features.

from catboost import CatBoostClassifier

cat_features = ['city', 'product_category', 'customer_segment']  # pass indices or names
model = CatBoostClassifier(
    iterations=1000,
    learning_rate=0.05,
    depth=6,
    cat_features=cat_features,   # no manual encoding required
    eval_metric='AUC',
    early_stopping_rounds=50,
    verbose=100
)
model.fit(X_train, y_train, eval_set=(X_val, y_val))

XGBoost vs. LightGBM vs. CatBoost

XGBoost LightGBM CatBoost
Tree growth Level-wise Leaf-wise Symmetric (oblivious trees)
Speed Baseline Fastest on large data Fastest inference
Categorical features Manual encoding required Manual or built-in (limited) Native, best handling
Regularization alpha, lambda, gamma num_leaves, min_child_samples depth, l2_leaf_reg
Best for General-purpose; well-documented Large datasets, memory-constrained High-cardinality categoricals

Model Stacking

Stacking (stacked generalization) trains a meta-learner on the out-of-fold predictions of base models. Base models see the training data; the meta-learner sees only base model predictions. Reduces variance and captures complementary model strengths.

from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
import lightgbm as lgb

base_models = [
    ('rf', RandomForestClassifier(n_estimators=200, random_state=42)),
    ('lgbm', lgb.LGBMClassifier(n_estimators=300, random_state=42)),
]

stack = StackingClassifier(
    estimators=base_models,
    final_estimator=LogisticRegression(),  # meta-learner: simple, regularized
    cv=5,                                   # k-fold for OOF predictions
    passthrough=False                        # meta-learner sees only base preds
)
stack.fit(X_train, y_train)

Key rule: the meta-learner should be simpler than the base models (logistic regression or ridge) to avoid overfitting on the OOF predictions. Stacking helps most when base models are diverse (different algorithms, different feature subsets).

Practice Questions

Q1: A model has 99% training accuracy and 72% validation accuracy. What is the problem and what are three ways to fix it?

Problem: High variance (overfitting). The model has memorized the training data and does not generalize.

Fixes: (1) More training data; (2) Reduce model complexity — fewer trees, shallower depth, fewer features; (3) Increase regularization — higher L2 penalty, min_child_weight, subsample < 1 in XGBoost; (4) Feature selection to remove noise features.

Q2: When would you choose L1 over L2 regularization?

Choose L1 when you suspect many features are irrelevant and want a sparse model (feature selection built in — many weights become exactly 0). Choose L2 when features are correlated and you want to retain all of them but reduce their magnitude. Use Elastic Net when you are unsure or have both problems.

Q3: You train XGBoost with 500 trees, max_depth=8, learning_rate=0.3 and see overfitting. What hyperparameters do you change?
  1. Reduce learning_rate to 0.05 and increase n_estimators proportionally (lower LR + more trees).
  2. Reduce max_depth to 3–6.
  3. Add L2 regularization: reg_lambda=1.0.
  4. Increase min_child_weight to require more samples per leaf.
  5. Add subsampling: subsample=0.8, colsample_bytree=0.8.
Q4: How does Random Forest reduce variance? What assumption does bagging rely on?

RF trains many decision trees on bootstrap samples (random sampling with replacement) with a random subset of features at each split. Averaging the predictions of many uncorrelated trees reduces variance without increasing bias. The key assumption is that the trees are somewhat independent — achieved by random feature selection, which de-correlates the trees even when they are trained on similar data.

Explain backpropagation in plain language. What problem does vanishing gradient cause?

Backpropagation applies the chain rule to compute how much each weight contributed to the prediction error. In a forward pass, inputs flow through the network to produce a prediction and loss. In the backward pass, the gradient of the loss is propagated from the output layer backward, layer by layer, using the chain rule: each layer's gradient is the product of the gradient from the layer above and the local derivative. Vanishing gradient occurs when these local derivatives are very small (sigmoid and tanh saturate near 0 gradient at their extremes). Multiplying many small numbers produces an exponentially small gradient in early layers — those layers barely learn. Solutions: use ReLU activations (gradient is 1 for positive inputs), add batch normalization (normalizes intermediate activations), or use residual/skip connections (gradient flows directly around layers).

When would you choose LightGBM over XGBoost or a neural network?

Choose LightGBM over XGBoost when: (1) the dataset is large (>100K rows) — LightGBM's leaf-wise growth and GOSS sampling are significantly faster; (2) memory is constrained — LightGBM uses histogram-based splitting which is memory-efficient. Choose LightGBM over a neural network for tabular data in most cases — GBTs typically outperform NNs on structured tabular data without extensive tuning. The exception is when you have very high-dimensional unstructured features (text, images), many missing values following non-trivial patterns, or when the relationship between features is extremely complex and hierarchical. In practice, start with LightGBM as the baseline for tabular ML tasks and only reach for NNs when GBTs plateau.

Action Items

  • Write out the cost functions for Linear Regression (MSE) and Logistic Regression (Log Loss/Cross-Entropy).
  • Contrast how Random Forest and Gradient Boosting handle outliers differently.
  • Review the impact of increasing L1 vs. L2 penalty on the magnitude and sparsity of coefficients.
  • Explain the XGBoost objective function (loss + regularization on leaf weights) in plain English.