Exploration and bounded learning
Exploration versus exploitation
Exploitation selects an action with a high current estimated value; exploration tries alternatives that may improve knowledge. A greedy agent can get stuck choosing an initially promising action. Epsilon-greedy chooses a uniformly random legal action with probability epsilon, otherwise a highest-valued action. Because the random branch can also select the greedy action, epsilon is not exactly the probability of choosing a nongreedy action. Ties need an explicit policy; these examples select the first action in the tuple. With known rewards and transitions, planning can avoid unnecessary trial-and-error.
One Q-learning update
Q-learning estimates action values from observed transitions without fitting an explicit transition model. For a nonterminal transition, target = reward + gamma * max(Q(next_state, legal_action)). For a terminal transition, target = reward. Then new Q = old Q + alpha*(target-old Q). Alpha is the learning rate, not the exploration probability. Gamma discounts future rewards. The next-action max makes the target greedy even if the behavior policy explores; this is an off-policy update. Use only legal next actions. An external time cap ends collection but does not erase the next-state estimate if the underlying MDP continues. This is different from true termination.
def q_update(old, reward, next_values, alpha, gamma, terminated): if not 0 <= alpha <= 1 or not 0 <= gamma <= 1: raise ValueError("alpha and gamma must be in [0, 1]") if not terminated and not next_values: raise ValueError("nonterminal state requires legal actions") target = reward if terminated else reward + gamma * max(next_values) return old + alpha * (target - old)
print(q_update(1, -1, [2, 4], 0.5, 0.5, False))print(q_update(1, 5, [], 0.5, 0.5, True))Work through the update
For old=1, reward=-1, next values [2,4], gamma=.5 and alpha=.5, the target is 1 and the estimate remains 1.0. On a terminal transition with reward 5, the new estimate is 3.0; there is no future reward term. Alpha=0 preserves the old value; alpha=1 takes the full target. Negative action values are valid: do not substitute zero for the maximum of negative legal values. A truncated rollout still uses next-state values for a continuing-task target.
Learn in a tiny simulation
Reuse the three-position grid from the previous lesson. The agent stores four action values, starts them at zero and performs at most 60 episodes of eight moves using a local seeded random generator. The environment returns rewards but the update does not consult the transition table. At evaluation time, freeze Q and act greedily. Compare with a uniform random policy using five separate evaluation seeds and the same start, reward rule, limit and undiscounted reporting metric. Training optimizes a discounted target; the report additionally shows undiscounted return and success count. The training seed differs from the evaluation seeds. This demonstrates a bounded experiment, not evidence that Q-learning always converges in 60 episodes.
def grid_step(state, action): if state not in (0, 1) or action not in ("left", "right"): raise ValueError("invalid state or action") # Positions 0, 1, 2; 2 is terminal. next_state = max(0, state + (1 if action == "right" else -1)) return next_state, (5 if next_state == 2 else -1), next_state == 2
def rollout(policy, limit): if type(limit) is not int or limit < 0: raise ValueError("nonnegative integer step limit required") state, rewards = 0, [] for _ in range(limit): state, reward, terminated = grid_step(state, policy(state)) rewards.append(reward) if terminated: return rewards, True return rewards, False
def q_update(old, reward, next_values, alpha, gamma, terminated): if not 0 <= alpha <= 1 or not 0 <= gamma <= 1: raise ValueError("alpha and gamma must be in [0, 1]") if not terminated and not next_values: raise ValueError("nonterminal state requires legal actions") target = reward if terminated else reward + gamma * max(next_values) return old + alpha * (target - old)
from random import Random
def train(seed, episodes=60, limit=8): if type(episodes) is not int or episodes < 0 or type(limit) is not int or limit < 0: raise ValueError("nonnegative integer budgets required") rng = Random(seed) actions = ("left", "right") q = {(s, a): 0.0 for s in (0, 1) for a in actions} for _ in range(episodes): state = 0 for _ in range(limit): action = rng.choice(actions) if rng.random() < 0.25 else max(actions, key=lambda a: q[state, a]) nxt, reward, done = grid_step(state, action) values = [] if done else [q[nxt, a] for a in actions] q[state, action] = q_update(q[state, action], reward, values, 0.5, 0.9, done) if done: break state = nxt return q
def evaluate(policy_factory, seeds, limit=8): if not seeds: raise ValueError("at least one seed required") outcomes = [rollout(policy_factory(seed), limit) for seed in seeds] return sum(sum(r) for r, _ in outcomes) / len(outcomes), sum(done for _, done in outcomes)
def random_policy(seed): rng = Random(seed) return lambda state: rng.choice(("left", "right"))
seeds = [101, 102, 103, 104, 105]q = train(7)print([max(("left", "right"), key=lambda a: q[s, a]) for s in (0, 1)])print(evaluate(lambda seed: lambda s: max(("left", "right"), key=lambda a: q[s, a]), seeds))print(evaluate(random_policy, seeds))Evaluate, do not overclaim
For the supplied Python fixture, the greedy policy chooses right in both nonterminal states and achieves return 4 in each evaluation episode. The random baseline reports (1.0, 5): all five episodes reach the goal, but they take more moves on average. These are sample results, not a guaranteed population average. The known always-right policy also returns 4 and succeeds in every episode; the learned policy matches it here. Five seeds in one tiny environment are too few to establish robust performance. Repeat training with independent seeds, report variability, inspect failed episodes and keep evaluation settings fixed. A constant learning rate and fixed exploration probability do not establish convergence in general. Tabular methods also become impractical for very large state spaces.
Reward design and safety
A reward is a designed signal, not the complete real-world goal. Rewarding only movement might encourage a loop without delivery; rewarding delivery without constraints might favor unsafe shortcuts. Inspect actual success and constraint violations alongside return. Keep experiments offline, restrict action space, cap episodes and steps, and record stop reasons. Never attach this exploration loop to production machinery, a live account or financial decisions. A deterministic policy may be the appropriate deployment choice even when learning is possible.
Practice and next step
Calculate the update for old=0, reward=-1, next values [-3,-2], alpha=.5, gamma=.5: target=-2, new=-1. Then compare a zero-step budget with an eight-step budget. Try three distinct training seeds without choosing the best seed after seeing test results. Record policy, mean return, success and truncation counts. Next chapter: attention and transformer structure; advanced RL algorithms belong to the Machine Learning track.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exploration and bounded learning quiz
Reason about returns and bounded decisions.
In the lesson’s epsilon-greedy policy, which actions are eligible on the random branch?
What is the target of a Q-learning update after a terminal transition with reward 5?
For a nonterminal transition, old Q=0, reward=−1, next legal Q values [−3,−2], gamma=0.5 and alpha=0.5. What is the updated Q?
Why freeze Q while evaluating a learned greedy policy?
Why cap the number of training episodes and moves per episode?