Leak-Free PCA Pipeline With CV Tuning
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement three functions with scikit-learn: `build_pipeline`, `tune_n_components` and `leakage_comparison`. Together they build a scaler, PCA and classifier pipeline, choose `n_components` by cross-validated accuracy, and compare a leaky procedure (PCA fit before the train/test split) against a clean one.
```python
def build_pipeline(n_components, C=1.0): ...
def tune_n_components(X, y, candidates, n_splits=5, seed=0): ...
def leakage_comparison(X, y, n_components, test_size=0.3, seed=0): ...
```
Requirements:
- `build_pipeline` returns an unfitted `Pipeline` with steps `"scaler"` (`StandardScaler()`), `"pca"` (`PCA(n_components, svd_solver="full")`) and `"clf"` (`LogisticRegression(C=C, max_iter=1000)`).
- `tune_n_components` scores each candidate with `StratifiedKFold(n_splits, shuffle=True, random_state=seed)` and `"accuracy"` scoring.
- It returns `(best_k, scores)`. `scores` is a float array of mean CV accuracy in candidate order, and `best_k` is a Python `int` (the first maximum wins ties).
- `leakage_comparison` splits row indices with `train_test_split(test_size=test_size, random_state=seed, stratify=y)`. Leaky: fit the scaler and PCA on all of `X`, then fit the classifier (same settings as the pipeline's classifier) on the training rows. Clean: fit `build_pipeline(n_components)` on the training rows.
- It returns a dict with keys `leaky_score` and `clean_score` (test accuracy as a `float`) and `leaky_components` and `clean_components` (the PCA `components_`, shape `(n_components, n_features)`).
```hint Same folds for every candidate
Candidate scores are only comparable when each one is measured on the same training and validation rows. Think about what makes a shuffled splitter produce identical folds on every call.
```
```hint Isolate the leak
The two procedures in `leakage_comparison` should differ in exactly one thing: which rows the scaler and PCA see while fitting. Keep the split and the classifier settings identical.
```
### Constraints & Assumptions
- `X` is a numeric array of shape `(n_samples, n_features)` and `y` is an array of `n_samples` class labels.
- `candidates` is a sequence of positive integers, each no larger than the number of features or the number of rows in a training fold.
- Every class has at least `n_splits` members, so stratified folds and a stratified test split can be built.
### What a Strong Answer Covers
- How every fit (each CV fold and the final split) keeps validation or test rows out of the scaler and PCA.
- How the candidates are made comparable and reproducible across folds.
- The exact return contract: types, candidate order and the tie-break for `best_k`.
- A leaky procedure that differs from the clean one only in where preprocessing is fit.
- Edge cases such as a candidate too large for a training fold, or a class too small to stratify.
### Follow-up Questions
- Why can the leaky score look optimistic even though PCA is unsupervised?
- How would you tune `n_components` and `C` jointly and still report an unbiased score?
- How could you choose `n_components` without a classifier in the loop?
Overview: Implement a scikit-learn pipeline that chains standard scaling, PCA and logistic regression, tune the number of components with seeded stratified cross-validation, and compare a leaky preprocessing setup against a clean one. It tests awareness of data leakage, reproducible model selection and exact return contracts.