Check Lasso KKT optimality conditions and flag violating features
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `check_lasso_kkt(X, y, coef, intercept, alpha, tol=1e-6, fit_intercept=True)` for the objective `(1/(2n))·||y - X@coef - intercept||² + alpha·||coef||₁` (intercept unpenalized). Compute per-feature KKT violations and return a dict with keys `gradient`, `violation`, `violating`, `intercept_gradient`, `is_optimal`.
The quantities are defined as follows:
```python
r = y - X @ coef - intercept
gradient = -(X.T @ r) / n # shape (p,)
# active (coef[j] != 0): |gradient[j] + alpha * sign(coef[j])|
# inactive (coef[j] == 0): max(0, |gradient[j]| - alpha)
violating = indices j with violation[j] > tol # ascending, int64 array
intercept_gradient = float(-mean(r)) if fit_intercept else 0.0
is_optimal = no violating features and |intercept_gradient| <= tol # Python bool
```
Example:
```python
X = [[1, 0], [0, 1], [1, 1], [0, 0]]
y = [1, 2, 3, 0]
check_lasso_kkt(X, y, [0.5, 0.0], 0.0, 0.5, fit_intercept=False)
# gradient=[-0.75, -1.125], violation=[0.25, 0.625], violating=[0, 1],
# intercept_gradient=0.0, is_optimal=False
```
```hint Where the two conditions come from
Write down the subdifferential of |c| separately for c > 0, c < 0 and c = 0. Each case tells you what the gradient must look like at the optimum.
```
```hint Return types
The contract fixes the types: an int64 index array, a Python float and a Python bool. NumPy scalars and default index dtypes can slip through unnoticed.
```
### Constraints & Assumptions
- `X` has shape `(n, p)`, `y` has length `n` and `coef` has length `p`. Inputs may be lists or arrays.
- `alpha > 0`, `tol >= 0`, and all values are finite.
- A feature is active if and only if `coef[j] != 0.0` exactly.
### What a Strong Answer Covers
- The gradient of the smooth loss, with the residual's sign and the `1/n` scaling right.
- Where the separate conditions for nonzero and zero coefficients come from.
- How the unpenalized intercept is checked, with and without fitting it.
- Output types and ordering exactly as specified.
- The cost of the check and its limits as a certificate of optimality.
### Follow-up Questions
- How would you use this check to build a strong screening rule?
- How does the check change for elastic net?
- Why is a fixed absolute `tol` fragile, and what would you use instead?
Overview: Write a NumPy function that checks the KKT optimality conditions of a Lasso fit, reports per-feature violations, and checks the unpenalized intercept. Tests subgradients of the L1 penalty, residual and gradient algebra, and exact output contracts.