Implement a CART Decision Tree Classifier with Gini Splits and Pre-Pruning
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `Node.is_leaf` and a `DecisionTreeClassifier` with `fit`, `predict`, `get_depth` and `get_n_leaves`. The model is a binary classification tree on numeric features that chooses splits by Gini impurity. The constructor takes `max_depth=None`, `min_samples_split=2` and `min_impurity_decrease=0.0`. `fit` stores the tree in `root_` and returns `self`.
The tree must follow these rules:
- Candidate thresholds are the midpoints between adjacent distinct sorted values of a feature. Rows with `x[feature] <= threshold` go left. Pick the split with the minimum weighted child Gini. Ties go to the lowest feature index, then the lowest threshold.
- Every node stores `value` (the majority label, smallest label on ties), `n_samples` and `impurity` (its Gini).
- A node becomes a leaf when it is pure, when `depth >= max_depth`, when `n_samples < min_samples_split`, or when all features are constant within it.
- A node also becomes a leaf when `(n_node / n_total) * (gini_node - weighted_child_gini) < min_impurity_decrease` for its best split, where `n_total` is the number of training rows.
- `predict` returns the original labels, whatever their dtype. A tree that is a single leaf has depth `0`. Mismatched `X` and `y`, or calling `predict` before fitting, raises `ValueError`.
Example:
```python
X = np.arange(1, 9, dtype=float).reshape(-1, 1)
y = np.array([0, 0, 0, 1, 0, 1, 1, 1])
t = DecisionTreeClassifier().fit(X, y)
t.root_.threshold, t.get_depth(), t.get_n_leaves() # 3.5, 3, 4
t.root_.right.impurity # 0.32 (up to float rounding)
t = DecisionTreeClassifier(min_impurity_decrease=0.1).fit(X, y)
t.get_depth(), t.get_n_leaves() # 1, 2
```
```hint Scoring every threshold in one pass
Sort the node's rows by one feature and keep running class counts. The counts on each side of a cut give both child Gini values without rescanning the rows.
```
```hint Ties and floating point
Two cuts with the same score can differ in the last bit after arithmetic, and the example root has two cuts that tie. Think about the scan order and how you compare a candidate with the current best.
```
### Constraints & Assumptions
- `X` is a 2-D numeric array with one row per label in `y`.
- `max_depth` is `None` or an integer of at least 0.
- Only NumPy is allowed.
### What a Strong Answer Covers
- A split search that scores every midpoint threshold of a feature from sorted cumulative class counts, without a quadratic rescan per cut
- Deterministic tie-breaking by feature index and then threshold that survives floating-point noise
- All the stopping rules, including the impurity decrease weighted by the node's share of the full training set
- Node bookkeeping (`value`, `n_samples`, `impurity`) and predictions mapped back to the original labels
- Input validation, the unfitted case, and depth and leaf counts where a single leaf has depth 0
### Follow-up Questions
- How would you add `min_samples_leaf`, and why does it have to be enforced inside the split search?
- Your tree and scikit-learn's pick different root features on a dataset where two features tie. What could cause that?
- How would you extend the split search to support sample weights?
- If you switch the criterion to entropy, why does the same `min_impurity_decrease` value prune differently?
Overview: Implement a CART decision tree classifier in NumPy with Gini splits, midpoint thresholds, deterministic tie-breaking and pre-pruning by depth, sample count and impurity decrease. It tests an efficient split search with cumulative class counts and exact handling of the stopping rules.