Reinforcement Learning
Understand how agents learn sequential decisions from rewards. Calculate returns and Bellman targets, compare planning with experience-driven learning, and trace every Q-value update from state to policy.
Q ← Q + α[r + γ max Q′ − Q]By the End of This Level, You Can
Six Building Blocks of Reinforcement Learning
RL connects behavior to delayed outcomes through a repeated interaction loop.
The learner or controller whose behavior is optimized.
Transitions to a state and returns a reward after an action.
Defines a deterministic action or distribution over actions.
An immediate scalar signal, not the complete long-term objective.
Estimates cumulative discounted reward from a state or state–action pair.
Tries uncertain actions instead of always exploiting current estimates.
Reinforcement Learning Optimizes Sequential Behavior
Unlike supervised learning, the agent does not receive the correct action label for every situation.
The observation summarizes the information available before acting.
The policy may be deterministic, stochastic or deliberately exploratory.
The same action may have uncertain consequences.
The reward and next state provide a target for improving future behavior.
An RL agent influences the data it later learns from. Actions change future states, rewards may arrive long after the decisions that caused them, and exploration can temporarily reduce performance while improving knowledge. The objective is expected cumulative return, not maximum immediate reward. A complete formulation identifies episode boundaries, observations, actions, transition uncertainty, reward timing and operational constraints. If the observation omits decision-relevant history, the process may not be Markov and the agent may need memory or a belief state.
A placement-training recommender chooses the next exercise, observes completion and later interview performance. Immediate engagement alone may reward easy questions and harm preparation.
Begin answers by separating state, action, reward, return and policy; then explain where experience comes from.
RL is not simply classification with reward as the label. Its actions affect future data and delayed outcomes.
An MDP Makes the Decision Process Explicit
A Markov decision process represents states, actions, transition probabilities, rewards and discounting.
s ∈ SEvery decision-relevant situation the agent can occupy.
a ∈ A(s)The legal choices available in the current state.
P(s′,r | s,a)The probability of each next state and reward.
0 ≤ γ ≤ 1Controls how strongly later rewards contribute to present return.
The Markov property states that the conditional distribution of the next outcome depends on the current state and action, not the full past. This is a property of the chosen state representation, not automatically of the real world. In a finite episodic task, termination bounds the return; in continuing tasks, γ below one keeps infinite-horizon returns finite under bounded rewards. Transition and reward models enable planning. Model-free algorithms instead estimate values or policies directly from sampled interaction.
Gₜ = Rₜ₊₁ + γRₜ₊₂ + γ²Rₜ₊₃ + … combines immediate and delayed outcomes.
Ask whether time, remaining budget, previous failures or hidden context must be included in state.
A small γ does not mean the future is unimportant in every domain; it changes the objective and effective horizon.
Policies and Value Functions Describe Different Questions
The policy selects behavior; value functions predict the return created by that behavior.
π(a|s)The probability of choosing action a in state s.
Vπ(s)=Eπ[Gₜ|Sₜ=s]Expected return from the state while following π.
Qπ(s,a)=Eπ[Gₜ|Sₜ=s,Aₜ=a]Expected return after taking a and then following π.
Aπ(s,a)=Qπ(s,a)−Vπ(s)How much better an action is than the policy’s average choice.
Vπ evaluates a state under a complete future policy, while Qπ evaluates the first action explicitly. If Q values are available, a greedy improvement selects an action with maximum Q. The advantage centers action quality relative to the state baseline and is valuable in policy-gradient methods because it reduces variance. Values are expectations: one observed trajectory return can differ greatly from the underlying value. Estimates should therefore be judged across many seeds, episodes and relevant initial states.
If Vπ(s)=6 and Qπ(s,review)=8, the review action has advantage +2 in that state.
State conditioning and policy conditioning precisely; do not describe V as merely “reward of a state.”
A high immediate reward does not guarantee a high Q value if it leads to poor future states.
Bellman Equations Turn Long Horizons into One-Step Backups
A value equals immediate expected reward plus the discounted value of what follows.
Vπ(s)=Σₐπ(a|s)Σₛ′,r p(s′,r|s,a)[r+γVπ(s′)]Evaluate one fixed policy by averaging over its actions and environment outcomes.
V*(s)=maxₐ Σₛ′,r p(s′,r|s,a)[r+γV*(s′)]Choose the action with the largest expected backed-up return.
The Bellman equation is a self-consistency condition. It decomposes an infinite or long return into one transition and a smaller value problem. A backup uses current successor estimates to revise a predecessor. Repeated backups propagate terminal rewards through the state space. In deterministic environments the expectation collapses to one successor; in stochastic environments every possible outcome must be probability-weighted. The optimality operator is a contraction for γ below one in finite discounted MDPs, which supports convergence of value iteration.
If an action gives reward 2, reaches values 8 and 4 with probabilities .75 and .25, and γ=.9, its target is 2+.9(.75×8+.25×4)=8.3.
Confirm whether reward belongs to the transition, source state or destination state and whether terminal values bootstrap.
Adding γ to the reward instead of multiplying the successor value changes the objective completely.
Dynamic Programming Plans with a Known Model
Policy evaluation, policy improvement and value iteration sweep through states using exact transition expectations.
Set arbitrary values, usually zero.
Apply Bellman backups to estimate returns.
Choose actions greedy with the new values.
Track maximum value change Δ.
Converge when Δ is below tolerance.
Iterative policy evaluation repeatedly applies the Bellman expectation operator for a fixed π. Policy iteration alternates sufficiently accurate evaluation with greedy improvement and stops when the policy is stable. Value iteration combines a partial evaluation and improvement through the Bellman optimality operator on every sweep. Synchronous updates read the previous sweep; in-place updates can propagate information faster but make order relevant. DP assumes the transition and reward model is available and the state space is small enough to enumerate.
Δ=maxₛ|Vnew(s)−Vold(s)| measures the largest state update in one sweep.
Compare algorithms by model requirement, backup operator, stopping criterion and output policy.
Value iteration is not interaction-based learning; it computes expected backups from a supplied environment model.
Monte Carlo and TD Learn from Experience Differently
Monte Carlo waits for a sampled return; temporal-difference learning bootstraps from the next estimate.
V(Sₜ) ← V(Sₜ)+α[Gₜ−V(Sₜ)]Uses complete sampled returns after an episode; unbiased by bootstrapping but often high variance.
V(Sₜ) ← V(Sₜ)+α[Rₜ₊₁+γV(Sₜ₊₁)−V(Sₜ)]Updates after one transition using a bootstrapped target; lower variance but target estimates introduce bias.
mix short and long targetsBalances rapid bootstrapping with more observed rewards before the target is formed.
MC methods require episode completion and can learn from a fixed batch of full trajectories. TD methods learn online in continuing tasks because they need only the next reward and state. The TD error δ=R+γV(S′)−V(S) is both an update direction and a useful diagnostic of surprise. Bootstrapping, off-policy data and function approximation can interact unstably—the classic deadly triad—so algorithm assumptions matter when moving beyond tables.
Longer returns rely more on observed rewards and usually have less bootstrap bias but greater sampling variance.
On-policy evaluation requires experience distributed like π unless importance sampling or another correction is used.
TD targets are not fixed labels; they change as the value function changes.
Q-Learning Separates Behavior from the Greedy Target
Tabular control learns action values while balancing exploration and exploitation.
r+γ maxₐ′Q(s′,a′)Behavior may explore, while the target assumes the greedy next action.
r+γQ(s′,a′)The next behavior action appears in the target, including its exploration risk.
random action or argmax QSimple, but treats all non-greedy actions equally and needs a schedule.
Q-learning updates only the experienced state–action entry toward a one-step optimality target. With sufficient exploration, appropriate learning-rate conditions and a finite stationary MDP, tabular Q-learning converges to optimal Q values. Constant α adapts to change but leaves persistent noise; decaying α supports classical convergence. Tie-breaking must be randomized or designed carefully because initial equal values can bias behavior. Exploration schedules should be evaluated by both learning efficiency and the real cost of unsafe exploratory actions.
Q=4, r=2, γ=.9, max Q′=6 and α=.5 gives target 7.4, error 3.4 and new Q=5.7.
Explain why Q-learning is off-policy and SARSA is on-policy using their different next-action targets.
Using max Q(s,a) from the current state instead of max Q(s′,a′) from the next state prevents correct credit propagation.
Deep RL Adds Representation Power and Instability
Neural networks approximate values or policies when tables cannot cover enormous state spaces.
Samples mini-batches from stored experience instead of only the latest trajectory.
Uses a delayed parameter copy to construct more stable bootstrap targets.
Include safety limits and monitor proxy exploitation rather than trusting one scalar metric.
Report returns, variance, success, violations and robustness across seeds and environments.
DQN combines Q-learning with a neural network, replay memory and a target network. Clipped or Huber loss, reward scaling, gradient clipping and Double DQN can further reduce instability or overestimation. Deep RL results are sensitive to seeds, environment versions, wrappers and evaluation protocol, so a single learning curve is insufficient. In real systems, offline data, simulators, constrained optimization, human approval and conservative policy improvement may be safer than unconstrained online exploration.
Model architecture is only one component; collection policy, replay distribution, reward, termination, logging and safety gates determine what is learned.
Compare the learned policy against rules and simple baselines under distribution shift, rare states and worst-case costs.
High simulated return does not prove real-world usefulness, safety or causal validity.
🗺️ Bellman Gridworld Planning Laboratory
Run real expectation or optimality backups. Inspect transition uncertainty, state values, greedy actions, convergence delta and the path induced by the current policy.
🎯 Q-Learning Training Laboratory
Generate reproducible episodes, make epsilon-greedy decisions, execute transitions and update one Q value from its reward, bootstrap estimate and TD error.
Trace Tabular Q-Learning from First Principles
Follow every episode reset, while-condition, greedy action, environment transition, max-next calculation, TD target, TD error and Q update. The cursor returns through both loops exactly as Python executes.
—Waiting for print(...)
💻 Reinforcement Learning Challenges
Attempt each program independently. Workspaces, hints and model programs remain collapsed initially.
Test Your Reinforcement-Learning Reasoning
Select one answer per question. Results show your choice, the correct answer and a clear explanation.
Diagnose RL Systems Like an AI Engineer
Inspect the decision process and data-generating policy before changing the neural network.
Check reward timing, terminal handling, state coverage, exploration, learning rate and whether updates use the next state.
Inspect positive reward cycles, missing time costs, discounting and episode termination.
Separate bootstrap targets, replay distribution, target-network lag, gradients and value overestimation.
Constrain actions, use a simulator or offline data, require approval and measure violations separately from return.
Version environment, wrappers, seeds, reward preprocessing, evaluation policy and stopping criteria.
Check proxy reward exploitation, distribution shift, omitted costs and whether the metric represents the real objective.
🎤 Reinforcement Learning — Interview Questions
Answer aloud before selecting Show Answer for each detailed explanation.
RL Learns Which Present Actions Create Better Futures
Represent the current decision state.
Balance exploration and exploitation.
Receive reward and next state.
Move estimates toward a Bellman target.
Test return, variance and constraints.
A reliable RL system makes its objective, experience source, bootstrap target, exploration cost and safety boundary as visible as its final policy.
Eight Practical Reinforcement-Learning Habits
Verify the reward and terminal transition using hand-calculated trajectories first.
Compare against random, fixed and myopic policies before claiming learning.
Track episode return, length, success and violations separately.
Use seeded evaluation episodes without exploration for fair comparison.
Test tabular logic before adding function approximation.
Log Q values, TD errors and visitation counts—not only final rewards.
Never bootstrap from a truly terminal state.
Prefer offline, simulated or constrained learning when exploration can cause harm.
Strengthen Reinforcement-Learning Reasoning
Calculate intermediate targets and defend every modeling, exploration and evaluation decision.
- 01
Formulate adaptive quiz selection as an MDP.
- 02
Calculate a five-step discounted return.
- 03
Compare γ=.5, .9 and .99 effective horizons.
- 04
Compute Vπ and Qπ for a two-state MDP.
- 05
Perform one stochastic Bellman expectation backup.
- 06
Perform two sweeps of value iteration.
- 07
Explain policy stability in policy iteration.
- 08
Compare MC and TD targets on one trajectory.
- 09
Calculate TD error and update V(s).
- 10
Calculate Q-learning and SARSA targets.
- 11
Design an epsilon decay schedule.
- 12
Explain the deadly triad.
- 13
Design a reproducible DQN evaluation.
- 14
Threat-model reward hacking in a student tutor.
