Implement a variance threshold feature selector with NaN-aware population variance
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement a class `VarianceThresholdSelector(threshold=0.0)`. `fit(X)` learns the population variance of each column (ddof=0, NaNs ignored). `transform(X)` keeps only the columns whose fitted variance is strictly greater than `threshold`.
Requirements:
- `fit` stores `variances_` (a float array) and returns `self`. An all-NaN column has variance `0.0`.
- `fit` raises `ValueError` for a negative `threshold`, and `transform` raises `ValueError` when the number of features differs from the one seen in `fit`.
- A DataFrame input gives a DataFrame output with column names, order and original dtypes kept. An ndarray input gives an ndarray output. The input is never mutated.
- `get_support()` returns a boolean mask, and `get_support(indices=True)` returns the integer positions of the kept columns.
- `fit_transform(X)` equals `fit(X).transform(X)`, and `transform` uses only statistics learned in `fit`.
Example:
```python
df = pd.DataFrame({"a": [1., 3., 5.], "b": [7., 7., 7.], "c": [0., 1., 0.]})
sel = VarianceThresholdSelector(threshold=0.5).fit(df)
sel.variances_ # [2.6667, 0.0, 0.2222]
sel.get_support() # [True, False, False]
sel.get_support(indices=True) # [0]
sel.transform(df) # df[["a"]]
```
```hint Constant columns in floating point
Work out what your variance code returns for a column holding the float 0.1 three times, and what the default threshold of 0 then does with that column.
```
### Constraints & Assumptions
- `X` is a 2-D numeric pandas DataFrame or NumPy array of shape `(n, d)` and may contain NaN.
- `threshold` is a float, `0.0` by default.
### What a Strong Answer Covers
- Population variance per column over the non-missing values only, with all-NaN columns set to `0.0`.
- A strict comparison against the threshold and validation of a negative threshold in `fit`.
- A `transform` that slices the original input by the mask frozen in `fit`, returning the same container type with names, order and dtypes intact and the input untouched.
- Constant columns coming out at exactly zero variance despite floating-point rounding.
- Both modes of `get_support` and a `fit_transform` that matches `fit` followed by `transform`.
### Follow-up Questions
- Why is variance threshold scale-sensitive, and how would you handle that?
- How would you compute the same variances in one pass over data that does not fit in memory?
- For a binary 0/1 column, what threshold removes it when one value appears in more than 80% of rows?
Overview: Implement a variance threshold feature selector that learns NaN-aware population variances in fit and drops low-variance columns in transform. It tests population variance with missing values, a strict threshold comparison, keeping DataFrame columns and dtypes intact, and floating-point care with constant columns.