v9.1.1
Menu

Decision Tree Prediction

mediumFREEDecision TreesMachine Learning 1

Traverse a decision tree to make predictions.

A decision tree is represented as nested dictionaries. Each internal node has:

  • "feature": index of the feature to check
  • "threshold": split value
  • "left": subtree for feature_value <= threshold
  • "right": subtree for feature_value > threshold

Each leaf node has:

  • "class": the predicted class label

Given a tree and a list of data points (each a list of feature values), return the predicted class for each point.

Example

Input
tree = {"feature": 0, "threshold": 5, "left": {"class": 0}, "right": {"class": 1}}
X = [[3], [7], [5]]
Output
[0, 1, 0]
Reasoning
  • Inputs: tree is a single split: its root says "look at feature 00 and compare it with the threshold 55", with leaf class 0 on the left and leaf class 1 on the right. X holds three points, each with just one feature value: [3], [7], [5].
  • Point [3]: feature 00 is 33, and 3≤53 \le 5, so it falls on the left side and gets class 0.
  • Point [7]: 7>57 > 5, so it falls on the right side and gets class 1.
  • Point [5]: 5≤55 \le 5 holds, so a value exactly equal to the threshold also goes left and gets class 0.
  • Output: one label per row of X, in the same order: [0, 1, 0].
  • Notice that the boundary case decides the third answer: with a strict << test, [5] would have been labelled 1. In a deeper tree a point keeps meeting such comparisons until it reaches a node that only carries a class.

Constraints

  • tree: nested dict with feature/threshold/left/right or class keys
  • X: 2D list of feature values
  • Return list of predicted class labels

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.