Implement a Class-Weighted CART Classifier: Gini, Splits and Leaf Prediction
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement a CART classifier where each sample of class `c` counts with weight `class_weight.get(c, 1.0)`. A `None` dict means all weights are 1. Fill in `gini`, `leaf_value`, `best_split`, `build_tree` and `predict`.
- `gini(y, class_weight=None)` returns ${1 - \sum_c p_c^2}$, with each $p_c$ taken from the weighted class counts. An empty `y` returns `0.0`.
- `leaf_value(y, class_weight=None)` returns the class with the largest weighted count. Ties go to the lowest label.
- `best_split(X, y, class_weight=None)` tries thresholds at the midpoints of consecutive unique values of each feature, and rows with `x <= t` go left. The gain is the parent Gini minus the children's Gini, each child weighted by its share of the parent's total class weight. Return `(feature, threshold, gain)`, keeping the first best split in feature order, then threshold order. Return `None` if no gain exceeds `1e-12`.
- `build_tree(X, y, max_depth=None, class_weight=None)` returns a leaf `{'leaf': True, 'value': ...}` when `depth >= max_depth`, the node is pure, or no split exists. Otherwise it returns `{'leaf': False, 'feature': ..., 'threshold': ..., 'left': ..., 'right': ...}`.
- `predict(tree, X)` returns an `np.ndarray` of leaf values.
For example:
```python
y = [0, 0, 0, 1]
gini(y) # 0.375
gini(y, {1: 3.0}) # 0.5 (weighted counts 3 vs 3)
leaf_value(y, {1: 3.0}) # 0 (tie, lowest label)
leaf_value(y, {1: 4.0}) # 1
best_split([[1], [2], [3], [4]], y, {1: 3.0}) # (0, 3.5, 0.5)
```
```hint Where the weights enter
Write one helper that returns the weighted count of each class. The impurity, the leaf vote and each child's share in the gain should all come from it.
```
```hint Ties under floating point
Two splits that tie exactly on paper can differ in the last bits once weights are involved. Decide how a new candidate has to compare with the current best so the earlier split keeps winning.
```
### Constraints & Assumptions
- `X` is numeric with shape `(n, d)`, and labels are integers.
- Class weights are positive. A class missing from `class_weight` has weight 1.0.
- `max_depth=None` means unlimited depth. The root is at depth 0.
### What a Strong Answer Covers
- Weighted class counts used the same way in the impurity, the leaf vote and each child's share of the parent weight
- Deterministic tie rules (lowest label for leaves, first feature then first threshold for splits) with the `1e-12` tolerance applied so rounding cannot reorder ties
- The three stopping conditions and the exact node dict shape, with `x <= threshold` going left both when growing and when predicting
- A check against the example numbers, and the observation that all weights equal to 1 reduce to plain CART
- The cost of the exhaustive split search and how to bring it down
### Follow-up Questions
- How would you make the split search faster than recounting both children for every threshold?
- When does class weighting give the same tree as oversampling the minority class, and when does it differ?
- How would you support per-sample weights on top of class weights?
- How would you return class probabilities from each leaf, and what do the class weights do to them?
Overview: Implement a CART classification tree in Python where every sample counts with its class weight, covering Gini impurity, weighted leaf votes, midpoint threshold search, tree growth and prediction. It tests whether the weights are applied consistently and whether the tie rules make the output deterministic.