Skip to content
LearnAI
PART 1 · FOUNDATIONS/ Learning from data

1.1Functions & learning from data

A model is just a function with knobs. Learning means turning those knobs until the function fits the examples. Drag data points and watch it happen.

⏱ 13 minBeginner

Everything is a function

A function takes an input and returns an output. “Square it” takes 3 and returns 9. A thermostat’s rule takes a temperature and returns “heat on” or “heat off”. Almost every task we want AI to do can be phrased this way:

  • Photo → label. Input: millions of pixel values. Output: “cat”.
  • House features → price. Input: size, location, age. Output: a number of dollars.
  • Text so far → next word. Input: “The cat sat on the”. Output: a probability for every possible next word.

That last one is what a language model does. The problem is that nobody knows how to write down the function that maps pixels to “cat” or a sentence to its likely continuation. So instead we pick a flexible family of functions with adjustable numbers inside, and let data choose the numbers.

That flexible function is a modelModelA function with adjustable parameters that maps inputs to outputs. Training sets the parameters so the outputs are useful., and the adjustable numbers are its parametersParameter (weight)A number inside a model that is adjusted during training. Modern LLMs have billions to trillions of them. (also called weights). The simplest example is a straight line:

y^=w x+b.\hat y = w\,x + b .

Here xx is the input, y^\hat y (“y-hat”) is the model’s prediction, and ww (the slope) and bb (the intercept) are two knobs. Different knob settings give different lines. Learning means finding the setting that best fits the examples you have.

ANALOGY· Tuning a radio by ear

An old analog radio has a couple of dials. You don’t know the exact frequency of the station, but you can hear when you are close: the static fades and the voice gets clearer. You nudge each dial until it sounds as clean as possible.

The radio’s circuit is the model and the dials are its parameters. The amount of static you hear is the loss, and nudging the dials to reduce the static is training. An LLM is a radio with billions of dials, tuned by an algorithm that measures the static far more precisely than your ear.

Measuring “fits well”

To let a computer tune the knobs, we need a single number that says how bad the current fit is. For each example, the gap between the true value yy and the prediction y^\hat y is called the residualResidualThe difference between a true value and the model's prediction for one data point: the error the model still has to explain.. Some residuals are positive and some negative, so we square them (making them all positive and punishing big misses extra) and average:

MSE=1n∑i=1n(yi−y^i)2.\text{MSE} = \frac{1}{n}\sum_{i=1}^{n} \big(y_i - \hat y_i\big)^2 .

This is the mean squared errorMean squared error (MSE)The average of the squared differences between predictions and true values. The standard loss for predicting numbers., the classic loss functionLoss functionA number measuring how wrong a model's predictions are. Training tries to make it small. for predicting numbers. Zero means every prediction is perfect. Training is the search for knob settings that make this number as small as possible.

The recipe behind every learning problem

Fitting a line looks humble, but it contains every ingredient of training an LLM. Whenever you meet a new machine-learning method, it helps to ask four questions:

  1. What is the data? Pairs of inputs and correct outputs. Here: points (x,y)(x, y). For an LLM: a stretch of text, paired with the token that actually came next.
  2. What is the model family? The shape of function we allow. Here: straight lines, or polynomials up to some degree. For an LLM: a Transformer with a fixed architecture and billions of parameters.
  3. What is the loss? How we score a prediction. Here: mean squared error. For an LLM: cross-entropy, which scores the probability given to the true next token.
  4. How do we search? How we find good parameters. Here: an exact formula. For an LLM: gradient descent, millions of small steps.

Change any one of the four and you get a different method. Swap squared error for a loss that counts misclassifications and you are doing classification instead of regression. Swap the polynomial for a neural network and you are doing deep learning. The vocabulary changes; the recipe does not.

Try it: fit a curve

In the demo below, the orange dots are data. The blue curve is the model, and each red bar is a residual. Start in “You” mode and tune the line by hand, then let least squares do it, then give the model more knobs.

INTERACTIVECurve-fitting playground
Who turns the knobs?
00.250.50.751x = 0x = 0.5x = 1
Data points8
Knobs (parameters)2
Error on these points0.0187
θ = [0.50, -0.35]

Drag the orange points, or click empty space to add one. Red bars are the errors (residuals); the score is the mean of their squares.

Drag the orange points, or click empty space to add one. In 'You' mode, tune the slope and intercept to make the error small, then press 'Solve for the best line'. In polynomial mode, slide the degree from 0 to 10 and turn on the fresh data.

Things to try:

  1. Fit the line by hand. Switch to “You (a straight line)” and move the sliders to shrink the error. Then press Solve for the best line. Did you get close? The computer’s answer is provably the best possible line for these points.
  2. Degree 0. In polynomial mode, a single knob gives a flat line at the average height of the points. That is the best constant prediction, and it ignores xx entirely.
  3. Degree 3 or 4. The curve now bends to follow the wave in the data. The error drops a lot.
  4. Degree 7 or higher with 8 points. With as many knobs as points, the curve passes through every point and the error is essentially zero. Now press Show fresh data: new points from the same underlying pattern. Compare the fresh-data error with what degree 3 gets: the zero-training-error curve does more than twice as badly, especially near the edges, where it swings away from the pattern. It has memorized the noise.
  5. Drag a single point far away. A low-degree fit shifts a bit; a high-degree fit swings wildly. Squaring the residuals makes one outlier pull hard.

Knobs, capacity and the danger of memorizing

What you just saw is the central tension of machine learning. A model with too few knobs underfits: a straight line simply cannot follow a wave, however you set it. A model with too many knobs can contort itself through every training point, including the random noise, and then fails on new data. This is overfittingOverfittingWhen a model memorizes quirks of its training data and performs worse on new data., and the whole of lesson 1.8 is about detecting and preventing it.

There is a sweet spot in between. On the demo’s wavy data, a degree around 3 or 4 follows the wave without chasing individual points, and it does well on both the training points and the fresh ones. Finding that sweet spot is a practical skill. You hold back some data the model never trains on, try several sizes, and keep the one that does best on the held-back data. Every serious training pipeline, from a spreadsheet regression to a frontier LLM, does some version of this.

The goal of learning is never to fit the training examples perfectly. It is to capture the pattern behind them so the model does well on examples it has never seen. That is why the error on fresh data, not on the training points, is what really matters.

From fitting curves to training networks

The polynomial in the demo and a neural network have the same structure: a function whose shape depends on a list of parameters, a loss that scores the fit, and a procedure for finding good parameters. The difference is the procedure.

For a straight line or polynomial with squared error, there is an exact formula for the best parameters, called least squaresLeast squaresFitting a model by choosing the parameters that minimize the sum of squared residuals. For linear models it has an exact solution, the normal equations.. The demo solves it instantly every time you drag a point. Neural networks are too complex for any such formula. Instead they use gradient descent: start with random knobs, measure which direction reduces the loss, take a small step, repeat. That is lesson 1.5.

To get there, we need a few tools. Inputs like images and words are represented as lists of numbers, called vectors. Models transform them with matrices. And classification outputs are probabilities scored with cross-entropy. Those are the next three lessons.

MATH CORNER · optionalLeast squares and the normal equations

Stack the inputs into a design matrix XX, with one row per example and one column per knob. For a line y^=b+wx\hat y = b + w x the row for example ii is (1,xi)(1, x_i); for a degree-dd polynomial it is (1,xi,xi2,…,xid)(1, x_i, x_i^2, \dots, x_i^d). Then all predictions at once are y^=Xθ\hat{\mathbf{y}} = X\theta, and the loss is

L(θ)=1n ∥y−Xθ∥2.L(\theta) = \frac{1}{n}\,\lVert \mathbf{y} - X\theta \rVert^2 .

Setting the gradient to zero gives the normal equations:

X⊤X θ=X⊤y.X^\top X\,\theta = X^\top \mathbf{y} .

This is an ordinary system of linear equations with one unknown per knob. The demo builds X⊤XX^\top X and X⊤yX^\top \mathbf{y} and solves the system with Gaussian elimination. (It rescales xx to the range [−1,1][-1, 1] first, which keeps high powers from becoming numerically unstable, and adds a tiny amount to the diagonal so the system stays solvable when there are more knobs than points.)

Worked example. Fit a line to three points: (0,1)(0, 1), (1,3)(1, 3), (2,4)(2, 4). With θ=(b,w)\theta = (b, w):

X⊤X=(n∑xi∑xi∑xi2)=(3335),X⊤y=(∑yi∑xiyi)=(811).X^\top X = \begin{pmatrix} n & \sum x_i \\ \sum x_i & \sum x_i^2 \end{pmatrix} = \begin{pmatrix} 3 & 3 \\ 3 & 5 \end{pmatrix}, \qquad X^\top \mathbf{y} = \begin{pmatrix} \sum y_i \\ \sum x_i y_i \end{pmatrix} = \begin{pmatrix} 8 \\ 11 \end{pmatrix}.

Solving 3b+3w=83b + 3w = 8 and 3b+5w=113b + 5w = 11: subtracting gives 2w=32w = 3, so w=1.5w = 1.5 and b=7/6≈1.167b = 7/6 \approx 1.167.

xxyyy^=1.167+1.5x\hat y = 1.167 + 1.5xresidual y−y^y - \hat ysquared
011.167−0.1670.028
132.667+0.3330.111
244.167−0.1670.028

MSE =(0.028+0.111+0.028)/3≈0.056= (0.028 + 0.111 + 0.028)/3 \approx 0.056. No other line does better on these three points. Notice the residuals sum to zero: that is guaranteed whenever the model has an intercept, because the first normal equation says exactly ∑i(yi−y^i)=0\sum_i (y_i - \hat y_i) = 0.

In code

The worked example in NumPy, first by solving the normal equations directly and then with the built-in helper:

import numpy as np

x = np.array([0.0, 1.0, 2.0])
y = np.array([1.0, 3.0, 4.0])

X = np.column_stack([np.ones_like(x), x])     # design matrix: rows (1, x_i)
theta = np.linalg.solve(X.T @ X, X.T @ y)     # normal equations
print(theta)                                  # [1.1667 1.5]  ->  b, w

y_hat = X @ theta
print(np.mean((y - y_hat) ** 2))              # MSE ≈ 0.0556

# Same thing for any polynomial degree (coefficients highest power first):
print(np.polyfit(x, y, deg=1))                # [1.5    1.1667]

In practice, libraries use more numerically careful methods (QR or SVD decompositions, as in np.linalg.lstsq) rather than forming X⊤XX^\top X, but the answer is the same.

COMMON MISCONCEPTIONS
  • “A model with zero training error is a perfect model.” Zero error on the training points usually means it memorized them, noise included. What matters is performance on new data.
  • “More parameters always make a better model.” More knobs increase what a model can represent, but without enough data they also increase overfitting. Size has to be matched with data (see scaling laws).
  • “Learning means the computer discovers the formula itself.” We choose the family of functions (lines, polynomials, neural networks). Learning only picks the parameter values within that family.
  • “Machine learning is fundamentally different from curve fitting.” At its core, supervised learning is curve fitting, just in very high dimensions, with flexible functions and clever ways to avoid overfitting.

Check your understanding

0/4 answered
  1. Q1.In the model ŷ = w·x + b, what are the parameters?

  2. Q2.A degree-9 polynomial fit to 10 noisy points has training error 0. What should you expect on new points from the same source?

  3. Q3.Why does mean squared error square the residuals instead of just adding them up?

  4. Q4.Why don't neural networks use the normal equations like the demo does?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.