{
  "id": "tree-ensembles",
  "module": "math-ml",
  "level": 2,
  "minutes": 40,
  "audiences": [
    "developer",
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "Trees and Ensembles: Decision Trees, Random Forests and Gradient Boosting",
      "description": "Tree models and ensemble methods for machine learning practice: Gini impurity and information gain in CART, cost-complexity pruning, bagging and random forests, AdaBoost, Friedman’s gradient boosting, and the objectives and systems design of XGBoost and LightGBM. Based on the original papers and the official scikit-learn, XGBoost, LightGBM and SHAP documentation, with a reproducible comparison and explanation experiment on the California Housing data set.",
      "updated": "2026-11-22",
      "takeaways": [
        "A decision tree recursively splits samples into purer subsets with feature thresholds. CART grows a binary tree, typically using Gini impurity for classification and squared error for regression. The quality of a split is the size-weighted impurity of the two children, and the algorithm chooses the feature and threshold that minimise that quantity.",
        "A single tree can fit the training set to zero error, so depth, leaf size or cost-complexity pruning must be controlled. Splits depend only on the order of feature values, so standardising features usually leaves the predictions unchanged; with the same random seed this lesson obtained identical test predictions.",
        "Bagging averages models trained on bootstrap samples in order to reduce variance. Random forests also search only a random subset of features at each node, which de-correlates the trees. Boosting adds models sequentially: AdaBoost up-weights examples the previous round got wrong, and gradient boosting fits the negative gradient of the current loss (the residual, when the loss is squared error).",
        "XGBoost uses a second-order Taylor expansion of a regularised objective to set leaf values and split gain, and does not split when the gain is smaller than gamma. The paper also gives a sparsity-aware split algorithm and a weighted quantile sketch for approximate splits. LightGBM uses histograms, leaf-wise growth, and the paper’s GOSS and EFB techniques to cut computation; num_leaves and min_data_in_leaf are the main controls against overfitting.",
        "On a single train/test split of California Housing, an unpruned tree had a test RMSE of 0.7312, a random forest 0.4875, and, with the settings in this lesson, LightGBM 0.4387 and XGBoost 0.4430. Both SHAP and permutation importance flag location and income as the main factors, but they do not rank the features identically, because they answer different questions."
      ],
      "faq": [
        {
          "q": "Why is a random forest usually more stable than a single tree?",
          "a": "A deep tree has high variance: its structure moves around with small changes in the training sample. A random forest fits each tree on a bootstrap sample (bagging) and, at every node, searches only a random subset of features, which reduces correlation among the trees. Averaging or voting then cancels much of the remaining error. In this lesson’s California Housing experiment, the unpruned tree had a test RMSE of 0.7312, and a forest of 200 trees with max_features=sqrt had a test RMSE of 0.4875."
        },
        {
          "q": "What does each round of gradient boosting fit?",
          "a": "In Friedman’s (2001) gradient boosting, each round takes a step in function space along the negative gradient of the loss with respect to the current prediction. When the loss is squared error, that negative gradient is the residual. The new tree’s output is scaled by a small learning rate (shrinkage) before it is added. XGBoost additionally uses second derivatives (a Newton step) to set leaf values and to compute split gain."
        },
        {
          "q": "Do tree models need feature standardisation?",
          "a": "Usually not. A split tests x_j ≤ t, so a monotone transformation or a standardisation of feature j does not change which side of the threshold a sample falls on. The scikit-learn decision-tree guide lists “little data preparation” as an advantage and notes that other methods often need normalisation. With the same random seed and max_depth=4, a regressor trained on raw features and one trained on StandardScaler features produced identical test predictions (maximum absolute difference 0) and the same test RMSE of 0.772620."
        },
        {
          "q": "When does XGBoost refuse a split?",
          "a": "The official tutorial writes the split gain as the score of the new left leaf plus the score of the new right leaf, minus the score of the original leaf, minus gamma. Gamma is the penalty for one extra leaf in the complexity term Ω(f) = γT + (1/2)λ∑w_j². If the gain is smaller than γ, the split does not reduce the objective and should not be made."
        },
        {
          "q": "Why does LightGBM treat num_leaves and min_data_in_leaf as the key parameters?",
          "a": "The official documentation states that LightGBM grows trees leaf-wise (best-first) by default: each step expands the leaf with the current largest gain, rather than growing a whole level at a time. That often reaches a lower loss sooner, but it can also grow a single path very deep. num_leaves caps the number of leaves and min_data_in_leaf prevents tiny leaves. Setting either of them too large tends to overfit."
        }
      ],
      "sources": [
        {
          "title": "scikit-learn user guide: 1.10 Decision Trees (Gini and entropy, CART, cost-complexity pruning)",
          "url": "https://scikit-learn.org/stable/modules/tree.html"
        },
        {
          "title": "scikit-learn user guide: 1.11 Ensembles (random forests, bagging, gradient boosting)",
          "url": "https://scikit-learn.org/stable/modules/ensemble.html"
        },
        {
          "title": "scikit-learn user guide: permutation feature importance",
          "url": "https://scikit-learn.org/stable/modules/permutation_importance.html"
        },
        {
          "title": "scikit-learn API: fetch_california_housing",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_california_housing.html"
        },
        {
          "title": "scikit-learn official examples",
          "url": "https://scikit-learn.org/stable/auto_examples/index.html"
        },
        {
          "title": "XGBoost official tutorial: Introduction to Boosted Trees",
          "url": "https://xgboost.readthedocs.io/en/stable/tutorials/model.html"
        },
        {
          "title": "XGBoost official documentation (parameters and Python API)",
          "url": "https://xgboost.readthedocs.io/en/stable/"
        },
        {
          "title": "Chen and Guestrin (2016), XGBoost: A Scalable Tree Boosting System, arXiv:1603.02754 (KDD 2016)",
          "url": "https://arxiv.org/abs/1603.02754"
        },
        {
          "title": "LightGBM official documentation: Features (histograms, leaf-wise growth, GOSS, EFB, categorical features)",
          "url": "https://lightgbm.readthedocs.io/en/stable/Features.html"
        },
        {
          "title": "LightGBM official documentation: Parameters Tuning (num_leaves, min_data_in_leaf)",
          "url": "https://lightgbm.readthedocs.io/en/stable/Parameters-Tuning.html"
        },
        {
          "title": "Ke, Meng, Finley et al. (2017), LightGBM: A Highly Efficient Gradient Boosting Decision Tree, NeurIPS 2017",
          "url": "https://papers.nips.cc/paper/2017/hash/6449f44a102fde848669bdd9eb6b76fa-Abstract.html"
        },
        {
          "title": "SHAP official documentation",
          "url": "https://shap.readthedocs.io/en/latest/"
        },
        {
          "title": "SHAP documentation: TreeExplainer",
          "url": "https://shap.readthedocs.io/en/latest/generated/shap.TreeExplainer.html"
        },
        {
          "title": "Lundberg and Lee (2017), A Unified Approach to Interpreting Model Predictions, arXiv:1705.07874",
          "url": "https://arxiv.org/abs/1705.07874"
        },
        {
          "title": "Breiman, Friedman, Olshen and Stone (1984), Classification And Regression Trees (CRC reprint DOI 10.1201/9781315139470)",
          "url": "https://doi.org/10.1201/9781315139470"
        },
        {
          "title": "Quinlan (1986), Induction of decision trees, Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00116251"
        },
        {
          "title": "Breiman (1996), Bagging predictors, Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00058655"
        },
        {
          "title": "Breiman (2001), Random Forests, Machine Learning",
          "url": "https://doi.org/10.1023/A:1010933404324"
        },
        {
          "title": "Freund and Schapire (1997), A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting, Journal of Computer and System Sciences",
          "url": "https://doi.org/10.1006/jcss.1997.1504"
        },
        {
          "title": "Freund and Schapire (1997), author-hosted PDF of the AdaBoost paper (Y. Freund, UC San Diego)",
          "url": "https://cseweb.ucsd.edu/~yfreund/papers/adaboost.pdf"
        },
        {
          "title": "Friedman (2001), Greedy function approximation: A gradient boosting machine, The Annals of Statistics",
          "url": "https://doi.org/10.1214/aos/1013203451"
        },
        {
          "title": "Google Machine Learning Crash Course: Decision Forests",
          "url": "https://developers.google.com/machine-learning/decision-forests"
        },
        {
          "title": "Google Decision Forests course: Introduction to gradient-boosted trees",
          "url": "https://developers.google.com/machine-learning/decision-forests/intro-to-gbdt"
        },
        {
          "title": "An Introduction to Statistical Learning (ISLP, freely available)",
          "url": "https://www.statlearning.com/"
        },
        {
          "title": "Kaggle Learn: Intermediate Machine Learning (includes an XGBoost exercise)",
          "url": "https://www.kaggle.com/learn/intermediate-machine-learning"
        }
      ],
      "url": "https://aimap.page/en/learn/math-ml/tree-ensembles/",
      "markdown": "**Summary.** A decision tree carves the input space into purer subsets with a sequence of feature thresholds. The rules are readable, but a single tree overfits easily. Combining many trees is one of the most widely used approaches on tabular data: a random forest reduces variance with bagging and feature sampling; gradient boosting fits residuals, or more generally the loss gradient, in sequence. This lesson proceeds from splits and pruning, through bagging and random forests, AdaBoost and gradient boosting, to XGBoost and LightGBM, and ends with a comparison and an explanation on the same data. Every figure in the text comes from the runnable example at the end, using scikit-learn 1.9.1, XGBoost 3.4.1, LightGBM 4.7.0 and SHAP 0.54.1, with `OMP_NUM_THREADS=3` and random seed 0.\n\nThis lesson belongs to the unit [Trees and Ensembles](/learn/unit/u21-trees). It builds on [Overfitting, Generalisation and Data Splits](/learn/generalization) and [The Machine Learning Workflow](/learn/ml-basics). The entropy subsection is consistent with [Probability, Statistics and Information Theory](/learn/probability-information). Related algorithm cards: [Decision Trees (CART)](/learn/algorithms/decision-tree), [Random Forests](/learn/algorithms/random-forest), [AdaBoost](/learn/algorithms/adaboost), [Gradient Boosting](/learn/algorithms/gbdt), [XGBoost](/learn/algorithms/xgboost) and [LightGBM](/learn/algorithms/lightgbm).\n\n## What problem do tree models solve?\n\nA tree partitions the input space into rectangular regions and predicts a constant in each region (the majority class or class probabilities for classification; the mean of the target for regression). Each split involves one feature and one threshold, which has several consequences:\n\n- The rule can be read as a sequence of if–then tests and is easy to visualise.\n- A split depends only on the order of the feature values, so standardisation is usually unnecessary. Some implementations can split on categorical features directly, without one-hot encoding. The scikit-learn 1.9 decision-tree documentation states that its CART implementation does not currently support categorical features; LightGBM and XGBoost can handle them directly when the corresponding options are enabled.\n- Trees are relatively insensitive to outliers and to the scale of the features, which is why they are a strong baseline on tabular problems such as house prices, credit scoring and click-through rates.\n\nImages and text, which have strong spatial or sequential structure, are usually a better fit for convolutional networks or Transformers than for an ordinary decision tree on raw pixels or tokens.\n\n## A single split: Gini impurity and information gain\n\nLet p_mk be the proportion of class k in node m. The scikit-learn decision-tree documentation gives two common classification impurities:\n\n- Gini impurity: `H = ∑_k p_k (1 − p_k)`. For two classes this is `2 p (1 − p)`. It is largest at `p = 0.5` and is 0 on a pure node.\n- Entropy (log loss): `H = − ∑_k p_k log p_k`. The numerical example below uses base 2; a pure node is again 0, and a balanced two-class node has entropy 1.\n\nA candidate split that produces a left child and a right child is scored by the size-weighted impurity:\n\n```text\nG(Q, t) = (n_L / n) H(Q_L) + (n_R / n) H(Q_R)\n```\n\nThe algorithm chooses the feature and threshold that minimise `G`. For entropy, the impurity of the parent minus `G` is the information gain; for Gini, the corresponding difference is the Gini gain. Regression replaces `H` with the within-region squared error (or another regression criterion), with the same structure.\n\nA 12-sample example with one numeric feature can be computed by hand. The root has six examples of each class, so the Gini impurity is 0.5000 and the entropy is 1.0000. Four candidate thresholds give the following results.\n\n| Threshold t | Left n / class counts | Right n / class counts | Weighted Gini | Gini gain | Weighted entropy | Information gain |\n|---|---|---|---|---|---|---|\n| 1.5 | 2 / [2, 0] | 10 / [4, 6] | 0.4000 | 0.1000 | 0.8091 | 0.1909 |\n| 2.5 | 4 / [4, 0] | 8 / [2, 6] | 0.2500 | 0.2500 | 0.5409 | 0.4591 |\n| 5.5 | 6 / [5, 1] | 6 / [1, 5] | 0.2778 | 0.2222 | 0.6500 | 0.3500 |\n| 8.5 | 8 / [5, 3] | 4 / [1, 3] | 0.4375 | 0.0625 | 0.9067 | 0.0933 |\n\nAmong these candidates the best split is `t = 2.5`, not the mid-gap value `t = 5.5`. For Gini, the left child at `t = 2.5` is pure (`H = 0`) and the right child has counts [2, 6], so `H = 2 × (2/8) × (6/8) = 0.375` and the weighted sum is `(8/12) × 0.375 = 0.2500`, a gain of 0.2500. At `t = 5.5` both sides are impure, the weighted Gini is 0.2778 and the gain is only 0.2222. The criterion is the drop in impurity, not the geometric midpoint on the feature axis.\n\nGrowth is greedy: each node chooses the best split for itself and does not backtrack. Stopping rules include reaching `max_depth`, having fewer than `min_samples_split` samples, or obtaining an impurity decrease smaller than `min_impurity_decrease` (see the scikit-learn documentation).\n\n## CART, ID3 and the scikit-learn implementation\n\nQuinlan’s ID3 (1986) uses information gain to make multi-way splits on categorical features, grows the tree to its full size and then prunes. C4.5 is its successor and removes the restriction that features must be categorical. CART (Classification and Regression Trees) by Breiman, Friedman, Olshen and Stone (1984) is close to C4.5, but it supports a numeric target (regression), grows a binary tree rather than a rule set, and uses cost-complexity pruning. The scikit-learn documentation states that it implements an optimised form of CART, choosing at each node the feature and threshold with the largest impurity decrease.\n\nThe CART book was first published by Wadsworth in 1984. The record used in this lesson to verify the title and authors is the CRC reprint (Crossref dates the reprint at 2017-10-19, DOI 10.1201/9781315139470); the year of first publication remains 1984.\n\n## Overfitting and cost-complexity pruning\n\nAn unconstrained tree can grow until almost every training example has its own leaf. scikit-learn writes minimal cost-complexity pruning as follows (the documentation points to Chapter 3 of the CART book):\n\n```text\nR_α(T) = R(T) + α |T̃|\n```\n\nHere `|T̃|` is the number of terminal nodes (leaves). In the traditional account `R(T)` is the total misclassification rate of the leaves; scikit-learn uses the total sample-weighted impurity instead. Larger `α ≥ 0` favours a smaller tree. The parameter name is `ccp_alpha`. In practice, pre-pruning parameters such as `max_depth` and `min_samples_leaf` are also common.\n\nThe experiment uses California Housing: 20,640 examples and eight features (MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude). The target is the median house value of a block group, in units of US$100,000. With `test_size=0.2` and `random_state=0` the split is 16,512 training rows and 4,128 test rows. The target has mean 2.0686, standard deviation 1.1539 and range 0.15 to 5.00. Training `DecisionTreeRegressor` at several values of `max_depth` (all other arguments left at their defaults) gives:\n\n| Max depth | Leaves | Train RMSE | Test RMSE |\n|---|---|---|---|\n| 1 | 2 | 0.9569 | 0.9660 |\n| 4 | 16 | 0.7391 | 0.7726 |\n| 8 | 236 | 0.5729 | 0.6679 |\n| 9 | 428 | 0.5254 | 0.6568 |\n| 12 | 1,895 | 0.3696 | 0.6714 |\n| 16 | 6,874 | 0.1746 | 0.7175 |\n| Unconstrained | 15,834 | 0.0000 | 0.7312 |\n\nTest RMSE is lowest at depth 9 (0.6568). Beyond that point the training error keeps falling while the test error rises. With no depth limit the tree has 15,834 leaves, close to the 16,512 training rows; the training RMSE is 0 and the test RMSE rises to 0.7312. That is a typical overfit.\n\n## Standardisation usually leaves the predictions unchanged\n\nThe scikit-learn documentation lists “little data preparation; other methods often require normalisation” among the advantages of decision trees. The reason is that a split tests `x_j ≤ t`. After the linear map `z_j = (x_j − μ_j) / σ_j` the threshold becomes `t' = (t − μ_j) / σ_j`, and each sample still falls on the same side.\n\nWith the same random seed and `max_depth=4`, a regressor trained on the raw features and one trained on `StandardScaler` features used the same split features, both had 16 leaves, the test predictions had a maximum absolute difference of 0, and both had a test RMSE of 0.772620. The thresholds match `(t − μ) / σ` to within floating-point error. Standardising features for a tree is therefore usually unnecessary, and it usually does not help; if a pipeline already contains a scaler, it generally will not change this tree’s predictions either.\n\n## Bagging and random forests\n\nA deep tree has high variance. Breiman’s bagging (bootstrap aggregating, 1996) draws bootstrap samples of the training set, fits a model on each sample, and averages the predictions (regression) or takes a vote (classification). For a bootstrap sample of size `n`, the probability that any given training point is left out is `(1 − 1/n)^n`. On this lesson’s training set, `n = 16,512`, that probability is 0.3679, which equals `1/e ≈ 0.3679`. The left-out points are the out-of-bag (OOB) sample and can be used to evaluate the model without a separate validation set.\n\nBreiman’s random forests (2001) add a second source of randomness on top of bagging: at each node the search for a split is restricted to a random subset of the features, whose size is controlled by `max_features`. The scikit-learn ensemble guide states that bootstrapping the samples and randomly selecting features at each split are there to reduce the variance of the forest estimator. The less correlated the trees, the more the average reduces variance.\n\nIn this lesson, a `RandomForestRegressor` with 200 trees and `max_features=\"sqrt\"` has a test RMSE of 0.4875 and a test R² of 0.8177. With `oob_score=True`, the OOB R² is also 0.8177. The agreement to four decimal places is a measurement on this split, not a general fact. OOB remains a useful approximation; scikit-learn’s notes on OOB estimates for gradient boosting also warn that they tend to be pessimistic, and that cross-validation should be preferred when it is affordable.\n\n## AdaBoost and gradient boosting\n\nBoosting runs in the opposite direction from bagging: models are added one after another, and later models concentrate on what the current ensemble has not yet fitted.\n\nAdaBoost, by Freund and Schapire (1997), was an early practical boosting algorithm. It trains a weak classifier (for example a very shallow tree), raises the weights of the examples it gets wrong, trains the next classifier, and finally takes a weighted vote. A random forest averages many trees in parallel; AdaBoost chains weak learners and weights them.\n\nFriedman (2001) writes boosting as gradient descent in function space. If the current model is `F_{t−1}`, the tree at step `t` is fitted to the negative gradient of the loss with respect to the current prediction. When the loss is squared error, that negative gradient is the residual `y − F_{t−1}(x)`. The new tree’s output is scaled by a small learning rate (shrinkage) before it is added, so that a single step cannot move too far. scikit-learn’s `GradientBoostingRegressor`, and later XGBoost and LightGBM, are built on this framework. Friedman (2002) also proposed stochastic gradient boosting: each round uses only a subset of the training examples (the documentation’s typical value is 0.5, drawn without replacement) and may also subsample features.\n\n## XGBoost: a regularised objective and second-order gain\n\nChen and Guestrin (2016) presented XGBoost as a scalable tree-boosting system at KDD 2016 (arXiv:1603.02754; conference DOI 10.1145/2939672.2939785). The official tutorial “Introduction to Boosted Trees” writes the objective as a training loss plus a regulariser:\n\n```text\nobj(θ) = L(θ) + Ω(θ)\nΩ(f) = γ T + (1/2) λ ∑_{j=1}^{T} w_j²\n```\n\n`T` is the number of leaves and `w_j` is the value of leaf `j`. `L` may be squared error, logistic loss, or another loss. Training is additive: each step learns one new tree. For a general loss the tutorial expands `L` to second order in a Taylor expansion and writes the step-`t` objective in terms of the first derivative `g_i` and the second derivative `h_i`. After summing the `g_i` and `h_i` that fall into a leaf as `G` and `H`, the gain from splitting one leaf into a left child and a right child is:\n\n```text\nGain = (1/2) [ G_L² / (H_L + λ) + G_R² / (H_R + λ) − (G_L + G_R)² / (H_L + H_R + λ) ] − γ\n```\n\nThe four terms are the score of the new left leaf, the score of the new right leaf, the score of the original leaf, and the regularisation penalty for the extra leaf. If the gain is smaller than `γ`, the split does not reduce the objective and should be refused. Whether to split is then part of the objective, rather than a separate heuristic.\n\nThe paper’s abstract also proposes a sparsity-aware algorithm for sparse data (missing values can follow a default direction) and a weighted quantile sketch for proposing approximate split points. It discusses cache access, compression and sharding so that the system can handle larger data with fewer resources. The learning rate (shrinkage) and column subsampling are further regularisers. The example in this lesson uses `tree_method=\"hist\"` (histogram approximate splitting), `n_estimators=300`, `learning_rate=0.1` and `max_depth=6`.\n\n## LightGBM: histograms, leaf-wise growth, GOSS and EFB\n\nLightGBM, by Ke, Meng, Finley, Wang, Chen, Ma, Ye and Liu (NeurIPS 2017), addresses the fact that conventional GBDT still scans all instances for every feature when it estimates split gain, which is costly in high dimension and on large samples. The paper introduces two techniques:\n\n- GOSS (Gradient-based One-Side Sampling): keep the examples with large gradients and subsample those with small gradients, so that gain can be estimated from fewer examples.\n- EFB (Exclusive Feature Bundling): bundle mutually exclusive features that rarely take non-zero values at the same time, which reduces the effective number of features. The paper proves that finding an optimal bundling is NP-hard, but a greedy algorithm can give a good approximation.\n\nOn several public data sets the paper reports a training speed-up of more than 20 times relative to conventional GBDT, with almost the same accuracy. Those figures are the paper’s results, not a reproduction in this lesson.\n\nThe official documentation emphasises two further implementation choices. A histogram algorithm buckets continuous features, which cuts the cost and memory of evaluating split gain. Trees grow leaf-wise (best-first) by default: each step expands only the current highest-gain leaf, rather than a whole level. Leaf-wise growth often reduces the loss faster, but it can also grow a single path too deep, so the documentation treats `num_leaves` and `min_data_in_leaf` as the main controls against overfitting. Categorical features can be split optimally without one-hot encoding. The example in this lesson uses `n_estimators=300`, `learning_rate=0.1` and `num_leaves=31` (the library’s default leaf count).\n\n## A comparison on the same split\n\nThe table below is a single comparison on the California Housing split above, with fixed hyperparameters and no grid search. It is meant to show how a single tree, bagging and boosting behave on the same data; it is not a claim that one implementation is always best. RMSE and MAE are in units of US$100,000.\n\n| Model | Train RMSE | Test RMSE | Test MAE | Test R² |\n|---|---|---|---|---|\n| Decision tree (unconstrained) | 0.0000 | 0.7312 | 0.4695 | 0.5900 |\n| Decision tree (`max_depth=8`) | 0.5729 | 0.6679 | 0.4662 | 0.6579 |\n| Random forest (200 trees, `max_features=sqrt`) | 0.1825 | 0.4875 | 0.3303 | 0.8177 |\n| scikit-learn gradient boosting (200 trees, learning rate 0.1, depth 3) | 0.4712 | 0.5053 | 0.3489 | 0.8042 |\n| XGBoost (300 trees, learning rate 0.1, depth 6) | 0.2703 | 0.4430 | 0.2926 | 0.8495 |\n| LightGBM (300 trees, learning rate 0.1, `num_leaves=31`) | 0.3057 | 0.4387 | 0.2931 | 0.8524 |\n\nA depth-limited tree already beats the unpruned tree on the test set, but it remains well behind the forest and the boosted models. The random forest brings test RMSE down from about 0.73 to about 0.49. With the settings in this lesson, LightGBM has a test RMSE of 0.4387 and XGBoost 0.4430; the two are close. Training times depend on the machine. In this run with three threads, the random forest took about 2.0 seconds, XGBoost about 0.27 seconds and LightGBM about 0.18 seconds; those figures are only a reference on the same machine.\n\n## Explaining the model with SHAP and permutation importance\n\nThe unit project asks for a comparison of a single tree, a random forest and XGBoost on the same data, and an explanation of the best model. Under the settings above, LightGBM has the lowest test RMSE (0.4387), so the explanation below is for that model. If the hyperparameters change, the best model may be XGBoost or another implementation; the steps stay the same.\n\nLundberg and Lee (2017) proposed SHAP, which decomposes a model prediction into feature contributions that satisfy a set of axioms consistent with Shapley values in cooperative game theory. In the official implementation, `TreeExplainer` provides an efficient algorithm for tree models. This lesson draws 400 test rows without replacement and reports `mean(|SHAP|)` for each feature. Permutation importance follows the scikit-learn documentation: shuffle one column and record the change in a chosen metric. The scoring rule here is `neg_root_mean_squared_error`, so the means in the table are the increase in test RMSE after that feature is shuffled, averaged over 10 repeats.\n\n| Feature | mean(|SHAP|) | Permutation importance (ΔRMSE) |\n|---|---|---|\n| Latitude | 0.4544 | 0.8057 ± 0.0098 |\n| MedInc | 0.3869 | 0.3908 ± 0.0094 |\n| Longitude | 0.3631 | 0.7116 ± 0.0058 |\n| AveOccup | 0.2095 | 0.1823 ± 0.0084 |\n| AveRooms | 0.1299 | 0.1220 ± 0.0047 |\n| HouseAge | 0.0500 | 0.0554 ± 0.0038 |\n| Population | 0.0246 | 0.0151 ± 0.0015 |\n| AveBedrms | 0.0239 | 0.0147 ± 0.0018 |\n\nBoth methods place latitude, longitude and median income (MedInc) at the top, which matches the fact that California house prices are sensitive to location and income. The internal ranking is not the same: in mean absolute SHAP, MedInc ranks above Longitude; in permutation importance, Longitude ranks above MedInc. That is not a contradiction. SHAP describes the average magnitude of a feature’s contribution to individual predictions under the fitted model; permutation importance describes how much test RMSE rises when the link between that feature and the target is broken. A single importance measure should not be used on its own, and feature importance should not be read as a causal claim.\n\n## Runnable example\n\nThe following code was run on scikit-learn 1.9.1, XGBoost 3.4.1, LightGBM 4.7.0 and SHAP 0.54.1. The numbers match the text above. The full script, including all twenty depth settings and the threshold comparison, is at `research/ai-algorithms/_work/daily/2026-11-22/tree_demo.py`. Setting `OMP_NUM_THREADS=3` is recommended.\n\n```python\nimport numpy as np\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.inspection import permutation_importance\nfrom xgboost import XGBRegressor\nfrom lightgbm import LGBMRegressor\nimport shap\n\n# 1) Toy split: balanced two-class root\nx = np.array([1, 1, 2, 2, 3, 3, 8, 8, 9, 9, 10, 10], dtype=float)\ny = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0])\n\ndef gini(c):\n    p = c / c.sum()\n    return float(np.sum(p * (1 - p)))\n\ndef entropy(c):\n    p = c[c > 0] / c.sum()\n    return float(-np.sum(p * np.log2(p)))\n\nroot = np.bincount(y)\nprint(\"root\", root, \"Gini\", round(gini(root), 4), \"entropy\", round(entropy(root), 4))\nfor t in (1.5, 2.5, 5.5, 8.5):\n    left, right = y[x <= t], y[x > t]\n    lc, rc = np.bincount(left, minlength=2), np.bincount(right, minlength=2)\n    n = len(y)\n    g = (len(left) * gini(lc) + len(right) * gini(rc)) / n\n    e = (len(left) * entropy(lc) + len(right) * entropy(rc)) / n\n    print(t, \"dGini\", round(gini(root) - g, 4), \"IG\", round(entropy(root) - e, 4))\n\n# 2) California Housing comparison\ndata = fetch_california_housing()\nX_tr, X_te, y_tr, y_te = train_test_split(\n    data.data, data.target, test_size=0.2, random_state=0\n)\nmodels = {\n    \"tree\": DecisionTreeRegressor(random_state=0),\n    \"tree_d8\": DecisionTreeRegressor(max_depth=8, random_state=0),\n    \"rf\": RandomForestRegressor(\n        n_estimators=200, max_features=\"sqrt\", random_state=0, n_jobs=3, oob_score=True\n    ),\n    \"gbm\": GradientBoostingRegressor(\n        n_estimators=200, learning_rate=0.1, max_depth=3, random_state=0\n    ),\n    \"xgb\": XGBRegressor(\n        n_estimators=300, learning_rate=0.1, max_depth=6,\n        tree_method=\"hist\", n_jobs=3, random_state=0, verbosity=0,\n    ),\n    \"lgbm\": LGBMRegressor(\n        n_estimators=300, learning_rate=0.1, num_leaves=31,\n        n_jobs=3, random_state=0, verbosity=-1,\n    ),\n}\nbest_name, best_est, best_rmse = None, None, None\nfor name, est in models.items():\n    est.fit(X_tr, y_tr)\n    pred = est.predict(X_te)\n    rmse = mean_squared_error(y_te, pred) ** 0.5\n    print(name, \"test_RMSE\", round(rmse, 4), \"MAE\", round(mean_absolute_error(y_te, pred), 4),\n          \"R2\", round(r2_score(y_te, pred), 4))\n    if best_rmse is None or rmse < best_rmse:\n        best_name, best_est, best_rmse = name, est, rmse\nprint(\"best\", best_name, best_rmse)\n\n# 3) SHAP and permutation importance (lowest test RMSE)\nidx = np.random.default_rng(0).choice(len(X_te), size=400, replace=False)\nsv = shap.TreeExplainer(best_est).shap_values(X_te[idx])\nprint(\"mean|SHAP|\", dict(zip(data.feature_names, np.mean(np.abs(sv), axis=0).round(4))))\nperm = permutation_importance(\n    best_est, X_te, y_te, n_repeats=10, random_state=0, n_jobs=3,\n    scoring=\"neg_root_mean_squared_error\",\n)\nprint(\"perm\", dict(zip(data.feature_names, perm.importances_mean.round(4))))\n```\n\nKey measured outputs: root Gini 0.5000, entropy 1.0000; at `t = 2.5` the Gini gain is 0.2500 and the information gain is 0.4591, both higher than 0.2222 and 0.3500 at `t = 5.5`. Test RMSE: unconstrained tree 0.7312, depth-8 tree 0.6679, random forest 0.4875 (OOB R² 0.8177), scikit-learn gradient boosting 0.5053, XGBoost 0.4430, LightGBM 0.4387. For LightGBM, the top three mean(|SHAP|) values are Latitude 0.4544, MedInc 0.3869 and Longitude 0.3631; the top three permutation importances are Latitude 0.8057, Longitude 0.7116 and MedInc 0.3908.\n\n## Exercises\n\n1. **Unit project.** On the same data set, compare a single decision tree, a random forest and XGBoost (LightGBM may be added), record the test error, and explain the model with the lowest test error using SHAP or permutation importance. You may reuse this lesson’s California Housing split or use your own tabular data. Fix the random seed and write down every hyperparameter.\n2. Complete the XGBoost exercise in [Kaggle Learn: Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning). Vary `n_estimators` and the learning rate and watch how the validation error changes.\n3. Run the ensemble examples in the [official scikit-learn example gallery](https://scikit-learn.org/stable/auto_examples/index.html), compare random forests, gradient boosting and AdaBoost, and change `max_depth`, `n_estimators` or `learning_rate`.\n4. Read the [XGBoost tutorial Introduction to Boosted Trees](https://xgboost.readthedocs.io/en/stable/tutorials/model.html) and check the gain formula by hand on a tree of depth 1. Then, using [LightGBM Parameters Tuning](https://lightgbm.readthedocs.io/en/stable/Parameters-Tuning.html), explain why `num_leaves=63` is not the same as a complete binary tree with `max_depth=6`.\n\n## Suggested reading order\n\nStart with the mathematical formulation and the CART subsection in the [scikit-learn decision-tree guide](https://scikit-learn.org/stable/modules/tree.html), and with the random-forest and gradient-boosting subsections of the [ensemble guide](https://scikit-learn.org/stable/modules/ensemble.html), to fix the contrast between a single tree, bagging and boosting. For a statistical-learning account, see the tree and ensemble chapters of the free textbook [An Introduction to Statistical Learning](https://www.statlearning.com/) and the [Google Decision Forests course](https://developers.google.com/machine-learning/decision-forests). For implementation details, read the [XGBoost tutorial](https://xgboost.readthedocs.io/en/stable/tutorials/model.html) and [LightGBM Features](https://lightgbm.readthedocs.io/en/stable/Features.html). For explanation, read the [SHAP documentation](https://shap.readthedocs.io/en/latest/) and the paper by Lundberg and Lee (2017). A natural next step in the same stage is linear models and support vector machines, or [Unsupervised Learning: Clustering, Dimensionality Reduction and EM](/learn/unsupervised-learning)."
    },
    "zh-hans": {
      "title": "树模型与集成学习：决策树、随机森林与梯度提升",
      "description": "面向机器学习实践的树模型与集成方法：CART 决策树的基尼不纯度与信息增益、代价复杂度剪枝、Bagging 与随机森林、AdaBoost、Friedman 的梯度提升，以及 XGBoost 与 LightGBM 的目标函数和工程设计。依据原始论文与 scikit-learn、XGBoost、LightGBM、SHAP 官方文档，并在 California Housing 数据集上给出可复现的对比与解释实验。",
      "updated": "2026-11-22",
      "takeaways": [
        "决策树用特征阈值把样本递归地分成更纯的子集。CART 构造二叉树，分类常用基尼不纯度，回归常用平方误差；一次划分的质量是左右子集不纯度的加权和，算法选择使该加权和最小的特征与阈值。",
        "单棵树很容易把训练集拟合到零误差，需要限制深度、叶子规模或做代价复杂度剪枝。划分只比较特征取值的顺序，因此对特征做标准化通常不会改变预测；本课在同一随机种子下得到完全相同的测试预测。",
        "Bagging 对有放回抽样得到的多个训练集分别建模再平均，用来降低方差；随机森林再在每个节点只使用随机抽取的一部分特征，使树与树去相关。Boosting 则顺序地加入模型：AdaBoost 提高上一轮分错样本的权重，梯度提升每轮拟合当前损失的负梯度（平方误差时即残差）。",
        "XGBoost 在正则化目标上用二阶泰勒展开确定叶子取值与分裂增益，增益小于 γ 时不分裂；论文还给出面向稀疏数据的分裂算法与用于近似分裂的加权分位数草图。LightGBM 用直方图、按叶生长（leaf-wise），以及论文中的 GOSS 与 EFB 来降低计算量，需用 num_leaves 与 min_data_in_leaf 控制过拟合。",
        "在 California Housing 的同一训练/测试划分上，未剪枝单棵树的测试 RMSE 为 0.7312，随机森林降到 0.4875，本课设定下的 LightGBM 为 0.4387、XGBoost 为 0.4430。SHAP 与置换重要性都把地理位置与收入标为主要因素，但二者的排序并不完全相同，因为它们回答的问题不同。"
      ],
      "faq": [
        {
          "q": "随机森林为何通常比单棵树更稳？",
          "a": "单棵深树方差大，容易随训练样本的波动而改变结构。随机森林对有放回抽样（Bagging）得到的训练集分别拟合一棵树，并在每个节点只在随机抽取的特征子集里寻找分裂，从而降低树与树的相关；再对预测取平均或投票，使各树的误差相互抵消。本课在 California Housing 上，未剪枝单棵树的测试 RMSE 为 0.7312，200 棵、max_features=sqrt 的随机森林为 0.4875。"
        },
        {
          "q": "梯度提升每一轮拟合什么？",
          "a": "按照 Friedman（2001）的梯度提升，每一轮在函数空间里沿损失对当前预测的负梯度下降。损失函数为平方误差时，这个负梯度就是残差。新树的输出再乘以一个较小的学习率（收缩，shrinkage）后加进模型。XGBoost 在此基础上用二阶导数（牛顿步）计算叶子取值与分裂增益。"
        },
        {
          "q": "树模型需要做特征标准化吗？",
          "a": "一般不需要。一次分裂比较的是某个特征上的排序或阈值，对特征做单调变换或标准化不会改变样本落在阈值哪一侧。scikit-learn 决策树文档也写明，树模型通常只需要很少的数据准备，而其他方法往往需要归一化。本课用同一随机种子、最大深度 4 的回归树，在原始特征与 Standardized 特征上得到完全相同的测试预测（最大绝对差为 0），测试 RMSE 同为 0.772620。"
        },
        {
          "q": "XGBoost 在什么情况下会放弃一次分裂？",
          "a": "官方教程给出的分裂增益是左右新叶得分之和减去原叶得分，再减去 γ。γ 是复杂度项 ω(f)=γT+(1/2)λ∑w_j² 里对一片新叶子的惩罚。增益小于 γ 时，这次分裂不会降低目标函数，因此不应进行。"
        },
        {
          "q": "LightGBM 为什么把 num_leaves 和 min_data_in_leaf 当作关键参数？",
          "a": "官方文档说明 LightGBM 默认按 leaf-wise（最佳优先）生长：每一步扩展当前增益最大的叶子，而不是整层一起长。这样往往比按层生长更低的损失，也更容易在某条路径上长得很深。因此需要用 num_leaves 限制叶子总数，用 min_data_in_leaf 避免过小的叶子。二者过大都容易过拟合。"
        }
      ],
      "sources": [
        {
          "title": "scikit-learn 用户指南：1.10 Decision Trees（基尼与熵、CART、代价复杂度剪枝）",
          "url": "https://scikit-learn.org/stable/modules/tree.html"
        },
        {
          "title": "scikit-learn 用户指南：1.11 Ensembles（随机森林、Bagging、梯度提升）",
          "url": "https://scikit-learn.org/stable/modules/ensemble.html"
        },
        {
          "title": "scikit-learn 用户指南：置换特征重要性",
          "url": "https://scikit-learn.org/stable/modules/permutation_importance.html"
        },
        {
          "title": "scikit-learn API：fetch_california_housing",
          "url": "https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_california_housing.html"
        },
        {
          "title": "scikit-learn 官方示例库",
          "url": "https://scikit-learn.org/stable/auto_examples/index.html"
        },
        {
          "title": "XGBoost 官方教程：Introduction to Boosted Trees",
          "url": "https://xgboost.readthedocs.io/en/stable/tutorials/model.html"
        },
        {
          "title": "XGBoost 官方文档（参数与 Python API）",
          "url": "https://xgboost.readthedocs.io/en/stable/"
        },
        {
          "title": "Chen、Guestrin（2016），XGBoost: A Scalable Tree Boosting System，arXiv:1603.02754（KDD 2016）",
          "url": "https://arxiv.org/abs/1603.02754"
        },
        {
          "title": "LightGBM 官方文档：Features（直方图、leaf-wise、GOSS、EFB、类别特征）",
          "url": "https://lightgbm.readthedocs.io/en/stable/Features.html"
        },
        {
          "title": "LightGBM 官方文档：Parameters Tuning（num_leaves、min_data_in_leaf）",
          "url": "https://lightgbm.readthedocs.io/en/stable/Parameters-Tuning.html"
        },
        {
          "title": "Ke、Meng、Finley 等（2017），LightGBM: A Highly Efficient Gradient Boosting Decision Tree，NeurIPS 2017",
          "url": "https://papers.nips.cc/paper/2017/hash/6449f44a102fde848669bdd9eb6b76fa-Abstract.html"
        },
        {
          "title": "SHAP 官方文档",
          "url": "https://shap.readthedocs.io/en/latest/"
        },
        {
          "title": "SHAP 文档：TreeExplainer",
          "url": "https://shap.readthedocs.io/en/latest/generated/shap.TreeExplainer.html"
        },
        {
          "title": "Lundberg、Lee（2017），A Unified Approach to Interpreting Model Predictions，arXiv:1705.07874",
          "url": "https://arxiv.org/abs/1705.07874"
        },
        {
          "title": "Breiman、Friedman、Olshen、Stone（1984），Classification And Regression Trees（CRC 再版 DOI 10.1201/9781315139470）",
          "url": "https://doi.org/10.1201/9781315139470"
        },
        {
          "title": "Quinlan（1986），Induction of decision trees，Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00116251"
        },
        {
          "title": "Breiman（1996），Bagging predictors，Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00058655"
        },
        {
          "title": "Breiman（2001），Random Forests，Machine Learning",
          "url": "https://doi.org/10.1023/A:1010933404324"
        },
        {
          "title": "Freund、Schapire（1997），A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting，Journal of Computer and System Sciences",
          "url": "https://doi.org/10.1006/jcss.1997.1504"
        },
        {
          "title": "Freund、Schapire（1997），AdaBoost 论文作者公开 PDF（Y. Freund，UC San Diego）",
          "url": "https://cseweb.ucsd.edu/~yfreund/papers/adaboost.pdf"
        },
        {
          "title": "Friedman（2001），Greedy function approximation: A gradient boosting machine，The Annals of Statistics",
          "url": "https://doi.org/10.1214/aos/1013203451"
        },
        {
          "title": "Google 机器学习课程：决策森林",
          "url": "https://developers.google.com/machine-learning/decision-forests"
        },
        {
          "title": "Google 决策森林课程：梯度提升入门",
          "url": "https://developers.google.com/machine-learning/decision-forests/intro-to-gbdt"
        },
        {
          "title": "An Introduction to Statistical Learning（ISLP，免费教材）",
          "url": "https://www.statlearning.com/"
        },
        {
          "title": "Kaggle Learn：Intermediate Machine Learning（含 XGBoost 练习）",
          "url": "https://www.kaggle.com/learn/intermediate-machine-learning"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/math-ml/tree-ensembles/",
      "markdown": "**概要**：决策树用一系列特征阈值把样本分成更纯的子集，规则清楚，但单棵树容易过拟合。把许多棵树组合起来，是表格数据上最常用的一类方法：随机森林通过 Bagging 与特征抽样降低方差；梯度提升则顺序地拟合当前模型的残差或损失梯度。本课按“单棵树的分裂与剪枝 → Bagging 与随机森林 → AdaBoost 与梯度提升 → XGBoost 与 LightGBM → 同一数据上的对比与解释”展开。文中实验数字均来自文末可运行示例，环境为 scikit-learn 1.9.1、XGBoost 3.4.1、LightGBM 4.7.0、SHAP 0.54.1，`OMP_NUM_THREADS=3`，随机种子 0。\n\n本课属于[树模型与集成学习](/learn/unit/u21-trees)单元，前置为[过拟合、泛化与数据划分](/learn/generalization)和[机器学习流程](/learn/ml-basics)。信息熵一节与[概率、统计与信息论](/learn/probability-information)一致。相关算法卡：[决策树（CART）](/learn/algorithms/decision-tree)、[随机森林](/learn/algorithms/random-forest)、[AdaBoost](/learn/algorithms/adaboost)、[梯度提升树](/learn/algorithms/gbdt)、[XGBoost](/learn/algorithms/xgboost)、[LightGBM](/learn/algorithms/lightgbm)。\n\n## 决策树解决什么问题\n\n树模型把输入空间切成若干矩形区域，每个区域给出一个常数预测（分类时是多数类或类别概率，回归时是该区域目标值的均值）。一次分裂只涉及一个特征与一个阈值，因此：\n\n- 规则可以用“如果……那么……”读出来，也便于可视化。\n- 分裂只看特征值的排序，一般不必做标准化；类别特征在一些实现里可以直接切分，不必先做独热编码。scikit-learn 1.9 的决策树文档写明，其 CART 实现目前还不支持类别特征；LightGBM 与 XGBoost 则可以在启用相应选项后直接处理类别特征。\n- 对异常值和特征量纲相对不敏感，因此在表格数据（房屋价格、信用评分、点击率等）上经常作为强基线。\n\n图像、文本这类有强空间或序列结构的数据，通常更适合卷积网络或 Transformer，而不是把像素或 token 直接交给一棵普通决策树。\n\n## 一次分裂：基尼不纯度与信息增益\n\n设节点 m 中，第 k 类的样本占比为 p_mk。scikit-learn 决策树文档给出两类常用的分类不纯度：\n\n- 基尼不纯度：`H = ∑_k p_k (1 − p_k)`。两类时等于 `2 p (1 − p)`，在 `p = 0.5` 时最大，在纯节点上为 0。\n- 熵（对数损失）：`H = − ∑_k p_k log p_k`。下面的数值示例用 2 为底，纯节点同样为 0，两类各半时为 1。\n\n一次候选分裂把节点分成左右两部分，质量用左右不纯度的加权和衡量：\n\n```text\nG(Q, t) = (n_L / n) H(Q_L) + (n_R / n) H(Q_R)\n```\n\n算法在特征和阈值中选择使 `G` 最小的分裂。对熵而言，根节点熵减去 `G` 就是信息增益；对基尼而言，相应差值是基尼增益。回归任务把 `H` 换成区域内的平方误差（或其他回归准则），思想相同。\n\n用 12 个样本、一个数值特征的例子可以直接算完。根节点两类各 6 个，基尼为 0.5000，熵为 1.0000。四个候选阈值的结果如下。\n\n| 阈值 t | 左侧 n / 类别计数 | 右侧 n / 类别计数 | 加权基尼 | 基尼增益 | 加权熵 | 信息增益 |\n|---|---|---|---|---|---|---|\n| 1.5 | 2 / [2, 0] | 10 / [4, 6] | 0.4000 | 0.1000 | 0.8091 | 0.1909 |\n| 2.5 | 4 / [4, 0] | 8 / [2, 6] | 0.2500 | 0.2500 | 0.5409 | 0.4591 |\n| 5.5 | 6 / [5, 1] | 6 / [1, 5] | 0.2778 | 0.2222 | 0.6500 | 0.3500 |\n| 8.5 | 8 / [5, 3] | 4 / [1, 3] | 0.4375 | 0.0625 | 0.9067 | 0.0933 |\n\n在这些候选中，最好的是 `t = 2.5`，而不是落在两类中心之间的 `t = 5.5`。以基尼为例：`t = 2.5` 的左侧是纯的（`H = 0`），右侧类别计数 [2, 6]，`H = 2 × (2/8) × (6/8) = 0.375`，加权和为 `(8/12) × 0.375 = 0.2500`，增益 0.2500；`t = 5.5` 左右都不纯，加权基尼为 0.2778，增益只有 0.2222。分裂看的是不纯度下降，不是特征轴上的“几何中点”。\n\n树的生长是贪心的：每个节点只为当前节点选最优分裂，不回溯。停止条件包括达到 `max_depth`、样本数小于 `min_samples_split`，或本次不纯度下降小于 `min_impurity_decrease`（见 scikit-learn 文档）。\n\n## CART、ID3 与 scikit-learn 的实现\n\nQuinlan（1986）的 ID3 用信息增益在类别特征上做多路分裂，树先长到最大再剪枝。C4.5 是它的后继，去掉了“特征必须是类别型”的限制。Breiman、Friedman、Olshen 与 Stone（1984）的 CART（Classification and Regression Trees）与 C4.5 相近，但支持数值型目标（回归），输出是二叉树而不是规则集，并使用代价复杂度剪枝。scikit-learn 文档写明：它实现的是优化过的 CART；分裂在每个节点选择使不纯度下降最大的特征与阈值。\n\nCART 原书于 1984 年由 Wadsworth 出版。本课用来核验题名与作者的是 CRC 再版（Crossref 记录的再版日期为 2017-10-19，DOI 10.1201/9781315139470），引用年份仍以 1984 年首版为准。\n\n## 过拟合与代价复杂度剪枝\n\n未加限制的树可以长到几乎每个训练样本一片叶子。scikit-learn 把最小代价复杂度剪枝写为（文档指向 CART 原书第 3 章）：\n\n```text\nR_α(T) = R(T) + α |T̃|\n```\n\n其中 `|T̃|` 是终端节点（叶子）个数，`R(T)` 在传统叙述里是叶子上的总误分率，scikit-learn 则使用叶子上按样本加权的总不纯度。`α ≥ 0` 越大，越偏向更小的树；参数名是 `ccp_alpha`。实务中也常用 `max_depth`、`min_samples_leaf` 等预剪枝参数。\n\n下面的实验用 California Housing：20,640 条样本、8 个特征（MedInc、HouseAge、AveRooms、AveBedrms、Population、AveOccup、Latitude、Longitude），目标是街区中位数房价，单位为 10 万美元。按 `test_size=0.2`、`random_state=0` 划分后，训练集 16,512 条，测试集 4,128 条。目标值均值为 2.0686，标准差 1.1539，范围为 0.15 到 5.00。在不同 `max_depth` 下训练 `DecisionTreeRegressor`（其余为默认值）：\n\n| 最大深度 | 叶子数 | 训练 RMSE | 测试 RMSE |\n|---|---|---|---|\n| 1 | 2 | 0.9569 | 0.9660 |\n| 4 | 16 | 0.7391 | 0.7726 |\n| 8 | 236 | 0.5729 | 0.6679 |\n| 9 | 428 | 0.5254 | 0.6568 |\n| 12 | 1,895 | 0.3696 | 0.6714 |\n| 16 | 6,874 | 0.1746 | 0.7175 |\n| 不限制 | 15,834 | 0.0000 | 0.7312 |\n\n测试 RMSE 在深度 9 时最低（0.6568），之后训练误差继续下降，测试误差回升。不限制深度时，叶子数 15,834，已接近训练样本数 16,512，训练 RMSE 为 0，测试 RMSE 升至 0.7312，是典型的过拟合。\n\n## 标准化通常不改变树的预测\n\nscikit-learn 文档把“很少需要数据准备，其他方法往往需要归一化”列为决策树的优点之一。原因是：分裂比较的是 `x_j ≤ t`，对第 `j` 个特征做线性变换 `z_j = (x_j − μ_j) / σ_j` 之后，阈值变成 `t' = (t − μ_j) / σ_j`，样本落在哪一侧不变。\n\n用同一随机种子、`max_depth=4` 的回归树，分别在原始特征与 `StandardScaler` 变换后的特征上训练：树的分裂特征完全相同，叶子数都是 16，测试预测的最大绝对差为 0，测试 RMSE 同为 0.772620。阈值与 `(t − μ) / σ` 在浮点误差范围内一致。因此，为树模型做特征标准化通常既无必要，也不会带来好处；若流水线里已经有标准化步骤，一般也不会破坏这棵树的预测。\n\n## Bagging 与随机森林\n\n单棵深树的方差大。Breiman（1996）的 Bagging（bootstrap aggregating）对训练集做有放回抽样，在每个自助样本上训练一个模型，再把预测平均（回归）或投票（分类）。对容量为 `n` 的有放回样本，任意一个训练点未被抽中的概率是 `(1 − 1/n)^n`，在本课训练集 `n = 16,512` 时等于 0.3679，与 `1/e ≈ 0.3679` 一致。这些未被抽中的样本称为袋外（out-of-bag, OOB）样本，可用来评估模型，而不必再留一份验证集。\n\nBreiman（2001）的随机森林在 Bagging 之上增加第二项随机性：每个节点只在随机抽取的特征子集里寻找最佳分裂，子集大小由 `max_features` 控制。scikit-learn 集成方法文档指出，对样本做自助抽样、再在节点上随机选特征，目的是降低森林估计量的方差。树与树越不相关，平均后的方差下降越明显。\n\n本课中，200 棵树、`max_features=\"sqrt\"` 的 `RandomForestRegressor` 测试 RMSE 为 0.4875，测试 R² 为 0.8177；同时打开 `oob_score=True` 得到的 OOB R² 为 0.8177。OOB 与测试集在小数点后四位上相同，是这一次划分里的实测结果，并不是一般性结论。OOB 仍是有用的近似，scikit-learn 对梯度提升的 OOB 估计也提醒：它往往偏保守，在负担得起的时候应优先用交叉验证。\n\n## AdaBoost 与梯度提升\n\nBoosting 与 Bagging 的方向不同：模型是顺序加入的，后面的模型专门处理前面还没拟合好的部分。\n\nFreund 与 Schapire（1997）的 AdaBoost 是早期实用的提升算法。它先训练一个弱分类器（例如很浅的树），提高被分错样本的权重，再训练下一个，最后按各弱分类器的加权结果投票。随机森林是许多树并行平均，AdaBoost 是许多弱学习器串行加权。\n\nFriedman（2001）把提升写成函数空间中的梯度下降：设当前模型为 `F_{t−1}`，第 `t` 棵树去拟合损失函数对当前预测的负梯度。当损失是平方误差时，这个负梯度就是残差 `y − F_{t−1}(x)`。新树的输出乘以一个较小的学习率（收缩，shrinkage）后再加进模型，以免一步走得太远。scikit-learn 的 `GradientBoostingRegressor` 以及后面的 XGBoost、LightGBM，都以这一框架为基础。Friedman（2002）还提出随机梯度提升：每一轮只使用一部分训练样本（文档中的典型取值是 0.5，且无放回），并可再对特征做子抽样。\n\n## XGBoost：正则化目标与二阶增益\n\nChen 与 Guestrin（2016）的 XGBoost 把梯度提升做成一个可扩展的系统，并在 KDD 2016 发表（arXiv:1603.02754，会议 DOI 10.1145/2939672.2939785）。官方教程“Introduction to Boosted Trees”把目标写成训练损失加正则：\n\n```text\nobj(θ) = L(θ) + Ω(θ)\nΩ(f) = γ T + (1/2) λ ∑_{j=1}^{T} w_j²\n```\n\n`T` 是叶子数，`w_j` 是第 `j` 片叶子的取值。`L` 可以是平方误差或逻辑损失等。模型按加法方式训练，每一步只学习一棵新树。对一般损失，教程把 `L` 展开到二阶泰勒项，用一阶导数 `g_i` 与二阶导数 `h_i` 来写第 `t` 步的目标。把落入一片叶子的 `g_i`、`h_i` 分别记为 `G`、`H` 后，一次“把一片叶子分成左右”的增益是：\n\n```text\nGain = (1/2) [ G_L² / (H_L + λ) + G_R² / (H_R + λ) − (G_L + G_R)² / (H_L + H_R + λ) ] − γ\n```\n\n四项依次是：新左叶得分、新右叶得分、原叶得分，以及对多出来那片叶子的正则惩罚。增益小于 `γ` 时，这次分裂不会降低目标，应当放弃。这把“要不要再分”从启发式剪枝写成了目标函数的一部分。\n\n论文摘要还提出：面向稀疏数据的分裂算法（缺失值可进入默认方向），以及用于近似分裂点提议的加权分位数草图；并讨论缓存访问、压缩与分片，使系统能在更少资源下处理更大规模的数据。学习率（收缩）与按列子抽样也是常用的正则手段。本课示例使用 `tree_method=\"hist\"`（直方图近似分裂），`n_estimators=300`，`learning_rate=0.1`，`max_depth=6`。\n\n## LightGBM：直方图、按叶生长、GOSS 与 EFB\n\nKe、Meng、Finley、Wang、Chen、Ma、Ye 与 Liu（NeurIPS 2017）的 LightGBM 针对高维、大样本时传统 GBDT 仍要对每个特征扫描全部样本来估计分裂增益的问题，提出两种技术：\n\n- GOSS（Gradient-based One-Side Sampling）：保留梯度较大的样本，对梯度较小的样本做抽样，用更少的样本估计增益。\n- EFB（Exclusive Feature Bundling）：把很少同时取非零值的互斥特征捆在一起，减少有效特征数。论文指出，求最优捆绑是 NP 难的，但贪心算法可以给出较好的近似。\n\n论文在多个公开数据集上报告：相对传统 GBDT，训练可加快至超过 20 倍，同时准确率几乎相同。这是原文中的实验结果，不是本课复现的数字。\n\n官方文档还强调另外两项实现选择。直方图算法把连续特征分桶，从而降低分裂增益的计算与内存。树默认按 leaf-wise（最佳优先）生长：每一步只扩展当前增益最大的那片叶子，而不是整层一起长。按叶生长往往下降更快，也更容易在某一条路径上过深，因此文档把 `num_leaves` 与 `min_data_in_leaf` 列为控制过拟合的关键参数。类别特征可以按最优切分处理，而不必先做独热编码。本课示例使用 `n_estimators=300`，`learning_rate=0.1`，`num_leaves=31`（库的默认叶子数）。\n\n## 同一划分上的模型比较\n\n下表是在上述 California Housing 划分上、固定超参数、未做网格搜索的一次对比。它用来说明“单棵树、装袋、提升”在同一数据上的相对行为，不能推广为某一实现总是最好。RMSE 与 MAE 的单位是 10 万美元。\n\n| 模型 | 训练 RMSE | 测试 RMSE | 测试 MAE | 测试 R² |\n|---|---|---|---|---|\n| 决策树（不限制深度） | 0.0000 | 0.7312 | 0.4695 | 0.5900 |\n| 决策树（`max_depth=8`） | 0.5729 | 0.6679 | 0.4662 | 0.6579 |\n| 随机森林（200 棵，`max_features=sqrt`） | 0.1825 | 0.4875 | 0.3303 | 0.8177 |\n| scikit-learn 梯度提升（200 棵，学习率 0.1，深度 3） | 0.4712 | 0.5053 | 0.3489 | 0.8042 |\n| XGBoost（300 棵，学习率 0.1，深度 6） | 0.2703 | 0.4430 | 0.2926 | 0.8495 |\n| LightGBM（300 棵，学习率 0.1，`num_leaves=31`） | 0.3057 | 0.4387 | 0.2931 | 0.8524 |\n\n限制深度后，单棵树的测试误差已经优于未剪枝树，但仍明显差于森林与提升。随机森林把测试 RMSE 从 0.73 降到 0.49 附近；本课设定下，LightGBM 的测试 RMSE 为 0.4387，XGBoost 为 0.4430，二者接近。训练时间随机器而变，本课脚本在 3 线程下，随机森林约 2.0 秒，XGBoost 约 0.27 秒，LightGBM 约 0.18 秒，仅作为同一台机器上的参考。\n\n## 用 SHAP 与置换重要性解释\n\n项目要求在同一数据上比较单棵树、随机森林与 XGBoost，并对最好的模型做解释。本课设定下测试 RMSE 最低的是 LightGBM（0.4387），下面的解释针对这一模型；若改超参数，最优模型可能变成 XGBoost 或其他实现，步骤相同。\n\nLundberg 与 Lee（2017）提出 SHAP，把模型预测分解为各特征的贡献，并使这些贡献满足一组与合作博弈中 Shapley 值一致的公理。官方实现里的 `TreeExplainer` 针对树模型提供高效算法。本课在测试集中无放回抽取 400 条样本，计算每个特征 `mean(|SHAP|)`。置换重要性则按 scikit-learn 文档：打乱某一列后观察预定指标的变化。这里的评分是 `neg_root_mean_squared_error`，因此表中的均值是“打乱该特征后测试 RMSE 增加了多少”，重复 10 次。\n\n| 特征 | mean(|SHAP|) | 置换重要性（ΔRMSE） |\n|---|---|---|\n| Latitude | 0.4544 | 0.8057 ± 0.0098 |\n| MedInc | 0.3869 | 0.3908 ± 0.0094 |\n| Longitude | 0.3631 | 0.7116 ± 0.0058 |\n| AveOccup | 0.2095 | 0.1823 ± 0.0084 |\n| AveRooms | 0.1299 | 0.1220 ± 0.0047 |\n| HouseAge | 0.0500 | 0.0554 ± 0.0038 |\n| Population | 0.0246 | 0.0151 ± 0.0015 |\n| AveBedrms | 0.0239 | 0.0147 ± 0.0018 |\n\n两种方法都把纬度、经度与中位数收入（MedInc）排在最前面，这与加州房价对区位和收入敏感的常识一致。二者的内部排序并不相同：SHAP 的均值绝对值里 MedInc 高于 Longitude，置换重要性则把 Longitude 放在 MedInc 之前。这并不矛盾。SHAP 描述的是：在已有模型里，该特征对单条预测的平均贡献幅度；置换重要性描述的是：破坏该特征与目标的关系之后，测试 RMSE 上升多少。解释模型时不应只用一种指标，也不应把特征重要性当成因果关系。\n\n## 可运行示例\n\n以下代码在 scikit-learn 1.9.1、XGBoost 3.4.1、LightGBM 4.7.0、SHAP 0.54.1 上实测，输出与上文数字一致。完整脚本（含深度曲线全部 20 档与阈值对照）在 `research/ai-algorithms/_work/daily/2026-11-22/tree_demo.py`。建议设置 `OMP_NUM_THREADS=3`。\n\n```python\nimport numpy as np\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.inspection import permutation_importance\nfrom xgboost import XGBRegressor\nfrom lightgbm import LGBMRegressor\nimport shap\n\n# 1) 玩具分裂：根节点两类各半\nx = np.array([1, 1, 2, 2, 3, 3, 8, 8, 9, 9, 10, 10], dtype=float)\ny = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0])\n\ndef gini(c):\n    p = c / c.sum()\n    return float(np.sum(p * (1 - p)))\n\ndef entropy(c):\n    p = c[c > 0] / c.sum()\n    return float(-np.sum(p * np.log2(p)))\n\nroot = np.bincount(y)\nprint(\"root\", root, \"Gini\", round(gini(root), 4), \"entropy\", round(entropy(root), 4))\nfor t in (1.5, 2.5, 5.5, 8.5):\n    left, right = y[x <= t], y[x > t]\n    lc, rc = np.bincount(left, minlength=2), np.bincount(right, minlength=2)\n    n = len(y)\n    g = (len(left) * gini(lc) + len(right) * gini(rc)) / n\n    e = (len(left) * entropy(lc) + len(right) * entropy(rc)) / n\n    print(t, \"dGini\", round(gini(root) - g, 4), \"IG\", round(entropy(root) - e, 4))\n\n# 2) California Housing 对比\ndata = fetch_california_housing()\nX_tr, X_te, y_tr, y_te = train_test_split(\n    data.data, data.target, test_size=0.2, random_state=0\n)\nmodels = {\n    \"tree\": DecisionTreeRegressor(random_state=0),\n    \"tree_d8\": DecisionTreeRegressor(max_depth=8, random_state=0),\n    \"rf\": RandomForestRegressor(\n        n_estimators=200, max_features=\"sqrt\", random_state=0, n_jobs=3, oob_score=True\n    ),\n    \"gbm\": GradientBoostingRegressor(\n        n_estimators=200, learning_rate=0.1, max_depth=3, random_state=0\n    ),\n    \"xgb\": XGBRegressor(\n        n_estimators=300, learning_rate=0.1, max_depth=6,\n        tree_method=\"hist\", n_jobs=3, random_state=0, verbosity=0,\n    ),\n    \"lgbm\": LGBMRegressor(\n        n_estimators=300, learning_rate=0.1, num_leaves=31,\n        n_jobs=3, random_state=0, verbosity=-1,\n    ),\n}\nbest_name, best_est, best_rmse = None, None, None\nfor name, est in models.items():\n    est.fit(X_tr, y_tr)\n    pred = est.predict(X_te)\n    rmse = mean_squared_error(y_te, pred) ** 0.5\n    print(name, \"test_RMSE\", round(rmse, 4), \"MAE\", round(mean_absolute_error(y_te, pred), 4),\n          \"R2\", round(r2_score(y_te, pred), 4))\n    if best_rmse is None or rmse < best_rmse:\n        best_name, best_est, best_rmse = name, est, rmse\nprint(\"best\", best_name, best_rmse)\n\n# 3) SHAP 与置换重要性（以测试 RMSE 最低的模型为准）\nidx = np.random.default_rng(0).choice(len(X_te), size=400, replace=False)\nsv = shap.TreeExplainer(best_est).shap_values(X_te[idx])\nprint(\"mean|SHAP|\", dict(zip(data.feature_names, np.mean(np.abs(sv), axis=0).round(4))))\nperm = permutation_importance(\n    best_est, X_te, y_te, n_repeats=10, random_state=0, n_jobs=3,\n    scoring=\"neg_root_mean_squared_error\",\n)\nprint(\"perm\", dict(zip(data.feature_names, perm.importances_mean.round(4))))\n```\n\n实测输出要点：根节点基尼 0.5000、熵 1.0000；`t = 2.5` 的基尼增益 0.2500、信息增益 0.4591，高于 `t = 5.5` 的 0.2222 与 0.3500。测试 RMSE：未剪枝树 0.7312，深度 8 的树 0.6679，随机森林 0.4875（OOB R² 0.8177），scikit-learn 梯度提升 0.5053，XGBoost 0.4430，LightGBM 0.4387。LightGBM 的 mean(|SHAP|) 前三项为 Latitude 0.4544、MedInc 0.3869、Longitude 0.3631；置换重要性前三项为 Latitude 0.8057、Longitude 0.7116、MedInc 0.3908。\n\n## 动手练习\n\n1. **单元项目**：在同一数据集上比较单棵决策树、随机森林与 XGBoost（可再加入 LightGBM），记录测试误差，并用 SHAP（或置换重要性）解释测试误差最低的模型。可以沿用本课的 California Housing 划分，也可以换成你自己的表格数据；请固定随机种子并写明全部超参数。\n2. 在 [Kaggle Learn：Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning) 中完成 XGBoost 练习，调节 `n_estimators` 与学习率，观察验证误差如何变化。\n3. 运行 [scikit-learn 官方示例库](https://scikit-learn.org/stable/auto_examples/index.html)里的集成方法示例，对比随机森林、梯度提升与 AdaBoost，并改动 `max_depth`、`n_estimators` 或 `learning_rate`。\n4. 阅读 [XGBoost 官方教程 Introduction to Boosted Trees](https://xgboost.readthedocs.io/en/stable/tutorials/model.html)，用一棵深度为 1 的树手工验算一页中的增益公式；再对照 [LightGBM Parameters Tuning](https://lightgbm.readthedocs.io/en/stable/Parameters-Tuning.html)，说明为什么 `num_leaves=63` 并不等价于 `max_depth=6` 的完全二叉树。\n\n## 推荐学习顺序\n\n先读 [scikit-learn 决策树指南](https://scikit-learn.org/stable/modules/tree.html)中的数学表述与 CART 一节，以及[集成方法指南](https://scikit-learn.org/stable/modules/ensemble.html)中随机森林与梯度提升两节，建立“单棵树、装袋、提升”的对照。统计学习的叙述可参考免费教材 [An Introduction to Statistical Learning](https://www.statlearning.com/) 中的树与集成章节，以及 [Google 决策森林课程](https://developers.google.com/machine-learning/decision-forests)。实现细节读 [XGBoost 教程](https://xgboost.readthedocs.io/en/stable/tutorials/model.html)与 [LightGBM Features](https://lightgbm.readthedocs.io/en/stable/Features.html)。解释模型时读 [SHAP 文档](https://shap.readthedocs.io/en/latest/)与 Lundberg、Lee（2017）的原文。随后可进入同一阶段的线性模型与支持向量机，或[无监督学习：聚类、降维与 EM](/learn/unsupervised-learning)。"
    }
  }
}