AI Wiki中文/EN

Reinforcement learning: learn from the consequences of acting

强化学习问题框架

Interact with a small environment, compare learned policy choices with model-derived values, and separate learning from planning.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two points now, or a chance to earn more later?

In an invented arcade game, you begin at an entry room. You can leave immediately for 2 points, or advance for no immediate reward. In the next room, leaving earns 4 points. Another action, spinning a wheel, earns 1.6 points and sends you back to the entry with probability 0.4, keeps you in the room with probability 0.4, or ends the game with probability 0.2.

An agent that always selects the largest immediate reward leaves at the entry. An agent concerned with future rewards may advance instead. If the agent does not know the wheel’s probabilities, it must learn about the consequences of its choices from interaction. Its choices also determine which situations it gets to observe.

That feedback loop is central to reinforcement learning. The learner receives outcomes and rewards rather than a correct-action label for every situation. Sutton and Barto’s working draft, Chapter 1 distinguishes this problem from supervised prediction. This article builds a small learning loop; MDPs describe the environment model, while later articles derive ways to evaluate and improve policies.

Three rules are tried through interaction; an independent seed and an exact model provide separate checks.
Three rules are tried through interaction; an independent seed and an exact model provide separate checks.

Separate the environment, the rule and the learning procedure

An agent chooses actions. The environment produces the next observation and reward. An episode is one run ending at a terminal state, followed by a reset for another run. In this example the observation is the full state: entry 0, room 1 or terminal 2. In a real problem, an observation may omit information needed to predict the next outcome; choosing a state representation is part of the modeling work.

A policy maps the current state to an action, or to a distribution over actions. For a stationary stochastic policy:

π(a∣s)≥0,∑a∈A(s)π(a∣s)=1.\pi(a\mid s)\geq0,\qquad \sum_{a\in\mathcal A(s)}\pi(a\mid s)=1.

Stationary means the rule does not explicitly change with time. It does not mean the environment stops changing. A deterministic policy gives one action probability 1. The policies below are deterministic, but the wheel still makes their trajectories random. The agent’s randomness and the environment’s randomness are separate choices.

Specify what the reward sequence is worth

We use discount 0.9: each additional step reduces the weight of a later reward. Starting from the entry, the objective for policy pi is its expected discounted return. The expectation averages over any random actions and transitions, and T is the episode’s terminal time:

J(π)=Eπ ⁣[∑t=0T−1γtRt+1∣S0=0],γ=0.9.J(\pi)=\mathbb E_\pi\!\left[\sum_{t=0}^{T-1}\gamma^tR_{t+1}\mid S_0=0\right],\qquad \gamma=0.9.

Leaving immediately gives 2. Advancing and then leaving gives 0 + 0.9 × 4 = 3.6. The zero reward for advancing does not make that action useless. Its consequence is access to a better future reward. The working draft’s return discussion makes this distinction between immediate reward and cumulative objective; rewards and returns examines the boundary conditions.

A small learning algorithm can search among complete rules

Consider three candidate policies, written as actions at entry and room. Action 0 means leave; action 1 means advance at entry and spin in the room:

CandidateEntry actionRoom action
0LeaveLeave
1AdvanceLeave
2AdvanceSpin

The unused room action in candidate 0 still defines a complete rule. The learner tries each candidate for 200 episodes. After a sampled episode return G_n, it updates that candidate’s mean without retaining all previous samples:

J^n=1n∑i=1nGi=J^n−1+Gn−J^n−1n.\widehat J_n=\frac1n\sum_{i=1}^{n}G_i =\widehat J_{n-1}+\frac{G_n-\widehat J_{n-1}}{n}.

The recurrence follows by separating the last term of the sum. We then choose the candidate with the largest observed mean, breaking an exact tie by its smaller index:

π^∈arg max⁡π∈{π0,π1,π2}J^(π).\widehat\pi\in\operatorname*{arg\,max}_{\pi\in\{\pi_0,\pi_1,\pi_2\}}\widehat J(\pi).

This is a limited form of policy search. The Kaelbling, Littman and Moore survey distinguishes searching over behaviors from methods that estimate the usefulness of actions within states. Our program demonstrates the former with only three predefined rules. It does not discover arbitrary rules, assign credit separately to every action, or implement Q-learning.

Round-robin sampling ensures every candidate receives experience. It spends the same episode count on each, although episode lengths and therefore interaction costs differ. A more selective exploration strategy might save samples, but it would require its own assumptions and analysis. Here the simple allocation makes the data collection visible.

A known model gives a separate reference

The environment author knows the probabilities, so we can calculate candidate 2’s exact value independently of the learner. Let v0 and v1 be its expected returns from entry and room. The terminal continuation is zero:

v0=0.9v1,v1=1.6+0.9(0.4v0+0.4v1+0.2⋅0),v0=36079≈4.556962.v_0=0.9v_1,\qquad v_1=1.6+0.9(0.4v_0+0.4v_1+0.2\cdot0),\qquad v_0=\frac{360}{79}\approx4.556962.

The learning function never receives this equation or its answer. If we gave it the transition table and solved these equations instead of collecting episodes, that would be known-model planning. Planning and learning can be combined, but a calculation from a supplied model alone does not demonstrate learning from experience.

An environment interface and an actual learning loop

Save this original program as interaction.py and run it with Python 3.12 or later. It uses the standard library. The environment provides reset and step; the learner receives states, rewards and a terminal flag. The model-derived reference is computed only in the demonstration after the learning call.

"""Learn among three fixed policies through a synthetic environment interface."""
import json
import math
import random


class Arcade:
    def __init__(self, seed):
        self.rng = random.Random(seed)
        self.state = 2

    def reset(self):
        self.state = 0
        return self.state

    def step(self, action):
        if type(action) is not int or action not in (0, 1) or self.state == 2:
            raise ValueError('valid action and a nonterminal state required')
        if self.state == 0:
            self.state, reward = (2, 2.0) if action == 0 else (1, 0.0)
        elif action == 0:
            self.state, reward = 2, 4.0
        else:
            u = self.rng.random()
            self.state = 0 if u < .4 else 1 if u < .8 else 2
            reward = 1.6
        return self.state, reward, self.state == 2


def rollout(env, policy, gamma=.9, horizon=100):
    if len(policy) != 2 or any(type(a) is not int or a not in (0, 1) for a in policy):
        raise ValueError('one deterministic action for each nonterminal state')
    if not math.isfinite(gamma) or not 0 <= gamma < 1:
        raise ValueError('discount must be in [0, 1)')
    if type(horizon) is not int or horizon < 1:
        raise ValueError('positive integer horizon required')
    state, total, weight, trace = env.reset(), 0.0, 1.0, []
    for _ in range(horizon):
        action = policy[state]
        next_state, reward, terminated = env.step(action)
        trace.append([state, action, reward, next_state])
        total += weight * reward
        weight *= gamma
        state = next_state
        if terminated:
            break
    return dict(return_=total, steps=len(trace), terminated=terminated,
                truncated=not terminated, trace=trace)


def search(env, policies, episodes_per_policy=200):
    if not policies or type(episodes_per_policy) is not int or episodes_per_policy < 1:
        raise ValueError('candidate policies and a positive sample count required')
    means, counts = [0.0]*len(policies), [0]*len(policies)
    steps, truncated, history = 0, 0, []
    for round_ in range(episodes_per_policy):
        for i, policy in enumerate(policies):
            sample = rollout(env, policy)
            counts[i] += 1
            means[i] += (sample['return_']-means[i])/counts[i]
            steps += sample['steps']
            truncated += sample['truncated']
        if round_+1 in (1, 5, 20, 50, episodes_per_policy):
            history.append(dict(episodes_per_policy=round_+1, means=means.copy()))
    best = max(range(len(policies)), key=lambda i: (means[i], -i))
    return dict(selected=best, means=means, counts=counts, environment_steps=steps,
                truncated_episodes=truncated, history=history)


def demo():
    policies = [[0, 0], [1, 0], [1, 1]]
    learned = search(Arcade(41), policies)
    test_env = Arcade(43)
    samples = [rollout(test_env, policies[learned['selected']]) for _ in range(2000)]
    return dict(policies=policies, training=learned,
                heldout_seed_mean=sum(x['return_'] for x in samples)/len(samples),
                heldout_truncated=sum(x['truncated'] for x in samples),
                example_trajectory=rollout(Arcade(17), policies[2]),
                # Model-derived reference kept outside the learning function.
                model_reference=[2.0, 3.6, .9*1.6/(1-.4*.9-.4*.9**2)],
                max_100_step_omitted_return=4*.9**100/(1-.9))


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, allow_nan=False))

With training seed 41, the three estimated means are 2, 3.6 and approximately 4.364807. The learner selects candidate 2 after 600 episodes and 2046 environment steps. A separate stream with seed 43 evaluates the selected rule for 2000 episodes and obtains approximately 4.575024. Neither sample mean is the exact 4.556962 reference. Finite samples fluctuate; a selected training maximum can also reflect favorable noise. A separate evaluation stream helps reveal that distinction but is not a guarantee of success in another environment.

The code caps a rollout at 100 steps. It separately records natural termination and an artificial cutoff. No rollout in these recorded runs hit the cap. With rewards bounded in magnitude by 4, the maximum omitted discounted tail at that cap is 4 × 0.9^100 / (1 − 0.9), approximately 0.00106246. It is an upper bound, not a measured error. A cutoff does not mean the environment has reached its terminal state.

For K candidate policies, N episodes per candidate and cap H, the loop uses at most KNH environment steps. Means and counts use O(K) memory. Training keeps one sampled trajectory of at most H steps at a time, plus a small set of checkpoints. The separate demonstration evaluation retains all N_test sample traces, adding O(N_test H) storage; that evaluation could instead stream its aggregate. Environmental simulation cost is separate from this bookkeeping. The program’s search uses the fixed discount and cap supplied by the default rollout; it is not a general-purpose training package.

The environment and the objective still matter

The candidate bank limits what can be learned. If every candidate makes the wrong decision in a state, more episodes cannot manufacture a missing policy. The game also reveals its complete state and resets cheaply. Real interactions may be expensive, state information may be incomplete, and a reset may be impossible. The tiny example does not settle those problems.

Rewards encode an objective, not an automatic definition of desirable behavior. An agent can optimize the supplied numbers while violating the designer’s intention. In this game, repeated spinning can be useful precisely because it pays points before transitioning. Whether such incentives are appropriate is a task-design question. The working draft’s reward discussion presents reward maximization as a modeling formulation; it is not evidence that any convenient score faithfully represents a user’s needs.

The 1996 survey supplies a historical framing of interaction and behavioral search, not an inventory of all later methods. Our sampled-policy baseline isolates the learning loop. It does not claim a public benchmark result, a general convergence rate, or superiority over a fixed rule outside this synthetic game.

Follow the information available to the learner

  1. Explain delayed consequences. Why does a rule that maximizes immediate reward leave at entry, and why can that be worse?

    Answer: Leaving pays 2 immediately while advancing pays 0. But advancing gives access to the room; advancing and then leaving earns discounted return 3.6. The immediate comparison omits that future opportunity.

  2. Calculate the reference. Under the always-advance/spin policy, substitute v0 = 0.9 v1 into the room equation. What are both values?

    Answer: The room equation becomes v1 = 1.6 + 0.684 v1, so v1 = 400/79, approximately 5.063291. Multiplying by 0.9 gives v0 = 360/79, approximately 4.556962. The 0.2 probability of termination contributes no continuation value.

  3. Inspect a cutoff. Run candidate 1 with a one-step cap. What is observed, and what would be wrong with calling this a completed episode worth zero?

    Answer: The agent advances from entry to room and receives zero. The rollout is truncated, not terminated; leaving on the next step would provide 4. Calling the observed prefix a complete episode would discard a remaining discounted value of 3.6 in this policy.

  4. Design a comparison. A colleague supplies the transition table and reports the exact best policy without running an episode. Another estimates candidate values by interaction. What should the report distinguish?

    Answer: Distinguish the known-model planning calculation from experience-based estimation, record what each method was allowed to know, count real or simulated interactions, and separate training selection from evaluation. An exact model answer and a sampled estimate have different information requirements and sources of error.

A framework before a catalogue of algorithms

Sutton and Barto’s 2014–2015 working draft develops the agent–environment loop and discounted objective. This is the explicitly identified in-progress version, not the completed 2018 edition. The first two pages of the 1996 survey explain behavioral search and value-based approaches as two routes through the problem.

Continue to rewards and returns for objective design, policies and values for conditional expectations, and Q-learning for an algorithm that updates action values from individual transitions. Knowing what information a procedure consumes is the first step toward comparing these methods fairly.

Make a prediction, then check

A planner receives the full transition and reward tables and computes an optimal policy. Has this alone shown learning from experience?

Choose one answer

Learning objectives

  • Identify the agent, observations, actions, reward, episode boundary and learning feedback in a concrete loop.
  • Run finite candidate-policy search from sampled episodes and distinguish sample estimates from known-model references.

Prerequisites & connections

Explore related knowledge →

References

  1. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  2. Reinforcement Learning: A Survey
    Leslie Pack Kaelbling; Michael L. Littman; Andrew W. Moore · 1996

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PDF1 identity;15–16 interaction and supervised-learning contrast;73–75 episodic/discounted returns and zero-reward absorbing completion;84 policy/value definitions. Read2026-09-23; exact existing2014–2015 working-draft Source object retained. Read physical PDF1–2: identity, publication month, interaction framing, behavioral search versus value-based methods and delayed consequences. No full survey, original benchmark reproduction or source-figure reuse. 5 paired equations and four explained exercises. Checked independent trace returns, stochastic branches, terminal versus cutoff flags, interface-only learning, seeds, counts and held-out evaluation. Three predefined rules, not general Q-learning; the model oracle is not used by the learner.

  • Checked independent trace returns, stochastic branches, terminal versus cutoff flags, interface-only learning, seeds, counts and held-out evaluation. Three predefined rules, not general Q-learning; the model oracle is not used by the learner.
  • Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. Twelve selected current captures visually checked: eight byte-identical to viewed initial images and four reviewed final images; line-wrap revisions retained. Full article acceptance recorded separately.

Source locations checked:

  • Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF1 identity;15–16 interaction and supervised-learning contrast;73–75 episodic/discounted returns and zero-reward absorbing completion;84 policy/value definitions. Read2026-09-23; exact existing2014–2015 working-draft Source object retained.
  • Reinforcement Learning: A Survey · Read physical PDF1–2: identity, publication month, interaction framing, behavioral search versus value-based methods and delayed consequences. No full survey, original benchmark reproduction or source-figure reuse.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.