Top-Down Hierarchical Classifier with Confidence Stopping

Quick Overview

Implement a top-down hierarchical classifier that trains one local model per parent node and stops descending when the best child's probability falls below a threshold. It tests path construction, aligning probability columns with sorted children, tie-breaking and partial predictions at internal nodes.

Top-Down Hierarchical Classifier with Confidence Stopping

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `TopDownHierarchicalClassifier(hierarchy, root="root", threshold=0.0, base_estimator_factory=None)`. `hierarchy` maps each parent node to a list of its children. Train one local classifier per parent node, then predict by descending from `root` and stopping early when the best child's probability is below `threshold`. The class must meet these requirements: - `fit(X, y)` returns `self`. Each label (leaf or internal) adds its row to every ancestor's classifier, with the next node on the label's path as the target. A label that is not in the hierarchy raises `ValueError`. - `local_classifiers_` holds one entry per parent node that received training rows, each built by calling `base_estimator_factory()` (default `LogisticRegression(random_state=0)`). If only one child of that parent is observed, store `None` and do not call the factory. - `local_proba(X, node)` returns an array of shape `(n, n_children)` with columns in sorted child order. Children the local model never saw get `0`, and a parent stored as `None` gives its single observed child `1.0`. - `predict(X)` moves to the argmax child if that child's probability is `>= threshold`, and otherwise stops at the current node. It also stops at any node with no entry in `local_classifiers_` (a leaf, or a parent that got no training rows). A `None` entry is not a stop, because its observed child has probability `1.0`. Ties go to the lowest sorted child. It returns an object `np.ndarray` of node names. - `predict_paths(X)` returns a list of tuples holding each prediction's root-to-node path, excluding `root`, so a `root` prediction gives `()`. Estimators expose `fit`, `predict_proba` and `classes_`. Example, with an estimator that ignores `X` and predicts each class's training frequency (for instance `base_estimator_factory=lambda: DummyClassifier(strategy="prior")`) and any 4-row `X`: ```python hierarchy = {"root": ["animal", "vehicle"], "animal": ["cat", "dog"], "vehicle": ["car", "truck"]} y = ["cat", "cat", "dog", "car"] # root: animal=0.75, vehicle=0.25 ; animal: cat=2/3, dog=1/3 # vehicle only saw "car": local_classifiers_["vehicle"] is None, # and local_proba(X, "vehicle") rows are [1.0, 0.0] for ["car", "truck"] threshold=0.5 -> "cat" # path ("animal", "cat") threshold=0.7 -> "animal" # path ("animal",) threshold=0.76 -> "root" # path () ``` ```hint Start from the paths Invert `hierarchy` into a child-to-parent map and walk it upward to get each label's path. Every consecutive pair of nodes on that path is one training row for the first node of the pair. ``` ```hint Line up the columns `predict_proba` columns follow the fitted estimator's `classes_`, which only lists the children it saw during training. Place them into the full sorted child list before taking the argmax. ``` ```hint Batch the descent Rows at the same current node can share one `predict_proba` call, so group active rows by node at each step. ``` ### Constraints & Assumptions - `X` is a 2-D numeric array with one row per entry of `y`. - `hierarchy` describes a tree: every node has at most one parent, and every valid label's chain of parents reaches `root`. - Node names are hashable and sortable, such as strings. ### What a Strong Answer Covers - Correct root-to-label paths, including labels at internal nodes and the `ValueError` for unknown labels - Per-parent training sets, with the single-observed-child case stored as `None` without calling the factory - Mapping `predict_proba` columns onto the sorted child list through `classes_`, zero-filling unseen children - The descent loop: the `>=` comparison, deterministic tie-breaking, and stopping only at nodes with no entry - The required return types for `predict` and `predict_paths` ### Follow-up Questions - How would you limit error propagation from a wrong decision near the root? - How would you evaluate predictions that stop at internal nodes? - Should every node share one global threshold?

Overview: Implement a top-down hierarchical classifier that trains one local model per parent node and stops descending when the best child's probability falls below a threshold. It tests path construction, aligning probability columns with sorted children, tie-breaking and partial predictions at internal nodes.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement TopDownHierarchicalClassifier(hierarchy, root="root", threshold=0.0, base_estimator_factory=None). hierarchy maps each parent node to a list of its children. Train one local classifier per parent node, then predict by descending from root and stopping early when the best child's probability is below threshold.

The class must meet these requirements:

  • fit(X, y) returns self . Each label (leaf or internal) adds its row to every ancestor's classifier, with the next node on the label's path as the target. A label that is not in the hierarchy raises ValueError .
  • local_classifiers_ holds one entry per parent node that received training rows, each built by calling base_estimator_factory() (default LogisticRegression(random_state=0) ). If only one child of that parent is observed, store None and do not call the factory.
  • local_proba(X, node) returns an array of shape (n, n_children) with columns in sorted child order. Children the local model never saw get 0 , and a parent stored as None gives its single observed child 1.0 .
  • predict(X) moves to the argmax child if that child's probability is >= threshold , and otherwise stops at the current node. It also stops at any node with no entry in local_classifiers_ (a leaf, or a parent that got no training rows). A None entry is not a stop, because its observed child has probability 1.0 . Ties go to the lowest sorted child. It returns an object np.ndarray of node names.
  • predict_paths(X) returns a list of tuples holding each prediction's root-to-node path, excluding root , so a root prediction gives () .

Estimators expose fit, predict_proba and classes_.

Example, with an estimator that ignores X and predicts each class's training frequency (for instance base_estimator_factory=lambda: DummyClassifier(strategy="prior")) and any 4-row X:

hierarchy = {"root": ["animal", "vehicle"],
             "animal": ["cat", "dog"],
             "vehicle": ["car", "truck"]}
y = ["cat", "cat", "dog", "car"]
# root: animal=0.75, vehicle=0.25 ; animal: cat=2/3, dog=1/3
# vehicle only saw "car": local_classifiers_["vehicle"] is None,
# and local_proba(X, "vehicle") rows are [1.0, 0.0] for ["car", "truck"]
threshold=0.5  -> "cat"     # path ("animal", "cat")
threshold=0.7  -> "animal"  # path ("animal",)
threshold=0.76 -> "root"    # path ()

Constraints & Assumptions

  • X is a 2-D numeric array with one row per entry of y .
  • hierarchy describes a tree: every node has at most one parent, and every valid label's chain of parents reaches root .
  • Node names are hashable and sortable, such as strings.

What a Strong Answer Covers Guidance

  • Correct root-to-label paths, including labels at internal nodes and the ValueError for unknown labels
  • Per-parent training sets, with the single-observed-child case stored as None without calling the factory
  • Mapping predict_proba columns onto the sorted child list through classes_ , zero-filling unseen children
  • The descent loop: the >= comparison, deterministic tie-breaking, and stopping only at nodes with no entry
  • The required return types for predict and predict_paths

Follow-up Questions Guidance

  • How would you limit error propagation from a wrong decision near the root?
  • How would you evaluate predictions that stop at internal nodes?
  • Should every node share one global threshold?