From one rule-based tree to a team of trees
Imagine deciding whether to bring an umbrella. You might first ask, “Is rain forecast?” and then, “How strong is the wind?” A decision tree makes predictions by following a sequence of tests like these. The questions are selected from training data rather than written manually by a programmer.
One decision tree is easy to inspect but can be unstable: a small change in the training data can sometimes produce a very different structure. Two common ensemble approaches try to improve predictions using many trees.
A random forest builds numerous diverse trees, usually using resampled examples and randomized feature choices, then aggregates their predictions. The goal is to reduce the instability of individual trees.
Gradient boosting builds models sequentially. Each new tree is fitted to improve an objective based on what the earlier ensemble still gets wrong. Its logic is different from simply averaging many independently built trees.
A useful mental model is: one tree makes a sequence of decisions; a random forest combines varied opinions; boosting iteratively corrects an ensemble. The details, evaluation, and limitations matter, but that distinction should stay clear as you go deeper.
A decision tree predicts by asking a sequence of questions about input features. A random forest combines predictions from many trees trained on varied samples and feature subsets. Boosting builds a sequence of models in which later models help correct weaknesses of the earlier ones. These approaches are especially useful for structured, or tabular, data such as transaction records, sensor readings, and customer information.
All three approaches are forms of supervised machine learning when used for classification or regression. They share the same basic task of learning relationships between input features and a target, but they differ in how they construct and combine predictions.
1. How a decision tree works
Definition: A decision tree is a predictive model that recursively divides the feature space into regions using decision rules and assigns a prediction to each resulting region.
Consider a simplified equipment-maintenance dataset with two features: operating temperature and whether a vibration alert is present. A trained tree might learn these rules:
The basic parts of a tree are:
- Root node: The first split, containing all training examples before division.
- Internal node: A question or test involving a feature.
- Branch: One possible outcome of a test.
- Leaf node: A terminal region that produces a prediction.
- Depth: The number of successive splits along a path, subject to the tree implementation’s depth convention.
For a new observation, the model follows a path from root to leaf. A classification leaf may predict the most common training class in that region and estimate class probabilities from class proportions. A regression leaf commonly predicts the mean target among training examples in that region.
The example above is easy to interpret, but learned trees may contain many more nodes and much less intuitive rules.
2. How trees choose splits
Tree training typically works greedily: at each node, the algorithm considers candidate splits and chooses one that improves a chosen measure of node quality. It then repeats this process on the resulting child nodes.
Classification: impurity
A classification split should ideally create groups that contain examples from fewer different classes. Two common impurity measures are Gini impurity and entropy.
For class probabilities within a node:
The term is treated as zero. Both measures are zero when all observations belong to one class. Higher values generally indicate more mixed class labels, though the numerical scales differ.
A candidate split is evaluated by comparing parent impurity with the weighted impurity of its child nodes:
Here, and are the numbers of observations in left and right children, and . A larger positive reduction means the split yields purer children according to the selected impurity measure.
Worked classification example
Suppose a node contains 10 observations: 6 positive and 4 negative. Its Gini impurity is:
A proposed split creates:
- Left child: 5 observations, all positive, with .
- Right child: 5 observations, 1 positive and 4 negative, with .
The weighted child impurity is:
The reduction is . The split makes the resulting groups substantially less mixed. Training compares such reductions across candidate splits and selects an allowed split with the strongest improvement.
Regression: reducing prediction error
For regression, a common splitting criterion is reduction in squared-error impurity. A split is useful when its child regions have target values more tightly clustered around their respective means. This leads the tree to predict different numerical values in different regions of the feature space.
3. Tree growth and overfitting
A tree with unrestricted depth can keep splitting until it fits details specific to its training data. It may achieve excellent training performance while performing poorly on unseen observations. This is overfitting.
Common controls include:
| Control | Effect |
|---|---|
max_depth | Limits how many levels a tree can grow. |
min_samples_split | Requires a minimum number of examples before a node can be split. |
min_samples_leaf | Requires a minimum number of training examples in each leaf. |
max_leaf_nodes | Limits the number of terminal regions. |
ccp_alpha | Applies cost-complexity pruning in supported scikit-learn trees. |
Pre-pruning constrains growth while the tree is being built. Post-pruning reduces the complexity of a tree after its initial construction. A smaller tree may generalize better, but overly restrictive settings can cause underfitting.
Decision trees can capture nonlinear effects and interactions without feature scaling. However, a single tree can be unstable: a small change in training examples may produce a substantially different tree structure.
4. Ensembles: combining several models
An ensemble combines multiple models to produce a final prediction. Its goal is often to improve predictive accuracy, stability, or robustness compared with an individual model.
Two important families are:
- Bagging: Train models using different resampled datasets, generally in parallel, and aggregate their outputs.
- Boosting: Train models sequentially so later models address errors or loss remaining from earlier stages.
These methods should not be confused with stacking, which learns a separate model to combine base-model predictions.
5. Random forests
Definition: A random forest is an ensemble of decision trees that uses randomized training samples and randomized feature selection to create a diverse collection of trees, then combines their predictions.
A typical random-forest training procedure is:
- Draw a bootstrap sample from the training set, sampling observations with replacement.
- Train a decision tree on that sample.
- At each split, consider a random subset of the available features rather than necessarily considering all features.
- Repeat to train many trees.
- Aggregate predictions: use class voting or averaged class probabilities for classification, and averaged tree outputs for regression.
The random feature subsets make trees less likely to all rely on the same dominant predictor. Bootstrapping introduces further differences. This diversity is important: simply averaging identical trees would provide little benefit.
Why random forests can outperform one tree
A deep tree often has low training bias but high variance: it can model complex relationships, yet its predictions may fluctuate when the training sample changes. Averaging many imperfectly correlated trees can reduce variance and improve generalization.
A forest does not guarantee better predictions in every problem. Its effectiveness depends on the available data, meaningful features, hyperparameters, and the evaluation method.
Out-of-bag evaluation
Each bootstrap sample leaves out some training observations. For a particular observation, trees that were not trained on it can provide an out-of-bag (OOB) prediction. Aggregating these predictions provides an internal performance estimate, although a properly held-out test set is still valuable for final assessment.
Important random-forest settings
n_estimators: Number of trees in the forest.max_features: Number or fraction of features examined when choosing a split.max_depth,min_samples_leaf: Controls on individual tree complexity.bootstrap: Whether the implementation trains using bootstrap samples.class_weight: Optional weighting to address different class costs or imbalance.
Random forests work well for many tabular classification and regression tasks. They can capture nonlinear interactions and normally do not require standardized numerical features.
6. Boosting and gradient-boosted trees
Boosting combines weak or moderately strong learners in successive stages. The broad idea is to create an increasingly capable prediction by focusing later learning on shortcomings of the current ensemble.
Two important approaches should be distinguished:
AdaBoost
Adaptive Boosting (AdaBoost) fits learners sequentially and adjusts the relative importance of training examples. In its classic classification formulation, misclassified observations receive more weight so later learners pay more attention to them. The combined prediction weights the learners according to their performance.
Gradient boosting
Gradient boosting builds an additive predictive model stage by stage. At each stage, a new learner is fitted to improve the current model according to a differentiable loss function. For squared-error regression, this can be understood as learning to predict current residuals, but the general method is based on negative gradients of the loss.
An additive model can be written as:
Here is the initial model, is the contribution learned at stage , is the number of stages, and is a learning rate that scales each update. Some boosting formulations also fit an additional stage-specific multiplier, which is absorbed into in this simplified expression.
A conceptual training cycle is:
- Start with a simple prediction, such as a constant baseline.
- Calculate how the current predictions affect the loss.
- Train a shallow decision tree to approximate the direction that will reduce the loss.
- Add its contribution, scaled by the learning rate, to the ensemble.
- Repeat until the stopping criterion is reached.
This is called gradient boosting because the new learners approximate directions for improving the loss, not because each decision tree is trained by backpropagation.
Popular implementation families include gradient-boosted decision trees and histogram-based variants. Libraries such as XGBoost, LightGBM, and CatBoost provide specialized implementations with different optimization and data-handling choices.
Learning rate and number of trees
A small learning rate usually requires more boosting stages to achieve similar training fit. A large learning rate may produce faster changes but can be less stable or generalize poorly. The number of trees, their depth, learning rate, and regularization therefore need to be tuned together.
For many datasets, boosting gives strong tabular-data performance. It can also overfit if the ensemble becomes too complex, and training is often less easily parallelized across stages than bagging.
7. Comparing the three approaches
| Property | Decision tree | Random forest | Gradient boosting |
|---|---|---|---|
| Model design | One tree | Many randomized trees | Sequential additive learners, commonly shallow trees |
| Main strategy | Recursive splitting | Bagging and feature randomness | Iteratively improving a loss |
| Interpretability | Often high when shallow | Lower than one tree | Lower than one tree |
| Main benefit | Simple rules, fast baseline | More stable predictions | Strong predictive performance on many tabular tasks |
| Main risk | High variance and overfitting | Large models and limited extrapolation | Overfitting or sensitivity to tuning |
| Training | One tree | Trees can be trained independently | Stages depend on previous stages |
| Feature scaling | Usually unnecessary | Usually unnecessary | Usually unnecessary for tree-based boosting |
Important: None of these models can reliably extrapolate numerical trends beyond the observed training regions in the way a correctly specified parametric trend model sometimes can. Tree-based regression often predicts values tied to the training data’s target ranges.
8. A complete scikit-learn example
The following example compares three classifiers using the same training and test split. It uses a built-in dataset so it does not require downloading external files.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# Educational dataset; not a clinical decision-making system.
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y,
)
models = {
"Decision tree": DecisionTreeClassifier(
max_depth=4, min_samples_leaf=5, random_state=42
),
"Random forest": RandomForestClassifier(
n_estimators=200, min_samples_leaf=3, random_state=42
),
"Gradient boosting": GradientBoostingClassifier(
n_estimators=100, learning_rate=0.05, max_depth=2,
random_state=42
),
}
for name, model in models.items():
model.fit(X_train, y_train)
predictions = model.predict(X_test)
score = accuracy_score(y_test, predictions)
print(f"{name}: test accuracy = {score:.3f}")
# Look beyond accuracy for the selected model.
chosen_model = models["Random forest"]
print(classification_report(y_test, chosen_model.predict(X_test)))
The specific scores depend on the dataset and split. A single split is useful for illustration, but it is not sufficient evidence that one algorithm is universally superior. In practice, use cross-validation for model selection and reserve an untouched test set for final evaluation.
Why no scaler is included
These models split observations using feature thresholds. Standardizing features is therefore not generally required for their predictive operation, unlike algorithms whose behavior depends on distances or gradient conditioning. A workflow may still require preprocessing for missing values, categorical variables, or other data-quality concerns.
Preventing evaluation leakage
Do not repeatedly inspect the test-set scores and then choose parameters based on those results. That makes the test set part of model selection. Prefer a training/validation strategy or cross-validation for tuning, followed by one final held-out evaluation.
9. Feature importance and explanations
Tree ensembles often expose measures of feature importance, but these measures need careful interpretation.
- Impurity-based importance summarizes how much a feature contributes to impurity reductions across fitted trees. It can favor features with many possible split values.
- Permutation importance measures how predictive performance changes when one feature is shuffled in an evaluation dataset. It depends on the metric and can be misleading with strongly correlated predictors.
- Individual predictions can be examined using decision paths or model explanation methods, but an explanation of the model’s computation is not automatically a causal explanation of the world.
A model can find a reliable statistical association without learning that changing the feature would cause the outcome to change. Interpretability and causal reasoning are related but different questions.
10. Choosing a method in practice
Use a single decision tree when a compact, explainable rule structure is a priority or when establishing a quick nonlinear baseline.
Try a random forest when you want a strong general-purpose tabular baseline that is typically less sensitive than a single deep tree to training-data fluctuations.
Try gradient boosting when predictive accuracy on tabular data is especially important and you have the resources to tune complexity, learning rate, and number of stages carefully.
Compare these with simpler baselines such as linear or logistic regression. Choose using the actual problem’s target, class imbalance, data size, inference cost, transparency requirements, and performance on unseen data.
11. Limitations and responsible use
Decision-tree ensembles have several shared limitations:
- Data quality: Incorrect labels, missing records, and sampling bias can produce unreliable patterns.
- Distribution shift: Performance can deteriorate if future data differs from the training population.
- Class imbalance: Accuracy alone can hide poor detection of rare but important classes.
- Unseen categories: A fitted representation may fail to handle categories absent from training.
- Extrapolation: Tree-based regression is generally poor at predicting trends beyond observed data ranges.
- Fairness and privacy: Strong predictive performance does not ensure acceptable or equitable real-world use.
- Operational complexity: Large ensembles consume more memory and inference time than one small tree.
For higher-stakes uses, evaluate not only predictive metrics but also calibration, error costs, subgroup performance, robustness, and human oversight needs.
12. Practice questions
- Why might a shallow decision tree generalize better than an unrestricted tree?
- How does a random forest create diversity among its trees?
- What is the difference between majority voting and averaging in ensemble predictions?
- Why is boosting sequential while standard random-forest training can be parallelized across trees?
- What would be wrong with choosing
max_depthafter repeatedly checking performance on the final test set? - Why is an important feature in a fitted model not necessarily a cause of the predicted outcome?
Show suggested answers
- Restricting depth can reduce sensitivity to noise and training-specific patterns, though too little depth can underfit.
- It uses bootstrap samples and random feature subsets at splits.
- Voting aggregates class choices; averaging combines numerical outputs or probability estimates.
- Boosting’s next stage depends on the current ensemble’s errors or gradients; forest trees do not depend on each other’s predictions during training.
- It leaks model-selection decisions into final evaluation and makes the reported result optimistic.
- Predictive associations can arise from confounding, proxies, or correlations without causal relationships.
13. Related concepts
- Machine Learning Paradigms — where supervised tree learning fits.
- Linear and Logistic Regression — simpler supervised baselines.
- How to Formulate an AI Problem — selecting targets and evaluation criteria.
- Data Splitting, Labeling, and Leakage — separating training and evaluation correctly.
- Feature Engineering, Encoding, and Scaling — preparing meaningful model inputs.
- Optimization and Gradient Descent — the optimization concept related to gradient boosting.
- Support Vector Machines and Nearest Neighbors — alternative predictive algorithms.
- Model Training, Overfitting, and Generalization — interpreting the bias-variance tradeoff.
- Evaluating Machine Learning Models — selecting reliable performance measures.
References and further reading
- scikit-learn User Guide: Decision Trees — splitting, classification, regression, and complexity controls.
- scikit-learn User Guide: Ensemble Methods — bagging, random forests, AdaBoost, and gradient boosting.
- scikit-learn: Permutation Feature Importance — interpreting feature influence through predictive performance.
- An Introduction to Statistical Learning — tree-based models in the wider context of statistical learning.
Related articles in
- Clustering and K-Means — Learn how unsupervised clustering discovers groups in data, how K-Means optimizes cluster centroids, and how to evaluate and use its results responsibly.
- Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
- Dimensionality Reduction and Principal Component Analysis — Understand why high-dimensional data is difficult to analyze, how PCA finds directions of maximum variance, and how to use and evaluate PCA without data leakage.