"""What the Lasso returns: a solution that is mostly exact zeros. No data file: the instance is the task's own generator (README, "Task"), at a size that fits on a card. With n = 12 it draws X (m = 5n by d = 10n, standard normal), beta with n standard normal non-zeros at random positions and y = X beta + 0.01 eps, then minimises f(w) = 1/(2m)||y - Xw||^2 + 0.1||w||_1 by cyclic coordinate descent, the reference solver's method. The figure checks the solution with the optimality conditions of that objective, so the zeros drawn are exact zeros, not small numbers. """ import random from pathlib import Path import kit ALPHA = 0.1 n = 12 m, d = 5 * n, 10 * n rnd = random.Random(0) X = [[rnd.gauss(0, 1) for _ in range(d)] for _ in range(m)] beta = [0.0] * d for j in rnd.sample(range(d), n): beta[j] = rnd.gauss(0, 1) y = [sum(X[i][j] * beta[j] for j in range(d)) + 0.01 * rnd.gauss(0, 1) for i in range(m)] col = [[X[i][j] for i in range(m)] for j in range(d)] nrm = [sum(v * v for v in c) / m for c in col] w = [0.0] * d r = list(y) # r = y - Xw for _ in range(2000): shift = 0.0 for j in range(d): rho = sum(col[j][i] * r[i] for i in range(m)) / m + nrm[j] * w[j] new = (abs(rho) - ALPHA) / nrm[j] * (1 if rho > 0 else -1) if abs(rho) > ALPHA else 0.0 if new != w[j]: shift = max(shift, abs(new - w[j])) for i in range(m): r[i] -= col[j][i] * (new - w[j]) w[j] = new if shift < 1e-12: break else: raise SystemExit('coordinate descent did not converge') # optimality of the Lasso objective: |grad| <= alpha where w_j = 0, = alpha sign(w_j) where it is not for j in range(d): g = sum(col[j][i] * r[i] for i in range(m)) / m assert abs(g) <= ALPHA + 1e-9 if w[j] == 0 else abs(g - ALPHA * (1 if w[j] > 0 else -1)) < 1e-9 nz = [j for j in range(d) if w[j] != 0] assert 0 < len(nz) < d base, top = 214.0, 30.0 X_ = lambda j: 26 + j * (588 / (d - 1)) hi = max(abs(v) for v in w) body = kit.line(20, base, 620, base, 'faint-s', 2) body += ''.join(kit.circle(X_(j), base, 3, 'faint') for j in range(d) if w[j] == 0) for j in nz: yv = base - abs(w[j]) / hi * (base - top) body += kit.line(X_(j), base, X_(j), yv, 'f-s', 4) body += kit.dot(X_(j), yv, 6, 'f') label = f'{d} coefficients, {d - len(nz)} of them exactly zero' kit.write(__file__, 'computer-science', body, label, f'The Lasso solution for an instance of the task at n = {n}: {len(nz)} non-zero coefficients ' f'of {d}, the other {d - len(nz)} exactly zero') print(label, 'nonzero at', nz)