Implement a univariate filter feature selector with F-test, chi-squared and mutual information scoring
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement a class `FilterSelector(score_func, k)` for univariate filter feature selection against a classification target. `fit(X, y)` scores every feature against `y` on its own, keeps the `k` highest-scoring features, and stores `scores_` and `pvalues_`. `transform(X)` applies the selection learned in `fit` to any data without refitting.
Requirements:
- `score_func` is `"f_classif"`, `"chi2"` or `"mutual_info"`. `f_classif` and `chi2` match sklearn's statistics and p-values on ordinary columns. `mutual_info` is the discrete plug-in mutual information in nats, where each distinct value of a column is a category, and it sets `pvalues_ = None`.
- A constant column (or an all-zero column for `chi2`) gets score `0` and p-value `1`. Ties in score are broken by lower column index.
- `fit` raises `ValueError` for an unknown `score_func`, for `k` outside `[0, n_features]` (the string `"all"` is also accepted and keeps every feature), or for negative values with `chi2`.
- `transform` returns a DataFrame for a DataFrame input and an ndarray for an ndarray input, keeping the original column order and dtypes.
- `get_support(indices=False)` returns a boolean mask, or an index array when `indices=True`. `get_feature_names_out()` returns a list of column names, or `"x0"`, `"x1"`, ... when `fit` was given an array.
- Inputs are never mutated.
Example:
```python
X = pd.DataFrame({"a": [1, 2, 3, 10, 11, 12],
"b": [5, 1, 4, 2, 6, 3],
"c": [0, 0, 1, 1, 0, 1]})
y = [0, 0, 0, 1, 1, 1]
sel = FilterSelector("f_classif", k=2).fit(X, y)
sel.scores_ # [121.5, 0.03846, 0.5]
sel.get_support() # [True, False, True]
sel.get_support(indices=True) # [0, 2]
sel.get_feature_names_out() # ["a", "c"]
```
```hint Degenerate columns
Work out what the F ratio becomes when a column has no spread inside any class but different class means, and what it becomes when the column is constant overall. The two cases need different outputs.
```
```hint Deterministic top k
Sorting on two keys (score descending, then column index ascending) makes the selection unique. Check which key your sort routine treats as the primary one, and whether it is stable.
```
### Constraints & Assumptions
- `X` is a 2-D numeric pandas DataFrame or NumPy array with `n` rows and `p` feature columns and no missing values.
- `y` is a 1-D array-like of `n` class labels with at least two distinct classes.
- `k` is an integer or the string `"all"`.
### Clarifying Questions to Ask
- Should `transform` on a DataFrame check that the column names match the ones seen in `fit`, or only the column count?
- What should `fit` do when `y` has a single class, or when `f_classif` has no more samples than classes?
- Can every column be cast to float for `mutual_info`, or should it accept string categories as well?
### What a Strong Answer Covers
- Correct per-column F and chi-squared statistics and p-values, with the formulas and degrees of freedom stated.
- Explicit handling of degenerate columns: constant columns, columns with zero within-class spread, and all-zero columns under `chi2`.
- A deterministic top-k selection with the lower-index tie rule and validated `k`, including `k=0` and `"all"`.
- A clean split between `fit` and `transform`: scores learned once, output type, column order and dtypes preserved, inputs untouched.
- A plug-in mutual information estimate built from a value-by-class contingency table in natural log units.
### Follow-up Questions
- How would you support a sparse `X` for `chi2` without converting it to a dense array?
- Which kinds of useful features does a univariate filter miss, and what would you use to catch them?
- How do you tune `k` with cross-validation without leaking the validation folds into the selection?
- Plug-in mutual information favors columns with many distinct values. How would you correct for that?
Overview: Implement a univariate feature selector that scores each column against a class label with the ANOVA F test, chi-squared or discrete mutual information and keeps the top k. It tests sklearn-compatible statistics, handling of constant and perfectly separating columns, deterministic tie-breaking and a clean fit and transform split.