- Learn
- Computer Science & IT
- Computer Science
- Artificial Intelligence
- Reinforcement Learning
Markov Decision Processes and Reinforcement Learning
IntermediateLesson 8 of 10 in Artificial Intelligence Course
What you will learn
- Describe a decision problem with uncertain outcomes in terms of states, actions, transition probabilities and rewards, and compare behaviors by their expected discounted reward.
- Describe the parts of a Markov decision processName the states, actions, transition model and reward function of an MDP, read them from a table, and explain the Markov property the model relies on.
- Compare policies using discounted returnsDefine policies and discounted returns, compute a return for a sequence of rewards, and explain how the discount factor and the reward per step change which behavior is best.
- Formulate a real problem as an MDPTurn a described situation into states, actions, probabilities, rewards and a discount factor, choose a state that satisfies the Markov property, and design rewards that express the real objective.
- Describe the parts of a Markov decision process
- Define the value of a state and of a state–action pair, for a given policy and for optimal behavior, and use Bellman equations to link each value to the values of the states that can follow.
- Define state values and Q-valuesExplain what V-values and Q-values measure, relate optimal values and optimal policies, and read a policy from Q-values.
- Write and check Bellman equationsDerive the Bellman equations for a fixed policy and for optimal values, solve a small policy-evaluation system by hand, and check whether given values satisfy the equations.
- Define state values and Q-values
- Compute the values of a policy and an optimal policy when the transition model and rewards are known, using policy evaluation, value iteration and policy iteration.
- Evaluate a fixed policyCompute the values of a given policy exactly or iteratively and explain what the intermediate values mean.
- Compute optimal values with value iterationApply the value-iteration update by hand, explain what the values mean after k iterations, decide when to stop, and extract the policy.
- Find optimal policies with policy iterationAlternate policy evaluation and policy improvement until the policy stops changing, and compare policy iteration with value iteration.
- Evaluate a fixed policy
- Explain how reinforcement learning differs from planning, and estimate a model or a policy's values from observed transitions with model-based learning, direct evaluation and temporal-difference learning.
- Explain the reinforcement learning setting and learn a modelDescribe what a learning agent knows and observes, distinguish passive from active learning, and build and use an estimated model from counts.
- Estimate values with direct evaluation and temporal-difference learningEstimate a fixed policy's values by averaging sampled returns and by temporal-difference updates, and explain why state values alone cannot choose actions without a model.
- Explain the reinforcement learning setting and learn a model
- Learn optimal behavior without a model using Q-learning, balance trying new actions against using the best known ones, and extend Q-learning to large problems with features.
- Learn optimal Q-values with Q-learningApply the Q-learning update to observed transitions, explain why it learns the optimal policy while behaving differently, and state when it converges.
- Balance exploration and exploitationExplain why a learning agent must sometimes try actions that look worse, and use epsilon-greedy action selection, exploration functions and confidence bounds to do so.
- Generalize with approximate Q-learningRepresent Q-values as a weighted sum of features, update the weights from experience, and explain what generalization gains and what it can break.
- Learn optimal Q-values with Q-learning
Reinforcement Learning study guide
1Model sequential decisions as Markov decision processes
A useful decision model describes both what an agent controls and what can happen by chance. A delivery robot can choose to work or charge, but it cannot choose whether its battery survives another job. States, transition probabilities, and rewards make this distinction precise. Policies then describe how to act across many possible runs, while discounted returns express how much the agent values rewards now and later.
1.1 Describe an agent's states and choices
A Markov decision process, or MDP, describes repeated decisions when actions can have uncertain outcomes. The agent observes its current state, chooses an available action, receives a reward, and moves to a new state. These four parts describe one transition; a sequence of transitions describes a run.
Read a transition model
The state set is , and lists the actions allowed in state . The transition model gives the chance of reaching after taking in . For each state–action pair, all these probabilities are nonnegative and sum to 1. The reward belongs to that transition. A negative reward represents a cost or penalty.
Consider a delivery robot with states High battery, Low battery, and Dead. Dead ends the episode. Its model is:
| State | Action | Next state and probability | Reward |
|---|---|---|---|
| High | Work | High: 0.7; Low: 0.3 | +4 for either outcome |
| High | Charge | High: 1 | 0 |
| Low | Work | Low: 0.6; Dead: 0.4 | +4 if Low; −10 if Dead |
| Low | Charge | High: 1 | 0 |
The two Work rows each sum to 1. For Work in Low, the expected immediate reward is . This average is useful for planning, but an actual attempt earns either 4 or −10. Choosing Work chooses the distribution; it does not choose the successful outcome.
Put the relevant past into the state
The Markov property means that the current state and action contain the information needed to predict the next state:
The world may have a long history. That history matters through the variables included in the current state. A robot's location alone may be insufficient if its battery determines whether a job succeeds. Including the battery level lets the model distinguish situations with different risks.
A standard MDP assumes the agent observes the state exactly. If important parts of the state are hidden, the agent needs a belief about possible states; that leads to a partially observable MDP, or POMDP.
Recognize endings and random movement
A terminal state has value 0 because no rewards follow it. The reward on entering it still counts: the robot receives −10 on its last transition into Dead. Episodic tasks end at a terminal state; continuing tasks, such as ongoing temperature management, need no terminal state.
In a grid world, an intended move can succeed with probability 0.8 and slip in either perpendicular direction with probability 0.1 each. An attempted move into a wall leaves the agent in place. Probabilities of outcomes that reach the same square must be combined.
Deterministic transitions are a special case: one successor has probability 1. For a known start and a suitable goal-reaching task, a fixed plan can suffice. With uncertain outcomes, a policy specifies how to respond in whichever state actually occurs. Some texts write rewards as or ; check the timing convention before translating a formula.
Key Takeaways
- A transition model assigns probabilities to next states for each state–action pair.
- The state must retain the information needed to predict outcomes and rewards.
- A terminal state has zero future value; its entry reward still counts.
- A policy supplies an action for each state the agent may encounter.
1.2 Compare rewards across time
A policy describes how the agent acts. A deterministic stationary policy chooses one action for each state and keeps that choice over time. For the robot, "Work when High, Charge when Low" is such a policy. A stochastic policy assigns probabilities to the available actions.
Calculate a return
The discounted return combines rewards across a run:
The first transition earns with weight 1. Each later reward receives one more factor of the discount . For rewards −1, −1, −1, and +10 followed by termination, using gives
With , the same run gives . The delayed gain loses much of its weight. Discounting can represent a preference for earlier rewards, or the chance that the process continues to another step.
A policy is judged by its expected return, averaging over its possible runs. One lucky run does not establish that a policy is good. An optimal policy gives the largest expected return from every state. A finite discounted MDP has an optimal policy that is deterministic and stationary.
Keep an infinite future finite
For bounded rewards and , the geometric series bounds every return. If , then
The robot's largest reward magnitude is 10, so gives . Since its largest positive reward is 4, its return also cannot exceed . These are bounds, not claims that the robot can achieve them.
The quantity is a rough effective horizon: about 10 steps for . It is not a cutoff. A reward 10 steps later still receives weight . Undiscounted continuing tasks need special care: repeated positive rewards can make returns infinite. A fixed finite horizon makes the sum finite; episodic models also need well-behaved episode lengths for finite expected values.
Let time and step rewards affect decisions
With a deadline, the best action can depend on the time left. Consider a machine in Worn condition. Run earns 6 and leaves it Worn or Broken with equal probability. Repair earns −4 and makes it Good. In Good, Run earns 10; in Broken, Repair earns −20. With one step left, Worn favors Run: . With two steps left and , Repair gives . Run gives . The extra time reverses the choice.
A grid world's living reward, earned on nonterminal steps, changes the cost of delay. Negative step rewards encourage reaching an exit; a larger penalty can make a nearby bad exit preferable to a long route. A sufficiently large positive step reward can favor staying in the grid. The exact choice also depends on discounting, distances, and slip risks.
Key Takeaways
- A return discounts later rewards; the current reward has weight 1.
- Policies are compared by expected return across possible runs.
- Bounded rewards and a discount below 1 bound infinite returns.
- A finite horizon can make the best action depend on time remaining.
- Living rewards change the value of delay and termination.
1.3 Build a state and reward model
Formulating an MDP turns a practical objective into decisions a computer can evaluate. Start by choosing when decisions happen. Then define an observable state, legal actions, transition probabilities, rewards, any terminal states, and a discount or horizon. The quality of the resulting policy depends on these choices.
Model machine maintenance
Suppose a machine is inspected once per decision step. Its condition is Good, Worn, or Broken. The model is:
| State | Action | Reward | Next condition |
|---|---|---|---|
| Good | Run | +10 | Good with 0.8; Worn with 0.2 |
| Worn | Run | +6 | Worn with 0.5; Broken with 0.5 |
| Worn | Repair | −4 | Good with 1 |
| Broken | Repair | −20 | Good with 1 |
Broken is not terminal: repair lets work continue. The task is continuing, with . Notice that available actions depend on the state; Run is unavailable when Broken.
Solving this model gives optimal values about 78.64 in Good, 66.78 in Worn, and 50.78 in Broken. In Worn, Repair has value . Run has value . The negative immediate reward for repair buys access to a more productive future.
Choose enough state information
The state must support predictions of both outcomes and rewards. A moving ball's position alone omits its velocity, so two identical positions can have different next positions. A board-game position also needs whose turn it is. If remaining time changes which actions pay off, include it in a finite-horizon decision rule or augment the state with it.
Extra variables increase the state space. Ten yes/no variables allow combinations. Keep information that changes predictions or rewards; storing the entire history can make a workable model needlessly large. The usual stationary MDP assumes the same transition and reward rules over time. Hidden state calls for a belief model, while strategic opponents call for a game model.
Make the reward express the objective
A cleaning robot rewarded for each piece of dirt collected can profit by spilling and recollecting dirt. This is reward hacking: successful optimization of a poor measure. A reward tied to the desired cleanliness avoids that particular loop. A sparse goal reward states success clearly but supplies little feedback during a long attempt.
Reward shaping adds feedback about progress. Arbitrary bonuses can change the objective. Two useful comparisons are:
- Multiplying all rewards by the same positive number preserves their policy ranking.
- Adding a constant to every reward preserves optimal policies in a continuing discounted task, because every policy gains the same discounted constant. In an episodic task, longer and shorter runs gain different amounts, so the ranking can change.
A policy-preserving shaping term has the form . Here assigns a potential to each state. With bounded potentials in a continuing discounted task, the added discounted terms cancel except for a start-state offset. For episodic tasks, setting every terminal potential to 0 removes the leftover terminal term. A nonzero terminal potential can change which ending, or which stopping time, is preferred.
Key Takeaways
- Define the decision timing before choosing states, actions, and rewards.
- States need enough information for predictions without unnecessary history.
- A broken machine can be a continuing state if repair remains possible.
- Reward design determines what the agent actually optimizes.
- Positive reward scaling preserves optimal policies; constant shifts need the right task setting.
- Potential-based shaping preserves optimal policies under its boundary conditions.
2Express values with Bellman equations
An immediate reward tells only part of the story. A state can be valuable because it opens up good decisions later, and an action can be costly now but worthwhile over time. State values and action values put numbers on those possibilities. Bellman equations connect each value to the states that can follow, using a probability-weighted average for chance outcomes and a choice among the actions the agent controls.
2.1 Read state values and action values
A value measures the return available from a situation under a particular way of acting. It includes future rewards, weighted by their probabilities and timing. This makes values different from the reward earned on a single transition.
Distinguish the starting choice
The state value is the expected discounted return starting in state and following policy . The action value fixes the first action to , then follows afterward. It does not mean taking at every later step.
Optimal values replace that continuation policy with the best possible behavior. Thus is the best expected return from , and is the best expected return after the first action is fixed. Their relationship is
The maximum is a number; the argmax identifies an action attaining it. If several actions tie, any tied action can be selected.
Read the robot's choices
For the delivery robot with , the optimal Q-values are:
| State | Work | Charge |
|---|---|---|
| High | 31.50 | 28.35 |
| Low | 13.71 | 28.35 |
Each row's maximum is the state's optimal value. High favors Work; Low favors Charge. Charge earns 0 immediately, but in Low it restores access to High and its better future opportunities. Work in Low still has positive optimal Q-value because a surviving robot can charge afterward.
The continuation policy matters. Under "always Work," the state values fall to about 8.27 in High and −3.48 in Low. The model has not changed; the decisions after each outcome have changed. A number labeled only "the value" is incomplete unless the intended policy or optimality is clear.
See choices and chance as separate layers
An expectimax tree alternates two kinds of nodes. At a state the agent selects an action; at a state–action pair, sometimes called a q-state, chance selects the next state according to the transition model. The agent maximizes across actions and averages across their outcomes.
A cyclic MDP repeats the same states at many tree locations. Dynamic programming stores a value for each state and reuses it. This avoids recomputing the same continuation problem every time a tree path returns to that state.
Extract a policy from the available values
With a Q-table, compare the action values in the current row. No transition model is needed. With state values alone, first calculate an action's expected reward plus discounted successor value:
That calculation needs transitions and rewards. Merely choosing the action that can reach the highest-value successor ignores how likely that successor is and what the action costs. A high expected value also leaves room for an unlucky run: it describes an average over outcomes, not a guaranteed reward on every attempt.
Key Takeaways
- A state value assumes a continuation policy from the start.
- A Q-value fixes the first action and then uses the stated continuation policy.
- The maximum Q-value gives the state value; an argmax gives an action.
- A Q-table supports action selection without a transition model.
2.2 Connect values with Bellman equations
A run's return can be split after its first transition: the immediate reward plus the discounted return from the next state. Taking an expectation produces a Bellman equation. It connects a state's value to successor values, including the possibility of returning to the same state.
Evaluate a fixed policy
For a deterministic policy, only its selected action appears:
Each branch contributes its probability times its immediate reward plus future value. There is one equation per state. In a finite discounted MDP, these are linear equations with a unique solution.
For the robot's "always Work" policy, begin at Low. The two possible transitions give
Expand and collect the unknown: , so . Therefore . The −10 reward remains even though Dead's future value is 0.
At High, both outcomes earn 4, so their immediate rewards combine to 4:
Collecting terms gives . Using the unrounded Low value yields . Keep full precision while substituting; round the reported values at the end.
Add the choice of action
For optimal values, calculate the expectation for each available action, then take the best:
The maximization sits outside the sum because the agent chooses one action before seeing the outcome. Choosing a different current action for each possible next state would give it information it does not yet have.
The Q-form fixes that first action but allows the best next action after observing the successor:
These optimality equations contain maxima, so a single fixed-policy linear solve does not directly solve them.
Check proposed values
Use the robot's candidate optimal values and . At High, Work gives . Charge gives . The larger result matches the candidate High value.
At Low, Work gives ; Charge gives 28.35. The maximum matches the candidate Low value too. A check of only one state would leave the other equation untested. Small discrepancies are expected when the candidate values have been rounded.
Discount only the future term. Replacing with incorrectly delays the immediate reward by one step.
Key Takeaways
- Bellman equations split return into an immediate reward and discounted continuation.
- A fixed policy gives a linear system with one equation per state.
- Optimality maximizes over complete action expectations.
- A terminal successor removes the future term, while retaining the transition reward.
- Check every state equation when testing candidate values.
3Solve known MDPs with dynamic programming
When transitions and rewards are known, an agent can calculate how to act before collecting new experience. Policy evaluation measures one proposed behavior. Value iteration searches for optimal values, and policy iteration improves a complete policy in rounds. These methods reuse values across repeated states, making small cyclic problems manageable without expanding an ever-growing tree of possible futures.
3.1 Calculate how good a policy is
Policy evaluation asks how much expected return a fixed policy earns. The model and policy are known. No action choices are improved during this calculation; the output is , which can later support a separate improvement step.
Solve the equations exactly
Take the policy "Work when High, Charge when Low" and . Charging Low gives no immediate reward and always reaches High, so . Working High gives
Substitute the first equation into the second:
Then , giving and . This establishes the values of that policy. Proving it optimal also requires checking competing actions.
Exact evaluation solves one linear equation per nonterminal state. Standard dense elimination costs on the order of operations. The method is convenient for a small model because the relationships can be inspected directly.
Evaluate by repeated sweeps
An iterative alternative starts with and applies the fixed-policy backup to every state:
Each new value uses the old array. For "always Work," the first three sweeps, in the order High then Low, give:
| Sweep | High | Low |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 4 | −1.6 |
| 2 | 6.088 | −2.464 |
| 3 | about 7.170 | about −2.931 |
For example, the second Low value is . High in that same sweep uses the old High value 4 and old Low value −1.6, giving .
With a discount below 1, the sweeps converge to about 8.27 and −3.48. A dense fixed-policy sweep costs on the order of operations because each state sums over successors. Sparse transition models can skip successors with probability 0.
Interpret intermediate values
Starting at zero, is the expected discounted reward over the next transitions under the fixed policy, with no value beyond that horizon. The first sweep sees only immediate rewards. The second includes one more transition. These intermediate values have a clear meaning even before convergence.
Updating in place uses some freshly computed values within the same sweep. With the usual discounted conditions it can also converge, but its intermediate arrays need not equal these synchronous finite-horizon values. In a hand calculation, keep separate old and new arrays when comparing synchronous sweeps.
Do not add a maximum over actions during evaluation. That would let the agent change its behavior and would answer a different question from the one the fixed policy defines.
Key Takeaways
- Evaluation computes a fixed policy’s values without changing its actions.
- Exact evaluation solves the policy’s Bellman equations.
- Synchronous iterative evaluation uses the previous array throughout a sweep.
- Zero-initialized sweep k evaluates k transitions under that policy.
3.2 Find optimal values by repeated backups
Value iteration repeatedly asks what is best when one more decision is allowed. It starts from and backs up each state's best expected reward plus discounted successor value. The same calculation handles cycles because successor values come from a stored array.
Make one complete sweep
For every nonterminal state, calculate
For the robot's first sweep, all future terms are 0. High compares Work at 4 with Charge at 0, so . Low compares Work at with Charge at 0, so .
The second sweep uses this entire old array. At High, Work gives , while Charge gives . At Low, Work still gives −1.6, while Charge gives 3.6. Thus . A third sweep gives about .
If the new High value 6.52 were used immediately to update Low, the result would differ. That is an in-place update, not the synchronous second sweep just shown.
Understand what converges
From zero initialization, is the optimal expected return with exactly decision opportunities remaining, allowing terminal episodes to end sooner. Each sweep extends the useful planning horizon by one. The Bellman optimality operator is a contraction for : the largest error over states shrinks by at least a factor of per application. Values converge to the unique from any finite starting array.
A dense sweep considers states, actions, and successors, costing on the order of operations. A discount close to 1 usually slows convergence because distant rewards retain more weight.
Stop with an error bound
Let . For , the new array's maximum error is bounded by . To ensure error below a chosen tolerance , it is sufficient that
For and tolerance 0.01, the threshold is about 0.00111. A change below 0.01 alone does not certify value error below 0.01. At , a single backup gives the optimal immediate rewards, so no division by the discount is needed.
Read out the policy
After stopping, compare action expectations using the final value array. This one-step lookahead gives a greedy policy. The policy can settle before the values: the robot's greedy policy from already says "Work when High, Charge when Low," but its values need 77 sweeps to come within 0.01 of the optimal pair .
A stable-looking policy and accurate values are different checks. The backup must compare expected outcomes for each action; selecting the single most valuable possible successor leaves out both risk and immediate reward.
Key Takeaways
- Value iteration applies a maximum over action expectations at every state.
- Zero-initialized sweep k gives optimal k-step values.
- Discounting makes the optimality backup a contraction.
- The largest sweep change needs scaling before it certifies value error.
- Extract a policy with a complete one-step lookahead.
- An optimal greedy policy can appear before values are close to their limits.
3.3 Improve a policy until it stops changing
Policy iteration alternates two jobs: measure a policy, then improve its actions using that measurement. Start from any deterministic policy. A good initial guess can save work, but it is not required for correctness in a finite discounted MDP.
Separate evaluation from improvement
First compute , the values of the current policy. Then, for every state, compare all actions using those same values:
Evaluation describes the old behavior. Improvement asks whether changing the first action would improve the return if the old policy were followed afterward. Changing all such actions gives a policy at least as good in every state. If the old policy is not optimal, an improvement is strict in at least one state.
Keep the current action whenever it ties for best. Otherwise, equally good actions can make a policy appear to keep changing even though there is no value improvement.
Improve the robot's policy
Start with "always Work." Exact evaluation gives High about 8.27 and Low about −3.48. In High, keeping Work gives 8.27; switching to Charge gives . Keep Work. In Low, Work gives −3.48 and Charge gives about 7.45. Switch Low to Charge.
Now evaluate the new policy "Work when High, Charge when Low." Its values are about 31.50 and 28.35. Improve again:
| State | Work expectation | Charge expectation | Keep |
|---|---|---|---|
| High | 31.50 | 28.35 | Work |
| Low | 13.71 | 28.35 | Charge |
No action changes, so policy iteration stops. The fixed-policy values also satisfy the optimality equations, establishing that this policy is optimal. The robot needed two full evaluations from this starting policy.
Explain why the process ends
A finite MDP has only finitely many deterministic policies. If every one of states has choices, there are such policies. The robot has two nonterminal states with two actions each, giving policies. With strict improvement whenever needed and consistent tie handling, the process cannot return to a worse policy and must finish.
Compare the planning methods
| Method | Main repeated work | Stopping idea |
|---|---|---|
| Value iteration | One optimality backup per state | Bound remaining value error |
| Policy iteration | Policy evaluation, then action improvement | Policy unchanged after improvement |
| Modified policy iteration | A few evaluation sweeps, then improvement | Continue partial evaluation and improvement to convergence |
Full evaluations make policy-iteration rounds more expensive, but often fewer rounds are needed. The robot's 77 value-iteration sweeps and two policy evaluations are different units of work, so the counts alone do not establish which method is faster. Use values belonging to the current policy during each improvement; mixing them with values from a previous policy breaks that step's meaning.
Key Takeaways
- Policy iteration alternates evaluation and improvement.
- Improvement compares actions using one consistent policy-value array.
- Keep the current action on ties and stop when no action changes.
- Finite policies and monotone improvement ensure termination.
- Fewer policy-iteration rounds can still involve more work per round.
4Learn about an unknown MDP from experience
A learning agent often starts without reliable transition probabilities or reward predictions. It must learn from observed actions and outcomes. One route estimates a model and then plans; another estimates values directly. Comparing whole-episode returns with one-step temporal-difference updates shows how feedback can teach an agent even before an episode ends, and why limited experience can give misleading estimates.
4.1 Learn a model from observed transitions
In reinforcement learning, an agent learns from experience in a decision problem. It observes a state, chooses an available action, and receives a sample : the previous state, action, reward, and next state. The objective remains high expected return, but transition probabilities and rewards must be learned.
Separate learning from planning
Planning uses an MDP model to calculate values or policies. It can happen before acting or while an agent replans during operation. Learning uses observed experience, either from ongoing interaction or from a previously collected data set. Offline reinforcement learning still learns from experience; it simply uses recorded experience.
In passive learning, a policy is fixed and the task is to estimate how well it performs. In active learning, the agent also chooses actions to discover better behavior. Those choices affect both collected reward and the information available for future updates.
Estimate transitions with counts
A model-based learner records how often each action is tried in each state. Let count those trials and count the trials ending in a particular successor. Then
The counts in the numerator partition the trials in the denominator, so their estimated probabilities sum to 1. An untried pair has denominator 0 and needs more experience or an explicit modeling choice; it has no empirical transition distribution yet.
For the robot, Work in High was tried 20 times: 13 transitions stayed High and 7 reached Low. The estimates are and . Work in Low was tried 10 times: 7 survived and 3 reached Dead, giving 0.7 and 0.3. The second estimate understates the true death probability 0.4.
Record rewards for each transition too. The robot has fixed rewards for its outcomes. If repeated identical transitions have noisy rewards, estimate their conditional mean reward from the observed samples.
Plan with the learned model
Use the estimated transitions and rewards in value iteration or policy iteration. For these robot counts, with Charge transitions known and , the estimated optimal values are about . The optimal action choices still match the true model: Work in High, Charge in Low. Similar policies can therefore arise from different value estimates.
Few samples can give inaccurate models. More representative experience improves the estimates, but collecting data only under one narrow policy can leave useful actions untried. A model-based learner still needs exploration.
Compare two learning routes
| Route | What is learned | How it supports decisions |
|---|---|---|
| Model-based | Transition and reward estimates | Plan in the estimated MDP |
| Model-free | Values or action values | Use learned values directly, with the needed action information |
A learned model can reuse samples for many planning backups and support replanning when objectives change. It also takes storage and computation, and model errors can distort the plan. Model-free methods avoid building a transition table, but usually require substantial experience to make their value estimates reliable.
Key Takeaways
- Reinforcement learning uses experience; planning uses a model.
- Passive learning evaluates a fixed policy; active learning also chooses actions.
- Estimate each transition probability from its state–action trial count.
- An untried action has no empirical transition estimate.
- A model-based learner plans with its estimated model.
- Model-free learning estimates values without first learning transitions.
4.2 Learn values from returns and TD targets
A fixed policy can be evaluated without knowing its transition model. Direct evaluation averages complete sampled returns. Temporal-difference learning, or TD learning, updates from a single reward and an estimated successor value. Both learn the policy's values from experience.
Average whole-episode returns
Follow "always Work" with . One robot episode is High → High (+4), High → Low (+4), Low → Dead (−10). The returns from its High visits are and . Its Low return is −10.
A second episode is High → Low (+4), Low → Low (+4), Low → Dead (−10). Its High return is −0.5; its Low returns are −5 and −10. The every-visit means are therefore for High and for Low. A first-visit method would count only the first visit to a state in each episode.
These estimates differ sharply from the true policy values because both episodes ended quickly. Whole returns have sampling variation. With sufficient representative completed episodes, their averages approach the policy's expected returns. Direct evaluation waits until the required return is available at episode end and estimates states separately.
Update after one transition
TD uses the current estimate of what follows:
The target is . The TD error is target minus current estimate. The learning rate controls the fraction of that error used in the update.
Suppose , , , and . After High → Low with reward 4, the target is . The error is , so the new High estimate is . Low's stored value remains 8 on this update. A terminal next state contributes no future term.
TD bootstraps: it uses an estimate to improve another estimate. This passes information through connected states and permits updates in continuing tasks, but early targets can be biased by poor successor estimates.
Control how much new evidence counts
| Method | Update target | Needs a completed episode? |
|---|---|---|
| Direct evaluation | Sampled discounted return | Yes, for the complete return |
| One-step TD | Reward plus discounted estimated next value | No |
A large learning rate reacts strongly to each target. At the old estimate is replaced by the latest target. A fixed positive rate generally keeps tracking sample noise. Suitably decreasing rates, with repeated visits and the usual finite discounted assumptions, support tabular TD convergence. A rate averages the sequence of observed TD targets; those targets themselves change as successor estimates improve.
State values alone do not reveal the best action without transition and reward information for a lookahead. Passive TD evaluates the behavior generating its samples. Learning action values gives an agent a direct way to compare actions without first learning a model.
Key Takeaways
- Direct evaluation averages complete returns from sampled visits.
- TD updates toward an immediate reward plus discounted next-state estimate.
- The TD error is target minus the current estimate.
- Bootstrapping permits learning before an episode ends.
- A decreasing learning rate must be paired with repeated visits for convergence.
- State values alone require a model to compare actions by lookahead.
5Learn to act with Q-learning and exploration
Choosing actions creates a second challenge for a learning agent: its decisions determine the experience it receives. Q-learning estimates action values directly, while exploration makes useful evidence available. A compact feature representation can share learning across many states, but it also changes the reliability guarantees. The central questions are what the update targets, how actions are sampled, and what the representation can express.
5.1 Update action values with Q-learning
Q-learning learns action values from observed transitions. Its target assumes the best next action, even while the agent chooses exploratory actions. This lets it learn how to act well without estimating a transition model.
Replace an expected backup with a sample
A model-based Q-backup averages over all possible successors:
Q-learning sees one successor at a time. After a sample , it computes
and updates . A terminal successor makes . The maximum is over actions available in the next state, not the state just left.
Initialize the Q-table, choose an action with an exploration rule, observe the result, update the selected entry, and continue from the next state. Restart after termination. To use the learned policy, select an action attaining the largest Q-value in the current row.
Work through two updates
Let and . Initially . The robot tries Work in Low and dies with reward −10. The target is −10, so the new value is . There is no future return after Dead.
Next suppose and the robot works High, earns 4, and reaches Low. At Low the estimates are Work at −2.5 and Charge at 3. The best next value is 3, making the target . The updated High–Work value is . This sample updates only that table entry.
Distinguish target behavior from actual behavior
Q-learning is off-policy: the continuation in its target is greedy, even if its action-selection rule explores. SARSA is on-policy: it uses for the action actually chosen next.
| Method | Next action used in target | Values being learned |
|---|---|---|
| Q-learning | Highest current next Q-value | Optimal action values, under convergence conditions |
| SARSA | Actual next action | Action values of the behavior policy |
Near a cliff, an exploring agent can take accidental dangerous steps. SARSA accounts for those future exploratory actions and can learn a more cautious route. Q-learning targets the greedy continuation and can favor a shorter edge route, even while exploration makes its training trips risky.
State the tabular guarantee precisely
In a finite stationary MDP with bounded rewards and , tabular Q-learning converges to with probability 1 when every state–action pair receives infinitely many updates and its learning rates satisfy
A per-pair rate has this form. A rate decreases too quickly: its total sum is finite, so it can leave too little adjustment to remove an initial error. Infinite total adjustment prevents learning from stopping too early; finite squared adjustment controls accumulated noise. Constant rates generally retain fluctuations in stochastic tasks. These are limiting conditions, so a finite training run still needs evaluation.
Key Takeaways
- Q-learning moves one action value toward a sampled optimality target.
- The target maximizes over next-state actions.
- A terminal successor makes the target equal to the observed reward.
- Off-policy learning separates the target policy from exploratory behavior.
- Tabular convergence requires repeated coverage and suitable per-pair learning rates.
5.2 Choose useful actions while learning
Exploitation selects the action that currently looks best. Exploration gathers information that may reveal a better choice. If an early unlucky Work attempt makes the robot prefer Charge in High, pure exploitation can keep it charging forever and leave the Work estimate uncorrected.
Count the random branch correctly
An epsilon-greedy rule explores uniformly with probability and otherwise chooses a greedy action. Suppose there is one greedy action among four and . Its selection probability is . Each other action has probability 0.05. The random branch includes the greedy action too.
Lower exploration early in training can leave useful actions untested; high exploration late in training keeps sacrificing reward. A schedule can become greedy in the limit while still trying every relevant pair infinitely often. This GLIE property is stronger than simply reducing epsilon, and reachability matters for whether all states are visited.
Favor actions with little evidence
An exploration function can add a bonus to a value estimate. With for a tried action, choose the action with the largest score. Give untried actions priority, such as score . With , a value 5 tried 20 times scores 5.5; a value 4 tried twice scores 9. The less-tried action is selected despite its lower current estimate.
The bonus can also enter a backup target: . This propagates the attraction of unexplored actions to earlier states. Optimistic initial Q-values can also encourage trying actions whose estimates have not yet been corrected by experience.
Use a confidence bound for bandits
A multi-armed bandit has one decision state and several arms with unknown fixed mean rewards. Each pull teaches the agent about an arm's reward distribution. UCB1 assumes bounded independent reward draws with a fixed distribution per arm; rescale rewards to the range 0 to 1. Pull every arm once, then choose the largest score
Here is arm 's sample mean, its pull count, and the total count across arms. The bonus grows for poorly sampled arms. With means 0.6 and 0.5 after 10 and 2 pulls, . The scores are about 1.30 and 2.08, so the second arm is selected. The score can exceed 1 even though observed rewards cannot: it is a decision index, not an observed reward.
Measure the cost of learning
Regret compares collected reward with what optimal choices would have earned. In a stationary bandit with a genuinely inferior arm, fixed positive epsilon keeps selecting that arm at a positive rate, producing linear expected regret. Under its stochastic bandit assumptions, UCB1 has logarithmic expected regret. A carefully tuned decreasing-epsilon schedule can also achieve that order; arbitrary decay cannot promise it.
Q-learning's off-policy target permits exploratory samples without redefining the optimal values it seeks. Exploration still affects the reward collected during training. For physical systems, use simulation, recorded experience, or permitted-action limits to keep exploration from causing harm.
Key Takeaways
- Epsilon-greedy exploration can randomly select the greedy action too.
- Exploration bonuses favor actions with limited evidence.
- UCB1 balances sample means against count-based uncertainty.
- Regret measures the reward cost of learning over time.
- Decreasing epsilon alone does not establish adequate exploration or logarithmic regret.
- Exploratory behavior can be costly even when an off-policy target is correct.
5.3 Share learning through features
A Q-table stores one number for every state–action pair. In a large problem, many pairs may never be visited. Separate entries also fail to share evidence between similar situations. Approximate Q-learning replaces the table with a function of features.
Represent values with a weighted sum
A feature is a number describing an aspect of the state and action. For a delivery robot, features could describe battery level, distance to a charger, and waiting packages. A linear approximation writes
The weights describe how strongly each feature contributes. Features can depend on the action as well as the state, allowing different choices in the same state to have different values.
Update every weight from one error
Compute the current Q-value, then the target . The difference drives each update:
All values used for the target and error come from the weights before the update. A zero feature produces no change to its weight. A nonzero feature scales the adjustment, including its sign.
For weights and current features , the estimate is . Suppose the reward is 4, the best next Q-value is 4, and . The target is , so . With :
The new estimate for the same features becomes . A shared-weight update is not the same as replacing one independent table entry by the target.
Understand the reach and limits of sharing
One weight participates in many predictions. Updating it changes values for every pair with a nonzero value of that feature. This is generalization, and it can help the agent act sensibly in unseen states. It can also spread a mistaken update.
If two situations have identical feature vectors for every corresponding action, the model must give them identical action values. If they require different actions, no amount of weight tuning can represent both decisions correctly. Better features or a richer function are needed. Tabular learning is the special case with one indicator feature for each state–action pair, active only for that pair.
| Representation | Sharing | Reliability issue |
|---|---|---|
| Q-table | Each pair has its own entry | Needs enough visits to each pair |
| Linear features | Shared weights affect many pairs | Features can miss important distinctions |
| Neural network | Learns a richer nonlinear representation | Training and stability need additional methods |
The convergence guarantee for tabular Q-learning does not extend to arbitrary function approximation. Off-policy bootstrapping with shared predictions can oscillate or diverge, so evaluate the learned policy on separate trials. Deep Q-networks learn features from inputs such as game-screen pixels; policy search instead adjusts a policy directly to increase return.
Key Takeaways
- Linear Q-approximation predicts values from weighted state–action features.
- Each weight update uses the same pre-update prediction error.
- Shared features let one sample change predictions for many pairs.
- Identical feature vectors cannot represent different values.
- Tabular convergence guarantees do not generally extend to function approximation.
Reinforcement Learning examples
1Build and judge a decision model
13 steps
- 1IntroductionDecisions with uncertain outcomes
A robot chooses whether to work or charge. It controls that decision, but it cannot choose whether a low battery survives another job. Repeated choices under chance like this form a Markov decision process (MDP).
We will describe those choices with states and probabilities, compare rewards across time as a discounted return, and examine how a model can accidentally reward the wrong behavior (reward hacking).
- 2ExplanationDescribe one transition
One MDP transition has four observable parts: current state, chosen action, reward, and next state. A model adds the probabilities of possible outcomes.
For Work in High, the robot earns 4 and reaches High with probability 0.7 or Low with probability 0.3. These probabilities sum to 1. A Work choice does not let the robot select which branch occurs.
- 3ExampleDistinguish failure from continuation
Work in Low has two outcomes: remain Low with probability 0.6 and reward 4, or enter Dead with probability 0.4 and reward −10.
Dead is terminal, so its future value is 0. The −10 is still received on entry. Charge in Low earns 0 and reaches High for certain. Charge in High earns 0 and stays High.
- 4ChallengeCheck what the state remembers
A moving object's next position depends on its position and velocity. A proposed state records position alone. Why can two visits to the same recorded state have different predictions?
---reveal---
The two visits can have different velocities. Adding velocity lets the state distinguish those situations. The Markov property requires the state to retain relevant information from the past; it does not require the physical world to forget its past.
- 5ConnectionReplace a route with a policy
A fixed route assumes the agent reaches the expected states. Random outcomes can push it elsewhere, so a policy supplies a response for each state.
"Work when High, Charge when Low" is a deterministic stationary policy: the same state always produces the same action. A finite deadline can require a rule that also considers time remaining.
- 6ExampleWeight each reward by its delay
Suppose a run earns −1, −1, −1, then 10 and ends. At discount 0.9, the weights are 1, 0.9, 0.81, and 0.729.
The return is . The first reward is not discounted. A lower discount places less weight on the late payoff; at 0.5, this same run has return −0.5.
- 7ChallengeCompare patience with a deadline
A worn machine can Run for reward 6 or Repair for reward −4. With one decision left before the task ends, which action has higher return? Why might the answer differ earlier in the task?
---reveal---
Run is best on the last step because and no later rewards remain. Earlier, repair can restore access to higher production rewards. A finite-horizon policy can therefore choose differently in the same condition at different times.
- 8Key InsightBound a continuing return
An infinite run can have a finite discounted return. If every reward has magnitude at most 10 and the discount is 0.9, the geometric sum gives .
For the robot, no positive reward exceeds 4, so return also cannot exceed 40. These bounds use the entire reward stream; the approximate 10-step effective horizon is not a cutoff.
- 9ExplanationChoose states that support predictions
Before listing states, decide when actions occur and what affects their consequences. A maintenance model can use Good, Worn, and Broken, with different legal actions in each.
Broken is not terminal if Repair can return the machine to Good. More state detail has a cost: ten yes/no variables already allow 1,024 combinations. Keep variables that change outcomes or rewards.
- 10ChallengeCheck the objective behind a reward
A cleaning robot earns one reward for every piece of dirt it collects. It can spill stored dirt and collect it again. What defect does this reveal in the reward design?
---reveal---
The measure rewards repeated collection even when cleanliness does not improve. This is reward hacking: optimizing the specified number through an unintended behavior. A reward tied to the desired cleanliness addresses this particular incentive.
- 11ExplanationShape progress without changing the goal
Potential-based shaping adds to a transition reward. Discounted terms cancel across a run, leaving an offset determined by the start when the boundary conditions hold.
Use bounded potentials in a continuing discounted task and zero terminal potentials in an episodic task. An arbitrary progress bonus can change the preferred behavior instead of merely helping the learner find it.
- 12ChallengeConnect stopping time with rewards
Two navigation policies reach the same exit, one quickly and one after a detour. The designer adds a positive reward to every transition. Must their original ranking stay the same?
---reveal---
No. The detour receives extra step rewards, so the added discounted totals can differ and change the ranking. A constant shift is policy-preserving for a continuing discounted stream, but variable episodic lengths break that equal-offset argument.
- 13RecapInspect a model before solving it
Check three things before computing values: does the state support predictions, do each action’s probabilities sum to 1, and does the reward express the intended objective?
Then identify terminal states and the discount or horizon. Those choices determine which future rewards the policy should pursue.
2Turn future rewards into Bellman equations
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSummarize a branching future
- 2ExplanationName the continuation behavior
- 3ExampleRead the maximum and the action
- 4ChallengeInterpret a first action correctly
- 5ExplanationSplit the return after one transition
- 6ExampleSolve the Low equation first
- 7ExampleSubstitute into High
- 8ChallengeKeep choice before chance
- 9ChallengeCheck optimality using the right continuation
- 10RecapIdentify the equation you need
3Solve the robot with two planning methods
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionUse a known model to plan
- 2ExplanationFix the policy before evaluating
- 3ExampleSolve the linked equations
- 4ChallengeInterpret an evaluation sweep
- 5ExampleStart value iteration from zero
- 6ExampleCompute the second High backup
- 7ChallengeFinish the synchronous sweep
- 8TipTurn small changes into an error test
- 9Key InsightNotice when actions settle early
- 10ExampleStart from a poor policy
- 11ExampleEvaluate the improved behavior
- 12ChallengeHandle an equal-value alternative
- 13ConnectionCompare computation fairly
- 14ChallengeConnect stability to the optimality equation
- 15RecapChoose the planning operation
4Learn from robot experience
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionReplace certainty with evidence
- 2ConnectionSeparate the learning task from planning
- 3ExampleCount successors of one action
- 4ChallengeFind the missing model row
- 5Key InsightPlan with estimates
- 6ExampleCalculate a complete return
- 7ChallengeKeep samples distinct from expectations
- 8ExplanationForm a TD target immediately
- 9ExampleApply the learning rate
- 10TipDistinguish a moving target from a return
- 11ChallengeConnect learned values to action choices
- 12RecapChoose what to estimate
5Learn action values and share experience
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionLet experience improve decisions
- 2ExplanationChoose the best next-state estimate
- 3ExampleUpdate after a terminal failure
- 4ExampleUpdate after reaching Low
- 5ChallengeCompare the targets of two learners
- 6TipCheck what a convergence claim needs
- 7ExampleInclude the greedy action in random exploration
- 8ExplanationUse counts to find missing evidence
- 9ExampleDistinguish confidence from observed reward
- 10ChallengeDiagnose permanent exploration cost
- 11Key InsightDistinguish decay from adequate coverage
- 12ExplanationReplace separate entries with features
- 13ExampleCalculate the prediction and error
- 14ExampleApply the shared-weight update
- 15ChallengeFind a feature representation’s blind spot
- 16ConnectionCheck generalization as well as fit
- 17ChallengeConnect exploration, targets, and representation
- 18RecapInspect the learning loop
Reinforcement Learning practice questions
Set 1: Models, improvement, and exploration10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: States, values, and first updates10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Check assumptions and connect the methods10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Solve, diagnose, and transfer10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Action
Action value
Active learning
B
Bellman backup
Bellman equation
Bellman optimality equation
Bootstrapping
C
Continuing task
Contraction
D
Deep reinforcement learning
Direct evaluation
Discount factor
Discounted return
Dynamic programming
E
Episodic task
Epsilon-greedy selection
Every-visit evaluation
Expectimax tree
Exploitation
Exploration
Exploration function
F
Feature
Finite horizon
First-visit evaluation
Function approximation
G
Generalization
GLIE
Greedy action
I
In-place update
Indicator feature
L
Learning rate
Linear Q-approximation
Living reward
M
Markov decision process
Markov property
Model-based learning
Model-free learning
Modified policy iteration
Multi-armed bandit
O
Off-policy learning
Offline reinforcement learning
On-policy learning
One-step lookahead
Optimal policy
P
Passive learning
Planning
Policy
Policy evaluation
Policy improvement
Policy iteration
Policy search
Potential-based shaping
Q
Q-learning
R
Regret
Reinforcement learning
Reward function
Reward hacking
Reward shaping
S
SARSA
Sparse reward
State
State representation
State value
Stationary policy
Stochastic policy
Synchronous sweep
T
Tabular representation
TD error
Temporal-difference learning
Terminal state
Tie handling
Transition model
U
UCB1
V
Value iteration
Value-error bound
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.