↓ Luncat ka eusi utama
  1. Catetan Rékayasa & Artikel Téknis/

Decision Trees & Kadominasian Ensemble Learning dina Tabular Data

Daptar eusi
Dasar Machine Learning - Artikel ieu mangrupikeun bagian tina hiji séri.
Bagian 6: Artikel ieu

1. Masalah Inti: Naonkeun Smooth Kernels Berat dina Realita Tabular
#

Dina Part 5, urang ngawangun Kernel Support Vector Machines—convex geometric classifiers anu bisa nyieun smooth non-linear boundaries di jero infinite-dimensional Hilbert spaces. Sanajan salaku anu dicatet dina tungtung Part 5, tabular datasets dunya nyata (financial ledgers, clinical diagnostics, multi-sensor telemetry, industrial logs) nembongkeun dua kalemahan struktural dina distance-based sareng linear models:

  1. Heterogeneous, Unaligned Scales & Uninformative Columns: Hiji tabular table biasana ngahijikeun skewed currency amounts anu nyebar $[0, 10^7]$, binary status flags, missing values, sareng lusinan noise columns anu teu relevan. Euclidean kernels sapertos RBF nganggap sadaya arah coordinate isotropic—hartina feature anu teu relevan atawa kaskala goreng langsung ngaruksak pairwise distances $\Vert{}x_i - x_j\Vert{}_2^2$.
  2. Irregular, Non-Smooth Target Functions: Hubungan tabular jarang kalakuan sapertos gelombang trigonometri smooth. Eta nembongkeun sharp step discontinuities sareng axis-aligned thresholds (upamana, risiko naek sacara kedah sakali voltage ngalangkungan $3.6\,\text{V}$ sareng temperature ngalintasi $65^\circ\text{C}$).

Sanajan dina era deep neural networks, benchmark sistematis sapertos Grinsztajn, Oyallon, sareng Varoquaux (2022) ngamastikeun tree-based ensembles tetep konsisten ngaliwatan standar deep learning architectures dina tabular datasets ukuran sedeng. Ngarti naonkeun eta peryogi ngalangkungan hiji axis-aligned Decision Tree ka dua pilar Ensemble Learning: reducing variance sacara paralel (Bagging & Random Forests) sareng reducing bias sacara beres (AdaBoost, Gradient Boosting, sareng XGBoost).


2. Intuisi Konsep: Twenty Questions, Independent Juries, sareng Sequential Specialists
#

Twenty Questions (Decision Trees)
#

Alih-alih ngaproyeksikeun data ngalangkungan dot products atawa smooth kernels, Decision Tree ngamainkeun kaulinan Twenty Questions. Unggal langkah, eta naroskeun hiji patarosan yes/no threshold anu pangcuramna dina hiji raw feature—“Is feature $x_j \le s$?"—ngapotong feature space jadi axis-aligned hyper-rectangles nepi ka unggal kotak ngandung kalayan mayoritas hiji kelas atawa numerical range anu heureut. Sabab splits ngan gumantung kana rank ordering dina unggal coordinate, ngalikeun kolom ku $10{,}000$ atawa nerapkeun unggal monotonic transform nganteun tree sampurna.

Independent Juries (Bagging & Random Forests)
#

Hiji deeply grown tree tunggal hypersensitive: ngarobah sabaraha training rows bisa ngarobah root split mungkin, cascading jadi tree structure anu sampurna beda (high variance). Pikeun ngabasahakeun instability eta, bayangkeun ngaganti hiji eccentric judge sareng committee of 100 independent judges, unggalna dipameran dossier bootstrapped anu saeutik beda sareng dimaksa ningali subsets evidence anu beda. Keunikan individual batalkeun salaku jumlahna dirata-ratakeun.

Sequential Specialists (Boosting)
#

Bagging ngawangun experts anu beda sacara paralel. Boosting ngawangun relay team tina specialist anu basajan sacara beres:

  • Specialist #1 ngahasilkeun prediksi kasar, low-capacity—ngan nyekel pola panggeusna.
  • Specialist #2 ngahenteukeun masalah asal sareng ngan ngarah ka ngaleungitkeun kasalahan anu ditinggalkeun ku Specialist #1.
  • Specialist #3 ngakoreksi residual errors anu meser tina dua mungkin, sareng seterusna.

Unggal tree individu sengaja tetep weak (shallow sareng high-bias), sanajan jumlah kumulatifna converges heureut ka pola non-linear kompleks.


3. Rumusan Matematis: Anatomi hiji Decision Tree (CART)
#

Dikenalkeun sacara sistematis ku Leo Breiman, Jerome Friedman, Richard Olshen, sareng Charles Stone (1984) dina CART (Classification and Regression Trees) sareng diparalelkeun dina bentuk information-theoretic ku Ross Quinlan (1986) dina ID3, hiji decision tree misahkeun input space $\mathcal{X}$ jadi $M$ disjoint rectangular regions $R_1, R_2, \dots, R_M$ sareng nembongkeun konstanta prediksi $c_m$ pikeun unggal leaf:

$$f(x) = \sum_{m=1}^{M} c_m \, \mathbb{I}[x \in R_m]$$

Mendakan tree partition optimal global dina sadaya kombinasi splits anu mungkin mangrupikeun NP-complete. Alih-alih, CART make greedy top-down recursive binary partitioning.

Splitting Criteria: Gini Impurity vs. Information Gain
#

Dina unggal internal node anu ngagambarkeun region $R_m$ sareng $N_m = \vert{}R_m\vert{}$ sampel, harti empirical proportion tina kelas $k \in \{1, \dots, K\}$ salaku:

$$p_{mk} = \frac{1}{N_m} \sum_{i \in R_m} \mathbb{I}[y_i = k]$$

Pikeun ngevaluasi sabaraha “mixed” hiji node, classification trees make salah sahiji ti dua strictly concave impurity functions $I(R_m)$:

  1. Gini Impurity (CART default): Ngukur probability nina misclassifying hiji elemen anu dipilih acak dina $R_m$ upami dilabel sacara acak nurutkeun distribusi kelas node:

    $$G(R_m) = \sum_{k=1}^{K} p_{mk}(1 - p_{mk}) = 1 - \sum_{k=1}^{K} p_{mk}^2$$
  2. Shannon Entropy (ID3 / C4.5): Ngukur expected information content (dina bits) anu diperyogikeun pikeun encode distribusi kelas di jero $R_m$:

    $$H(R_m) = -\sum_{k=1}^{K} p_{mk} \log_2 p_{mk}$$

Pikeun regression, impurity ngan within-node variance sabudeureun leaf mean $\bar{y}_m$:

$$V(R_m) = \frac{1}{N_m} \sum_{i \in R_m} (y_i - \bar{y}_m)^2$$

Ayeuna tes unggal candidate feature $j \in \{1, \dots, d\}$ sareng threshold $s$, misahkeun $R_m$ jadi left sareng right children $R_L(j, s) = \{x \in R_m : x_j \le s\}$ sareng $R_R(j, s) = \{x \in R_m : x_j \gt s\}$. Optimal split $(j^*, s^*)$ ngamaksimalkeun Impurity Reduction (disebut Information Gain lamun $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
#

Sabab splits sampurna hierarchical sareng greedy, fluktuasi sampling leutik anu ngarobah root split ngalangkungan unggal branch sanggeusna. Grown ka full depth, hiji decision tree tunggal ngahasilkeun near-zero bias ($\text{Bias}^2 \approx 0$) ku ngeusian individual samples, dina biaya Variance anu ageung—ngahasilkeun standalone trees anu teu reliable predictors dina noisy datasets.


4. Variance Reduction: Bagging & Random Forests
#

Catet Bias–Variance Decomposition tina Part 4. Upami single deep trees parantos ngabogaan bias handap, urang teu peryogi model anu langkung kompleks—urang peryogi mekanisme anu nyumputkeun variance tanpa ngaronjatkeun bias.

Bootstrap Aggregating (Bagging)
#

Anu diajanjian ku Leo Breiman (1996), Bagging narik $B$ bootstrap training sets $S^{(1)}, \dots, S^{(B)}$—unggalna dieusikeun ku sampling $n$ baris with replacement tina training set asal $S$—ngafit hiji unpruned tree $\hat{f}_b(x)$ pikeun unggalna, sareng ngarata-ratakeun prediksi:

$$\hat{f}_{\text{bag}}(x) = \frac{1}{B} \sum_{b=1}^{B} \hat{f}_b(x)$$

(Pikeun unggal bootstrap sample, probability training point hiji teu kalaulaweun dipilih mangrupikeun $(1 - 1/n)^n \to e^{-1} \approx 36.8\%$. Baris anu dileungitkeun ieu jadi Out-of-Bag (OOB) validation samples anu diwangun tanpa biaya compute tambahan.)

The Correlation Bottleneck & The Random Forest Fix
#

Naonkeun teu berhenti dina Bagging? Anggap $B$ trees $\hat{f}_1(x), \dots, \hat{f}_B(x)$ anu identically distributed unggalna mibanda variance $\sigma^2$ sareng positive pairwise correlation $\rho = \operatorname{Corr}(\hat{f}_b(x), \hat{f}_{b'}(x))$ pikeun $b \neq b'$. Ngitung variance tina rata-rata ieu langsung ngahasilkeun:

$$\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$$

Tingali rumus ieu kalayan sakedik:

  • Naekan jumlah trees $B \to \infty$ nurunkeun istilah kadua $\frac{1-\rho}{B}\sigma^2 \to 0$.
  • Tapi, eta teu bisa nyumputkeun istilah kahiji $\rho \sigma^2$. Upami hiji strong predictor nangtu dina dataset, hampir unggal bagged tree milih feature anu sami dina root—ngajaga $\rho$ katingal kalacak ka $1$.

Breiman (2001) ngahancurkeun correlation ceiling ieu sareng Random Forests: dina unggal node split tunggal, tree dibatasi ngalanglang ngan dina random subset enggal tina $m \lt d$ candidate features (biasana $m = \lfloor \sqrt{d} \rfloor$ pikeun classification sareng $m = \lfloor d / 3 \rfloor$ pikeun regression).

Ku sakali nyumputkeun dominant feature dina candidate splits, weaker predictors ngabogaan kasempetan pikeun ngadalikeun upper splits—decorrelating the ensemble ($\rho \downarrow$) sareng nurunkeun asymptotic variance floor $\rho \sigma^2$ sacara dramatis sambing ngajaga bias kira-kira teu robah.


5. Bias Reduction: Tina AdaBoost ka Gradient Boosting Machines
#

Random Forests nyerang variance ku ngarata-ratakeun deep, low-bias trees. Boosting malikkeun strategy sampurna: mimitian sareng shallow, high-bias “weak learners” (sering depth 1 ka 6) sareng ngahijikeun sacara beres pikeun nyerang bias.

5.1 AdaBoost: Adaptive Reweighting & Exponential Loss
#

Dikenalkeun ku Yoav Freund sareng Robert Schapire (1997), AdaBoost (Adaptive Boosting) iteratively ngelatih binary weak classifiers $h_m: \mathcal{X} \to \{-1, +1\}$ sambing ngajaga probability distribution $D_m(i)$ dina training samples (diinisialisasi seragam dina $D_1(i) = 1/n$).

Dina round $m = 1, \dots, M$:

  1. Latih $h_m$ pikeun ngaminimalkeun weighted error rate:
$$\varepsilon_m = \sum_{i=1}^{n} D_m(i) \, \mathbb{I}[h_m(x_i) \neq y_i]$$
  1. Bereskeun classifier $h_m$ voting weight anu inversely linked ka error-na:
$$\alpha_m = \frac{1}{2} \ln\!\left( \frac{1 - \varepsilon_m}{\varepsilon_m} \right)$$
  1. Up-weight misclassified points sareng down-weight correctly classified points (sareng normalizing constant $Z_m$):
$$D_{m+1}(i) = \frac{D_m(i) \exp\big(-\alpha_m y_i h_m(x_i)\big)}{Z_m}$$

Final prediction nyandak weighted sign vote $F_M(x) = \operatorname{sign}\!\left(\sum_{m=1}^{M} \alpha_m h_m(x)\right)$.

Lajeng, Friedman, Hastie, sareng Tibshirani (2000) nembongkeun identitas statistik anu leuwih jero di jero AdaBoost: eta exact Forward Stagewise Additive Modeling ngaminimalkeun Exponential Loss $L(y, F(x)) = \exp(-y F(x))$. Sabab $\exp(-y F)$ naek exponential pikeun negative margins ageung, AdaBoost notoriously sensitif ka mislabeled outliers—hiji corrupted label tunggal narik sample weights anu kabebas.

5.2 Gradient Boosting Machines (GBM): Gradient Descent in Function Space
#

Jerome Friedman (2001) nga-eneralisasi boosting ka unggal differentiable loss function $L(y, F(x))$—Squared Error, Huber Loss, Binary Cross-Entropy, Poisson Deviance—ngalangkungan Gradient Boosting.

Dina Part 3, urang ngaminimalkeun loss ku ngalangkah iteratively ngalangkungan parameter space: $w_t = w_{t-1} - \eta \nabla_w J(w_{t-1})$. Breakthrough Friedman’s nyaeta nganggap vector predictions $\mathbf{F} = [F(x_1), \dots, F(x_n)]^\top$ salaku optimization variable sareng ngalakukeun gradient descent in function space:

$$F_m(x) = F_{m-1}(x) + \nu \, f_m(x)$$

Dina iterasi $m$, urang ngitung negative gradient tina loss dina predictions model kiwari—anu disebut 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$$

Tingali naon $r_{im}$ sarua pikeun dua canonical losses urang tina 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!).

Urang lajeng ngafit shallow regression tree $f_m(x)$ langsung ka targets $\{(x_i, r_{im})\}_{i=1}^n$ supados tree nga-aproksimasi steepest-descent direction dina function space, sareng nambahan eta scaled ku shrinkage factor (learning rate) $\nu \in (0, 1]$ pikeun nyegah overfitting.


6. Second-Order Boosting: Nurunkeun XGBoost tina Prinsip Dasar
#

Classical Gradient Boosting ngan make first-order gradient information ($r_{im}$) sareng nga-tree make standard MSE splits tanpa explicit structural complexity penalty di jero split criterion.

Tianqi Chen sareng Carlos Guestrin (2016) ngaronjatkeun Gradient Boosting ka kadominasian industri sareng XGBoost (eXtreme Gradient Boosting), ngagabungkeun second-order regularized Newton objective sareng hardware-aware systems engineering.

6.1 The Regularized Objective & Second-Order Taylor Expansion
#

Dina boosting step $t$, urang ngajaga predictions kiwari $\hat{y}_i^{(t-1)}$ tetep sareng ngalanglang tree enggal $f_t$ anu ngaminimalkeun:

$$\mathcal{L}^{(t)} = \sum_{i=1}^{n} l\big(y_i, \hat{y}_i^{(t-1)} + f_t(x_i)\big) + \Omega(f_t)$$

dimana structural regularizer $\Omega(f_t)$ ngahukum jumlah leaves $T$ sareng norma $L_2$ tina leaf weights $w = (w_1, \dots, w_T)$:

$$\Omega(f_t) = \gamma T + \frac{1}{2} \lambda \sum_{j=1}^{T} w_j^2$$

Pikeun ngoptimasi unggal smooth loss function $l$ sacara analitis dina hiji rengking unified, nerapkeun second-order Taylor expansion sabudeureun $\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$$

dimana $g_i$ sareng $h_i$ mangrupikeun first-order gradient persis sareng second-order Hessian (curvature) pikeun 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}$$

Upamana, dina binary classification sareng Log-Loss sareng 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
#

Leungitkeun istilah konstanta $l(y_i, \hat{y}_i^{(t-1)})$ sareng ngagabungkeun sadaya sampel anu ditugaskeun ka leaf $j$ ka index set $I_j = \{i : q(x_i) = j\}$ (dimana unggal sampel dina $I_j$ nampi sami output leaf $f_t(x_i) = w_j$).

Harti aggregated leaf gradient sareng Hessian sums:

$$G_j = \sum_{i \in I_j} g_i, \qquad H_j = \sum_{i \in I_j} h_i$$

Objective step-$t$ runtuh ka $T$ independent 1D quadratics anu sampurna—hiji 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$$

Ngalakukeun turunan dina unggal leaf weight $w_j$ sareng nyetel turunan ka nol ngahasilkeun Newton-regularized optimal leaf weight anu persis:

$$w_j^* = -\frac{G_j}{H_j + \lambda}$$

Substitusikeun $w_j^*$ balik ka $\tilde{\mathcal{L}}^{(t)}$ ngahasilkeun Structure Score anu persis ngevaluasi sabaraha alus unggal candidate tree topology $q$:

$$\tilde{\mathcal{L}}^{(t)}(q) = -\frac{1}{2} \sum_{j=1}^{T} \frac{G_j^2}{H_j + \lambda} + \gamma T$$

Akhirna, pikeun mutuskeun naonkeun splitting hiji parent node $I = I_L \cup I_R$ jadi left sareng right children nyata ngaronjatkeun regularized objective, ngitung loss reduction persis—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$$

Tingali elegan engineering anu padat di jero hiji persamaan:

  • Second-order curvature awareness ($H$): Sampel sareng certainty leuwih luhur (leutik $h_i = p_i(1-p_i)$) mibanda kontribusi curvature leutik, sacara otomatis scaling step sizes sapertos Newton’s method.
  • Built-in $L_2$ shrinkage ($\lambda$): Nyegah leaves leutik sareng $H_j$ leutik ngahasilkeun leaf weights ekstrem—nyumputkeun $w_j^*$ sacara mulus ka nol.
  • Exact pre-pruning ($\gamma$): Splitting nambahan hiji leaf enggal, ngabayar $\gamma$. Upami $\text{Gain} \le 0$, split ditolak sampurna.

6.3 System-Level Engineering & Tabular Dominance
#

Salian matematik, Chen & Guestrin (2016) ngamajukeun tilu inovasi sistem anu lajeng di-refine ku LightGBM (Ke et al., 2017) sareng CatBoost (Prokhorenkova et al., 2018):

  1. Weighted Quantile Sketch / Histogram Binning: Tibatan nyortir sadaya $n$ continuous values unggal split, features di-bucket jadi candidate quantiles anu weighted ku $h_i$ (ngalebetkeun resolusi split anu leuwih padat dimana loss curvature pangluhur).
  2. Sparsity-Aware Split Finding: Missing values (NaN) sareng zero entries teu peryogi manual imputation—unggal split, XGBoost ngevaluasi ngirim sadaya missing values ka kenca vs. katuhu sareng ngajar ka default branch direction anu optimal sacara otomatis.
  3. Cache-Aware Column Blocks: Features disimpen dina compressed, pre-sorted column blocks anu aligned sareng CPU L1/L2 cache lines pikeun parallel split evaluation.

Salaku Grinsztajn et al. (2022) ngajelaskeun dina 45 tabular benchmarks, kombinasi ieu ngajelaskeun naonkeun Gradient Boosted Decision Trees (GBDTs) tetep langkung hese kalahan dina tabular data: Eta invariant ka monotonic feature scaling, sacara alami robust ka uninformative columns (sabab trees ngan teu kalaulaweun milih noise features pikeun splits), sareng tailored ka irregular, axis-aligned decision boundaries dimana smooth MLPs cenderung over-smooth.


Single tree step function vs. boosting and ensemble error curves

Figure 6. Kenca: shallow tree mangrupikeun coarse step function, sambing boosting ngawangun smooth additive fit. Katuhu: validation error salaku trees ditambahan ka Random Forest sareng Gradient Boosting.

7. Ringkasan Perbandingan 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 dina NumPy
#

Pikeun ngaverifikasi unggal persamaan dina artikel ieu langsung, script di handap ngawangun tilu model sampurna ti nol dina pure NumPy make vectorized exact split search (np.argsort + np.cumsum):

  1. CARTClassifier make exact Gini Impurity reduction.
  2. RandomForestScratch ngagabungkeun bootstrap resampling sareng random max_features subsampling.
  3. XGBoostClassifierScratch ngitung 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, sareng closed-form regularized leaf weights $w_j^* = -G_j / (H_j + \lambda)$.

Sakalih tilu model dibenchmark dina synthetic heterogeneous tabular dataset anu ngandung skewed scales ([1, 100000]), sharp threshold interactions, sareng opat 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}")

Ngajelaskeun Kiarana
#

Tilu mekanika ensemble inti katingal langsung dina benchmark output:

  1. Single Deep Tree Overfitting: Standalone depth=10 CART tree ngahapal training set (high Train Acc sareng low Train BCE), sanajan runtuh dina test set sareng probabilities anu kalacak (Test BCE sering ngalangkungan 2.0+ sabab pure leaf predictions ngaluarkeun confident 0.0 atawa 1.0 dina noisy samples).
  2. Random Forest Variance Collapse: Ngarata-ratakeun 35 decorrelated deep trees langsung ngastabilkeun probability estimates sareng nyumputkeun Test BCE sabaraha kali sambing ngaronjatkeun Test Acc—tanpa peryogi unggal feature scaling dina skewed column x1 [7 .. 100,000].
  3. Second-Order XGBoost Precision: Sanajan ngabatasan unggal individu tree ngan depth=3, iteratively updating dina exact Log-Loss gradients $g_i$ sareng Hessians $h_i$ sareng $\lambda$-shrinkage sareng $\gamma$-pruning ngahasilkeun probabilities anu well-calibrated sareng generalization pangkuatna (Test Acc sareng Test BCE), nganteun sakabeh opat pure-noise columns.

9. Wates & Jembatan ka Part 7
#

Dina sakabeh Parts 2 ka 6, unggal algoritma anu urang wangun—Linear Models, Logistic Regression, Kernel SVMs, Random Forests, sareng XGBoost—ngandelan hiji kabebasan: explicit ground-truth labels $y_i$.

Naon anu kajadian lamun anjeun mewarisi jutaan sensor readings, customer event logs, atawa high-dimensional embeddings sareng nol labels—atawa lamun feature matrix anjeun nyebar sarebuan dimensi dimana Euclidean distances runtuh dina Curse of Dimensionality?

Dina Part 7: Unsupervised Learning, Dimensionality Reduction & Manifold Learning, urang ninggalkeun labeled supervision sampurna. Urang bakal nganalisis geometri high-dimensional space, ngabandingkeun hard clustering (K-Means) sareng probabilistic latent-variable models (Gaussian Mixture Models & the EM Algorithm), nurunkeun PCA & Singular Value Decomposition (SVD)—pondasi linear-algebraic persis di jero modern LLM adapters sapertos LoRA—sareng mbedah non-linear manifold projections (t-SNE sareng UMAP).


Rujukan
#

  1. 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).
  2. Quinlan, J. R. (1986). “Induction of Decision Trees.” Machine Learning, 1(1), 81–106. (ID3 and Information Gain via Shannon Entropy).
  3. Breiman, L. (1996). “Bagging Predictors.” Machine Learning, 24(2), 123–140. (Bootstrap aggregating and variance reduction).
  4. 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).
  5. 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).
  6. Breiman, L. (2001). “Random Forests.” Machine Learning, 45(1), 5–32. (Feature subsampling, tree decorrelation, and OOB error).
  7. 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).
  8. 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.
  9. 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.
Dasar Machine Learning - Artikel ieu mangrupikeun bagian tina hiji séri.
Bagian 6: Artikel ieu