LLM Basics
Lesson 6 of 6

Overfitting and Regularization

The network from the last lesson has 4 hidden neurons and 2 inputs each — 8 weights, plus 4 hidden biases, plus 4 output weights and a bias: 17 numbers, all free to move however gradient descent likes. Given enough capacity and few enough training points, a network can drive the loss on those exact points to nearly zero by memorizing quirks and outliers instead of learning the actual pattern. That's overfitting.

One common fix is L2 regularization: add a penalty to the loss proportional to the sum of the squared weights, loss + λ · Σ(w²). Now the network isn't just rewarded for fitting the data — it's also taxed for having large weights. Since large, wild weights are exactly what's needed to carve tight, jagged regions around individual noisy points, this penalty pushes the network toward smoother, simpler boundaries.

Same noisy data, trained with vs. without L2

final loss: 0.205

Without regularization, the network is free to carve out tight little regions around noisy/mislabeled points — high training accuracy, but a boundary that likely won't generalize well.

This is the same XOR data as before, but with a handful of mislabeled-looking points scattered near the center. Toggle regularization off and the boundary twists itself to carve out little pockets around those noisy points — technically lower training loss, but almost certainly worse at generalizing to new data. Toggle it on and the boundary stays smoother, accepting a few "wrong" points near the noisy region rather than contorting around every one of them.

The only change from the previous lesson's training loop: the L2 term added directly into each gradient before the update:

Python

That's the full arc of this course: a single neuron, a layer of them, stacked into an MLP, given a loss function, trained with gradient descent, and finally kept honest with regularization. Every one of these ideas — weighted sums, nonlinearities, backpropagation, gradient descent — is the exact same machinery underneath a transformer, just at a scale small enough to watch happen in your browser.

What does an L2 regularization penalty do to a network's training?