Decision trees and random forests
How decision trees split data into simple rules and how random forests average many randomized trees to give accurate, robust predictions for classification and regression on tabular data.
What it is
A decision tree is a model that predicts an outcome by asking a sequence of yes/no questions about the input variables, such as “is temperature above 30 °C?”, branching until it reaches a leaf that gives a class or a number. Trees are easy to read and handle numeric and categorical data without scaling. A random forest, introduced by Leo Breiman in 2001, builds hundreds of decision trees on random subsets of the data and variables and averages their predictions (majority vote for classification, mean for regression). A single tree is unstable and overfits, whereas averaging many different trees cancels much of the noise. Random forests are among the most reliable general-purpose methods for tabular data and are used in ecology, medicine, remote sensing, materials science, finance and chemistry.
It answers questions such as: Which class does this sample belong to? What value is expected for these conditions? Which variables are most important for prediction? What simple rules separate the groups? Are there outliers or unusual samples? Forests give strong accuracy with little tuning, while a single tree is chosen when readable rules matter.
Fundamentals
Growing a tree
A tree is built by greedy recursive partitioning. At each node the algorithm searches all variables and all split points for the one that makes the child nodes most “pure”. For classification, impurity is measured by the Gini index, G = 1 − Σk pk2, or by entropy, H = −Σk pk log2 pk, where pk is the fraction of class k in the node; a node with only one class has G = 0, and a 50/50 two-class node has G = 0.5. The reduction in impurity from a split is the information gain. For regression, the split minimizes the sum of squared deviations from the mean in the children (variance reduction), and each leaf predicts the mean of its samples. Splitting continues until a stopping rule applies, such as maximum depth, minimum samples per leaf, or no gain. This procedure is called CART (Classification and Regression Trees); related algorithms are ID3, C4.5 and C5.0.
Overfitting and pruning
A tree grown to full depth memorizes the training data, giving perfect training accuracy but poor performance on new samples. Remedies are pre-pruning (limit depth, require a minimum number of samples to split or in a leaf) and post-pruning by cost-complexity pruning, which minimizes error + α × (number of leaves), choosing α by cross-validation. Trees have further weaknesses: small changes in the data can change the tree structure (high variance), their predictions are piecewise-constant, they cannot extrapolate beyond the range of training values, and they favor variables with many possible split points. Categorical variables with many levels can mislead splits.
Random forests: bagging and random feature selection
A random forest uses two sources of randomness. Bagging (bootstrap aggregation) trains each tree on a bootstrap sample, n observations drawn with replacement, which leaves out about 1/e ≈ 36.8% of the observations for each tree. At each split only a random subset of m variables is considered (commonly √p for classification and p/3 for regression), which decorrelates the trees, because otherwise strong predictors would dominate every tree. The variance of an average of B trees with variance σ2 and pairwise correlation ρ is ρσ2 + (1 − ρ)σ2/B, so more trees help up to a point (100–500 is usually enough), while lowering ρ gives further gains. Individual trees are grown deep and unpruned. Main hyperparameters: number of trees, m (max_features), minimum leaf size and maximum depth. Forests are robust to noise, work with little tuning and handle mixed data types, nonlinearity and interactions, and they do not overfit as trees are added.
Out-of-bag error, importance and interpretation
Because each tree skips about a third of the data, predictions for each observation can be made using only trees that did not see it: this out-of-bag (OOB) error is an almost free estimate of test error, without a separate validation set. Variable importance has two main forms: impurity-based (total impurity decrease from splits on a variable, fast but biased toward continuous or high-cardinality variables) and permutation importance (the drop in accuracy when a variable’s values are shuffled, preferably computed on OOB or held-out data and handled with care when variables are correlated). Partial dependence plots and SHAP values describe how predictions depend on variables (see explainable AI). Forests also give proximity measures for clustering and outlier detection, and quantile regression forests give prediction intervals. Variants include extremely randomized trees (random split points), and isolation forests for anomaly detection (see anomaly detection).
Typical applications and limits
Used for species and land-cover classification, disease diagnosis, credit scoring, fault detection and property prediction in chemistry and materials. Software: scikit-learn (RandomForestClassifier), R (ranger, randomForest) and others. Limits: forests are less interpretable than one tree, can be large and slow for prediction, cannot extrapolate, and may be outperformed on some problems by gradient boosting (see gradient boosting) or deep learning.
Basic operation
- Prepare the data. Clean, encode categories and handle missing values.
- Split the data. Hold out a test set.
- Fit a baseline tree. Check readable rules and depth.
- Fit a random forest. Use a few hundred trees and default settings first.
- Tune. Adjust
max_features, leaf size and depth by cross-validation. - Check performance. Use OOB error and the held-out test set, with class-appropriate metrics.
- Inspect importance. Use permutation importance and partial dependence plots.
- Collect the output. You obtain predictions and variable rankings; tuning and imbalanced data handling are covered in the video.
Good practice
- Use proper validation. For spatial or time-ordered data, split by block or time.
- Handle class imbalance. Use class weights or resampling and suitable metrics.
- Prefer permutation importance. Impurity importance can mislead.
- Beware extrapolation. Do not predict far outside the training range.
- Fix random seeds. Make results reproducible.
- Consider consequences. For medical, legal or credit decisions, check for bias, explain predictions and keep a human in the decision loop.
Key terms
- Gini impurity — a measure of how mixed the classes are in a node.
- Pruning — reducing tree size to avoid overfitting.
- Bagging — training models on bootstrap samples and averaging them.
- Out-of-bag error — error estimated from observations left out of each tree’s sample.
- Permutation importance — importance measured by the loss in accuracy when a variable is shuffled.
- Ensemble — a combination of many models.
- Leaf — a terminal node that gives the prediction.
Video coming soon
About five minutes on Decision trees and random forests: how it works in detail, how the data is acquired, and how it is analyzed.
More in 4.3 AI and Machine Learning
- Regularized linear models
- Decision trees and random forests
- Gradient boosting (XGBoost)
- Support vector machines
- k-NN
- k-means
- Gaussian processes
- Neural networks
- CNNs
- RNN/LSTM
- Transformers
- Autoencoders
- GANs
- Diffusion models
- Graph neural networks
- Reinforcement learning
- Transfer learning
- Federated learning
- Explainable AI (SHAP, LIME)
- Physics-informed neural networks
- Bayesian optimization
- Active learning
- Symbolic regression
- Genetic algorithms and particle swarm optimization
- Dimensionality reduction (t-SNE, UMAP)
- NLP and large language models
- Retrieval-augmented generation
- Computer vision (detection, segmentation)
- Anomaly detection
- Machine-learned interatomic potentials
- AutoML
