Implicit regularization: what gradient descent chooses
Study how optimization selects among infinitely many empirical-risk minimizers: minimum-norm least-squares GD, early stopping as ridge, maximum-margin logistic regression, and stability of SGD with few passes.
After this lesson you can
- Prove that GD initialized in the row space of X converges to the minimum-norm solution X⁺y.
- Relate early stopping to ridge by comparing filters 1 - (1 - ημ_i)^t and μ_i/(μ_i + λ).
- State and numerically verify Soudry et al.’s directional maximum-margin convergence at rate 1/log t.
- Prove the SGD stability bound for convex, Lipschitz and smooth losses (Hardt, Recht and Singer).
- Explain with diagonal linear networks how implicit bias depends on parameterization and initialization scale.
Before you start
- 13Uniform and on-average algorithmic stabilityOn-average stability implies generalizationMargin-based generalization boundSpectral risk of kernel ridge regressionEffective dimensionRegularized loss minimization
- 06O(1/k) rate of gradient descent for smooth convex functionsLinear convergence of gradient descent for strongly convex functionsStochastic gradient descent
- 02Moore-Penrose pseudoinverseMinimum-norm solution
- 11Logistic regression
Motivation: train without a regularizer and still generalize
All theory in this topic so far controls risk by restricting the hypothesis class: a bounded-norm ball, an explicit penalty as in regularized loss minimization, or finite VC dimension. Modern practice does something else. A network with tens of millions of parameters trains with SGD on a loss without a regularization term until training error reaches zero, yet generalizes. In that regime empirical risk has infinitely many global minimizers, many poor out of sample, and the optimization problem alone does not say which is obtained.
The algorithm decides. Starting point, update geometry, parameterization and number of steps select a particular minimizer, and that minimizer is often the solution to a regularization problem nobody wrote down.
The lesson studies four cases where this rule can be stated precisely, three with complete proofs and classification with its essential argument, and a fifth where the rule has a different form:
- In least squares with more parameters than data, GD from zero converges to the minimum -norm interpolator, the same as ridge with .
- Stopping GD at iteration applies a filter to each data eigendirection nearly identical to ridge with .
- For classification with separable data, weight norm diverges and direction converges very slowly to the maximum-margin SVM.
- With parameterization , initialization scale shifts bias from to without changing the function class or loss.
- SGD with few passes is uniformly stable, so it generalizes for a reason independent of any norm.
Overparameterized least squares: GD stays in the row space
Take and and squared empirical risk
with and eigenvalues . If , has at least zero eigenvalues, is not strictly convex and its minimizers form an affine subspace: , where is the pseudoinverse applied to . If also , all interpolate: .
The smallest case containing the whole idea has one equation and two unknowns: with and . Solutions form a line. The gradient of is : it always points in direction , perpendicular to the solution line. GD cannot move in any other direction.
The figure shows three facts formalized by the next theorem: the component of in the null space of never changes (the “null component” readout is the same initially and finally); the limit does not depend on step size while the algorithm is stable; and update geometry does change it.
Proof
Let . It satisfies the normal equations because (one Moore-Penrose identity). Then and error obeys
Diagonalize with orthonormal . The with span and those with span . In the eigenbasis, :
- if , because , and the component tends geometrically to zero;
- if , the component does not change: , because has no null-space component.
Therefore and with the stated convergence factor. This limit lies in . For any other with , since , Pythagoras gives
which is minimized exactly at .
∎The proof uses nothing specific to GD beyond each update being a linear combination of gradients, all in . The same argument holds for Polyak or Nesterov momentum, SGD with any batch size and any step sequence: all preserve the null component, so if they converge to a minimizer it is the same one. A fixed preconditioner instead moves iterates through , generally not orthogonal to the null space, and the limit becomes the minimizer closest to in norm (the ellipse in the figure).
GD choosing does not yet show generalizes. It does show the trained model is not an arbitrary minimizer but the minimum-norm one, and norm is exactly what Rademacher complexity bounds control for balls . When that control suffices is the question of benign interpolation.
Early stopping as spectral regularization
Now do not wait for convergence. From , the proof gives , namely,
Compare with ridge, . Since ,
the spectral shrinkage of ridge. Both estimators have the same form: take and multiply its component in each eigendirection by filter , which passes high-eigenvalue directions and suppresses low-eigenvalue directions that amplify noise most. This is what early stopping is regularization means: iteration count plays the role of .
Calibration comes from where each filter is half. For small , , so GD’s filter approximates gradient flow at time , . With , the filters are and if : they are for small , tend to 1 for large and transition near , i.e. . The effective parameter count , which for ridge is effective dimension, grows with just as it grows as falls.
The similarity is quantitative. Ali, Kolter and Tibshirani compared estimation risk of the two estimators calibrated at and obtained a uniform bound in without assumptions on (Ali, Kolter and Tibshirani, 2019, Theorem 1). The proof fits in a few lines.
Proof
For spectral estimator , , and since ,
The last term is the same for both estimators. With , flow uses and ridge with uses . Two scalar inequalities for suffice:
- because . Thus each flow bias term is no larger than ridge’s.
- with , attained at (calculated by the lab cell). Thus each flow variance term is at most times ridge’s.
Summing, flow risk is at most times ridge risk. The paper rounds upward: and .
∎Observe the breakdown: early stopping always has less bias than ridge calibrated at and at most 69% more variance. For discrete GD with bias remains smaller because , and a crude variance bound follows from : constant instead of . With the GD filter exceeds 1 in high-curvature directions, as the figure shows, and the ridge analogy breaks precisely there.
Separable classification: norm diverges and direction converges to maximum margin
Classification is more extreme: separable data have no minimizer. Take examples with , define and minimize logistic regression loss without intercept or regularization,
Data are separable if some satisfies for all . Then as ; the infimum is 0 and unattained. Since , is -smooth with and , so is -smooth, where has rows .
Proof
Let be the smoothness constant of , so . By the descent lemma, with . Summing gives , hence . Now use the separator: since ,
The left side tends to zero and , so each tends to zero, i.e. . Hence , all margins eventually become positive, and since , norm diverges.
∎The interesting question is the direction of divergence. Recall the maximum-margin classifier: hard-margin SVM without intercept,
whose geometric margin is . By KKT conditions, with and except on support vectors, examples satisfying .
This is the result of Soudry et al. (2018), Theorems 3, 4 and 5. It is the implicit bias toward maximum margin: without mentioning margin in the loss, GD eventually produces the geometric maximum-margin classifier, the same margin controlled by the margin bound.
The reason appears in a self-consistent argument, the proof sketch given in the paper. For large , . Suppose with bounded . Each example then contributes to the gradient with weight
Examples with weigh ; those with margin exactly 1 weigh . But the one-step increment of is . For both to agree, at order ,
a positive-coefficient combination of margin-1 examples is needed. (The minimum margin of must also equal exactly 1 by the order: with smaller margin , dominant terms would be order and could not equal increment .) No example can have either: its weight would dominate and push toward it faster than . Margin at least 1 for all, with a nonnegative combination of those with margin exactly 1, gives the hard-margin SVM KKT conditions, which characterize its solution by convexity. Coefficients are , giving the theorem’s equation, and loss behaves as because .
Figure values come from running GD on that explicit model, and the lab cell reproduces the first Python iterations. Angle goes from 63.4° at to 10.1° at , 3.2° at and 1.7° at ; the figure continues to 1.2° at and 0.94° at , where the theorem asymptote also gives 0.94°. Each decade divides angle by a smaller factor: 1.8, 1.4 and 1.3 in the final three.
Practical consequences. Rate is extremely slow: asymptotically, halving the angle requires squaring . The paper notes three consequences:
- Continuing to train after zero error changes the model: margin keeps growing slowly even when training loss is tiny.
- Validation logistic loss can rise while validation classification error falls. If one validation example satisfies , its loss grows as because norm diverges (Corollary 6). Stopping on validation loss can stop too early.
- The limiting direction does not depend on or within the stable range; speed does.
Parameterization matters
The previous two results concern GD directly on linear-model weights. A multilayer linear network represents the same function class, , but writes as a product of matrices and applies GD to factors. By the chain rule, if with Jacobian , gradient flow induces in function space
a flow preconditioned by state-dependent matrix . The first figure showed that a fixed preconditioner changes the limit; a state-dependent one can change it much more.
Diagonal linear networks
The simplest model fully calculable is Woodworth et al. (2020): , with and elementwise product. It is a two-layer linear network with diagonal connections, and the difference of squares permits weights of both signs. Initialize at , so for any scale , and minimize by gradient flow in .
Since , is strictly convex; KKT conditions characterize it and give the result.
Both limits follow from . For small , , so with large (all small), : a multiple of squared norm. For large , , so with small
and the first term dominates: minimizing is, to first order, minimizing . Woodworth et al. call the first extreme the kernel regime: with large weights barely move relatively, the model behaves like its linearization at initialization, and bias is minimum tangent-kernel norm (here ), the kernel regime studied in lesson 18. The second is the rich regime: weights grow orders of magnitude from near zero and bias is no longer that of a fixed kernel.
With the same data and loss, the sole change between figure extremes is initialization scale, and recovery error differs as between solving the problem (near-zero error, like lasso with ) and not solving it (ridgeless error near 2). The rich regime costs time: flow needs order time for coefficients to leave scale , and discrete GD feels it; in the figure with , GD does not fully interpolate in 60,000 steps.
Matrix factorization and limits of norms
In matrix factorization the model is and observations are linear measurements . Gunasekar et al. (2017) observed that GD with small steps and near-zero initialization finds low nuclear-norm solutions even with full-dimensional factorization, where nothing restricts rank, and conjectured its limit is the minimum nuclear-norm solution; they proved it when matrices commute. This is the matrix version of the diagonal network: commuting measurements diagonalize simultaneously, returning to the earlier case with nuclear norm playing the role of on eigenvalues.
The general case is not resolved this way. Razin and Cohen (2020) constructed matrix-completion problems where GD on deep factorization drives every norm and even every quasinorm to infinity while effective rank falls. They conclude implicit bias is better described as a low-rank tendency than norm minimization. General lesson: not every implicit bias minimizes a norm, and always seeking one may seek something nonexistent.
Other algorithms, other geometries
Parameterization is not the only geometry changer. Gunasekar, Lee, Soudry and Srebro (2018) generalized the prior result to steepest descent with respect to an arbitrary norm: with exponential loss and separable data, normalized margin converges to maximum margin in that norm (Theorem 5). With norm, whose descent direction is gradient sign, the limit is maximum -margin classifier, distinct from SVM. For AdaGrad the same work finds bias depends on initialization and step size, even for strictly monotonic losses. Adaptive methods like Adam are close relatives of both, so do not assume they inherit GD bias.
SGD stability: few passes generalize
So far implicit bias described which solution is selected. An algorithm can also regularize without an explicit term by staying close to what it would do on another sample. This is lesson 11’s uniform stability. Recall the randomized-algorithm version of Hardt, Recht and Singer (2016): is -uniformly stable if for every pair of size- samples differing in one example,
with expectation over internal algorithm randomness. And the stability-generalization relationship: if is -uniformly stable, .
Here SGD is iteration with uniform in and independent at each step, the stochastic version of GD. Write . Two update properties suffice for the analysis:
- is -bounded if . If is -Lipschitz, and the gradient update is -bounded.
- is -expansive if for every .
Proof
For convex, -smooth the gradient is cocoercive: . With and ,
because .
∎Proof
Run SGD on and (differing at example ) from the same with the same index sequence , and write , with . At step :
- with probability , choose ; both runs apply the same update and by the lemma ;
- with probability , choose ; updates differ but both are -bounded, and the triangle inequality gives .
Taking expectations, , so . For any , because is -Lipschitz, .
∎This is SGD stability. With constant step and data passes, and the bound becomes : it does not depend on alone but on step times passes. Few passes at moderate step give a stable algorithm and therefore a small expected generalization gap regardless of class complexity. This is the idea in the paper’s title Train faster, generalize better: fewer training steps also regularize. Together with optimization error, which falls with , this yields the fit-stability tradeoff, with early stopping at the balance.
The figure also shows the bound is worst-case. With , and 5 passes, the bound is 10 and measured mean distance 0.34; from 5 to 10 passes the bound doubles while the mean barely changes. In practice the update not only fails to expand but contracts: near the optimum, logistic regression with nonseparable data has positive curvature along , and each same-example step brings the twins closer (the green curve falls between jumps). The paper gives two useful variants. If is also -strongly convex and projected SGD uses constant step , the update contracts and the bound stops growing with : (Theorem 3.9). Without convexity, for , -Lipschitz and -smooth with steps , updates can expand by factor and the bound becomes order (Theorem 3.12): still useful for few iterations but degrading with long training.
import numpy as np
rng = np.random.default_rng(3)
n, d = 100, 5
X = rng.normal(size=(n, d))
X /= np.maximum(1, np.linalg.norm(X, axis=1))[:, None] # ||x|| <= 1: L = 1, beta = 1/4
y = np.where(rng.uniform(size=n) < 1 / (1 + np.exp(-2 * X @ np.array([1.5, -1, 0.5, 0, 0]))), 1.0, -1.0)
Xp = X.copy()
Xp[0] = -X[0] # S': solo cambia el ejemplo 0
def twin_sgd(alpha, T, runs=40):
"""SGD sobre S y S' con la misma sucesión de índices; devuelve E[delta_T] y la fracción de pasos expansivos."""
deltas, expans, same = np.zeros(runs), 0, 0
for r in range(runs):
w, wp, prev = np.zeros(d), np.zeros(d), 0.0
for i in rng.integers(0, n, T):
w += alpha * y[i] * X[i] / (1 + np.exp(y[i] * X[i] @ w))
wp += alpha * y[i] * Xp[i] / (1 + np.exp(y[i] * Xp[i] @ wp))
delta = np.linalg.norm(w - wp)
if i != 0:
same += 1
expans += delta > prev * (1 + 1e-9) + 1e-12
prev = delta
deltas[r] = delta
return deltas.mean(), expans / same
T = 3 * n # tres pasadas
print(" alpha E[delta_T] cota 2*alpha*T/n pasos expansivos")
for alpha in [1.0, 4.0, 8.0, 12.0, 16.0]:
m, frac = twin_sgd(alpha, T)
print(f"{alpha:5.1f} {m:9.4f} {2 * alpha * T / n:10.1f} {100 * frac:5.2f} %")Through there is not one expansive step; above it, slightly more than 6% of same-example steps separate the twins. The mean of remains far below the bound in every case.
What these results do and do not explain for deep networks
This lesson’s theorems are exact for linear models, specially structured linear networks and convex losses. For nonlinear deep networks there are partial results, which should be distinguished from conjecture.
What is known.
- In the kernel regime (very wide networks with suitable initialization and step scales), training behaves like GD on a model linear in parameters, and implicit bias is minimum norm in the tangent-kernel RKHS: the first theorem applied to linearization. Lesson 18 studies the kernel regime.
- For parameter-homogeneous networks (such as fully connected or convolutional ReLU or Leaky ReLU networks without biases) trained with logistic or cross-entropy loss, Lyu and Li (2020) proved that once training loss drops below a threshold, a smoothed normalized margin grows and normalized margin converges to the value of a KKT point of margin maximization. This generalizes Soudry et al. to a KKT point, not necessarily the global maximum.
- The SGD stability bound applies without convexity (Hardt et al., Theorem 3.12), although it degrades with iteration count.
What they do not explain.
- A real network’s rich regime has no formula like . Razin and Cohen’s examples show that even in deep linear factorizations bias is not always norm minimization.
- Bounds derived from norms or stability are often vacuous for real networks. Standard networks can fit random labels (Zhang et al., 2017), and lesson 17’s random-label memorization examines implications for uniform bounds. Many passes with large steps make the stability bound useless.
- Bias depends on learning rate (large steps change which minima are stable), batch size, optimizer, normalization and weight decay, and these effects interact. “SGD generalizes because of implicit bias” is a research program, not a theorem.
Lab: implicit bias in least squares and logistic regression
Start with the first theorem. With equations and unknowns, GD from zero should end at the pseudoinverse, and from random at plus the projection of onto the null space.
import numpy as np
rng = np.random.default_rng(0)
n, d = 20, 50 # más incógnitas que ecuaciones
X = rng.normal(size=(n, d))
y = rng.normal(size=n)
def gd_least_squares(X, y, w0, eta, T):
"""T pasos de GD sobre R(w) = ||Xw - y||^2 / (2n) desde w0."""
n = X.shape[0]
w = np.array(w0, dtype=float).copy()
for _ in range(T):
w -= eta * X.T @ (X @ w - y) / n
return w
mu = np.linalg.eigvalsh(X.T @ X / n) # autovalores de Sigma = X^T X / n
mu_pos = mu[mu > 1e-10]
eta = 1.0 / mu.max()
print(f"autovalores no nulos: {mu_pos.size} de {d}; mu_max = {mu.max():.3f}, mu_min+ = {mu_pos.min():.4f}")
print(f"factor de contracción en el espacio de filas: {1 - eta * mu_pos.min():.4f}")
w_dag = np.linalg.pinv(X) @ y # interpolador de mínima norma
w_gd = gd_least_squares(X, y, np.zeros(d), eta, 1000)
print(f"desde 0: ||w_GD - X^+ y|| = {np.linalg.norm(w_gd - w_dag):.1e}, residuo = {np.linalg.norm(X @ w_gd - y):.1e}")
w0 = rng.normal(size=d)
P_row = np.linalg.pinv(X) @ X # proyector sobre el espacio de filas
w_pred = w_dag + (np.eye(d) - P_row) @ w0
w_gd0 = gd_least_squares(X, y, w0, eta, 1000)
print(f"desde w0: ||w_GD - (X^+ y + (I - P) w0)|| = {np.linalg.norm(w_gd0 - w_pred):.1e}")
print(f"normas: ||X^+ y|| = {np.linalg.norm(w_dag):.3f}, ||w_GD desde w0|| = {np.linalg.norm(w_gd0):.3f}")
print(f"componente en el núcleo: al principio {np.linalg.norm((np.eye(d) - P_row) @ w0):.4f}, al final {np.linalg.norm((np.eye(d) - P_row) @ w_gd0):.4f}")The 20 nonzero eigenvalues of range from 0.36 to 6.61, so with error is multiplied by 0.9456 each step, reaching rounding scale in 1000 steps. Both solutions interpolate, but the one from has norm 5.566 versus 0.598: it retains the entire null-space component of , unchanged even at the fourth digit.
The second cell checks the Ali, Kolter and Tibshirani theorem: it calculates proof constant and exact risks of both paths for an unequal spectrum, and validates ridge risk against scikit-learn Ridge. Watch the scale: scikit-learn minimizes , so this lesson’s corresponds to .
import numpy as np
from scipy.optimize import minimize_scalar
from sklearn.linear_model import Ridge
c = lambda x: (1 - np.exp(-x)) * (1 + x) / x
opt = minimize_scalar(lambda x: -c(x), bounds=(1e-6, 20), method="bounded")
print(f"c = sup (1 - e^-x)(1 + x)/x = {c(opt.x):.5f} en x = {opt.x:.3f}; c^2 = {c(opt.x)**2:.5f}")
rng = np.random.default_rng(1)
n, d, sigma = 100, 60, 1.0
X = rng.normal(size=(n, d)) @ np.diag(np.linspace(0.2, 2.0, d)) # espectro desigual
beta0 = rng.normal(size=d) / np.sqrt(d)
mu, V = np.linalg.eigh(X.T @ X / n)
b2 = (V.T @ beta0) ** 2
def risk(g):
"""E||b - beta0||^2 de un estimador espectral con filtro g(mu)."""
return np.sum((1 - g) ** 2 * b2) + sigma**2 / n * np.sum(g**2 / mu)
taus = np.logspace(-1, 3, 400)
r_gf = np.array([risk(1 - np.exp(-mu * t)) for t in taus])
r_rd = np.array([risk(mu / (mu + 1 / t)) for t in taus])
print(f"máx riesgo(flujo, tau) / riesgo(ridge, 1/tau) = {np.max(r_gf / r_rd):.4f} (cota: 1.6862)")
print(f"riesgo óptimo: flujo {r_gf.min():.4f}, ridge {r_rd.min():.4f}")
# la fórmula frente a scikit-learn, con lambda = 1/tau = 0.2
tau = 5.0
y = X @ beta0 + sigma * rng.normal(size=n)
b_sk = Ridge(alpha=n / tau, fit_intercept=False).fit(X, y).coef_
b_np = np.linalg.solve(X.T @ X / n + np.eye(d) / tau, X.T @ y / n)
print(f"Ridge de sklearn frente a la fórmula: diferencia {np.linalg.norm(b_sk - b_np):.1e}")
A = np.linalg.solve(X.T @ X / n + np.eye(d) / tau, X.T / n) # b = A y
E = sigma * rng.normal(size=(n, 4000))
errs = np.sum((A @ (X @ beta0[:, None] + E) - beta0[:, None]) ** 2, axis=0)
print(f"riesgo de ridge con tau = 5: fórmula {risk(mu / (mu + 1 / tau)):.4f}, Monte Carlo {errs.mean():.4f}")The maximum of is 1.2984 at , and its square is 1.6859. In this problem the risk ratio across the path never exceeds 1.38 and optimal risks nearly coincide.
Now logistic regression. The cell uses the same twelve points as the figure, calculates hard-margin SVM without intercept by its dual, and compares with LinearSVC (without intercept and with large , approaching hard margin on separable data) and SVC. It then runs GD and compares angle with theorem asymptote .
import numpy as np
from scipy.optimize import minimize
from sklearn.svm import LinearSVC, SVC
pos = np.array([[3.6, 1.1], [4.1, 0.6], [3.3, 0.3], [4.4, 1.4], [3.8, -0.2], [0.2, 1.3]])
neg = np.array([[-3.7, -0.9], [-4.2, -0.4], [-3.4, -1.3], [-4.0, -0.3], [-3.1, -0.5], [0.9, -0.9]])
Xc = np.vstack([pos, neg])
yc = np.r_[np.ones(6), -np.ones(6)]
Z = yc[:, None] * Xc
# SVM de margen duro homogéneo por su dual: max sum(a) - ||Z^T a||^2 / 2, a >= 0
dual = minimize(lambda a: 0.5 * np.sum((Z.T @ a) ** 2) - a.sum(), np.zeros(12),
jac=lambda a: Z @ (Z.T @ a) - 1, bounds=[(0, None)] * 12, method="L-BFGS-B",
options={"ftol": 1e-15, "gtol": 1e-12})
w_hat = Z.T @ dual.x
print("w_hat =", np.round(w_hat, 4), " márgenes:", np.round(np.sort(Z @ w_hat), 3))
def ang(a, b):
return np.degrees(np.arccos(np.clip(a @ b / np.linalg.norm(a) / np.linalg.norm(b), -1, 1)))
lsvc = LinearSVC(loss="hinge", fit_intercept=False, C=1e3, tol=1e-10, max_iter=1_000_000).fit(Xc, yc)
svc = SVC(kernel="linear", C=1e6).fit(Xc, yc)
print(f"LinearSVC sin intercepto: ángulo con w_hat = {ang(lsvc.coef_[0], w_hat):.4f}°")
print(f"SVC con intercepto (b = {svc.intercept_[0]:.3f}): ángulo con w_hat = {ang(svc.coef_[0], w_hat):.2f}°")
eta = 0.9 * 8 / np.linalg.norm(Z, 2) ** 2 # eta < 2 / (beta sigma_max^2) con beta = 1/4
S = np.where(Z @ w_hat < 1 + 1e-6)[0]
alpha_sv = dual.x[S]
w_tilde = np.linalg.solve(Z[S], -np.log(alpha_sv / eta)) # eta exp(-z_n^T w~) = alpha_n
print(f"eta = {eta:.4f}, vectores soporte {S}, alpha = {np.round(alpha_sv, 4)}")
print(" t ángulo(w_t, w_hat) asíntota ||w_t|| ||w_hat|| log t")
w = np.zeros(2)
for t in range(1, 20_001):
w += eta * Z.T @ (1 / (1 + np.exp(Z @ w)))
if t in (1, 10, 100, 1000, 10_000, 20_000):
th = w_hat * np.log(t) + w_tilde
asin = f"{ang(th, w_hat):8.3f}°" if t >= 100 else " - "
print(f"{t:6d} {ang(w, w_hat):8.3f}° {asin} {np.linalg.norm(w):7.3f} {np.linalg.norm(w_hat) * np.log(t):7.3f}")LinearSVC without intercept matches the dual. SVC does not, and not due to inaccuracy: its intercept is unpenalized, so it solves another problem and its weight vector makes about 9° with . GD treats any intercept as another weight (if a column of ones is added to ), so it converges to the SVM that also penalizes , solved by LinearSVC. The final table shows the logarithmic march: from 63.4° to 1.7° in steps and only 1.5° after doubling iterations, with asymptote increasingly close (1.67° at , 1.50° at ). Norm lies below because has a negative component along .
Lab: diagonal linear networks and initialization scale
The second lab reproduces the transition from to . References are minimum norm, a linear program ( with ), and minimum norm, the pseudoinverse.
import numpy as np
from scipy.optimize import linprog
rng = np.random.default_rng(0)
n, d, k = 20, 50, 3
X = rng.normal(size=(n, d)) / np.sqrt(n)
w_star = np.zeros(d)
supp = rng.choice(d, k, replace=False)
w_star[supp] = rng.choice([-1, 1], k) * rng.uniform(1, 2, k)
y = X @ w_star
# referencias: mínima norma l1 (programa lineal) y mínima norma l2 (pseudoinversa)
lp = linprog(np.ones(2 * d), A_eq=np.hstack([X, -X]), b_eq=y, bounds=(0, None))
w_l1 = lp.x[:d] - lp.x[d:]
w_l2 = np.linalg.pinv(X) @ y
print(f"mínima l1: error {np.linalg.norm(w_l1 - w_star):.1e}, ||w||_1 = {np.abs(w_l1).sum():.3f}")
print(f"mínima l2: error {np.linalg.norm(w_l2 - w_star):.3f}, ||w||_1 = {np.abs(w_l2).sum():.3f}")
def gd_diagonal(X, y, alpha, T=60_000, tol=1e-6):
"""GD sobre ||X(u*u - v*v) - y||^2 / 2 desde u = v = alpha * 1."""
L = np.linalg.norm(X, 2) ** 2
eta = 0.2 / (L * max(1.0, alpha**2))
u = np.full(X.shape[1], float(alpha))
v = u.copy()
for t in range(T):
r = X @ (u * u - v * v) - y
if t % 50 == 0 and np.linalg.norm(r) < tol:
break
g = X.T @ r
u *= 1 - 2 * eta * g
v *= 1 + 2 * eta * g
return u * u - v * v, t
print(" alpha pasos error ||w||_1 coef. > 0.05")
res_gd = {}
for alpha in [0.03, 0.1, 0.3, 1.0]:
w, steps = gd_diagonal(X, y, alpha)
res_gd[alpha] = w
print(f"{alpha:6.2f} {steps:6d} {np.linalg.norm(w - w_star):.3f} {np.abs(w).sum():.3f} {np.sum(np.abs(w) > 0.05)}")With GD reproduces minimum -norm solution (error 1.945 versus 1.948 for the pseudoinverse) and distributes weight over 41 coordinates. As falls, error and norm fall and the solution concentrates: with , 8 coordinates remain above 0.05 and error is 0.333. Notice the steps column: each threefold scale reduction costs several times more iterations.
For smaller scales GD needs too many steps for a browser cell, but the theorem gives the limit without training: the minimizer with . By the derivation, with the critical point of convex dual , found in a few Newton iterations.
def q_alpha_min(X, y, alpha, iters=100):
"""argmin Q_alpha(w) s.a. Xw = y por Newton sobre el dual: w = 2 alpha^2 sinh(X^T nu)."""
a2 = alpha**2
nu = np.zeros(X.shape[0])
def phi(v):
with np.errstate(over="ignore"):
return np.sum(2 * a2 * np.cosh(X.T @ v)) - y @ v
for _ in range(iters):
z = X.T @ nu
grad = X @ (2 * a2 * np.sinh(z)) - y
if np.linalg.norm(grad) < 1e-12:
break
H = (X * (2 * a2 * np.cosh(z))) @ X.T
step = np.linalg.solve(H, -grad)
s = 1.0
while phi(nu + s * step) > phi(nu) + 0.25 * s * grad @ step:
s /= 2
nu = nu + s * step
return 2 * a2 * np.sinh(X.T @ nu)
for alpha in [0.03, 0.1, 1.0]:
print(f"alpha = {alpha:4.2f}: ||w_GD - argmin Q_alpha|| = {np.linalg.norm(res_gd[alpha] - q_alpha_min(X, y, alpha)):.4f}")
print(" alpha error de argmin Q_alpha ||w||_1")
for alpha in [1e-4, 1e-3, 1e-2, 1e-1, 1.0, 10.0]:
wq = q_alpha_min(X, y, alpha)
print(f"{alpha:7.0e} {np.linalg.norm(wq - w_star):.4f} {np.abs(wq).sum():.3f}")
print(f"alpha = 10: ||argmin Q - X^+ y|| = {np.linalg.norm(q_alpha_min(X, y, 10.0) - w_l2):.1e}")
print(f"alpha = 1e-4: ||argmin Q - w_l1|| = {np.linalg.norm(q_alpha_min(X, y, 1e-4) - w_l1):.1e}")GD and the minimizer are within 0.02 of each other, compared with distances of order 1 between solutions with different ; remaining difference is finite step size, since the theorem concerns continuous flow. The table completes the transition: recovery error falls from 1.94 at to 0.12 at and 0.0017 at , and norm approaches the minimum -norm solution’s value. The limit is slow: is needed to approach minimum within because correction to is relative order . Woodworth et al. quantify this slowness in Theorem 2.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. Which property of iterates do you use first?
Step 1 of 5. How do you compare runs on and ?
gd_least_squares(X, y, w0, eta, T) returning weights after T GD steps on from w0 with step eta. Do not modify w0. Tests check one exact step, convergence from zero to the pseudoinverse and convergence from w0 to plus the projection of w0 onto the null space of .import numpy as np
def gd_least_squares(X, y, w0, eta, T):
"""Pesos tras T pasos de GD sobre ||Xw - y||^2 / (2n) desde w0."""
w = np.array(w0, dtype=float)
# tu código: T actualizaciones w <- w - eta * gradiente
return wSummary
- Least-squares GD stays in and converges to the minimizer closest to ; from zero, to . Step and momentum do not change the limit; initialization, preconditioning and parameterization do.
- Stopping at iteration applies filter to each eigendirection, almost ridge’s with . Gradient flow has less bias than ridge and at most 1.69 times its variance.
- With separable data, logistic regression drives norm to infinity as and direction to maximum-margin SVM at rate : halving angular error requires squaring .
- Implicit bias depends on parameterization: in , the limit minimizes , ranging from (kernel regime, large ) to (rich regime, small ). Not every implicit bias minimizes a norm.
- SGD with steps on convex losses is -uniformly stable: with constant step the bound is per pass, independent of hypothesis class.
- For deep networks these results explain the kernel regime and partly homogeneous-network margins, but not the general rich regime: actual bias depends on architecture, initialization, step, optimizer and normalization.