Machine Learning · Insper

Gradient Descent & Regularization

Advanced approach

What the gradient looks like with many features, why scaling decides whether the descent works, and why L1 zeroes where L2 shrinks

The path of this part

  1. Any number of parametersone formula per weight; the matrix form
  2. Read the landscapenarrow valleys, round bowls and scaling
  3. Complexity is relativeparameters against data points
  4. Inside the penaltiescircle and diamond; the path; correlated features
Each stage answers one question: what is the gradient with \(d\) features? → why does the descent zigzag, and what fixes it? → too complex compared with what? → why does lasso select and ridge spread?
Stage 1 · what is the gradient with \(d\) features?

One formula for every parameter

Model \(\hat y_i = w_0 + w_1 x_{i1} + \dots + w_d x_{id}\), residual \(e_i = y_i - \hat y_i\), loss \(J = \frac{1}{n}\sum_i e_i^2\). With the column of ones \(x_{i0} = 1\), the intercept is just one more weight, and \(\partial e_i / \partial w_j = -x_{ij}\) for every \(j\):

\[ \frac{\partial J}{\partial w_j} = -\frac{2}{n}\sum_{i=1}^{n} e_i\,x_{ij} \]
parameterits column of \(X\)partial derivative
\(w_0\)the column of ones\(-\frac{2}{n}\sum_i e_i \cdot 1\)
\(w_1\)\(x_1\)\(-\frac{2}{n}\sum_i e_i x_{i1}\)
\(w_j\)\(x_j\)\(-\frac{2}{n}\sum_i e_i x_{ij}\)
Predict. Entry \(j\) is column \(j\) of \(X\) dotted with the residuals. What single matrix product computes all \(d+1\) entries at once?

Stacking them: the matrix form

\[ \nabla_w J = -\frac{2}{n}X^\top e = -\frac{2}{n}X^\top(y - Xw) \]

The table of the previous slide, written compactly: one line of numpy for a million parameters.

first reading

set it to zero: \(X^\top(y - Xw) = 0\), the normal equations. Same statement, two routes: solve it at once, or walk there.

second reading

a residual-weighted sum: well-predicted points barely vote, badly missed points dominate the step.

Move each weight in the direction the errors point, by an amount proportional to how large they are. Word for word true in a 100-layer network.
Stage 2 · why does the descent zigzag, and what fixes it?

The landscape you are walking down

  • Every point of the plane \((w_0, w_1)\) is a candidate line; the height is its error \(J\).
  • Minimizing = finding the bottom of the valley; \(-\nabla J\) is the direction of steepest descent.
Predict. In the hand table on the points \((1,2), (2,4), (3,7)\), \(w_1\) felt the residuals 2.4 times more than \(w_0\). What shape do you expect the valley to have?

Simulator: the loss surface

Click on the left to drop a start and press Step. Then switch center x on and start again from a similar point.

Why scaling comes before fitting

uncentered

a long narrow valley: tilting a line whose \(x\) values sit far from zero also raises or lowers it, so \(w_0\) and \(w_1\) are coupled. The gradient points across the valley; the path zigzags and drags.

centered

a round bowl: the same steps go nearly straight to the answer, and a larger \(\eta\) is tolerated.

The closed form returns the same line either way. The iterative route cares enormously: standardizing reshapes the surface the optimizer crosses. The lab measures by how much.
Stage 3 · too complex compared with what?

"Too complex" depends on how much data you have

A degree-10 polynomial has 11 free parameters. Training error as root mean squared error (RMSE):

training points5810111530
train RMSE3·10⁻¹⁵1·10⁻¹¹1·10⁻¹¹0.400.771.53
  • Up to 11 points the curve passes through every one: zero training error means nothing was left over.
  • From the eleventh point on it has to choose, and the error lifts off the floor.
The same degree-10 model is too complex for 10 points and reasonable for 100.
Stage 4 · why does lasso select and ridge spread?

Why L1 zeroes and L2 does not

Write the penalty as a budget: minimize the error subject to \(\sum |w_j| \le t\) (lasso, L1) or \(\sum w_j^2 \le t^2\) (ridge, L2). Every \(\alpha\) has a matching \(t\).

  • The error contours are ellipses centered on the ordinary least squares (OLS) solution.
  • The solution is where the growing ellipse first touches the region.
Predict. The ridge region is a circle; the lasso region is a diamond with corners on the axes. Which one will usually be touched exactly on an axis?

Simulator: circle versus diamond

Drag the OLS optimum around and count how often each region is touched on an axis.

Watching the path

Eight features: three with real signal, three pure noise, two near-copies (\(c_1, c_2\), both truly 2). Predict. As \(\alpha\) grows, which coefficients does lasso drop first?

What the path shows

αlasso: non-zeroridge: non-zero
0.058 / 88 / 8
0.27 / 88 / 8
0.66 / 88 / 8
2.05 / 88 / 8

Lasso removes the noise features first; ridge keeps all eight, small.

The correlated pair at \(\alpha = 2\):

lasso (1.89, 0.98): starts to pick one, almost arbitrarily.

ridge (1.02, 0.97): splits the weight evenly.

That is why ridge is the standard answer to multicollinearity, and lasso is not.

Ridge also fixes the numerics

two nearly identical columns

condition number of \(X^\top X\) (largest eigenvalue over smallest): \(7.2\times10^{7}\)

OLS: \((1.000, -0.000)\), an arbitrary split

\(\alpha = 0.01\) on the diagonal

condition number: \(6\times10^{3}\)

answer: \((0.500, 0.500)\), the sum preserved

Stable coefficients, an invertible matrix, faster gradient convergence: one mechanism, \(\alpha I\) raising every eigenvalue.

Practical profile

decisiondefaultwhen to change it
closed form or gradient descent?closed form for a few thousand featuresmany features, many rows or no closed form: stochastic gradient descent (SGDRegressor) in mini-batches
learning ratetry \(10^{-3}\), \(10^{-2}\), \(10^{-1}\)the loss grows: smaller; barely moves: larger, after standardizing
scalingstandardize, inside a Pipelinenever skip it before gradient descent or a penalty
ridge, lasso or Elastic Net?ridge: keeps every featurelasso for a short list of features; Elastic Net for many correlated ones
\(\alpha\)cross-validation (RidgeCV, LassoCV)never the training error, which always prefers \(\alpha = 0\)
Advanced lab · about 35 min, in pairs

Scale, many features and mini-batches, steps 4 to 6

  • Same notebook, same session: the steps use x, y, gradient and train from steps 1 to 3.
  • Step 4: the landscape of the three points, with and without centering. Step 5: the gradient in one line, on 20,640 California districts, raw and standardized. Step 6: mini-batches.
  • Notebook on Colab (in Portuguese), from section 4.
  • Simulations: where the limit sits (step 4) and the brake inside the engine, ridge by gradient descent (step 5).

Pace: step 4 and the first simulation in 12 min; step 5 and the second in 15 min; step 6 in 8 min.