Fit linear regression with non-negative slopes and a free intercept in scikit-learn
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def nonnegative_coefficients(X: np.ndarray, y: np.ndarray) -> np.ndarray` that fits a multiple linear regression of `y` on `X` (with intercept) subject to every slope being `>= 0`, and returns the constrained slopes. This is a hard inequality constraint, not a penalty, with no tuning parameter.
The function should:
- Fit with `sklearn.linear_model.LinearRegression(positive=True)`.
- Include an intercept in the fit but exclude it from the returned array.
- Return a shape-`(3,)` `np.ndarray` of slopes in `X` column order, every entry `>= 0`.
```hint Which parameters are constrained
Check which attribute of the fitted estimator holds the slopes, which holds the intercept, and which of the two the `positive` flag applies to.
```
```hint Compare with clipping
Fit plain OLS, set its negative coefficient to zero by hand, and compare the other slopes with the constrained fit. Ask yourself whether they should match.
```
### Constraints & Assumptions
- `X` is float with shape `(30, 3)` and `y` has shape `(30,)`.
- On the test data, unconstrained OLS yields one clearly negative coefficient that must come out as zero.
- The intercept is fitted without a sign constraint; only the three slopes must be non-negative.
### What a Strong Answer Covers
- Fitting with `positive=True` and an intercept, then returning only `coef_` in `X` column order.
- How the intercept stays unconstrained while the slopes are restricted.
- Why a constrained coefficient lands at exactly 0.
- How the result differs from fitting OLS and clipping negative coefficients to zero.
- How a hard sign constraint differs from ridge or lasso penalties.
### Follow-up Questions
- Why can NNLS return exactly `0` for a coefficient instead of a small negative value?
- How does this differ from Lasso or Ridge regularization?
- How would you reproduce the fit with `scipy.optimize.nnls`, and how do you handle the intercept there?
Overview: Fit a multiple linear regression with an unconstrained intercept where every slope must be non-negative, using scikit-learn, and return the slopes. Tests understanding of hard sign constraints, why constrained coefficients land at exactly zero, and how the fit differs from clipping OLS or from ridge and lasso.