Decision Trees and Random Forests
🌳 What is a decision tree? A decision tree classifies a point by asking a chain of yes/no questions about its features, such as "is feature 2 at most 3.5?", until it reaches a leaf that holds a class. Training picks, at every node, the question that makes the two resulting groups as pure as possible, and stops when a group is pure or small.
It is a staple of the from-scratch classic-ML round, and its randomized cousin, extra trees, also shows up as the buggy code in the find-the-bugs variant.
The Prompt
A tree has more moving parts than k-means: an impurity function, a split search, a recursion with stopping rules, and a prediction walk. The interviewer watches whether you keep them separate and whether the split search is fast enough to build a forest on top of.
"Implement a decision tree classifier with
fitandpredict, using Gini impurity. Then turn it into a random forest."
Clarifying Questions
You: What are the inputs? I'll assume X is an (n, d) float array with no missing values and y holds
integer labels 0..C-1.
Interviewer: Yes. Numeric features only, no categorical handling.
You: Where do thresholds go, and how are ties between splits broken?
Interviewer: Midway between two consecutive distinct values. On equal gain, take the lower feature index, then the lower threshold.
You: When does a node stop splitting?
Interviewer: Support max_depth and min_samples_split. Also stop when the node is pure or no split
improves impurity.
You: What does a leaf predict? And for the forest, how many features per split?
Interviewer: The majority class, lower label on ties; expose class probabilities too. For the forest, a
random sqrt(d) features at each split and a bootstrap sample per tree.
What You'll Build
gini(counts) -> (...): impurity from class counts, batched over leading axes.best_split(X, y, n_classes, features) -> (feature, threshold, gain): the best cut, orNoneif no cut helps.DecisionTree(max_depth, min_samples_split, max_features, seed)withfit(X, y),predict_proba(X)of shape(m, C)andpredict(X)of shape(m,).RandomForest(n_trees, max_features, seed, extra): bagged trees whose probabilities are averaged;extra=Truegives extra trees.