Tag: Trees

  • ML0161 CatBoost Ordered Boosting

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0122 Neural Nets vs Trees on Tabular

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0030 Gini Split From Scratch

    Mode B · Build & Trace 30 Min NumPy + sklearn 4 NumPy Blanks

    Quant research teams that fit gradient-boosted trees on market features spend most of their training time inside one routine, the per-feature split search, which open-source learners such as Microsoft’s LightGBM rebuild around histograms for speed. This screen (reported by candidates from several quant and applied-AI loops) asks you to write the exact version of that routine by hand. You implement best_split for one continuous feature in NumPy, and no tree library may be called inside the function.

    The column x has shape (m,) and the labels y are integers in \{0, \ldots, C - 1\}. Your function returns the threshold t (left child: x \leq t) and its expected information gain under the Gini criterion 1 - \sum_c p_c^2, or (None, 0.0) when no split exists. The interviewer grades three things. Candidates must be midpoints of sorted unique values rather than observed values. The scan must stay at O(m \log m) with no Python loop over classes. Degenerate columns must be handled honestly.

    Complete the 4 missing operations in the skeleton below and trace the array shape after each line. Then verify your routine against a hand-computed two-threshold fixture and cross-check the threshold and gain with a depth-1 sklearn.tree.DecisionTreeClassifier on a toy dataset.

    Skeleton Code (Fill Blanks 1-4):

    01  import numpy as np
    02
    03
    04  def gini(counts: np.ndarray) -> np.ndarray:
    05      """Gini impurity from class counts of shape (..., C)."""
    06      # TODO (Blank 2): 1 - sum_c p_c^2 over the class axis only,
    07      #                 vectorized over any leading axes (no class loop)
    08      impurity = ...
    09      return impurity
    10
    11
    12  def best_split(x, y, n_classes, min_samples_split=2):
    13      """Best Gini threshold for one feature (left child: x <= threshold).
    14      Returns (threshold, gain), or (None, 0.0) when no split exists."""
    15      m = len(x)
    16      # TODO (Blank 1): candidate thresholds, shape (K,), ascending
    17      candidates = ...
    18      # TODO (Blank 4): guard contract, return (None, 0.0) when this node
    19      #                 or this column cannot be split
    20      ...
    21      order = np.argsort(x, kind="stable")
    22      x_sorted, y_sorted = x[order], y[order]                     # (m,)
    23      parent_counts = np.bincount(y_sorted, minlength=n_classes)  # (C,)
    24      parent_gini = gini(parent_counts)
    25      # TODO (Blank 3): weighted Gini gain of all K candidates in one
    26      #                 vectorized pass (no Python loop), shape (K,);
    27      #                 best = argmax index, ties go to the lowest threshold
    28      gains = ...
    29      best = ...
    30      return float(candidates[best]), float(gains[best])
    Operator contract for best_split: input columns x and y of shape (m,) flow through a question-marked candidate step, a provided argsort, a question-marked Gini gain step, and a question-marked argmax step to an output pair of threshold and gain; below, boxes list the guard contract, the O(m log m) budget, and the two test oracles

    Figure 1: the input and output contract is fixed and the sort is provided, while the question-marked steps between them are yours to write in plain NumPy.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the fixture and sklearn checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Candidate Set: A useful threshold must change the partition. Count how many distinct partitions x <= t can produce, and make sure no candidate leaves a child empty.
    (2) Impurity on Counts: The helper receives class counts, both as one (C,) row and as a (K, C) table. Reduce over the class axis only.
    (3) Scan Budget: Count how many full passes over the m rows your scan makes. The budget is one sort plus a constant number of linear passes, with no Python loop.
    (4) Degenerate Inputs: List the inputs for which no honest threshold exists, and return (None, 0.0) for them before anything divides or indexes.

    2Visual Review Map (Figure 2)
    Shape trace for best_split: the top row marks the target shape of Blank 1 as (K,) and a question-marked Blank 4 early exit before the provided sort and the parent class counts of shape (C,); the bottom row shows question-marked target shapes for child counts (K, C), child Gini (K,), gains (K,), the best index, and the output pair

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce; writing the operations that reach them is the exercise.

    3Interviewer Nudge & Line Focus

    Pin the input shape, output shape, and failure inputs of each blank before writing the NumPy call:

    Blank 1 (Candidate Thresholds): For x = [2, 2, 5, 9], which thresholds produce genuinely different partitions under x <= t, and how many are there? If you used t = 9, what size would the right child have when you later divide by it?
    Blank 2 (Gini on Counts): The helper is called once with (C,) for the parent and once per side with (K, C) for every candidate. Which axis must each row be normalized over, and what does a reduction without an axis argument return for the table case?
    Blank 3 (One-Pass Scan): After sorting, which rows belong to the left child of the k-th candidate? If you had running class counts down the sorted order, how would you read off every left child at once, and how would you get the right child without rescanning? When two gains tie to the last bit, which index does your selection return?
    Blank 4 (Guard Contract): List every input where the scan would index an empty array or reduce over zero candidates, plus the input where every gain is exactly 0. In which order must the checks run so none of them can itself raise?
    Answer
    Login to view more content
  • CD0012 Debug Extra Trees

    Mode A · Bug Hunt 30 Min Python 3 + NumPy 4 Silent Bugs

    Anthropic’s evaluation tooling keeps repair tasks dependency-free: a 45-line pure NumPy implementation of an Extremely Randomized Trees (ExtraTrees) classifier sits behind a hidden test suite it currently fails, and the rules forbid rewriting the file, a format candidates have publicly described from Anthropic’s online assessment. The file fits, it predicts, and it beats a coin flip on a toy dataset whose features lie in [0, 1], so nothing crashes and no warning fires.

    The spec is the original ExtraTrees algorithm. Every tree is grown on the full training set without bootstrap, and each node scores K candidate splits (one randomly chosen feature with one random cut-point each), keeps the candidate with the highest Gini gain, and recurses. A node that stops splitting becomes a leaf that predicts for every sample reaching it, and the forest takes a majority vote over its M trees.

    The hidden suite reports three failing behaviors: (1) the learned trees are suspiciously deterministic across seeds, (2) accuracy collapses on a fixture where cut-points must be drawn between the observed feature values rather than across a fixed range, and (3) leaf predictions are wrong whenever the first sample reaching a leaf is not the majority class. Find the 4 planted bugs in the split-selection and leaf-aggregation code, explain which part of the ExtraTrees contract each one breaks, apply minimal in-place fixes, and describe the test that would have caught each bug.

    Code Under Review (Lines 01-45):

    01  import numpy as np
    02
    03  class ExtraTreesClassifier:
    04      def __init__(self, n_estimators=30, max_features=2, max_depth=12, seed=0):
    05          self.n_estimators, self.max_features = n_estimators, max_features
    06          self.max_depth, self.seed = max_depth, seed
    07
    08      def _gini(self, y):
    09          p = np.bincount(y, minlength=self.n_classes_) / len(y)
    10          return 1.0 - np.sum(p * p)
    11
    12      def _build(self, X, y, depth, rng):
    13          best, parent = None, self._gini(y)
    14          if depth < self.max_depth and parent > 0:
    15              feats = np.argsort(X.var(axis=0))[-self.max_features:]
    16              for j in feats:
    17                  t = rng.uniform(0.0, 1.0)
    18                  left = X[:, j] <= t
    19                  if left.all() or not left.any():
    20                      continue
    21                  w = left.mean()
    22                  gain = parent - w * self._gini(y[left]) - (1 - w) * self._gini(y[~left])
    23                  if best is None or gain > best[0]:
    24                      best = (gain, j, t, left)
    25          if best is None:
    26              return ("leaf", int(y[0]))
    27          _, j, t, left = best
    28          return ("node", j, t, self._build(X[left], y[left], depth + 1, rng),
    29                  self._build(X[~left], y[~left], depth + 1, rng))
    30
    31      def fit(self, X, y):
    32          self.n_classes_, self.trees_ = int(y.max()) + 1, []
    33          for _ in range(self.n_estimators):
    34              rng = np.random.RandomState(0)
    35              self.trees_.append(self._build(X, y, 0, rng))
    36          return self
    37
    38      def _predict_one(self, node, x):
    39          while node[0] == "node":
    40              node = node[3] if x[node[1]] <= node[2] else node[4]
    41          return node[1]
    42
    43      def predict(self, X):
    44          votes = np.array([[self._predict_one(t, x) for t in self.trees_] for x in X])
    45          return np.array([np.bincount(v, minlength=self.n_classes_).argmax() for v in votes])
    Top row: the ExtraTrees spec as six steps, from fit on the full data through K candidate features, one random cut-point per feature, best Gini gain, a leaf label, and a vote over M trees. Bottom row: three observed hidden-suite failures: identical forests across seeds, one label for every row when features lie in [3, 5], and leaf labels that change when rows are reordered.

    Figure 1: the spec contract every tree must follow (top) and the three behaviors the hidden suite reports (bottom); mapping each failure to the lines that cause it is the exercise.

    Interactive Python Workspace: Switch to the split-screen workspace to repair the listing in the live editor and run the behavioral test suite.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Cut-Point Support: For each candidate feature, compare the interval the cut-point is sampled from with the values that actually reach the current node.
    (2) Randomness Lifecycle: Count how many random generators one call to fit creates, and check which constructor argument, if any, controls them.
    (3) Candidate Feature Set: The spec randomizes some node-level choices and optimizes others; mark the line that makes each choice and ask whether it depends on the seed.
    (4) Leaf Aggregation: A leaf summarizes a set of samples; check whether its stored label would change if those samples arrived in a different order.
    (5) Decoy Stages: Gini (L08-10), the weighted gain (L21-22), routing (L38-41), and the vote (L43-45) deserve a quick audit too, because not every stage hides a bug.

    2Visual Review Map (Figure 2)
    Review map of the 45-line listing split into eight stages, four inside _build and four at forest level, each marked with an identical question mark.

    Figure 2: The listing split into eight inspection stages, each with the same “?” marker. Four stages hide a silent bug and four are correct; deciding which is which is the exercise.

    3Interviewer Nudge & Line Focus

    Walk each stage and answer the Socratic check before editing:

    Cut-Point Draw: Feed the forest a feature whose values all lie in [3, 5]. For a cut-point drawn on line 17, what fraction of draws sends at least one sample left and at least one sample right?
    Randomness Lifecycle: Every tree here sees the same full training set. If two trees consume exactly the same random stream, can they differ at all, and how many distinct streams does this loop produce for seed 0 versus seed 1?
    Candidate Features: Multiply one feature by 1000 without changing the information it carries. Should the set of features a node considers change, and does it change in this code?
    Leaf Label: A node stops splitting while holding labels [0, 1, 1, 1]. What label should it store, and would your answer change if those four rows arrived shuffled?
    Answer
    Login to view more content
  • ML0087 AdaBoost vs Gradient Boosting

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0082 XGBoost Improves Gradient Boosting

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0081 Gradient Boosting vs Random Forest

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0080 Decision Tree Pruning

    Why do decision trees need pruning, and how is it done?

    A three-panel question card showing a decision tree trained on 8,000 loan records with no stopping rule, its report of depth 27, 1,146 leaves, 100 percent train accuracy and 71 percent test accuracy, and one leaf whose long chain of splits ends on a single training sample.

    The Problem: A decision tree is fit to loan-default data with no depth or leaf limits. It reaches 100% train accuracy but only 71% on test, and one of its leaves holds a single applicant. Why did this happen, and what should be done to the tree?

    Answer

    An unconstrained decision tree grows until every leaf is pure, which on real data means it memorizes noise: training accuracy hits 100% while test accuracy sags. Pruning is the cure, and it comes in two forms. Pre-pruning stops growth early with rules like maximum depth, minimum samples per leaf, or minimum impurity decrease. Post-pruning grows the full tree first, then cuts back the branches whose complexity is not repaid by fit, using a validation-based criterion such as cost-complexity pruning. Post-pruning is usually stronger because a split that looks useless alone may unlock a highly valuable subtree below it; pre-pruning can never see that.

    (1) Why Trees Overfit: depth adds one axis-aligned cut per level, so a deep tree carves the training set into tiny pure cells, which is high variance by construction.
    (2) Pre- vs Post-Pruning: pre-pruning is cheap but myopic (it can miss XOR-style interactions); post-pruning explores the full tree and then removes only the provably weakest links.
    (3) Production Default: scikit-learn implements minimal cost-complexity pruning via the ccp_alpha parameter: its documented example shows an unpruned tree at 100% train / 88% test accuracy, while sweeping the pruning path finds ccp_alpha near 0.015 maximizing test accuracy.

    Train and test accuracy versus ccp_alpha: train accuracy falls monotonically, test accuracy rises to a peak near alpha 0.015 then falls, marking the bias-variance sweet spot

    Figure 1: The pruning path: as ccp_alpha grows, more of the tree is cut, training accuracy declines, and test accuracy peaks where complexity is repaid by generalization (the sklearn example peaks near 0.015).

    Cost-complexity pruning scores each subtree by its error plus a per-leaf penalty, so a branch survives only if it reduces impurity enough to pay for its leaves. Pruning proceeds weakest-link-first: at each step the node whose removal costs the least accuracy per leaf is collapsed, producing a nested sequence of subtrees indexed by alpha. You then pick alpha by cross-validation rather than by training-set performance, which is what makes the chosen tree a generalization-optimal member of the sequence.

    Two trees side by side: a deep full tree with many leaves and low purity, and its pruned version where dashed subtrees were collapsed into single leaves

    Figure 2: Post-pruning in action: the full tree (left) contains branches fitted to noise; the dashed subtrees are the weakest links, and the pruned tree (right) collapses them into leaves.

    Mathematical Formulation:
    R_{\alpha}(T) = R(T) + \alpha\,|\widetilde{T}|
    \alpha_{eff}(t) = \frac{R(t) - R(T_t)}{|T_t| - 1}

    Where:

    • R(T) is the total (sample-weighted) impurity of the leaves of tree T, and |\widetilde{T}| is its number of terminal nodes.
    • \alpha is the complexity parameter (ccp_alpha in scikit-learn); larger alpha prunes more aggressively.
    • \alpha_{eff}(t) is the effective alpha of node t: the penalty value at which keeping its branch T_t costs exactly as much as collapsing it, so the node with the smallest value is pruned first.
    AspectPre-Pruning (Early Stop)Post-Pruning (Grow Then Cut)
    Knobsmax_depth, min_samples_leaf, min_impurity_decreaseccp_alpha chosen from cost_complexity_pruning_path by CV
    Failure ModeMyopic: stops before a weak-looking split that enables a strong subtreeCosts a full grow pass plus a validation sweep
    Typical AccuracyGood, knob-sensitiveUsually better; principled weakest-link order
    When UsedMassive data, streaming, latency-critical fitsDefault for single interpretable trees

    Login to view more content
  • ML0079 No Free Lunch

    What is the No Free Lunch theorem, and what does it imply about choosing algorithms?

    Question card with three panels: four different incoming problems (tabular churn, X-ray images, support-ticket text, and an unknown next task), four candidate algorithms (linear model, tree ensemble, k-NN, neural net), and a team proposal to benchmark once and use a single algorithm everywhere.

    The Problem: A team faces very different problems, from tabular churn to images to text to tasks not seen yet, and can maintain only one model family. Someone proposes to benchmark once and use the winner everywhere. Is there one algorithm that is best on every problem?

    Answer

    The No Free Lunch theorem (Wolpert, 1996) says that if you average performance over every possible problem, meaning every possible way inputs could map to outputs, then all learning algorithms perform identically. Any edge one algorithm has on some problems is exactly canceled by losses on others. The practical reading is that no algorithm is universally best; every learner carries inductive bias that helps when it matches the true structure of the problem and hurts when it does not. So algorithm choice cannot be settled in the abstract. It must be settled empirically, by cross-validated evaluation on data drawn from your actual problem distribution.

    (1) The Formal Claim: for any two learners, their expected off-training-set error, averaged uniformly over all possible target functions, is equal; greatness exists only relative to a class of problems.
    (2) What It Does Not Say: it does not say all algorithms are equal in practice, because real problems are drawn from a tiny, highly structured corner of “all possible problems”; gradient boosting dominates tabular benchmarks precisely because real tabular data has exploitable structure.
    (3) How Industry Operationalizes It: AutoML systems embody the theorem by searching instead of assuming: Amazon SageMaker Autopilot evaluates a variety of algorithms with cross-validation and picks per-dataset. Its two modes carry different candidate families, ensembling mode runs LightGBM and CatBoost while hyperparameter-optimization mode runs linear learner, XGBoost, and an MLP, and in AUTO mode it chooses ensembling below 100 MB of data and hyperparameter tuning above it.

    Grouped bar chart: on dataset A a linear model wins, on dataset B a tree ensemble wins, and averaged across both they tie

    Figure 1: The theorem in miniature: the linear model wins on the dataset whose structure matches its bias, the tree ensemble wins on the other, and the cross-problem average is a tie.

    The theorem’s bite is against a priori rankings. “Deep learning is always better” or “XGBoost always wins tabular” are claims about problem distributions, not about algorithms; they hold only insofar as your problems keep resembling the ones where those statements were measured. The theorem also justifies feature and problem analysis as the first step of modeling: since bias must match structure, understanding the structure (linearity, interactions, invariances, noise level, sample size) is how you narrow the search before touching AutoML.

    Mathematical Formulation:
    \sum_{f \in \mathcal{F}} E[\,\mathrm{err}(A_1 \mid f)\,] = \sum_{f \in \mathcal{F}} E[\,\mathrm{err}(A_2 \mid f)\,]

    Where:

    • \mathcal{F} is the set of all possible target functions (all conceivable input-output relationships), and the average is uniform over it.
    • A_1, A_2 are any two learning algorithms, including a brilliant one and a random guesser.
    • E[\mathrm{err}(A \mid f)] is the expected generalization (off-training-sample) error when the true problem is f.
    What the Theorem ImpliesPractical Consequence
    No universal winnerEvaluate on your data with cross-validation; never pick by reputation alone
    Bias must match structureAnalyze the problem (linearity, interactions, noise, size) before choosing a family
    Search has valueAutoML (SageMaker Autopilot) tries multiple algorithm families per dataset, choosing its mode by data size
    Expertise is not obsoleteDomain knowledge narrows the search to distributions where your bias wins

    Login to view more content
  • ML0065 Random Forest III

    How to choose the number of features in a random forest?

    Three-panel question card showing a training table with 1,000 rows and 30 feature columns, a split node that randomly draws m of the 30 features, and an unset slider for m running from 1 to 30.

    The Problem: A random forest is being trained on a table with 30 features, and every split in every tree is chosen from only m features drawn at random. The knob m (max_features) can be set anywhere from 1 to 30. How should m be chosen?

    Answer

    Select the number of features considered at each split (the m, or max_features) by starting from the default heuristics, then tuning with cross-validation or out-of-bag (OOB) error to find the best value for your specific dataset. The choice trades bias against variance and accuracy against training cost.

    (1) Default Heuristics: Classification: m = \sqrt{p}; regression: m = p/3; solid starting points.
    (2) Bias-Variance Trade-Off: Smaller m adds randomness: less correlated trees (lower variance) but potentially higher bias; larger m strengthens each tree (lower bias) but correlates their errors (higher variance).
    (3) Systematic Search: Grid or randomized search over a range of values with cross-validation is the most robust method; OOB error offers a validation-free alternative unique to bagged models.

    Cross validation accuracy versus max features from 1 to 30 with a noisy plateau peaking at 15

    Figure 1: CV accuracy across max_features on a 30-feature dataset: accuracy is poor when m is tiny (trees too weak), then plateaus with a noisy peak at m = 15; the \sqrt{p} \approx 5.5 heuristic lands inside the good region, and CV refinement picks the best value on the plateau.

    Mathematical Formulation:
    m = \sqrt{p} \quad \text{(classification)}
    m = \frac{p}{3} \quad \text{(regression)}

    Where:

    • p is the total number of features in the dataset.
    • m is the number of features randomly drawn and considered at each split (max_features in most libraries).
    • These are heuristics, not optima; cross-validation or OOB error refines them per dataset.

    Login to view more content