Check lasso optimality with the KKT subgradient conditions
Why it matters Lasso and elastic net solvers stop when the KKT violation is small, and the same check powers safe feature screening rules.
The lasso objective is not differentiable at 0, so optimality is checked with subgradients (the KKT conditions). This is how solvers decide they have converged.
Write lasso_kkt_violation(X, y, w, alpha) for the objective (1 / (2n)) ||y - X w||^2 + alpha ||w||_1 (no intercept). Let c = X^T (y - X w) / n. For coordinates with w_j != 0 the condition is c_j = alpha * sign(w_j), so the violation is |c_j - alpha * sign(w_j)|. For w_j == 0 the condition is |c_j| <= alpha, so the violation is max(|c_j| - alpha, 0). Return (viol, max_viol): the float array of per-coordinate violations and its maximum as a float.
def lasso_kkt_violation(X, y, w, alpha)Example
X [[1, 0], [0, 1]], y [3, 0.1], w [2.5, 0], alpha 0.25 gives viol [0.0, 0.0] and max_viol 0.0.
Understand the idea
For a smooth loss, the bottom is where the gradient is zero. The lasso adds alpha * |w|, which has a sharp corner at 0, so we use the subgradient: at the corner, the slope of |w| can be anything between -1 and 1.
That gives two rules. If w_j is not zero, the pull from the data, c_j = X_j^T (y - X w) / n, must exactly balance the penalty slope: c_j = alpha * sign(w_j). If w_j is zero, the data pull only needs to be weak: |c_j| <= alpha. A strong pull would mean moving w_j away from 0 lowers the loss.
Worked example: X = I (n = 2), y = [3, 0.1], w = [2.5, 0], alpha = 0.25. Residual [0.5, 0.1], so c = [0.25, 0.05]. Coordinate 0 is active with sign +1: |0.25 - 0.25| = 0. Coordinate 1 is zero and |0.05| <= 0.25: violation 0. So w is optimal.
Rule: violation_j = |c_j - alpha sign(w_j)| if w_j != 0, else max(|c_j| - alpha, 0).
Lasso solvers stop when the largest violation is below a tolerance.