AI Wiki中文/EN

Exploration and exploitation: when is another try worth it?

探索与利用

Separate greedy choices from informed choices; compare constant and decaying exploration with an explicit noise-lock example.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

One disappointing try can hide the better option

Consider an invented two-button machine. Button A always pays 0.4. Button B pays 1 with probability 0.8 and otherwise pays 0. After trying each button once, you happen to see A: 0.4, B: 0. A rule that always chooses the largest sample mean will now keep pressing A. Its mean stays 0.4; B’s estimate stays zero because the rule never gathers another observation.

The unlucky first B result has probability 0.2. Conditional on that result, every subsequent press sacrifices 0.4 in expected reward. Twenty more presses lose 8 against always choosing B. No calculation of the current averages can reveal the missing evidence.

This is an exploration–exploitation problem. Exploitation uses current information to choose an apparently good action; exploration gathers information that may improve later decisions. Sutton and Barto’s working draft explains the tradeoff through action-value estimates. Silver’s lecture distinguishes random exploration, optimism and probability matching. The button example is original, not a reported experiment.

Uniform exploration can choose a greedy arm. A separate 30-seed experiment compares four schedules; the two-button lock is another example.
Uniform exploration can choose a greedy arm. A separate 30-seed experiment compares four schedules; the two-button lock is another example.

A good estimate and a good decision are different objects

In a stationary bandit, each of K actions has an unknown fixed mean reward mu_a. At round t, choose A_t using previously observed feedback and then observe only its reward R_t. For a finite horizon T, the objective is

μa=E[Rt∣At=a],max⁡π  Eπ[∑t=1TRt].\mu_a=\mathbb E[R_t\mid A_t=a],\qquad \max_\pi\;\mathbb E_\pi\left[\sum_{t=1}^{T}R_t\right].

Here pi is the entire decision rule, including its use of history. The objective rewards useful information only through its effect on later rewards. It does not reward collecting data for its own sake. If this really is the last decision and there is no other use for the data, sacrificing expected reward purely to learn has no future payoff.

An empirical estimate is not the unknown mean. Let q_t(a) be the estimate before round t, and let M_t contain all maximizing actions. With epsilon-greedy selection, explore uniformly over all actions with probability epsilon; otherwise choose uniformly among M_t:

Mt=argmax⁡aqt(a),Pr⁡(At=a∣Ht−1)=ϵtK+1−ϵt∣Mt∣1[a∈Mt].M_t=\operatorname*{argmax}_a q_t(a),\qquad \Pr(A_t=a\mid H_{t-1})= \frac{\epsilon_t}{K}+\frac{1-\epsilon_t}{|M_t|}\mathbf1[a\in M_t].

H_(t−1) denotes the observed history. Exploration can select a greedy action too. For estimates [0.2,0.5,0.5] and epsilon 0.3, the probabilities are [0.1,0.45,0.45]. Choosing uniformly only among nongreedy actions would be a different rule. When every estimate ties, this convention is uniform regardless of epsilon.

For stationary rewards, keep a count and sample mean per action. After observing reward r from a, update

N(a)←N(a)+1,q(a)←q(a)+r−q(a)N(a).N(a)\leftarrow N(a)+1,\qquad q(a)\leftarrow q(a)+\frac{r-q(a)}{N(a)}.

The new mean equals the old sum plus r, divided by the new count. Untouched actions retain both their counts and estimates. An initialized estimate with count zero is a convention, not an observation. The program forces one initial pull of each action so later comparisons do not depend on this convention. The working draft’s Sections 2.2–2.3 connects sample means, action choice and incremental updates.

Continuing to explore has a cost; stopping too quickly has a risk

Let mu_* be the largest true mean and Delta_a=mu_*−mu_a the nonnegative gap. After initialization, the conditional expected gap of an epsilon-greedy decision is

E[ΔAt∣Ht−1]=ϵtK∑aΔa+1−ϵt∣Mt∣∑a∈MtΔa≥ϵtK∑aΔa.\mathbb E[\Delta_{A_t}\mid H_{t-1}] =\frac{\epsilon_t}{K}\sum_a\Delta_a +\frac{1-\epsilon_t}{|M_t|}\sum_{a\in M_t}\Delta_a \geq\frac{\epsilon_t}{K}\sum_a\Delta_a.

This follows by substituting the action probabilities and dropping a nonnegative term. A constant positive epsilon therefore incurs a linear total exploration cost whenever some gap is positive, even if the greedy estimates become correct. It is a lower bound, not the total regret: choosing a wrongly estimated greedy arm adds another cost. Silver’s constant-epsilon argument uses this distinction.

Making epsilon smaller does not automatically solve the problem. After three forced pulls, compare epsilon_t=1/sqrt(t) with epsilon_t=1/t². The latter has only a finite remaining exploration budget. If E_t means that the random-exploration branch is taken, a union bound and the integral of x⁻² give

Pr⁡(⋃t=4∞Et)≤∑t=4∞1t2≤∫3∞dxx2=13.\Pr\left(\bigcup_{t=4}^{\infty}E_t\right) \leq\sum_{t=4}^{\infty}\frac1{t^2} \leq\int_3^\infty\frac{dx}{x^2}=\frac13.

Thus the probability of never taking that branch again is at least two-thirds. This alone does not prove failure—the greedy rule might already be right—but it removes a general promise to repair bad early estimates. The slower schedule has a divergent exploration sum and a vanishing exploration fraction. Those facts still do not establish a particular finite-time regret rate for every task.

Compare schedules without sharing the learner’s answer key

Save this standalone Python 3 program as exploration.py and run python3 exploration.py. It uses only the standard library. The synthetic Bernoulli means are [0.25,0.45,0.70]; the learner chooses from observed estimates. The known means are used separately to generate rewards and compute the evaluator’s path pseudo-regret.

Each arm has its own seeded reward stream; action randomization uses another stream. The four policies share the seed labels 0–29 for paired comparisons, so they are not independent of one another. Within each policy, the 30 simulated runs provide the reported mean and standard error. If their results are z_1,…,z_m, the calculation is

zˉ=1m∑i=1mzi,SE⁡(zˉ)=∑i=1m(zi−zˉ)2m(m−1).\bar z=\frac1m\sum_{i=1}^m z_i,\qquad \operatorname{SE}(\bar z)= \sqrt{\frac{\sum_{i=1}^m(z_i-\bar z)^2}{m(m-1)}}.

This is simulation uncertainty across runs, not a deterministic performance bound or an automatic confidence interval. Each run lasts 800 rounds including the three initialization pulls. The separate two-button trace above is also returned; it uses a deterministic 0.4-paying arm, unlike the three-Bernoulli training experiment.

import math
import random
import statistics


def integer(x, name, minimum=0):
    if isinstance(x, bool) or not isinstance(x, int) or x < minimum:
        raise ValueError(name + ' must be an integer >= ' + str(minimum))
    return x


def finite(x, name, low=None, high=None):
    if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x):
        raise ValueError(name + ' must be finite')
    if (low is not None and x < low) or (high is not None and x > high):
        raise ValueError(name + ' is outside its domain')
    return float(x)


def probabilities(values):
    p = [finite(v, 'probability', 0, 1) for v in values]
    if not p:
        raise ValueError('at least one arm is required')
    return p


class Bernoulli:
    """The learner receives only pull(action), never the mean vector."""
    def __init__(self, means, seed):
        self._means = probabilities(means)
        integer(seed, 'seed')
        self._streams = [random.Random(seed + 104729 * a) for a in range(len(means))]

    def pull(self, action):
        integer(action, 'action')
        if action >= len(self._means):
            raise ValueError('unknown action')
        return int(self._streams[action].random() < self._means[action])


def summary(values):
    if len(values) < 2:
        raise ValueError('at least two independent runs are needed for an SE')
    return dict(mean=statistics.mean(values), se=statistics.stdev(values) / math.sqrt(len(values)))


def action_probabilities(estimates, epsilon):
    q = [finite(x, 'estimate') for x in estimates]
    epsilon = finite(epsilon, 'epsilon', 0, 1)
    if not q:
        raise ValueError('empty estimates')
    best = max(q); winners = [a for a, value in enumerate(q) if value == best]
    return [epsilon / len(q) + ((1 - epsilon) / len(winners) if a in winners else 0) for a in range(len(q))]


def schedule(name, step):
    integer(step, 'step', 1)
    if name == 'greedy': return 0.0
    if name == 'constant': return 0.1
    if name == 'slow': return 1 / math.sqrt(step)
    if name == 'fast': return 1 / step**2
    raise ValueError('unknown schedule')


def run(name, steps=800, seed=0):
    integer(steps, 'steps', 3); integer(seed, 'seed')
    means = [.25, .45, .7]; env = Bernoulli(means, seed)
    rng = random.Random(seed + 1000003); counts = [0] * 3; q = [0.] * 3
    loss = 0.; reward = 0; curve = []
    for t in range(1, steps + 1):
        eps = schedule(name, t)
        a = t - 1 if t <= 3 else rng.choices(range(3), weights=action_probabilities(q, eps))[0]
        r = env.pull(a); counts[a] += 1; q[a] += (r - q[a]) / counts[a]
        reward += r; loss += max(means) - means[a]
        if t in [3, 20, 100, 400, steps]: curve.append(dict(step=t, pseudoregret=loss))
    return dict(counts=counts, estimates=q, reward=reward, pseudoregret=loss, curve=curve)


def demo():
    comparisons = {}
    for name in ['greedy', 'constant', 'slow', 'fast']:
        runs = [run(name, seed=s) for s in range(30)]
        comparisons[name] = dict(pseudoregret=summary([r['pseudoregret'] for r in runs]), reward=summary([r['reward'] for r in runs]))
    # Separate authored path: deterministic arm .4, better Bernoulli .8 fails on first try.
    q = [.4, 0.]; counts = [1, 1]; actions = []
    for _ in range(20):
        a = max(range(2), key=q.__getitem__); actions.append(a)
        counts[a] += 1; q[a] += (.4 - q[a]) / counts[a]
    return dict(horizon=800, seeds=list(range(30)), comparisons=comparisons,
                policy=action_probabilities([.2, .5, .5], .3),
                constant_exploration_floor=.1 / 3 * (.7 - .25 + .7 - .45),
                lock=dict(actions=actions, estimates=q, counts=counts, initial_bad_event_probability=.2),
                single_seed=run('constant', seed=0))


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

Mean cumulative pseudo-regret is approximately 54.4733 for greedy, 31.1217 for constant epsilon 0.1, 20.6567 for the slow schedule and 54.5767 for the fast schedule. Their standard errors are about 16.3177, 4.1130, 3.0529 and 16.3063. The large greedy variation matters: one run can look convincing while other seeds lock onto a worse arm.

Action selection scans K estimates, so a round costs O(K), while the selected mean update costs O(1). The learner stores O(K) counts and estimates. This demonstration also retains a few curve checkpoints and aggregates m runs; it does not keep every reward. Testing every reward stream or simulating longer horizons adds actual computation and must be included in an experiment budget.

The right uncertainty depends on the task

Uniform exploration spends equal probability on an almost certainly poor arm and a promising but uncertain arm. UCB uses confidence indices; Thompson sampling uses posterior samples. Neither comparison licenses a universal ranking based on this one set of means.

Stationarity also matters. A lifetime average reacts slowly after rewards change; a constant update step can give recent rewards more weight, but it changes the estimator and does not by itself solve change detection. In a full MDP, an action can alter future states and information, so independent per-state random actions need not provide useful coverage. The bandit schedule calculation above is not a theorem about exploring an arbitrary MDP.

Predict before running another seed

  1. Two estimates are unequal and epsilon is 0.2. What is the probability of choosing the currently greedy action?

    Answer: 0.9: exploitation contributes 0.8 and uniform exploration contributes 0.1. A nongreedy-only exploration rule would give a different answer.

  2. For means [0.25,0.45,0.70], what is the one-round exploration lower bound with epsilon 0.1 after initialization?

    Answer: The gaps are 0.45, 0.25 and 0, giving 0.1×0.70/3 ≈ 0.0233333. Wrong greedy choices can make total expected loss larger.

  3. Does a finite sum of exploration probabilities prove that the learner chooses the wrong arm?

    Answer: No. It permits insufficient future exploration; it does not say the estimates are wrong. In the two-button example, the initial failure creates that problem, and always-greedy selection then preserves it.

  4. The slow schedule wins this 30-seed comparison. What should change before calling it a generally better algorithm?

    Answer: Test different gaps, reward noise, horizons and seeds; state the comparison metric and uncertainty. For a theoretical claim, identify assumptions and prove the relevant rate. Repeating the same favorable instance is not a general argument.

Randomness is one way to buy information

Sutton and Barto use simple bandits to isolate evaluative feedback; Silver places epsilon-greedy beside optimism and probability matching. The shared question is which information can change a future decision enough to justify its cost. This article compares elementary schedules; exact Bayesian planning and regret-optimal algorithms are separate problems.

Make a prediction, then check

Two actions have different estimates. With epsilon0.2, how often is the currently greedy action selected?

Choose one answer

Learning objectives

  • Compute epsilon-greedy action probabilities including ties and exploratory greedy picks.
  • Distinguish constant exploration cost, insufficient exploration and finite-seed evidence.

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. Lecture 9: Exploration and Exploitation
    David Silver · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PDF46–48 and50: greedy/epsilon feedback tradeoff and task-dependent examples;55 distinguishes directed uncertainty exploration. Read2026-09-23; same2014–2015 working-draft Source retained. Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse. 6 paired equations and four explained exercises. Checked epsilon probabilities including maximizing ties, selected greedy actions during exploration, independent arm streams, forced initialization, gap-count losses, seeded standard errors and a separate deterministic-arm lock. Summable exploration is not itself a failure theorem.

  • Checked epsilon probabilities including maximizing ties, selected greedy actions during exploration, independent arm streams, forced initialization, gap-count losses, seeded standard errors and a separate deterministic-arm lock. Summable exploration is not itself a failure theorem.
  • Four computed SVG variants per topic;12 numeric/geometry tests and30 responsive cases passed. Ten selected current captures inspected: seven final captures directly viewed, three byte-identical to directly viewed earlier captures; actual byte identity checked. Browser inputs bound by SHA before integration. Full article acceptance recorded separately.

Source locations checked:

  • Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF46–48 and50: greedy/epsilon feedback tradeoff and task-dependent examples;55 distinguishes directed uncertainty exploration. Read2026-09-23; same2014–2015 working-draft Source retained.
  • Lecture 9: Exploration and Exploitation · Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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