Fit Logistic Regression on Sparse CSR Input in scikit-learn
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `def sparse_fit_proba(X_dense: np.ndarray, y: np.ndarray) -> np.ndarray`. Convert the mostly-zero `X_dense` to CSR, fit `LogisticRegression` directly on it (no `.toarray()`), and return positive-class probabilities for the same sparse matrix. `y` contains only integer labels 0 and 1.
Requirements:
- Convert via `scipy.sparse.csr_matrix(X_dense)` and fit on it directly.
- Pin `penalty='l2'`, `C=1.0`, `solver='lbfgs'`, `max_iter=1000`, `tol=1e-6`, `fit_intercept=True`.
- Return `model.predict_proba(X_sparse)[:, 1]` as a 1-D `np.ndarray` of shape `(n_samples,)`, dtype `float64`.
- The result must match a dense fit to solver tolerance.
Example:
```python
X_dense = np.array([[0, 0, 3],
[0, 1, 0],
[2, 0, 0],
[0, 0, 0]], dtype=float)
y = np.array([1, 0, 1, 0])
proba = sparse_fit_proba(X_dense, y)
# proba.shape == (4,), dtype float64
# equal to a dense-fit predict_proba(...)[:, 1] up to solver tolerance
```
```hint Checking the result
Fit the same model on `X_dense` and compare the two probability vectors. Think about what kind of comparison two floating-point fits can pass.
```
### Constraints & Assumptions
- `X_dense` is a 2-D array of shape `(n_samples, n_features)` in which most entries are zero.
- `y` has one 0/1 label per row, and both classes appear.
- The probabilities are returned for the same rows the model was fit on.
### What a Strong Answer Covers
- Building the CSR matrix once and passing it to both `fit` and `predict_proba` without densifying it.
- Using the pinned hyperparameters and taking the class-1 column of `predict_proba` as a 1-D `float64` array.
- Why the sparse and dense fits optimize the same objective, and how to compare their outputs.
- When CSR storage saves memory and time, and when it does not.
### Follow-up Questions
- Why does CSR fitting produce the same results as a dense fit (up to round-off)?
- When would sparse input actually help performance?
- Which solvers support sparse input for logistic regression?
Overview: Fit a scikit-learn logistic regression directly on a CSR sparse matrix without converting it back to dense, and return the positive-class probabilities. It tests how sparse storage works with the lbfgs solver, why the result matches a dense fit, and when sparse input saves memory and time.