Reproducible Cross-Validated Logistic Regression Scoring with StratifiedKFold
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `cv_logistic_scores(X: np.ndarray, y: np.ndarray) -> dict` that runs a reproducible 5-fold cross-validation of logistic regression and returns per-fold accuracy plus summary statistics.
Requirements:
- Estimator: `LogisticRegression(solver='lbfgs', max_iter=1000, tol=1e-6, C=1.0, class_weight='balanced', random_state=0)`.
- Splitter: `StratifiedKFold(n_splits=5, shuffle=False)` (no `random_state`).
- Scores via `cross_val_score(..., cv=cv, scoring='accuracy')`.
- Return exactly these keys: `'scores'` (the raw output, a 1-D float ndarray of shape `(5,)`), `'mean'` (Python `float`), and `'std'` (`np.std` with `ddof=0`, Python `float`).
Example:
```python
out = cv_logistic_scores(X, y)
out['scores'] # array([0.90, 0.88, 0.91, 0.89, 0.90]) shape (5,)
out['mean'] # 0.896 (Python float)
out['std'] # 0.010 (population, ddof=0)
```
```hint Pin every source of variation
List what could make two runs on the same data disagree (fold assignment, the solver, the summary formula, the return types) and check that each one is fixed in your code.
```
### Constraints & Assumptions
- `X` is a 2-D numeric array of shape `(n_samples, n_features)` and `y` is a 1-D array of class labels in the same row order.
- Every class has at least 5 samples, so stratified 5-fold splitting is possible.
- The returned scores are compared with a reference run using `assert_allclose(rtol=1e-5)`.
### What a Strong Answer Covers
- Builds the estimator and splitter exactly as specified and passes the splitter object to `cross_val_score`.
- Returns exactly the three keys with the right types: the raw score array, and the mean and population standard deviation as Python floats.
- Explains what makes the output deterministic and what would break that.
- Says what stratification guarantees about the folds and what it does not fix about accuracy as a metric.
### Follow-up Questions
- Why prefer `StratifiedKFold` over plain `KFold` here?
- Accuracy is a weak metric for imbalanced data despite `class_weight='balanced'`. What would you report instead?
- How would you keep results reproducible if shuffling were genuinely required?
- If you added feature scaling, where in the cross-validation would it have to go, and why?
Overview: Write a function that runs a reproducible stratified 5-fold cross-validation of a pinned logistic regression and returns the per-fold accuracy with its mean and population standard deviation. It tests what makes a scikit-learn evaluation deterministic and how stratified folds behave on imbalanced labels.