Extract Logistic Regression Coefficients from a scikit-learn Pipeline with named_steps
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `pipeline_coefficients(X, y)`. It fits `Pipeline([('scaler', StandardScaler()), ('clf', LogisticRegression(...))])` on `(X, y)` and returns `pipe.named_steps['clf'].coef_`. `y` contains only the integer labels 0 and 1.
```python
def pipeline_coefficients(X: np.ndarray, y: np.ndarray) -> np.ndarray:
...
```
The function must:
- name the steps `'scaler'` and `'clf'`, with `StandardScaler` left at its defaults;
- pin `LogisticRegression` to `penalty='l2'`, `C=1.0`, `solver='lbfgs'`, `max_iter=1000`, `tol=1e-6`, `fit_intercept=True`;
- return a 1-D `float64` array of shape `(n_features,)`, flattening the `(1, n_features)` `coef_`.
The returned weights apply to the standardized features, not to the raw columns of `X`.
```hint Reaching into the pipeline
After `fit`, a pipeline keeps its fitted steps under the names you gave them. Check the shape of `coef_` for a binary problem before you return it.
```
```hint What the numbers mean
Think about what the scaler did to each column before the classifier saw it. That decides what a one-unit change in a feature means for these coefficients.
```
### Constraints & Assumptions
- `X` is a 2-D numeric array of shape `(n_samples, n_features)`.
- `y` has shape `(n_samples,)` and contains both labels 0 and 1.
- The hyperparameters above are fixed so the output is reproducible.
### What a Strong Answer Covers
- Building the pipeline with the required step names and pinned hyperparameters, and fitting it in one call.
- Reading `coef_` from the fitted classifier through `named_steps` and flattening it to shape `(n_features,)`.
- What a coefficient on a standardized feature means and why the magnitudes can be compared across features.
- Edge cases such as constant features, a single class in `y`, and convergence.
### Follow-up Questions
- How would you recover the coefficients and intercept on the original raw feature scale?
- Why chain the scaler inside the `Pipeline` instead of scaling `X` once up front?
- Would those raw-scale coefficients match what you get by fitting the same L2-penalized model on raw `X`? Why?
- How would you read the coefficients if the pipeline were tuned with `GridSearchCV`?
Overview: Fit a StandardScaler and LogisticRegression pipeline in scikit-learn and return the fitted classifier's coefficients through named_steps. It tests pipeline mechanics, what coefficients on standardized features mean, how to map them back to the raw scale, and why scaling inside the pipeline prevents leakage.