Find a course

Module 3: Classification Models and MetricsLesson 6 of 1116 min

Decision Trees, Nearest Neighbors and Ensembles

Learn how decision trees split data using Gini impurity, how k-nearest neighbors predicts from similar examples, and why forests and boosting win.

Step 1 of 11Learn

Twenty questions with data

A decision tree predicts by asking a series of yes/no questions about the features, like a game of twenty questions. To predict whether a customer will cancel a phone plan:

  • Is the contract month-to-month? If no, predict "stays."
  • If yes: has the customer called support more than 3 times in the last month? If yes, predict "cancels."
  • If no: is tenure under 6 months? ...

Each internal node tests one feature against a threshold; each leaf gives a prediction, either the majority class (classification) or the average value (regression) of the training examples that reach it.

How does the tree choose questions? At each node, the algorithm tries every feature and many thresholds, and picks the split that makes the resulting groups as pure as possible, meaning each group is dominated by one class. A common purity measure is Gini impurity:

Gini = 1 − Σ pₖ²

where pₖ is the share of class k in the node.

  • A node with 10 "cancel" and 0 "stay": Gini = 1 − (1² + 0²) = 0, perfectly pure.
  • A node with 5 and 5: Gini = 1 − (0.5² + 0.5²) = 0.5, the worst possible for two classes.
  • A node with 8 and 2: Gini = 1 − (0.8² + 0.2²) = 1 − 0.68 = 0.32.

The best split is the one that most reduces the weighted average impurity of the child nodes. Another measure, entropy, works similarly and usually picks similar splits.

Trees are popular because they are easy to visualize and explain, handle numeric and categorical features, need no scaling, and capture nonlinear patterns and interactions automatically.

Step 2 of 11Practice · Diagram

The phone-plan churn tree

Each question splits the customers; each leaf gives a prediction. Tap the nodes.

A month-to-month customer with 1 support call and 2 years of tenure ends at which leaf?

Tap the shape that answers the question, then press Check.

The phone-plan churn treeHierarchy diagram: Month-to-month contract?, No: stays, Yes: >3 support calls?, Yes: cancels, No: tenure < 6 months?, Yes: cancels, No: stays.Month-to-monthcontract?No: staysYes: >3 supportcalls?Yes: cancelsNo: tenure < 6months?Yes: cancelsNo: stays
Month-to-month contract?
No: stays

Customers on longer contracts rarely cancel.

Yes: >3 support calls?
Yes: cancels

Frustrated customers with flexible contracts leave.

No: tenure < 6 months?
Yes: cancels

New customers are still deciding.

No: stays

Step 3 of 11Try the calculator

Gini impurity of a node

Enter how many training examples of each class reach a node. A pure node scores 0; an evenly mixed two-class node scores 0.5.

Share of class A
0.8
Gini impurity
0.32

Step 4 of 11Practice · Work it out

A tree node contains 6 examples of class A and 4 examples of class B. What is its Gini impurity?

Step 5 of 11Learn

Trees overfit; forests and boosting fix it

Left unchecked, a decision tree keeps splitting until every leaf is pure, which often means a leaf for a single training example. That tree has memorized the training data, and it overfits badly. Small changes in the data can produce a completely different tree, so single deep trees have high variance.

Ways to control a single tree include limiting its maximum depth, requiring a minimum number of samples per leaf, and pruning branches that don't improve validation performance. These are hyperparameters.

The bigger breakthrough was combining many trees into an ensemble:

Random forest. Train hundreds of trees, each on a bootstrap sample (a random sample of the training data drawn with replacement), and at each split consider only a random subset of the features. Each tree overfits in its own way, but their errors are partly independent, so averaging their votes cancels much of the noise. This technique of training on bootstrap samples and averaging is called bagging. Random forests work well out of the box with little tuning.

Gradient boosting. Build trees sequentially. Each new, usually shallow, tree is trained to correct the errors (residuals) of the ensemble so far. Adding many small corrections, scaled by a learning rate, produces a very accurate model. Popular implementations such as XGBoost, LightGBM and CatBoost are frequent winners on tabular data.

The trade-off: ensembles are more accurate than a single tree but lose the easy, one-picture explanation. Tools that measure feature importance or explain individual predictions help recover some interpretability.

Step 6 of 11Compare

Single tree vs. random forest vs. gradient boosting

AspectSingle decision treeRandom forestGradient boosting
How trees are builtOne treeMany independent trees on bootstrap samples, averagedMany shallow trees built in sequence, each fixing earlier errors
Main strengthEasy to read and explainRobust, accurate, little tuning neededOften the most accurate on tabular data
Main weaknessOverfits; unstableLarger and slower; less interpretableMore hyperparameters; can overfit if over-trained
Reduces mostlyNeither, unless prunedVarianceBias, and variance with careful tuning

Step 7 of 11Learn

k-nearest neighbors: predict like your neighbors

k-nearest neighbors (kNN) may be the simplest learning algorithm of all. It doesn't build a model during training; it just stores the training data. To predict for a new point:

  1. Compute the distance from the new point to every training example.
  2. Find the k closest examples, its nearest neighbors.
  3. For classification, take a majority vote of their labels. For regression, average their values.

The usual distance is Euclidean distance, the straight-line distance:

d = √((x₁ − y₁)² + (x₂ − y₂)² + …)

For points (1, 1) and (4, 5): d = √(3² + 4²) = √25 = 5.

The choice of k controls the bias-variance balance:

  • k = 1: the prediction copies the single closest example. Very flexible and very sensitive to noise: it overfits.
  • Large k: predictions average over many neighbors, giving smoother boundaries but possibly blurring real patterns: it can underfit.
  • An odd k avoids ties in two-class problems.

kNN has notable practical issues:

  • Scaling is essential. Without it, features with large numeric ranges dominate the distance.
  • Prediction is slow on large datasets, because every prediction compares against all stored examples, though special data structures and approximate search help.
  • The curse of dimensionality. With many features, points become far apart and distances become less meaningful, so "nearest" neighbors are not very near.

kNN remains useful as a baseline and is the idea behind many recommendation and similarity search systems: find items whose feature vectors are close to the ones a user liked.

Step 8 of 11Compare

Choosing k in k-nearest neighbors

Aspectk = 1Moderate k (e.g. 5 to 15)Very large k
Decision boundaryJagged, follows every pointSmooth but flexibleAlmost flat
Training errorZeroLowHigh
Main riskOverfitting (high variance)BalancedUnderfitting (high bias)
Extreme caseCopies the nearest noisePick it with cross-validationk = n predicts the majority class everywhere

Step 9 of 11Practice · Code challenge

Write distance(a, b) that returns the Euclidean distance between two points given as arrays of the same length.

Runs in a sandbox in your browser.
  • distance([0, 0], [3, 4])
  • distance([1, 2, 3], [1, 2, 3])
  • distance([1, 1], [4, 5])
  • distance([2, -1, 0, 3], [2, 1, 4, 7])

Step 10 of 11Practice · Sort into groups

For each change, does it make the model more prone to overfitting or more prone to underfitting?

Tap an item, then tap its group (or drag it there).

Step 11 of 11Practice · Choose one

Why does a random forest usually generalize better than a single deep decision tree?