Implement a Classifier Chain for Multi-Label Classification
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement a `ClassifierChain` class for multi-label classification with `fit(X, Y)`, `predict(X)` and `predict_proba(X)`. `X` is an `(n, d)` feature matrix and `Y` is an `(n, L)` matrix of 0/1 labels. The chain trains one binary classifier (a link) per label, and each link sees `X` plus the labels that come earlier in the chain.
The constructor is `ClassifierChain(base_estimator_factory, order=None)`, and the class must behave as follows:
- `order` is a permutation of the label indices, and `None` means `0..L-1`. Anything that is not a permutation of `0..L-1` raises `ValueError`.
- In `fit`, link `k` is a fresh `base_estimator_factory()` trained on `hstack([X, Y[:, order[:k]]])` (the true labels) with target `Y[:, order[k]]`. `fit` returns `self`.
- The fitted links are stored in chain order in `estimators_`.
- In `predict`, link `k` sees `X` plus the hard `predict` outputs of links `0..k-1`. The result is an int 0/1 matrix of shape `(n, L)` with columns in the original label order.
- `predict_proba` passes the same hard predictions down the chain, and each column is that link's `predict_proba(...)[:, 1]`, again in the original label order.
Example with a stub base estimator whose `fit` does nothing and whose `predict(X)` returns `1 - X[:, -1]`:
```python
class Stub:
def fit(self, X, y):
return self
def predict(self, X):
return 1 - X[:, -1]
# L = 3, default order; the stub ignores the training data
chain = ClassifierChain(Stub).fit(np.zeros((4, 1)), np.zeros((4, 3), dtype=int))
chain.predict(np.array([[0.0], [1.0]]))
# row 0: link0 sees [0] -> 1, link1 sees [0, 1] -> 0, link2 sees [0, 1, 0] -> 1
# row 1: link0 sees [1] -> 0, link1 sees [1, 0] -> 1, link2 sees [1, 0, 1] -> 0
# returns [[1, 0, 1],
# [0, 1, 0]]
```
```hint Column bookkeeping
Run the links in chain order and keep their outputs in chain order. Work out once, at the end, which chain position each original label column comes from, and test with an order that is not the identity.
```
```hint What the links see
At inference there are no true labels. Check that the extra columns you build for link `k` are the same kind of values, in the same order, as the label columns it was trained on.
```
### Constraints & Assumptions
- Base estimators follow the scikit-learn `fit` / `predict` / `predict_proba` API, and each call to the factory returns a new unfitted estimator.
- `Y` holds only 0 and 1. `L` comes from `Y`, so `order` can only be checked in `fit`.
- Results must match `sklearn.multioutput.ClassifierChain` with its default settings (no cross-validation, hard predictions passed down the chain).
### What a Strong Answer Covers
- How each link's training input is built from `X` and the true upstream labels, with a fresh estimator per link
- Inference that passes hard predictions down the chain in both `predict` and `predict_proba`
- Mapping chain-ordered outputs back to the original label order, with the right output dtypes
- Validation of `order`, including duplicates, wrong length and non-integer values
- The cost per link and edge cases such as a label column that holds a single class
### Follow-up Questions
- Why can training on true labels while predicting from predicted labels hurt accuracy, and how would you fix it?
- How would you reduce the model's sensitivity to the chosen label order?
- Should the chain pass probabilities down instead of hard labels? What would have to change in training?
Overview: Implement a classifier chain for multi-label classification with fit, predict and predict_proba, where each binary link sees the features plus the earlier labels in the chain. It tests label-order bookkeeping, inverse permutations and the gap between training on true labels and predicting from predicted ones.