← → / SPACE to navigate
LECTURE 07 · FUNCTION APPROXIMATION

Bend math —
to predict Q.

Through L6 our V and Q lived in tables — one row per state. That breaks fast. Today we replace the table with a function we can train: a line, then a ReLU, then a small neural network. Same Bellman target — vastly more states.

📏 Linear approx 📐 ReLU bend 🧠 Universal approximator 🤖 DQN
Title
01 / 16
WHERE WE ARE

From tables to a wall.

Lectures 3–6 built a complete pipeline for solving any MDP — as long as it's small enough to write down and we know its rewards and slip probabilities. Today we relax both.

L3 – L6 · SO FAR

Tabular V/Q + Bellman.

  • L3–L4: the MDP, values \(V\) and \(Q\), and the Bellman equation \(V^*\) must satisfy
  • L5: policy & value iteration solve known MDPs
  • L6: policy iteration up close — evaluate every state, improve, repeat
  • Every state \(s\) still has its own row in \(V[s]\) or \(Q[s,a]\)
L7 · TODAY

The scaling wall.

  • Real problems: states ≫ rows we can store
  • We need a function \(Q(s,a;\theta)\) that generalizes
  • Build from scratch: line → ReLU → network
  • End: train a Deep Q-Network on Atari pixels
Recap
02 / 16
THE WALL

A table can't hold 10²¹⁴ rows.

Tabular methods are perfect — for problems with thousands of states. The interesting problems have vastly more. We can't allocate one number per state, and even if we could, we'd never visit each state enough times to learn its value.

🎲

Snakes & Ladders

~100

fits in a table easily.

♟️

Chess positions

~10⁴⁵

more than atoms in Earth.

⚫

Go board states

~10¹⁷⁰

more than atoms in observable universe.

🎮

Atari pixel screens

~10²¹⁴

(84 × 84 × 4 frames, 256 grays)

And robotics, self-driving, language — all continuous states. Tables don't even apply.

Scaling Wall
03 / 16
THE FIX

Replace the table with a function.

Don't memorize one number per state. Learn a function \(V(s;\theta)\) — same input, same output, but only \(\theta\) (a handful of parameters) to store. Similar states get similar values for free — that's generalization.

BEFORE · TABULAR
V[s_1] = 4.2
V[s_2] = 3.7
V[s_3] = 5.1
V[s_4] = ?
   ⋮
V[s_N] = ?     N may be huge

Each entry independent. Unseen states have no value. Doesn't fit in memory once N gets big.

→
AFTER · PARAMETERIZED
V(s; θ) ≈ V*(s)
θ = (a few thousand
     numbers, total)

Feed any \(s\) → get a value. Similar \(s\) → similar values. Storage independent of state count.

Same goal as before — make \(V(s;\theta)\) satisfy Bellman. The only question: what shape should the function be?

Parameterize
04 / 16
FIRST TRY · LINEAR

The simplest function: a straight line.

Pick a few features \(\phi(s)\) — numbers we extract from the state. The simplest model is a weighted sum of those features. Just two parameters: weights \(w\) and bias \(b\).

RECIPE · LINEAR FA
\( V(s;\, w,b) = w \cdot \phi(s) + b \)

Same shape you saw in linear regression in stats class. We tune \(w\) and \(b\) to match Bellman targets.

For a 1-D feature, this is just y = wx + b. For an N-D feature, it's a hyperplane.

EXAMPLES OF \(\phi(s)\)
🚗 Pole-cart: \(\phi(s) = (\text{angle},\, \text{velocity})\)
🤺 Warrior tree: \(\phi(s) = (\text{depth},\, \text{leftness})\)
🎮 Pong: \(\phi(s) = (\text{ball x},\, \text{ball y},\, \text{paddle y})\)

The features are how we tell the model "what matters about \(s\)." Pick well — your linear model has a chance. Pick badly — no number of weights will save you.

So… can a line fit any V? Let's try, on the next slide. (Spoiler: a stubborn one.)

Linear FA
05 / 16
★ INTERACTIVE PLAYGROUND

Bend math: line → ReLU → network.

Three stages. Drag sliders, watch MSE drop. Stage ① fails. Stage ② fits half. Stage ③ — stack ReLUs and the curve snaps. Hit Auto-Fit to watch gradient descent in 1.5s. Then click "What does this have to do with RL?"

Playground
06 / 16
THE THEOREM

Universal Approximation: any shape, given enough neurons.

What you just did with sliders has a name and a proof. A one-hidden-layer net with enough neurons (and a nonlinearity like ReLU or sigmoid) can approximate any continuous function on a closed region — to any precision you want.

Cybenko (1989) · Hornik (1991) · Leshno et al. (1993)

Universal Approximation Theorem (informal)

For any continuous function \(f:[a,b]^n \to \mathbb{R}\) and any tolerance \(\varepsilon > 0\), there exists a one-hidden-layer neural network \(\hat{f}\) with finitely many neurons such that \(\sup_{x} |\hat{f}(x) - f(x)| < \varepsilon\).

Translated: "Stack enough ReLUs (or sigmoids), tune their weights, and you can match any reasonable function as closely as you like."

EXISTENCE

Some such network exists. The theorem doesn't tell us how to find it.

CAPACITY

Width can grow with precision \(\varepsilon\). Smaller \(\varepsilon\) → more neurons.

PRACTICE

In practice we use deeper nets — fewer parameters per accuracy. But the same idea.

UAT
07 / 16
CONNECT TO RL

From x → y to state → Q.

The playground had inputs \(x\) and targets \(y\). RL's setup is identical in structure — just relabel the axes. Same neurons, same training; new application.

PLAYGROUND

Fit y(x).

input\(x \in \mathbb{R}\) target\(y\) (some function of \(x\)) model\(\hat{y}(x;\theta) = \sum_i w_i\,\text{ReLU}(\ldots)\) lossMSE: \( \tfrac{1}{N}\sum (\hat{y}-y)^2 \)

You drove this manually. Auto-Fit did gradient descent for you.

DEEP Q-NETWORK

Fit Q(s, a).

inputstate \(s\) (pixels, joint angles, …) targetBellman: \(r + \gamma \max_{a'} Q(s',a')\) model\(Q(s,a;\theta)\) — same neurons, just bigger losssquared Bellman error

Same machinery. Replace MSE-against-truth with MSE-against-the-Bellman-target. That's it.

From Demo to RL
08 / 16
NO MODEL? SAMPLE IT.

No \(P\)? Use the step you actually took.

L6 ended on a question: what if we don't know the rewards and slip probabilities? Value iteration needs them — it averages over every next state. Without them, we just play, record each step \((s,a,r,s')\), and learn from what happened.

L5 · VALUE ITERATION

Average over every \(s'\).

needs\(r(s,a)\) and \(P(s'\!\mid\! s,a)\) for every \(s'\) target\(r(s,a)+\gamma\sum_{s'}P(s'\!\mid\! s,a)\,\max_{a'}Q(s',a')\)

Exact — but only if someone hands us the model, and we can sweep every state.

TODAY · FROM EXPERIENCE

Use the \(s'\) you landed in.

needsone recorded step \((s,a,r,s')\) target\(r+\gamma\max_{a'}Q(s',a')\)

No \(P\) at all. One step is noisy, but averaged over many steps it matches the backup on the left — that average is the \(\mathbb{E}\) in the loss.

No Model
09 / 16
THE LOSS

"Train" means: minimize squared Bellman error.

Bellman tells us what \(Q^*\) should satisfy. We build a network \(Q(s,a;\theta)\), then push \(\theta\) so that the network's output matches the Bellman target. The gap, squared, is the loss.

\[ \mathcal{L}(\theta) \;=\; \mathbb{E}\!\Big[\, \big(\,\underbrace{r + \gamma\, \max_{a'} Q(s',a';\theta^-)}_{\text{Bellman target}} \;-\; \underbrace{Q(s,a;\theta)}_{\text{network's guess}}\,\big)^{\!2} \,\Big] \]
① TARGET

What \(Q\) should equal: the immediate reward plus discounted best-next-Q. (Computed with frozen weights \(\theta^-\) for stability.)

② GUESS

What our network currently outputs for \((s,a)\). Just one forward pass.

③ SQUARED GAP

Penalize big mismatches harder than small ones — and make the loss differentiable so gradients flow.

\(\mathcal{L}(\theta) = 0\) means the network satisfies Bellman's equation everywhere — i.e., it has found \(Q^*\).

Bellman Error
10 / 16
HOW THE TRAINING ACTUALLY HAPPENS

Gradient descent — in four steps.

You felt this when you clicked Auto-Fit: the sliders moved themselves. Under the hood, the computer asks "which way do I nudge each parameter to lower the loss?" and steps that direction. Repeat until convergence.

①

Forward.

Run a batch of \((s, a, r, s')\) through the network → get \(Q(s,a;\theta)\).

②

Compute loss.

Squared gap to Bellman target. L = (target − Q)².

③

Gradient.

Auto-diff (PyTorch / TF) returns \(\nabla_\theta \mathcal{L}\) — direction of steepest increase.

④

Step against it.

θ ← θ − α · ∇L. \(\alpha\) is the learning rate. Repeat from ①.

Same recipe trains image classifiers, language models, and Q-networks. Gradient descent is the universal solvent.

Gradient Descent
11 / 16
THE FULL PICTURE

DQN: Atari from pixels.

Mnih et al., DeepMind, 2015 (Nature). One network architecture. 49 Atari games. Beat humans on most. Same loss we just wrote — plus two stabilization tricks.

① INPUT

Stacked frames →

4 grayscale 84×84 frames
= 28,224 pixels per state

Convolutional layers extract features automatically. No hand-designed \(\phi(s)\).

② NETWORK

\(Q(s,a;\theta)\) →

conv → conv → conv
→ dense → 18 outputs (one per action)

~1.7M parameters. Outputs Q-value for every legal action at once — one forward pass per state.

③ TRAIN

Squared Bellman error →

replay buffer + target network
+ gradient descent

Buffer breaks correlation in samples. Target net (\(\theta^-\)) keeps the moving target still long enough to chase.

The reveal: the playground you just used is a DQN, in miniature. Strip away the convolutions and the replay buffer, and you have the same idea: a neural net trained to satisfy Bellman. Width: 4 ReLUs vs 1.7M parameters. Same equation either way.
DQN
12 / 16
PAUSE & THINK

Quick function-approx check.

Tap each card to reveal the answer.

Q1 · WHY NOT JUST A LINEAR MODEL?

Linear function approximators (\(V = w \cdot \phi(s) + b\)) are simple and trainable. What's wrong with stopping there?

Linear can't capture curves.

Most real value functions are non-linear in raw state — see the U-shape in the playground. Stage 1 hits an MSE floor that no slope/intercept can reduce. ReLU adds bends; stacking them gives universal approximation.

tap to reveal
Q2 · WHAT DOES "TRAINING" MINIMIZE?

When DQN "learns to play Atari," what specific quantity is gradient descent driving toward zero?

Squared Bellman error.

\(\mathcal{L}(\theta) = \mathbb{E}\big[(r + \gamma \max_{a'} Q(s',a';\theta^-) - Q(s,a;\theta))^2\big]\). When this hits zero, the network satisfies Bellman — i.e., it has found \(Q^*\) (under the data distribution).

tap to reveal
Q3 · WHAT DOES UAT GUARANTEE — AND NOT?

The Universal Approximation Theorem says a wide-enough network can fit any continuous function. Does it tell us we'll find the right weights via gradient descent?

No. Existence ≠ findability.

UAT is an existence result — a good network exists. Whether gradient descent (with finite data, finite compute) actually reaches it is a separate, much harder question. In practice it usually works — but we have no general guarantee. That's why training deep RL is engineering, not just math.

tap to reveal
Quiz
13 / 16
WHEN TO USE WHAT

Tabular & neural — both have a place.

Function approximation is more powerful, but it's not always the right tool. Tabular still wins when the state space is small enough — and when you want a guaranteed-to-converge solution.

📊 Tabular V/Q

  • Exact answer when state count is small
  • Provably converges (value/policy iteration)
  • Easy to debug — every value is visible
  • No generalization — unseen states have nothing
  • Memory grows with \(|\mathcal{S}|\)
use it when: small state space, every state is reachable, you want guarantees

🧠 Neural \(V(s;\theta), Q(s,a;\theta)\)

  • Handles huge or continuous state spaces
  • Generalizes — similar states share value
  • Works on raw inputs (pixels, sensors)
  • No exact convergence guarantee in general
  • Training tricks needed (replay buffer, target net)
use it when: real-world states, deep features needed, scale matters more than guarantees
Tab vs Neural
14 / 16
OPTIONAL · TRY IT

Bend math yourself.

No grade. The point is to feel the equations, not to perform them.

① PLAY

Open the Universal Approximator playground in its own tab. Try: can you beat Auto-Fit? Get MSE under 0.05 with only 3 neurons. Then try with 2.

② ESTIMATE

Pick a game you know — tic-tac-toe, Tetris, Minecraft. Roughly how many states does it have, and would a table fit? If you built a Q-network for it, what would you feed in as the state? Bring your answers to L8.

Optional. No grade. Bring questions to L8.

Homework
15 / 16
NEXT WEEK · LECTURE 8

Q is one family.
What about π directly?

📌 TODAY · APPROXIMATE Q

We replaced the table with a network and trained it on the squared Bellman error. Value iteration + samples + a neural net = DQN. Same target, vastly bigger problems.

🔭 L8 · FUNCTION APPROXIMATION FOR POLICIES

Point the same tool at the policy: make π itself a network πθ(a|s) and train it by optimizing return directly. One objective, careful steps — the idea behind PPO and RLHF.

Next
16 / 16