1. The Core Problem: Why Smooth Kernels Struggle on Tabular Reality #
In Part 5, we built Kernel Support Vector Machines—convex geometric classifiers capable of carving smooth non-linear boundaries inside infinite-dimensional Hilbert spaces. Yet as noted at the end of Part 5, real-world tabular datasets (financial ledgers, clinical diagnostics, multi-sensor telemetry, industrial logs) expose two structural weaknesses in distance-based and linear models:
- Heterogeneous, Unaligned Scales & Uninformative Columns: A typical tabular table mixes skewed currency amounts spanning $[0, 10^7]$, binary status flags, missing values, and dozens of irrelevant noise columns. Euclidean kernels like RBF treat all coordinate directions isotropically—meaning uninformative or badly scaled features directly distort pairwise distances $\Vert{}x_i - x_j\Vert{}_2^2$.
- Irregular, Non-Smooth Target Functions: Tabular relationships rarely behave like smooth trigonometric waves. They exhibit sharp step discontinuities and axis-aligned thresholds (for instance, risk jumping abruptly once voltage exceeds $3.6\,\text{V}$ and temperature crosses $65^\circ\text{C}$).
Even in the era of deep neural networks, systematic benchmarks such as Grinsztajn, Oyallon, and Varoquaux (2022) confirmed that tree-based ensembles still consistently outperform standard deep learning architectures on medium-sized tabular datasets. Understanding why requires moving from a single axis-aligned Decision Tree to the two pillars of Ensemble Learning: reducing variance in parallel (Bagging & Random Forests) and reducing bias sequentially (AdaBoost, Gradient Boosting, and XGBoost).
2. Conceptual Intuition: Twenty Questions, Independent Juries, and Sequential Specialists #
Twenty Questions (Decision Trees) #
Instead of projecting data through dot products or smooth kernels, a Decision Tree plays a game of Twenty Questions. At every step, it asks the single sharpest yes/no threshold question along one raw feature—“Is feature $x_j \le s$?"—chopping the feature space into axis-aligned hyper-rectangles until each box contains mostly a single class or tight numerical range. Because splits depend only on rank ordering along individual coordinates, multiplying a column by $10{,}000$ or applying any monotonic transform leaves the tree completely unchanged.
Independent Juries (Bagging & Random Forests) #
A single deeply grown tree is hypersensitive: altering a handful of training rows can change the very first root split, cascading into an entirely different tree structure (high variance). To tame that instability, imagine replacing one eccentric judge with a committee of 100 independent judges, each shown a slightly different bootstrapped dossier and forced to examine different subsets of evidence. Individual quirks cancel out when their votes are averaged.
Sequential Specialists (Boosting) #
Bagging builds diverse experts in parallel. Boosting builds a relay team of simple specialists in sequence:
- Specialist #1 makes a rough, low-capacity prediction—capturing only the broadest pattern.
- Specialist #2 ignores the original problem and focuses exclusively on fixing the mistakes left behind by Specialist #1.
- Specialist #3 corrects the remaining residual errors of the first two combined, and so on.
Each individual tree remains intentionally weak (shallow and high-bias), yet their cumulative sum converges tightly onto complex non-linear patterns.
3. Mathematical Formulation: Anatomy of a Decision Tree (CART) #
Introduced systematically by Leo Breiman, Jerome Friedman, Richard Olshen, and Charles Stone (1984) in CART (Classification and Regression Trees) and parallelized in information-theoretic form by Ross Quinlan (1986) in ID3, a decision tree partitions input space $\mathcal{X}$ into $M$ disjoint rectangular regions $R_1, R_2, \dots, R_M$ and assigns a constant prediction $c_m$ to each leaf:
$$f(x) = \sum_{m=1}^{M} c_m \, \mathbb{I}[x \in R_m]$$Finding the globally optimal tree partition across all possible combinations of splits is NP-complete. Instead, CART uses greedy top-down recursive binary partitioning.
Splitting Criteria: Gini Impurity vs. Information Gain #
At any internal node representing region $R_m$ with $N_m = \vert{}R_m\vert{}$ samples, define the empirical proportion of class $k \in \{1, \dots, K\}$ as:
$$p_{mk} = \frac{1}{N_m} \sum_{i \in R_m} \mathbb{I}[y_i = k]$$To evaluate how “mixed” a node is, classification trees use one of two strictly concave impurity functions $I(R_m)$:
-
Gini Impurity (CART default): Measures the probability of misclassifying a randomly chosen element in $R_m$ if labeled randomly according to the node’s class distribution:
$$G(R_m) = \sum_{k=1}^{K} p_{mk}(1 - p_{mk}) = 1 - \sum_{k=1}^{K} p_{mk}^2$$ -
Shannon Entropy (ID3 / C4.5): Measures the expected information content (in bits) required to encode the class distribution inside $R_m$:
$$H(R_m) = -\sum_{k=1}^{K} p_{mk} \log_2 p_{mk}$$
For regression, impurity is simply the within-node variance around the leaf mean $\bar{y}_m$:
$$V(R_m) = \frac{1}{N_m} \sum_{i \in R_m} (y_i - \bar{y}_m)^2$$Now test every candidate feature $j \in \{1, \dots, d\}$ and threshold $s$, partitioning $R_m$ into left and right children $R_L(j, s) = \{x \in R_m : x_j \le s\}$ and $R_R(j, s) = \{x \in R_m : x_j \gt s\}$. The optimal split $(j^*, s^*)$ maximizes Impurity Reduction (called Information Gain when $I = H$):
$$(j^*, s^*) = \arg\max_{j, s} \left[ I(R_m) - \frac{\vert{}R_L\vert{}}{N_m} I(R_L) - \frac{\vert{}R_R\vert{}}{N_m} I(R_R) \right]$$Gini vs. Entropy in Practice: Both curves peak at $p = 0.5$ and vanish at pure nodes ($p \in \{0, 1\}$). Empirically, they agree on split choices over 95% of the time; Gini is slightly faster because it avoids computing logarithms at every candidate threshold, while Entropy penalizes impure minority classes marginally more strongly.
The High-Variance Pathology of Single Trees #
Because splits are strictly hierarchical and greedy, a minor sampling fluctuation that alters the root split propagates down every subsequent branch. Grown to full depth, a single decision tree achieves near-zero bias ($\text{Bias}^2 \approx 0$) by isolating individual samples, at the cost of massive Variance—making standalone trees unreliable predictors on noisy datasets.
4. Variance Reduction: Bagging & Random Forests #
Recall the Bias–Variance Decomposition from Part 4. If single deep trees already have low bias, we do not need a more complex model—we need a mechanism that slashes variance without inflating bias.
Bootstrap Aggregating (Bagging) #
Proposed by Leo Breiman (1996), Bagging draws $B$ bootstrap training sets $S^{(1)}, \dots, S^{(B)}$—each created by sampling $n$ rows with replacement from the original training set $S$—fits an unpruned tree $\hat{f}_b(x)$ to each, and averages their predictions:
$$\hat{f}_{\text{bag}}(x) = \frac{1}{B} \sum_{b=1}^{B} \hat{f}_b(x)$$(For each bootstrap sample, the probability that a given training point is never picked is $(1 - 1/n)^n \to e^{-1} \approx 36.8\%$. These excluded rows serve as built-in Out-of-Bag (OOB) validation samples at zero extra compute cost.)
The Correlation Bottleneck & The Random Forest Fix #
Why not stop at Bagging? Suppose $B$ identically distributed trees $\hat{f}_1(x), \dots, \hat{f}_B(x)$ each have variance $\sigma^2$ and positive pairwise correlation $\rho = \operatorname{Corr}(\hat{f}_b(x), \hat{f}_{b'}(x))$ for $b \neq b'$. Computing the variance of their average directly yields:
$$\operatorname{Var}\!\left( \frac{1}{B} \sum_{b=1}^{B} \hat{f}_b(x) \right) = \frac{1}{B^2} \left( \sum_{b=1}^{B} \operatorname{Var}(\hat{f}_b) + \sum_{b \neq b'} \operatorname{Cov}(\hat{f}_b, \hat{f}_{b'}) \right)$$$$\operatorname{Var}\big(\hat{f}_{\text{bag}}(x)\big) = \rho \sigma^2 + \frac{1 - \rho}{B} \sigma^2$$Inspect that formula closely:
- Increasing the number of trees $B \to \infty$ drives the second term $\frac{1-\rho}{B}\sigma^2 \to 0$.
- However, it cannot reduce the first term $\rho \sigma^2$. If one strong predictor dominates the dataset, almost every bagged tree chooses that same feature at the root—keeping $\rho$ dangerously close to $1$.
Breiman (2001) broke this correlation ceiling with Random Forests: at every single node split, the tree is restricted to searching over a fresh random subset of $m \lt d$ candidate features (typically $m = \lfloor \sqrt{d} \rfloor$ for classification and $m = \lfloor d / 3 \rfloor$ for regression).
By periodically hiding the dominant feature at candidate splits, weaker predictors gain a chance to govern upper splits—decorrelating the ensemble ($\rho \downarrow$) and dropping the asymptotic variance floor $\rho \sigma^2$ dramatically while keeping bias nearly unchanged.
5. Bias Reduction: From AdaBoost to Gradient Boosting Machines #
Random Forests attack variance by averaging deep, low-bias trees. Boosting flips the strategy completely: start with shallow, high-bias “weak learners” (often depth 1 to 6) and combine them sequentially to attack bias.
5.1 AdaBoost: Adaptive Reweighting & Exponential Loss #
Introduced by Yoav Freund and Robert Schapire (1997), AdaBoost (Adaptive Boosting) iteratively trains binary weak classifiers $h_m: \mathcal{X} \to \{-1, +1\}$ while maintaining a probability distribution $D_m(i)$ over training samples (initialized uniformly at $D_1(i) = 1/n$).
At round $m = 1, \dots, M$:
- Train $h_m$ to minimize the weighted error rate:
- Assign classifier $h_m$ a voting weight inversely linked to its error:
- Up-weight misclassified points and down-weight correctly classified points (with normalizing constant $Z_m$):
The final prediction takes the weighted sign vote $F_M(x) = \operatorname{sign}\!\left(\sum_{m=1}^{M} \alpha_m h_m(x)\right)$.
Later, Friedman, Hastie, and Tibshirani (2000) revealed the deeper statistical identity behind AdaBoost: it is exact Forward Stagewise Additive Modeling minimizing Exponential Loss $L(y, F(x)) = \exp(-y F(x))$. Because $\exp(-y F)$ grows exponentially for large negative margins, AdaBoost is notoriously sensitive to mislabeled outliers—a single corrupted label attracts runaway sample weights.
5.2 Gradient Boosting Machines (GBM): Gradient Descent in Function Space #
Jerome Friedman (2001) generalized boosting to any differentiable loss function $L(y, F(x))$—Squared Error, Huber Loss, Binary Cross-Entropy, Poisson Deviance—via Gradient Boosting.
In Part 3, we minimized loss by stepping iteratively through parameter space: $w_t = w_{t-1} - \eta \nabla_w J(w_{t-1})$. Friedman’s breakthrough was to treat the vector of predictions $\mathbf{F} = [F(x_1), \dots, F(x_n)]^\top$ as the optimization variable and perform gradient descent in function space:
$$F_m(x) = F_{m-1}(x) + \nu \, f_m(x)$$At iteration $m$, we compute the negative gradient of the loss with respect to the current model’s predictions—termed pseudo-residuals:
$$r_{im} = -\left[ \frac{\partial L\big(y_i, F(x_i)\big)}{\partial F(x_i)} \right]_{F(x_i) = F_{m-1}(x_i)}, \qquad i = 1, \dots, n$$Look at what $r_{im}$ equals for our two canonical losses from Part 2:
- Squared Error $L(y, F) = \frac{1}{2}(y - F)^2 \implies r_{im} = y_i - F_{m-1}(x_i)$ (literal prediction residuals!).
- Binary Log-Loss $L(y, F) = \log(1 + e^F) - y F \implies r_{im} = y_i - \sigma(F_{m-1}(x_i))$ (probability residuals!).
We then fit a shallow regression tree $f_m(x)$ directly to the targets $\{(x_i, r_{im})\}_{i=1}^n$ so the tree approximates the steepest-descent direction in function space, and add it scaled by a shrinkage factor (learning rate) $\nu \in (0, 1]$ to prevent overfitting.
6. Second-Order Boosting: Deriving XGBoost from First Principles #
Classical Gradient Boosting uses only first-order gradient information ($r_{im}$) and grows trees using standard MSE splits without an explicit structural complexity penalty inside the split criterion.
Tianqi Chen and Carlos Guestrin (2016) elevated Gradient Boosting to industrial dominance with XGBoost (eXtreme Gradient Boosting), combining a second-order regularized Newton objective with hardware-aware systems engineering.
6.1 The Regularized Objective & Second-Order Taylor Expansion #
At boosting step $t$, we hold the previous predictions $\hat{y}_i^{(t-1)}$ fixed and search for a new tree $f_t$ that minimizes:
$$\mathcal{L}^{(t)} = \sum_{i=1}^{n} l\big(y_i, \hat{y}_i^{(t-1)} + f_t(x_i)\big) + \Omega(f_t)$$where the structural regularizer $\Omega(f_t)$ penalizes both the number of leaves $T$ and the $L_2$ norm of the leaf weights $w = (w_1, \dots, w_T)$:
$$\Omega(f_t) = \gamma T + \frac{1}{2} \lambda \sum_{j=1}^{T} w_j^2$$To optimize arbitrary smooth loss functions $l$ analytically in a single unified framework, apply a second-order Taylor expansion around $\hat{y}_i^{(t-1)}$:
$$\mathcal{L}^{(t)} \approx \sum_{i=1}^{n} \left[ l\big(y_i, \hat{y}_i^{(t-1)}\big) + g_i f_t(x_i) + \frac{1}{2} h_i f_t(x_i)^2 \right] + \gamma T + \frac{1}{2} \lambda \sum_{j=1}^{T} w_j^2$$where $g_i$ and $h_i$ are the exact first-order gradient and second-order Hessian (curvature) for sample $i$:
$$g_i = \frac{\partial l\big(y_i, \hat{y}_i^{(t-1)}\big)}{\partial \hat{y}_i^{(t-1)}}, \qquad h_i = \frac{\partial^2 l\big(y_i, \hat{y}_i^{(t-1)}\big)}{\partial \big(\hat{y}_i^{(t-1)}\big)^2}$$For example, in binary classification with Log-Loss and predicted probability $p_i = \sigma(\hat{y}_i^{(t-1)})$:
$$g_i = p_i - y_i, \qquad h_i = p_i(1 - p_i)$$6.2 Closed-Form Leaf Weights & Exact Split Gain #
Drop the constant term $l(y_i, \hat{y}_i^{(t-1)})$ and group all samples assigned to leaf $j$ into the index set $I_j = \{i : q(x_i) = j\}$ (where every sample in $I_j$ receives the same leaf output $f_t(x_i) = w_j$).
Define the aggregated leaf gradient and Hessian sums:
$$G_j = \sum_{i \in I_j} g_i, \qquad H_j = \sum_{i \in I_j} h_i$$The step-$t$ objective collapses into $T$ completely independent 1D quadratics—one per leaf:
$$\tilde{\mathcal{L}}^{(t)} = \sum_{j=1}^{T} \left[ G_j w_j + \frac{1}{2}(H_j + \lambda) w_j^2 \right] + \gamma T$$Differentiating with respect to each leaf weight $w_j$ and setting the derivative to zero gives the exact Newton-regularized optimal leaf weight:
$$w_j^* = -\frac{G_j}{H_j + \lambda}$$Substituting $w_j^*$ back into $\tilde{\mathcal{L}}^{(t)}$ yields the exact Structure Score evaluating how good any candidate tree topology $q$ is:
$$\tilde{\mathcal{L}}^{(t)}(q) = -\frac{1}{2} \sum_{j=1}^{T} \frac{G_j^2}{H_j + \lambda} + \gamma T$$Finally, to decide whether splitting a parent node $I = I_L \cup I_R$ into left and right children actually improves the regularized objective, compute the exact loss reduction—XGBoost Split Gain:
$$\text{Gain} = \frac{1}{2} \left[ \frac{G_L^2}{H_L + \lambda} + \frac{G_R^2}{H_R + \lambda} - \frac{(G_L + G_R)^2}{H_L + H_R + \lambda} \right] - \gamma$$Look at the sheer engineering elegance compressed into that single equation:
- Second-order curvature awareness ($H$): Samples with higher certainty (smaller $h_i = p_i(1-p_i)$) contribute less curvature, automatically scaling step sizes like Newton’s method.
- Built-in $L_2$ shrinkage ($\lambda$): Prevents tiny leaves with small $H_j$ from producing extreme leaf weights—shrinking $w_j^*$ smoothly toward zero.
- Exact pre-pruning ($\gamma$): Splitting adds one new leaf, costing $\gamma$. If $\text{Gain} \le 0$, the split is rejected outright.
6.3 System-Level Engineering & Tabular Dominance #
Beyond the math, Chen & Guestrin (2016) introduced three system innovations later refined by LightGBM (Ke et al., 2017) and CatBoost (Prokhorenkova et al., 2018):
- Weighted Quantile Sketch / Histogram Binning: Rather than sorting all $n$ continuous values at every split, features are bucketed into candidate quantiles weighted by $h_i$ (putting denser split resolution where loss curvature is highest).
- Sparsity-Aware Split Finding: Missing values (
NaN) and zero entries do not require manual imputation—at every split, XGBoost evaluates sending all missing values left vs. right and learns the optimal default branch direction automatically. - Cache-Aware Column Blocks: Features are stored in compressed, pre-sorted column blocks aligned with CPU L1/L2 cache lines for parallel split evaluation.
As Grinsztajn et al. (2022) demonstrated across 45 tabular benchmarks, this combination explains why Gradient Boosted Decision Trees (GBDTs) remain so hard to beat on tabular data: they are invariant to monotonic feature scaling, naturally robust to uninformative columns (since trees simply never pick noise features for splits), and tailored to irregular, axis-aligned decision boundaries where smooth MLPs tend to over-smooth.

Figure 6. Left: a shallow tree is a coarse step function, while boosting builds a smooth additive fit. Right: validation error as trees are added to Random Forest and Gradient Boosting.
7. Summary Comparison of Tree & Ensemble Architectures #
| Model | Learning Paradigm | Primary Error Targeted | Individual Tree Depth | Key Inductive Bias / Mechanism | Primary Vulnerability |
|---|---|---|---|---|---|
| Single CART Tree | Standalone recursive split | — | Deep (unpruned) or pruned | Axis-aligned rectangular partitions; rank-invariant | Extreme variance; minor data shifts reshape the tree |
| Bagging | Parallel bootstrap ensemble | Variance | Deep (low bias) | Averages $B$ bootstrapped trees; OOB validation | High inter-tree correlation $\rho$ caps variance drop |
| Random Forest | Parallel bootstrap + feature subsampling | Variance ($\rho \downarrow$) | Deep (low bias) | Random $m$-feature subset per split decorrelates trees | Struggles to extrapolate trends; higher bias than GBDT on fine residuals |
| AdaBoost | Sequential sample reweighting | Bias | Stumps (depth 1–2) | Exponential loss minimization via adaptive weights | Sensitive to noisy/mislabeled outliers |
| Gradient Boosting (GBM) | Sequential function-space GD | Bias | Shallow (depth 3–6) | Fits trees to 1st-order pseudo-residuals $r_{im}$ | Slower; lacks integrated 2nd-order leaf regularization |
| XGBoost (GBDT) | Sequential 2nd-order Newton boosting | Bias + Variance | Shallow (depth 3–8) | Exact $g_i, h_i$ Split Gain + $L_2$/leaf penalty + sparsity-aware splits | Sensitive to hyperparameter tuning; struggles on unstructured raw pixels/text |
8. Minimal Implementation: Single Tree, Random Forest & Second-Order XGBoost in NumPy #
To verify every equation in this article directly, the script below builds three complete models from scratch in pure NumPy using vectorized exact split search (np.argsort + np.cumsum):
CARTClassifierusing exact Gini Impurity reduction.RandomForestScratchcombining bootstrap resampling with randommax_featuressubsampling.XGBoostClassifierScratchcomputing exact Binary Log-Loss gradients $g_i = p_i - y_i$, non-constant Hessians $h_i = p_i(1 - p_i)$, exact XGBoost Split Gain, and closed-form regularized leaf weights $w_j^* = -G_j / (H_j + \lambda)$.
All three models are benchmarked on a synthetic heterogeneous tabular dataset containing skewed scales ([1, 100000]), sharp threshold interactions, and four pure noise columns.
import numpy as np
def sigmoid(z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-np.clip(z, -500.0, 500.0)))
def bce_loss(y: np.ndarray, p: np.ndarray) -> float:
p = np.clip(p, 1e-12, 1.0 - 1e-12)
return float(-np.mean(y * np.log(p) + (1.0 - y) * np.log(1.0 - p)))
# =====================================================================
# 1. CART Decision Tree Classifier (Exact Vectorized Gini Splits)
# =====================================================================
class CARTClassifier:
def __init__(self, max_depth: int = 8, min_samples_split: int = 4, max_features=None):
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.max_features = max_features
self.tree = None
def fit(self, X: np.ndarray, y: np.ndarray, rng=None):
self.rng = rng if rng is not None else np.random.default_rng(0)
self.tree = self._build(X, y, depth=0)
return self
def _best_split(self, X: np.ndarray, y: np.ndarray):
n, d = X.shape
p_parent = float(np.mean(y))
parent_gini = 2.0 * p_parent * (1.0 - p_parent)
if parent_gini == 0.0:
return None, None, 0.0
# Feature subsampling for Random Forest decorrelation
if self.max_features is not None and self.max_features < d:
feat_idxs = self.rng.choice(d, size=self.max_features, replace=False)
else:
feat_idxs = range(d)
best_gain, best_feat, best_thresh = 0.0, None, None
total_pos = float(np.sum(y))
for j in feat_idxs:
order = np.argsort(X[:, j])
x_s = X[order, j]
y_s = y[order]
valid = x_s[:-1] != x_s[1:]
if not np.any(valid):
continue
n_L = np.arange(1, n, dtype=float)
n_R = n - n_L
pos_L = np.cumsum(y_s)[:-1]
pos_R = total_pos - pos_L
p_L = pos_L / n_L
p_R = pos_R / n_R
gini_L = 2.0 * p_L * (1.0 - p_L)
gini_R = 2.0 * p_R * (1.0 - p_R)
gains = parent_gini - (n_L * gini_L + n_R * gini_R) / n
gains = np.where(valid, gains, -np.inf)
idx = int(np.argmax(gains))
if gains[idx] > best_gain:
best_gain = float(gains[idx])
best_feat = int(j)
best_thresh = float(0.5 * (x_s[idx] + x_s[idx + 1]))
return best_feat, best_thresh, best_gain
def _build(self, X: np.ndarray, y: np.ndarray, depth: int):
prob = float(np.mean(y))
if depth >= self.max_depth or len(y) < self.min_samples_split:
return {"leaf": True, "prob": prob}
feat, thresh, gain = self._best_split(X, y)
if feat is None or gain <= 1e-12:
return {"leaf": True, "prob": prob}
left_mask = X[:, feat] <= thresh
return {
"leaf": False,
"feat": feat,
"thresh": thresh,
"left": self._build(X[left_mask], y[left_mask], depth + 1),
"right": self._build(X[~left_mask], y[~left_mask], depth + 1),
}
def _predict_row(self, x: np.ndarray, node: dict) -> float:
while not node["leaf"]:
node = node["left"] if x[node["feat"]] <= node["thresh"] else node["right"]
return node["prob"]
def predict_proba(self, X: np.ndarray) -> np.ndarray:
return np.array([self._predict_row(row, self.tree) for row in X])
# =====================================================================
# 2. Random Forest Classifier (Bagging + Feature Subsampling)
# =====================================================================
class RandomForestScratch:
def __init__(self, n_trees: int = 35, max_depth: int = 10, max_features: int = 3):
self.n_trees = n_trees
self.max_depth = max_depth
self.max_features = max_features
self.trees = []
def fit(self, X: np.ndarray, y: np.ndarray, seed: int = 42):
rng = np.random.default_rng(seed)
n = X.shape[0]
self.trees = []
for _ in range(self.n_trees):
boot_idx = rng.integers(0, n, size=n) # Sample with replacement
tree = CARTClassifier(max_depth=self.max_depth, max_features=self.max_features)
tree.fit(X[boot_idx], y[boot_idx], rng=rng)
self.trees.append(tree)
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
preds = np.array([t.predict_proba(X) for t in self.trees])
return preds.mean(axis=0)
# =====================================================================
# 3. Second-Order XGBoost Classifier (Exact g_i, h_i Split Gain & Leaf w*)
# =====================================================================
class XGBoostTree:
def __init__(self, max_depth: int = 3, lam: float = 1.0, gamma: float = 0.1):
self.max_depth = max_depth
self.lam = lam
self.gamma = gamma
self.tree = None
def fit(self, X: np.ndarray, g: np.ndarray, h: np.ndarray):
self.tree = self._build(X, g, h, depth=0)
return self
def _best_split(self, X: np.ndarray, g: np.ndarray, h: np.ndarray):
n, d = X.shape
G_tot = float(np.sum(g))
H_tot = float(np.sum(h))
parent_score = (G_tot ** 2) / (H_tot + self.lam)
best_gain, best_feat, best_thresh = 0.0, None, None
for j in range(d):
order = np.argsort(X[:, j])
x_s = X[order, j]
g_s = g[order]
h_s = h[order]
valid = x_s[:-1] != x_s[1:]
if not np.any(valid):
continue
G_L = np.cumsum(g_s)[:-1]
H_L = np.cumsum(h_s)[:-1]
G_R = G_tot - G_L
H_R = H_tot - H_L
# Exact XGBoost Split Gain equation (Chen & Guestrin, 2016)
gains = 0.5 * (
(G_L ** 2) / (H_L + self.lam)
+ (G_R ** 2) / (H_R + self.lam)
- parent_score
) - self.gamma
gains = np.where(valid, gains, -np.inf)
idx = int(np.argmax(gains))
if gains[idx] > best_gain:
best_gain = float(gains[idx])
best_feat = int(j)
best_thresh = float(0.5 * (x_s[idx] + x_s[idx + 1]))
return best_feat, best_thresh, best_gain
def _build(self, X: np.ndarray, g: np.ndarray, h: np.ndarray, depth: int):
# Closed-form Newton-regularized leaf weight w* = -G / (H + lambda)
leaf_weight = -float(np.sum(g) / (np.sum(h) + self.lam))
if depth >= self.max_depth or len(g) < 4:
return {"leaf": True, "weight": leaf_weight}
feat, thresh, gain = self._best_split(X, g, h)
if feat is None or gain <= 0.0:
return {"leaf": True, "weight": leaf_weight}
left_mask = X[:, feat] <= thresh
return {
"leaf": False,
"feat": feat,
"thresh": thresh,
"left": self._build(X[left_mask], g[left_mask], h[left_mask], depth + 1),
"right": self._build(X[~left_mask], g[~left_mask], h[~left_mask], depth + 1),
}
def predict(self, X: np.ndarray) -> np.ndarray:
out = np.empty(X.shape[0], dtype=float)
for i, row in enumerate(X):
node = self.tree
while not node["leaf"]:
node = node["left"] if row[node["feat"]] <= node["thresh"] else node["right"]
out[i] = node["weight"]
return out
class XGBoostClassifierScratch:
def __init__(self, n_rounds: int = 45, lr: float = 0.15, max_depth: int = 3, lam: float = 1.0, gamma: float = 0.1):
self.n_rounds = n_rounds
self.lr = lr
self.max_depth = max_depth
self.lam = lam
self.gamma = gamma
self.base_score = 0.0
self.trees = []
def fit(self, X: np.ndarray, y: np.ndarray):
p0 = float(np.clip(np.mean(y), 1e-6, 1.0 - 1e-6))
self.base_score = float(np.log(p0 / (1.0 - p0))) # Initial log-odds
logits = np.full(X.shape[0], self.base_score, dtype=float)
self.trees = []
for _ in range(self.n_rounds):
p = sigmoid(logits)
g = p - y # Exact 1st derivative of Log-Loss
h = p * (1.0 - p) # Exact 2nd derivative (Hessian)
tree = XGBoostTree(max_depth=self.max_depth, lam=self.lam, gamma=self.gamma)
tree.fit(X, g, h)
logits += self.lr * tree.predict(X)
self.trees.append(tree)
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
logits = np.full(X.shape[0], self.base_score, dtype=float)
for tree in self.trees:
logits += self.lr * tree.predict(X)
return sigmoid(logits)
# =====================================================================
# Benchmark: Heterogeneous Tabular Data (Skewed Scales + Noise Columns)
# =====================================================================
def make_tabular_dataset(n: int, seed: int):
rng = np.random.default_rng(seed)
x0 = rng.uniform(-2.0, 2.0, size=n) # Continuous feature
x1 = np.exp(rng.uniform(2.0, 11.5, size=n)) # Skewed scale [7 .. 100,000]
x2 = rng.uniform(-2.0, 2.0, size=n) # Interaction partner
x3 = rng.integers(0, 2, size=n).astype(float) # Binary indicator
noise_cols = rng.normal(0.0, 10.0, size=(n, 4)) # 4 uninformative noise columns
X = np.column_stack([x0, x1, x2, x3, noise_cols])
# Axis-aligned thresholds + non-linear XOR interaction + smooth shift
true_logit = (
2.2 * ((x0 * x2) > 0.2).astype(float)
+ 1.8 * (x1 > 1200.0).astype(float)
+ 1.2 * x3
- 2.4
)
y = (rng.uniform(size=n) < sigmoid(true_logit)).astype(float)
return X, y
X_tr, y_tr = make_tabular_dataset(n=450, seed=11)
X_te, y_te = make_tabular_dataset(n=500, seed=99)
models = [
("Single CART Tree (depth=10)", CARTClassifier(max_depth=10).fit(X_tr, y_tr)),
("Random Forest (35 trees, m=3)", RandomForestScratch(n_trees=35, max_depth=10, max_features=3).fit(X_tr, y_tr)),
("XGBoost Scratch (45 x depth=3)", XGBoostClassifierScratch(n_rounds=45, lr=0.15, max_depth=3, lam=1.5, gamma=0.15).fit(X_tr, y_tr)),
]
print(f"Tabular Benchmark: {len(y_tr)} train | {len(y_te)} test | 8 features (4 signal, 4 noise)\n")
print(f"{'Model':<32} | {'Train Acc':<9} | {'Test Acc':<8} | {'Train BCE':<9} | {'Test BCE'}")
print("-" * 78)
for name, model in models:
p_tr = model.predict_proba(X_tr)
p_te = model.predict_proba(X_te)
acc_tr = float(np.mean((p_tr >= 0.5) == y_tr)) * 100.0
acc_te = float(np.mean((p_te >= 0.5) == y_te)) * 100.0
loss_tr = bce_loss(y_tr, p_tr)
loss_te = bce_loss(y_te, p_te)
print(f"{name:<32} | {acc_tr:>7.1f}% | {acc_te:>6.1f}% | {loss_tr:>9.4f} | {loss_te:>8.4f}")Interpreting the Behavior #
Three core ensemble mechanics appear directly in the benchmark output:
- Single Deep Tree Overfitting: The standalone
depth=10CART tree memorizes the training set (highTrain Accand lowTrain BCE), yet collapses on the test set with heavily miscalibrated probabilities (Test BCEoften exceeding2.0+because pure leaf predictions output confident0.0or1.0on noisy samples). - Random Forest Variance Collapse: Averaging 35 decorrelated deep trees immediately stabilizes probability estimates and slashes
Test BCEby severalfold while liftingTest Acc—without needing any feature scaling on the[7 .. 100,000]skewed columnx1. - Second-Order XGBoost Precision: Despite restricting every individual tree to just
depth=3, iteratively updating along exact Log-Loss gradients $g_i$ and Hessians $h_i$ with $\lambda$-shrinkage and $\gamma$-pruning produces well-calibrated probabilities and the strongest overall generalization (Test AccandTest BCE), cleanly ignoring all four pure-noise columns.
9. Limitations & Bridge to Part 7 #
Across Parts 2 through 6, every algorithm we built—Linear Models, Logistic Regression, Kernel SVMs, Random Forests, and XGBoost—relied on one luxury: explicit ground-truth labels $y_i$.
What happens when you inherit millions of sensor readings, customer event logs, or high-dimensional embeddings with zero labels—or when your feature matrix spans thousands of dimensions where Euclidean distances collapse under the Curse of Dimensionality?
In Part 7: Unsupervised Learning, Dimensionality Reduction & Manifold Learning, we step outside labeled supervision entirely. We will analyze the geometry of high-dimensional space, contrast hard clustering (K-Means) against probabilistic latent-variable models (Gaussian Mixture Models & the EM Algorithm), derive PCA & Singular Value Decomposition (SVD)—the exact linear-algebraic foundation behind modern LLM adapters like LoRA—and dissect non-linear manifold projections (t-SNE and UMAP).
References #
- Breiman, L., Friedman, J. H., Olshen, R. A., & Stone, C. J. (1984). Classification and Regression Trees. Wadsworth & Brooks/Cole. (Foundational CART framework and Gini Impurity).
- Quinlan, J. R. (1986). “Induction of Decision Trees.” Machine Learning, 1(1), 81–106. (ID3 and Information Gain via Shannon Entropy).
- Breiman, L. (1996). “Bagging Predictors.” Machine Learning, 24(2), 123–140. (Bootstrap aggregating and variance reduction).
- Freund, Y., & Schapire, R. E. (1997). “A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting.” Journal of Computer and System Sciences, 55(1), 119–139. (AdaBoost).
- Friedman, J., Hastie, T., & Tibshirani, R. (2000). “Additive Logistic Regression: A Statistical View of Boosting.” The Annals of Statistics, 28(2), 337–407. (Proof of AdaBoost as forward stagewise exponential loss minimization).
- Breiman, L. (2001). “Random Forests.” Machine Learning, 45(1), 5–32. (Feature subsampling, tree decorrelation, and OOB error).
- Friedman, J. H. (2001). “Greedy Function Approximation: A Gradient Boosting Machine.” The Annals of Statistics, 29(5), 1189–1232. (Gradient descent in function space and pseudo-residuals).
- Chen, T., & Guestrin, C. (2016). “XGBoost: A Scalable Tree Boosting System.” Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD ‘16), 785–794. arXiv:1603.02754.
- Grinsztajn, L., Oyallon, E., & Varoquaux, G. (2022). “Why Do Tree-Based Models Still Outperform Deep Learning on Typical Tabular Data?” Advances in Neural Information Processing Systems (NeurIPS 2022). arXiv:2207.08815.