1. Home
  2. Explore
  3. Computer Science
  4. Neural Networks Overview

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Neural Networks Overview

Decision Trees, Ensembles, and Random Forests

Beyond Neural Nets: The ML Toolbox

While neural networks, convolutional neural networks, and recurrent neural networks are powerful tools for vision and language tasks, they are not the only tools in the machine learning toolbox. Interpretability and predictive performance are both important considerations, and different methods serve different needs. Linear regression and logistic regression remain widely used. Decision trees excel when interpretability is essential, and ensembles (like random forests) often achieve top predictive performance on tabular data.

Why Interpretability Matters

There are several compelling reasons to choose interpretable models over black-box methods:

  • Transparency for stakeholders: Election audits, for example, require methods that are understandable to election officials and the public. More complex models, even if more efficient, may face resistance.

  • Detecting problematic patterns: In a medical study, an interpretable model revealed that asthma patients with pneumonia had lower risk of death – a counterintuitive finding that turned out to be due to Simpson's paradox: those patients were admitted to the ICU and received aggressive care, lowering their mortality risk. A neural net would not have made this pattern visible.

  • Reducing human error: When humans must apply a model (e.g., diagnosing heart attacks in an emergency room), a decision tree that provides a clear chain of if-then rules is less prone to misuse than a complex black-box method.

Predictive Performance Still Matters

Even when only predictive accuracy is the goal, tree-based methods play a central role. Many top-performing entries in machine learning competitions (e.g., Kaggle) rely on ensembles of decision trees such as LightGBM, XGBoost, and CatBoost. For many types of structured/tabular data, tree ensembles often outperform neural networks.


Decision Trees: Structure and Definition

A decision tree is a binary tree of decisions used for classification or regression. It consists of:

  • Internal nodes: Each internal node is defined by a dimension index jjj and a split value sss. The test at the node is: is xj≥sx_j \ge sxj​≥s? Depending on the answer, the input goes to one of two child nodes.

  • Leaf nodes: Each leaf node is defined by a label (a class for classification, a real number for regression). When a data point reaches a leaf, that label is the prediction.

A decision tree is a binary tree where internal nodes specify a split on a single feature (axis-aligned), and leaves assign a constant prediction.

Example: Classification Tree (Heart Attack Risk)

Consider a tree for assessing patient risk after a heart attack:

  • Root: Is minimum systolic blood pressure over 24 hours ≥91\ge 91≥91? If no → high risk. If yes → next question.

  • Second node: Is age ≥65\ge 65≥65? If no → low risk. If yes → next question.

  • Third node: Is sinus tachycardia present? If no → low risk. If yes → high risk.

This tree, when expressed in terms of features x1,x2,…x_1, x_2, \dotsx1​,x2​,…, becomes a classifier: the internal nodes test conditions like x6≥91x_6 \ge 91x6​≥91, x2≥65x_2 \ge 65x2​≥65, x5≥1x_5 \ge 1x5​≥1, and leaves output labels (e.g., +1+1+1 for high risk, −1-1−1 for low risk).

Example: Regression Tree (Running Distance)

Features: temperature (x1x_1x1​) and precipitation (x2x_2x2​). Label: kilometers run.

  • Root: Is x2≥0.3x_2 \ge 0.3x2​≥0.3 (heavy precipitation)? If yes → predict 3 km (treadmill). If no → next.

  • Second node: Is x1≥−5x_1 \ge -5x1​≥−5 (cool)? If no → predict 2 km. If yes → next.

  • Third node: Is x1≥33x_1 \ge 33x1​≥33 (hot)? If yes → predict 0 km. If no → predict 5 km.

The tree defines an axis-aligned partition of the feature space. Each leaf corresponds to a rectangular region where a constant value is predicted. The overall prediction function is a step function.


Learning Decision Trees

Like other machine learning methods, building a decision tree requires:

  1. A forward prediction – given features and parameters, compute the label.

  2. A loss function – e.g., squared error for regression, cross-entropy for classification.

  3. A method to choose parameters – typically by minimizing training loss.

Parameters Are Not Fixed-Dimension

The parameters of a decision tree are not a fixed-size vector. They include:

  • For each internal node: split dimension jjj, split value sss, and references to two children.

  • For each leaf: a label value.

  • The tree structure itself (which nodes are internal vs. leaves) is part of the parameterization.

Because the number of parameters can grow as the tree grows, standard gradient-based optimization (which requires differentiability and fixed dimensions) is not applicable. Instead, a heuristic approach is used: grow the tree greedily, then prune it back.

Growing a Tree (BuildTree)

The algorithm BuildTree takes a set of data indices III and a hyperparameter kkk (minimum number of points allowed in a leaf). It recursively builds the tree:

  1. If ∣I∣≤k|I| \le k∣I∣≤k: Create a leaf node. The label y^\hat{y}y^​ is chosen to minimize the loss on the points in III. For squared error loss, the optimal constant is the mean of the labels in III. $$ \hat{y} = \frac{1}{|I|} \sum_{i \in I} y^{(i)} $$

  2. Otherwise: Find the best split (j,s)(j, s)(j,s) that minimizes the total loss after splitting.

    • For each dimension jjj:

      • For each candidate split value sss (typically midpoints between distinct feature values):

        • Partition III into I+(j,s)={i:xj(i)≥s}I_+(j,s) = \{i: x_j^{(i)} \ge s\}I+​(j,s)={i:xj(i)​≥s} and I−(j,s)={i:xj(i)<s}I_-(j,s) = \{i: x_j^{(i)} < s\}I−​(j,s)={i:xj(i)​<s}.

        • Compute the optimal predictions y^+\hat{y}_+y^​+​ and y^−\hat{y}_-y^​−​ as the means of the labels in each partition.

        • Compute the total loss: L(j,s)=∑i∈I+(y(i)−y^+)2+∑i∈I−(y(i)−y^−)2L(j,s) = \sum_{i \in I_+} (y^{(i)} - \hat{y}_+)^2 + \sum_{i \in I_-} (y^{(i)} - \hat{y}_-)^2L(j,s)=∑i∈I+​​(y(i)−y^​+​)2+∑i∈I−​​(y(i)−y^​−​)2.

    • Choose (j∗,s∗)(j^*, s^*)(j∗,s∗) that minimizes L(j,s)L(j,s)L(j,s).

    • Create an internal node with this split.

    • Recursively build the left child on I−(j∗,s∗)I_-(j^*, s^*)I−​(j∗,s∗) and the right child on I+(j∗,s∗)I_+(j^*, s^*)I+​(j∗,s∗).

Key properties:

  • Greedy: The algorithm chooses the split that minimizes loss right now, without considering future splits.

  • Finite candidate splits: Although feature values are continuous, only splits between data points change the training loss. Using midpoints between distinct feature values is sufficient. The number of candidate splits is at most O(n)O(n)O(n) per dimension.

Example Build

On a small dataset with 11 points (regression labels 0 or 5), starting with k=2k=2k=2:

  • At the root, 11 points → find a split, e.g., x2≥0.28x_2 \ge 0.28x2​≥0.28. This separates 8 points (mostly 5s) from 3 points (0s).

  • Left child (8 points) → split on x1x_1x1​ (e.g., x1≥7.2x_1 \ge 7.2x1​≥7.2), separating into 5s and 0s.

  • Continue recursively until each leaf contains ≤2\le 2≤2 points.

The resulting tree partitions the feature space into rectangles, each predicting a constant.


Regularization and Pruning

The Overfitting Problem

Growing a tree to very small leaf sizes (e.g., k=1k=1k=1) fits the training data perfectly but often overfits. Stopping growth when the loss does not improve (e.g., no reduction in squared error) can be short-sighted. Consider a dataset that requires two splits to capture a pattern (e.g., XOR-like structure). A single split may not reduce loss at all, yet a second split yields a perfect fit. Stopping early would miss this.

Cost-Complexity Pruning

A more principled regularization approach is to grow a large tree and then prune it back using a cost-complexity objective:

Cα(T)=∑i=1nL(y(i),T(x(i)))+α⋅∣leaves(T)∣C_\alpha(T) = \sum_{i=1}^n L(y^{(i)}, T(x^{(i)})) + \alpha \cdot |\text{leaves}(T)|Cα​(T)=∑i=1n​L(y(i),T(x(i)))+α⋅∣leaves(T)∣
  • TTT is the tree predictor.

  • The first term is the training loss (e.g., sum of squared errors).

  • The second term penalizes the number of leaves in the tree, controlled by α≥0\alpha \ge 0α≥0.

  • For α=0\alpha = 0α=0, only training loss matters. As α\alphaα increases, simpler trees (fewer leaves) are favored.

How Pruning Works

  1. Grow a very large tree (small kkk).

  2. For each internal node, consider replacing the subtree rooted at that node with a single leaf (that predicts the mean of all points in that region).

  3. If the cost-complexity CαC_\alphaCα​ of the pruned version is lower than the original, the subtree is not worth keeping: it adds leaves without sufficient reduction in training loss.

  4. As α\alphaα increases, more subtrees become prunable. By gradually increasing α\alphaα, one obtains a sequence of nested subtrees.

  5. Use cross-validation to select the best α\alphaα (and corresponding tree) from this sequence.

This procedure avoids the greedy mistake of stopping growth too early: it allows the tree to capture complex patterns and then simplifies it based on a global penalty.


Ensembles: Bagging

An ensemble combines multiple predictors to produce a single, often much better predictor. The general idea: using multiple weak or moderately good models collectively outperforms any single model.

Bootstrap Aggregating (Bagging)

Bagging (short for bootstrap aggregating) is a general ensemble method:

  1. Bootstrap: Create BBB new datasets by sampling with replacement from the original training set. Each bootstrap dataset has the same size nnn as the original, but because of replacement, some original points appear multiple times and some not at all.

  2. Aggregate: Train a predictor fbf_bfb​ on each bootstrap dataset bbb. For regression, the final prediction is the average of all fbf_bfb​: $$ \hat{f}{\text{bag}}(x) = \frac{1}{B} \sum{b=1}^B f_b(x) $For∗∗classification∗∗,thefinalpredictionistheclasswiththemostvotesacrosstheFor **classification**, the final prediction is the class with the most votes across theFor∗∗classification∗∗,thefinalpredictionistheclasswiththemostvotesacrosstheB$ classifiers (majority voting).

Bagging is effective because it reduces variance without significantly increasing bias – especially for unstable predictors (like decision trees, which can change a lot with small data changes). It works with any learning algorithm.

Why It Works

Each bootstrap dataset is a slightly different version of the training data. The predictors trained on these datasets make different errors. Averaging (or voting) cancels out some of the errors, yielding a more stable and accurate predictor.


Random Forests

A random forest is bagging applied to decision trees, with one additional source of randomness to reduce correlation among the trees:

  1. For each bootstrap dataset bbb, build a decision tree using the standard growing algorithm, but at each internal node, instead of considering all ddd features for the split, randomly select a subset of mmm features (without replacement) and pick the best split only among those mmm features.

    • mmm is typically much smaller than ddd, e.g., m≈dm \approx \sqrt{d}m≈d​ for classification or d/3d/3d/3 for regression.

  2. Grow each tree to a large depth (often until leaves are pure or a minimum leaf size is reached). Do not prune – the ensemble itself provides regularization.

  3. Aggregate predictions by averaging (regression) or voting (classification).

Why the Extra Randomness?

Without the random feature subset, trees grown on different bootstrap datasets would still be quite correlated, because the best splits often occur on the same strong features. By forcing each split to consider only a random subset of features, the resulting trees become more diverse (less correlated). Averaging more diverse trees reduces variance further.

Trade-off: Interpretability vs. Performance

  • Single decision tree: Highly interpretable – the entire prediction logic is a clear sequence of if-then rules. But limited predictive power.

  • Random forest: Much higher predictive performance (often among the best for tabular data). However, interpretability is largely lost – it is not possible to trace a prediction through thousands of trees.

Choosing between them depends on the application: if understanding why a prediction is made is critical (e.g., medicine, law, lending), a single tree (or a small, pruned tree) may be preferable. If pure accuracy is the goal, random forests (or boosted tree ensembles) are often the tool of choice.


Key takeaway: Decision trees provide interpretability through simple, axis-aligned partitions. Ensemble methods like bagging and random forests boost predictive performance by combining many trees, trading away interpretability for accuracy. Both are essential parts of the machine learning toolbox.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent