Bandits and Reinforcement Learning
Learning by acting: you only see the reward of what you tried, so every choice is both a bet and an experiment. Pull arms yourself and watch your regret, race greedy against explore-then-commit, step UCB and LinUCB round by round, run policies through a small Markov decision process and solve it backwards, then see the neural networks and gradient descent that let these ideas scale.
The bandit modules follow T. Lattimore and Cs. Szepesvári, Bandit Algorithms (Cambridge, 2020; free online), Chapters 4–7 and 19–20. The MDP modules use the finite-horizon notation of C. Jin, Z. Allen-Zhu, S. Bubeck and M. Jordan, “Is Q-learning provably efficient?” (NeurIPS 2018), with R. Sutton and A. Barto, Reinforcement Learning (2nd ed., MIT Press, 2018), Chapters 3–4, for background. The last two modules are shared with Neural Networks and Optimization, which goes further. The questions and examples are written for this page. For how this subject connects to the others, see the roadmap.
The bandit problem and regret
There are slot machines (arms). Each pull pays a random reward; each arm has its own average, which you never get to see. You have pulls. Every pull of a worse arm costs you something, and the bill is called regret.
The idea
Why you can't see your own regret. Regret is defined through the means, and the means are exactly what you don't know. Flip a coin twelve times and get eleven heads: your estimate is , but the coin could be fair-ish with and you were lucky. After a thousand flips the estimate is better, never exact. A bandit algorithm only ever sees estimates; the figure below lets you see both.
Explore
Worked example
Three arms with . In five rounds a learner pulls . Compute the regret two ways.
Find and the gaps.
, so , , . A gap is never negative because is the largest mean.
Add up the regret round by round.
Each round costs the gap of the arm pulled: . The actual rewards don't enter: this is the regret in expectation.
Now use the decomposition.
, , : . Same answer, grouped by arm instead of by round.
Key terms
- Arm
- One of the options you can choose each round, with a fixed but unknown average payoff.
- Bandit feedback
- You see the reward of the option you chose and nothing about the ones you didn't.
- Gap
- How much worse an option's average is than the best option's average.
- Regret
- The expected total reward you gave up by not always choosing the best option.
- Empirical mean
- The average of the rewards an option has actually paid so far: an estimate, never the truth.
Check your understanding
A learner happens to get lucky rewards from a bad arm. Can its regret be negative?
- Yes, if the rewards it got add up to more than .That compares realized rewards; is defined with an expectation.
- No: is a sum of nonnegative terms.
An algorithm that pulls arms uniformly at random forever, with , has regret:
- Each arm gets about pulls, forever.
- , linear in .
- , because it tries every arm.Trying every arm is good; continuing to try them is the cost.
Why can't a bandit algorithm compute its own regret as it goes?
- It would take too long to compute.The formula is a short sum.
- The formula needs the true means , and it only has estimates.
- Rewards are hidden from the learner.It sees the reward of every arm it pulls.
Practice
The decompositionProve it
Prove .
Hint
Write and condition on in each term.
Solution
, because given the past and the choice , the new reward is a fresh draw from arm . Summing over : . Since , .
Two arms, one gapBounds from counts
Two arms with gap . An algorithm pulls the bad arm at most times in expectation. Bound its regret at , and compare with uniform play.
Solution
. Uniform play has . Logarithmic dependence on is what the algorithms in the next modules achieve.
Explore or exploit
Pulling the arm that looks best (exploiting) earns reward now. Pulling an arm that looks worse (exploring) buys information, because it may only look worse by bad luck. Every bandit algorithm is a rule for splitting rounds between the two.
The idea
Think of giving a new student a first project. If it goes badly, was it the student or bad luck with the project? One bad outcome isn't enough to know, so you give a second chance, maybe a third. But you can't give chances forever: at some point the evidence is good enough to act on. Randomness is why you must explore; cost is why you must stop.
Explore
Worked example
Two Bernoulli arms with means and . Greedy pulls each once and then follows the higher estimate (ties broken at random). Estimate the chance that greedy never pulls the good arm after round 2.
Which first two outcomes make greedy prefer arm 2?
Arm 1 pays 0 and arm 2 pays 1: probability . Then .
Once that happens, can greedy ever return to arm 1?
Only if drops below , which can't happen (estimates are averages of 0s and 1s, and a tie at 0 needs every arm-2 reward to be 0). With mean , arm 2's average stays positive with high probability. So arm 1 is abandoned for good.
What does that do to the regret?
With probability at least about (more, counting the tie cases), greedy pays every round: . Linear, however large is.
Check your understanding
In the simulation, greedy's average regret can look fine while its shaded band is wide. Why?
- Most runs lock onto the right arm and pay almost nothing; a few lock onto a wrong one and pay a lot.
- The rewards are noisy, so every run pays about the same.Then the band would be narrow.
ETC with too small, on arms whose means are very close, mostly fails by:
- Committing to the wrong arm, then paying its gap for the rest of the game.
- Exploring for too long.That's the failure when is too large.
ε-greedy with a fixed on three arms with gaps has regret at least about:
- It explores in a fixed fraction of rounds, forever.
Practice
The ETC trade-offChoose m
Using the bound , find the that minimizes the right-hand side, and the resulting regret.
Solution
Differentiate in : , so and . Then , of order . (Round up to an integer; if , take , and the regret is at most .)
When does greedy work?An easy instance
Suppose rewards are deterministic: arm always pays exactly . What is the regret of greedy?
Solution
After one pull of each arm the estimates are exact, so greedy commits correctly: , constant in . Exploration is only needed because of noise; the noisier the rewards, the more it costs.
Concentration of sums
A sum of independent terms with values in exceeds its mean by with probability at most , for every , not just in the limit. Hoeffding, Chernoff and Bernstein are three versions of this, and the differences between them matter exactly when some terms are rare.
The idea
All of these come from one move: apply Markov to , factor using independence, and optimise over .
a Gaussian tail for moderate , an exponential one far out.
Key terms in plain words
The ideas above without the symbols. Switch to Quiz me to test yourself: you see an explanation and pick the term it describes.
- Hoeffding's inequality
- A sum of independent bounded variables rarely strays far from its mean: the chance of straying by falls off like , scaled by the ranges of the variables.
- Chernoff bound
- A sharper tail bound for sums of independent yes-or-no variables, especially when successes are rare: it behaves like a Poisson tail.
- Subgaussian
- Describes a random variable whose tails die off at least as fast as a normal distribution's. Bounded variables and normal ones are examples.
- ψ₂ norm
- A single number measuring the spread of a variable with normal-like tails: the scale at which its tails look like a normal's.
- Subexponential
- Describes a variable whose tails may be heavier than a normal's but still fall off exponentially, like the square of a normal variable.
- Bernstein's inequality
- A tail bound for sums of independent variables with exponential tails: it looks like a normal tail for moderate deviations and only exponential far out.
Explore
Worked example
An A/B test estimates a click rate by the fraction of independent users who click. We want with probability at least . How many users are needed?
Use Chebyshev, knowing only .
. Setting this to gives .
Use Hoeffding (each click indicator lies in ).
Two-sided: . We need , i.e. . Sixty-five times fewer users.
Suppose you also know . Bernstein's inequality for variables with reads . What does it give?
Here and , so the exponent is . We need it to be at least :
Another factor of 11. Hoeffding pays for the worst-case variance ; Bernstein pays only for the actual variance.
How does each answer scale with the failure probability ?
Chebyshev needs ; Hoeffding and Bernstein need . Asking for instead of multiplies the Chebyshev answer by 1000, but the Hoeffding answer by less than 2.
Check your understanding
Which of these random variables is not subgaussian?
- A random variable with almost surelyBounded variables are subgaussian: , which is at most 2 for large .
- The Gaussian is the model subgaussian variable, with a constant times .
- An exponential random variable
- A sum of 100 independent random signsThat sum is bounded by 100, and better, it has norm of order .
, so . Hoeffding bounds by about ; Chernoff by about . Why is Hoeffding so weak here?
- It only uses that each term lies in , not that each term is almost always 0.
- Hoeffding needs identically distributed terms.It doesn't, and these terms are identically distributed anyway.
- Hoeffding needs symmetric terms.The version for bounded variables needs only independence and the ranges.
- Hoeffding only holds for large .It holds for every . It is a true bound here, just a useless one.
Let with i.i.d. standard normal, so the are mean-zero subexponential. For which deviations does Bernstein give a Gaussian-type bound for ?
- For
- For Compare with : which is smaller when is large?
- For all Then would be subgaussian, but alone already decays like .
- Only for is the typical size of the sum, but the Gaussian regime extends much further.
Practice
Two subgaussian normsComputing ψ₂ from the definition
(a) Show that if , then , with equality for with equal probability. (b) Compute for .
Hint
For (b), for .
Solution
(a) once ; for the first inequality is an equality, so this is the smallest. (b) Set : then , , .
From MGFs to a tail boundThe exponential moment method
Suppose are independent and for all . Prove for .
Solution
For , Markov and independence give with . The exponent is smallest at , where it equals . Random signs satisfy the hypothesis with , because ; this recovers Hoeffding.
From Vershynin, High-Dimensional Probability (2nd ed., Cambridge, pre-publication version, 2025)
Numbers match the book. Each question is restated in our own words; the hints and solutions are written for this page.
Exercise 2.13Chernoff for Poisson
Let . Prove: (a) for ; (b) for ; (c) for ; (d) for integers .
Hint
. Optimise Markov's inequality over ; the optimum is .
Solution
(a) For , . With this is .
(b) For , . With we get the same expression.
(c) At the bounds read with . Elementary calculus gives and on (compare derivatives: , ). Add the two tails.
(d) , since .
Exercise 2.25Distributions that aren't subgaussian
Explain why the exponential, Poisson, geometric, chi-squared, Gamma, Cauchy and Pareto distributions are not subgaussian.
Hint
Subgaussian means for some . Compare each tail with .
Solution
For each, find a lower bound on the tail that decays slower than any :
- Exponential: .
- Geometric: , again exponential.
- Poisson: , which is .
- Chi-squared with degrees of freedom: , and .
- Gamma: density , tail of order .
- Cauchy: ; it doesn't even have a mean.
- Pareto: polynomial tail .
Since , none of these can satisfy a subgaussian tail bound. (The first five are subexponential; Cauchy and Pareto are heavier still.)
UCB: optimism under uncertainty
Give each arm the benefit of the doubt: score it by the most it could plausibly be worth, its empirical mean plus a bonus that shrinks as it is pulled. Pull the arm with the highest score. Exploration then happens exactly where the uncertainty is, and stops on its own.
The idea
The bonus is the width of a confidence interval. By the concentration module, for -sub-Gaussian rewards (rewards in qualify),
and with the right-hand side is . So with high probability every arm's true mean lies below its index. An arm is pulled for one of two reasons: its mean is high (exploitation) or its bonus is high (exploration). Either way, pulling it is a reasonable bet.Explore
Worked example
Two arms, , bonus . Rounds 1 and 2 pull arm 1 then arm 2 (both indices start at ) and pay and . Round 3 pays , round 4 pays . Follow UCB.
Compute both indices before round 3. Which arm is pulled?
. , . Arm 1.
Arm 1 paid . Indices before round 4?
with : bonus , so . Arm 2 is unchanged at . Arm 2 is pulled: its interval is wider, so it might still be the better arm.
Arm 2 paid . Which arm is pulled in round 5?
, . Arm 1. With equal counts, the arm with the higher mean wins: the bonus only matters while counts differ.
The proof, step by step
Prove for every suboptimal arm . Write for the mean of the first rewards of arm and .
Define a “good event” on which every confidence interval is correct, and bound .
. Each of the bad events has probability at most . By the union bound, .
On , show the optimal arm's index is always at least .
. Optimism: the best arm is never underrated.
On , when can a suboptimal arm with pulls so far be chosen?
It needs . But on , . So , that is, . Once arm has that many pulls it is never chosen again, so .
Combine the two events.
. Multiply by and sum: the gap-dependent bound.
Remove the gaps with Cauchy–Schwarz.
. The second factor is ; by the previous step each . So .
Check your understanding
Why does UCB keep pulling a suboptimal arm occasionally, even late in the game?
- Its bonus grows relative to the others' while it sits unpulled ( grows, doesn't), until its upper end overtakes the best arm's.
- It pulls a random arm with some fixed probability.That is ε-greedy. UCB is deterministic given the history.
In the proof, what goes wrong without the optimism step ()?
- The best arm could be underrated, so a suboptimal arm could beat it without needing a large bonus.
- The union bound fails.The union bound is about the good event, which doesn't involve the algorithm.
Two suboptimal arms with gaps and . Which one costs UCB more regret?
- The gap arm: each pull costs ten times more.But it is pulled about a hundred times less.
- The gap arm: about versus .
Practice
Where the 16 comes fromTracking constants
Redo step 3 of the proof with bonus . What constant replaces 16, and which are allowed by step 1?
Solution
Step 3 gives . Step 1 needs to be summable over events with a total of , so . Smaller explores less and often works better in practice (as in the figure with UCB1), but this proof no longer covers it.
See it runOn this site
The Bandits Lab project races UCB, Thompson sampling and others against the Lai–Robbins lower bound. Find an instance where Thompson sampling clearly beats UCB, and explain it with the third concept check above.
Hint
UCB's bonus uses a sub-Gaussian bound, which is loose for Bernoulli arms with means near 0 or 1; the KL in Lai–Robbins is much larger there than .
Contextual bandits and LinUCB
Arms now come with feature vectors, and an arm's mean reward is a linear function of its features. Instead of estimating separate means, you estimate one vector , so pulling one arm teaches you about all of them.
The idea
The mean is least squares in disguise. The empirical mean of rewards minimizes : set the derivative to zero. The contextual version replaces the number by the vector :
writing for the feature vector actually played. The ridge term makes invertible from the start; each round adds a positive semidefinite , so only grows.
Explore
Worked example
Two arms with fixed features , , , . Arm 1 pays every time it is pulled. Ties go to arm 1. Run LinUCB.
Round 1: , . Indices?
Both . Tie: arm 1, reward . Now , , .
Round 2: indices?
, . Arm 1 again, reward : , .
Round 3?
. Arm 2, which has never been tried, wins on its bonus alone: its direction is the long axis of the ellipse.
With orthogonal features like these, LinUCB reduces to something you have seen. What?
is diagonal with entries , so (a mean shrunk toward 0 by the ridge term) and the bonus is . That is UCB with one coordinate per arm. LinUCB gains when features overlap, so one pull informs several arms.
Check your understanding
You have played a hundred times and twice. The confidence ellipse is:
- Thin along the first axis and long along the second.
- Long along the first axis and thin along the second.More data in a direction means more certainty there.
- A circle, since is the same in every direction. is one number, but is not a multiple of .
Why does LinUCB's regret not grow with the number of arms ?
- It estimates the coordinates of , and every arm's mean is determined by them.
- It only ever pulls of the arms.It can pull any arm; it just doesn't need to try each one separately.
What is ?
- That is the answer for a ball of radius , i.e. .
Practice
Least squaresDerive the formula
Show that minimizes .
Solution
The gradient is . Using , setting it to zero gives , i.e. . The objective is strictly convex for ( is positive definite), so this is the unique minimizer.
Reading an ellipseFrom V to a picture
With , and , describe and compute the bonus of and .
Solution
: an ellipse with semi-axes along and along . Bonuses: and , exactly the semi-axis in the feature's direction. (Note it is , not , in the ellipse: with the set would grow as data arrives.)
MDPs, policies and trajectories
A bandit is a single state. A Markov decision process has many, and your action decides not only the reward but also, at random, which state you land in next. Good choices now have to account for where they send you.
The idea
What the learner actually sees. The figure shows every reward and transition probability so you can follow along. A learner sees none of them: only the state it is in, the action it took, the reward it got and the next state. To learn that an action sends you up with probability , it must take that action many times and count.
Real problems. For a self-driving car the state is everything that matters right now (position, speed, the cars nearby, the weather) and an action might be a steering angle and an acceleration, a rectangle of choices. States and actions are then continuous rather than a handful of circles, but the definitions on this page are the same.
Explore
Worked example
Take the policy “always the first action” ( everywhere) in the MDP above. Find the probability of each trajectory that starts , and the policy's expected return.
What is the probability of , and what does that episode earn?
. Rewards .
List all four trajectories with their probabilities.
: , return . : , return . : , return . : , return . The probabilities add to 1.
Expected return?
. Run this policy for 1,000 episodes in the figure and the average lands near , never exactly on it.
Check your understanding
How many deterministic policies does the MDP in the figure have?
- A policy chooses at every state, not every layer.
- There are five states with choices, not three.
You run the same policy twice and get returns and . What changed?
- The policy picked different actions.A deterministic policy picks the same action every time it is in the same state.
- The random transitions sent the agent to different states.
In the “total only” mode the learner sees one number per episode. What is lost?
- Nothing: the total is what we want to maximize.It is the objective, but it hides which step earned it.
- Credit assignment: which actions along the way were responsible for a good or bad total.
Practice
A bandit is a one-state MDPFit the definitions
Describe a -armed bandit played for rounds as an episodic MDP. What are , the states, and the episodes?
Solution
, a single state , actions with rewards drawn from the arms, and each episode is one round, so there are episodes. Transitions play no role: there is no next state to influence. Everything new in MDPs comes from transitions.
Simulating by handEstimate a probability
You take action at fifteen times and go up 8 times. What is your estimate of , and roughly how far from the truth (0.8) could it reasonably be?
Solution
. The standard deviation of a 15-sample average of a Bernoulli is , so is about 2.6 standard deviations low: unlucky but possible. Hoeffding gives a two-sided 95% radius of . With fifteen samples you know the probability only roughly.
Value functions and backward induction
At the last layer the best action is obvious: take the bigger reward. Knowing the value of the last layer makes the layer before it easy too, and so on back to the start. That is the whole of dynamic programming.
The idea
Why does weighting by transition probabilities give the right answer? After taking you land in with probability , and from there, by definition, you expect more. The expected future is the average of these, and the reward of itself is added on top.
Watch
- Start at the end. After the last layer there is nothing left to earn, so at the terminal state.
- Layer 2, state : both actions end the episode, so is just the reward: and . Take the larger: .
- Layer 2, state : and , so .
- Layer 1, state . Now the future matters: and . So .
- Layer 1, state : and . So .
- Layer 0: and . .
- Read the optimal policy off the filled dots: everywhere. No other policy has a higher expected return than .
Worked example
Evaluate the policy “ everywhere” by the same backward recursion (no max: use the policy's action). Then compute its regret per episode.
Layer 2.
, .
Layer 1.
; .
Layer 0, and the gap to optimal.
, matching the trajectory-by-trajectory computation in the previous module. The regret of one episode of is .
Check your understanding
Why start at the last layer rather than the first?
- At the last layer is just the reward; every earlier needs the values of the layer after it.
- It's a convention; going forward works equally well.Forward, you would need the future values before you have them.
and are equal when:
- , the action the policy takes anyway.
- is the action with the higher reward.Reward alone ignores the future.
- Always. lets the first action differ from 's.
In this MDP the optimal action at also has the higher immediate reward. Is that always so?
- Yes: a bigger reward now can only help.It can send you to worse states.
- No: a smaller reward can be optimal if it leads to more valuable states.
Practice
When greedy is wrongChange one action
Suppose action at always led to (probability 1) and paid reward . Everything else is unchanged. For which is the optimal first action, even though ?
Solution
Layers 1 and 2 are unchanged, so and . as before. So is optimal when . For , the optimal first action has the smaller reward: it buys a guaranteed trip to the better state .
Counting the workWhy the recursion is cheap
An MDP has layers of states each and actions per state, with any state reachable from any state in the previous layer. How many multiplications does backward induction need, and how does that compare with evaluating every deterministic policy?
Solution
Each is a sum over next states: multiplications. There are of them, so in total. There are deterministic policies. For , , : 2,000 multiplications versus policies.
Learning an unknown MDP
Backward induction needs the rewards and transition probabilities. A reinforcement-learning agent has to estimate them by playing, and the estimates are only ever approximately right. It is the bandit problem again, now with states: explore enough to learn, exploit enough to earn.
The idea
Plug-in learning. Keep counts. Estimate as the average reward seen and as the fraction of times led to . Run backward induction on the estimates and follow the resulting policy. This is “certainty equivalence”: act as if the estimates were the truth. It has greedy's weakness: an action whose first outcomes were unlucky gets a low estimate and may never be tried again.
Model-free learning. Q-learning skips and updates directly from each observed step, : a running average of one-sample Bellman updates. Jin et al. show that with an optimistic bonus it is also provably efficient.
Explore
Worked example
After a few episodes the plug-in agent has tried at four times, always reaching with total reward each time (), and has tried at once, getting reward (a Bernoulli reward came up 0) and reaching .
What are and ?
from one sample; is the average of four rewards with mean , say .
Here the plug-in agent is right to prefer . In which situation would the same mechanism hurt it?
When the unlucky action is the good one. In the “when greedy is wrong” variant of the previous module, is optimal; one unlucky sample makes small, and the agent may stop trying it for a long time.
What does the optimistic agent compute for with ?
at , plus optimistic values downstream: now looks attractive, so it is tried again until its count makes the bonus small. The bonus is the price of being sure.
Check your understanding
An agent's estimate is , but the truth is . The best way to close the gap is to:
- Take at more often: the estimate converges as the count grows.
- Run backward induction more carefully.Planning is exact; the input is what's wrong.
With a very large bonus constant , the optimistic agent's regret is high early. Why?
- It keeps exploring actions it already knows are worse, because the bonus still dominates their estimates.
- Large bonuses make backward induction unstable.The bonus just adds to the rewards; nothing becomes unstable.
Regret per episode uses expected values. If an agent follows and gets an unlucky return of 1.2, its regret for that episode is:
- That uses the realized return.
Practice
Where regret comes fromA simulation-lemma view
Suppose the agent's estimates are within of the truth in every reward and within in total variation in every transition, and values lie in . Argue that the policy planned on the estimates loses at most about in value.
Hint
Compare under the true and estimated models one layer at a time: each layer adds a reward error and a transition error of at most .
Solution
For any fixed policy, the true and estimated values differ by at most per layer, so by at most overall. The planned policy is optimal for the estimate, so , the middle term being . Accurate models give near-optimal policies; the hard part is getting accurate where it matters.
Bandits inside MDPsA lower bound
Explain why an RL algorithm on episodic MDPs with actions must have regret at least of order in the worst case.
Solution
Take and one state: the MDP is an -armed bandit played for rounds, and the bandit lower bound applies. Richer MDPs contain such bandits at every state, which is how the lower bounds that grow with and are built.
Neural networks as functions
A neural network is just a family of functions with adjustable weights, and machine learning, at its core, is picking the member of the family that fits the data. The family is built from one simple principle: an affine map followed by a nonlinearity, repeated. (In reinforcement learning, this is how value functions and policies are represented once states are continuous.)
The idea
Learning is function fitting. Given data , find a function with , then predict at inputs you haven't seen. The family of functions you search matters: if it only contains straight lines and the data curve, every prediction will be off.
The theorem says a good network exists; it does not say how wide it must be, or how to find its weights. Smaller generally needs more parameters, and under smoothness assumptions on one can say how many. In the figure, a ReLU network with hidden units is the piecewise-linear interpolant at points; for twice-differentiable its error falls like .
Explore
Worked example
A network with one hidden layer of two ReLU units: , , output . Evaluate it at and .
Forward pass at .
, . .
Forward pass at .
, . .
Count the parameters, and say what the network looks like as a function.
First layer: a matrix and 2 biases (6); output: 2 weights and 1 bias (3). Total 9. Each ReLU is zero on one side of a line and linear on the other, so is piecewise linear with at most four pieces, cut by the lines and . Large networks are the same thing with far more pieces.
Check your understanding
A network has ten hidden layers of width 100, but no activation functions. It can represent:
- Any continuous function, given enough layers.Composing affine maps never leaves the affine maps.
- Only affine functions .
Universal approximation guarantees that:
- Training by gradient descent will find a network within of the target.It says nothing about training.
- Some network within of the target exists, of some size.
- A network with a fixed number of units can approximate every continuous function.The size depends on and on the target.
In the figure, the steep step needs many more units than sin for the same error. Why?
- Piecewise-linear interpolation error is controlled by the target's slope and curvature, and the step is very steep in one place.
- ReLU networks cannot represent increasing functions.Each unit is increasing; sums of them certainly can be.
Practice
The hat functionThree ReLUs make a bump
Write the hat as a combination of ReLUs .
Solution
. Check: for all are 0; on it is ; on it is ; for , . Three hidden units. Sums of shifted hats are exactly the piecewise-linear interpolants, which proves universal approximation in one dimension.
Error versus widthA rate
Using equally spaced pieces on , how many hidden units are needed to approximate to within ?
Solution
, , so the error is at most . Need : . Ten times more accuracy costs only about times more units, because is smooth.
Gradient descent, momentum and mini-batches
Fitting a network means minimizing a loss over its weights. Gradient descent does it by walking downhill: from wherever you are, take a small step in the direction in which the loss decreases fastest.
The idea
Why the negative gradient? The rate of change of in a unit direction is the directional derivative , where is the angle between them. It is most negative when , that is, when points opposite to . So
The gradient says which way to go, not how far: the learning rate is a choice. In machine learning is the average loss over the data, and computing its gradient through the network's layers is backpropagation.
Explore
Worked example
, so . Start at .
With : the per-step factors in each coordinate, and .
and . So : the steep coordinate is solved in one step, and after that. Reaching takes steps.
With ?
Factors and . The second coordinate flips sign and grows by 1.5 each step: divergence, since .
What is the best fixed , and how fast is it?
Balance the two factors: , so and both have size . About 35 steps for three digits. Momentum improves this to roughly per step.
Check your understanding
Why step against the gradient rather than along it?
- is smallest at : the loss falls fastest opposite to the gradient.
- Along the gradient the step would be too long.Length is set by ; direction is the issue.
On an ill-conditioned quadratic () plain gradient descent is slow because:
- must be below for the steep direction, which makes progress in the flat direction tiny.
- The gradient points away from the minimum.It points downhill, just not at the minimum: it zigzags across the valley.
Doubling the batch size changes the mini-batch gradient's standard deviation by a factor of:
- That is the variance, not the standard deviation.
- : the noise comes from the data, not the batch.Averaging more independent samples reduces it.
Practice
The gradient of a quadraticThree lines
For with symmetric, show , find the minimizer, and rewrite gradient descent as .
Solution
by symmetry, and . The minimizer solves . Then ; subtract .
Momentum on a lineThe characteristic equation
Apply heavy ball to . Show that satisfies , and find when it converges for , .
Solution
Substitute . The roots of have product ; the iteration converges iff both have modulus below 1, which (Jury's test) means : . Momentum enlarges the stable range from to .