Imitation learning: why can a good action predictor drift off course?
模仿学习
Compare behavior cloning and DAgger, calculate how zero training error can become closed-loop drift, and account for expert queries.
imitation-learningPredicting the next action is not the same as finishing a route
Show a novice some driving recordings and ask which way to steer in each frame: that is supervised learning. Once the novice drives, the previous steering decision changes the next frame. The recordings may show a car centered in its lane while the novice is already crossing the line. High accuracy on those recordings does not explain how to recover.
Imitation learning learns decisions from demonstrated behavior. Behavior cloning (BC) directly maps observations to actions. Interactive imitation also lets the learner visit states and asks an expert for additional labels. Inverse reinforcement learning instead infers a reward that explains behavior, then plans a policy. Imitation does not require numeric rewards on every demonstration, nor does it imply that the demonstrator is optimal.
The crucial question is whose route produced the training states. BC mainly sees states reached by the expert; deployment requires actions at states reached by the learner. DAgger adds the latter to the training data, addressing this distribution shift. Distributions and dataset aggregation
Our original teaching task isolates that causal chain. There are two lanes and sixteen steps; lane 0 is desirable. Action 0 preserves the lane, and action 1 flips it. An additional actuator flip occurs independently with probability 0.1 each step. The demonstrator stays in lane 0 and corrects from lane 1. The learner uses a table indexed by time and lane, with no images or neural network.
Start with two expert episodes, giving 32 labels. Memorizing every observed action does not imply seeing every recovery state. At seed 0, BC makes zero training errors but is expected to spend 6.05629 steps off lane; the expert spends 1.6. We will calculate the difference rather than leaving “compounding error” unexplained.
Separate demonstration error from closed-loop cost
Let demonstrations pair states with expert actions. A stochastic policy can minimize negative log-likelihood. Continuous actions may use regression losses, but squared error learns a conditional mean, which need not be a valid choice between several feasible actions. Steering left or right around an obstacle can be safe while their average, going straight, is not. Check whether actions are multimodal before choosing a model and loss. The implemented BC objective
Our program has deterministic labels and minimizes empirical zero-one error by tabular majority vote. Ties and unseen states choose action 0. This is the same direct imitation approach, but not a neural cross-entropy training run.
Let T be the task horizon and let the time-indexed state distribution describe where a policy is at step t. Its time average and the action error under the expert distribution are defined below. A time-dependent task can include time in the state.
This is a population-distribution error, not the error fraction on a finite training set. With per-step task costs between zero and one, a deviation can affect every remaining step. Bounding the chance of an earlier first deviation by a union bound of the order of (t−1)ε and summing costs gives a quadratic scale. The guarantee used in the paper is: Conditions on the error bound
This can be a loose upper bound; it does not mean every task has quadratic growth. Recoverable states have much smaller consequences. To see the missing condition, let u bound the additional cost of deviating from the expert for one action at a learner-visited state and following the expert thereafter. Let εL be action error under the learner’s own state distribution. Replacing the policy one step at a time telescopes the intermediate costs:
Here Q measures cost, not reward; u can grow with T. DAgger does not remove irreversibility or establish that u is small.
In each round, DAgger collects trajectories under a mixed policy, requests expert labels at visited states, and trains on old and new pairs together. The mixture controls whose action is executed. Even when the learner’s action is executed, the training label remains the expert’s answer for that state.
The union means aggregation with repeated samples retained, not deduplication. The paper connects this procedure to no-regret online learning, with conditions on losses, mixture decay and sampling. Its results identify a good candidate in the sequence; its algorithm also recommends validation selection. This does not say that any classifier trained for six rounds has a good final policy. Our experiment returns the final iterate without selecting it using evaluation results. Algorithm 3.1 and guarantee scope
In our task, a correct intended action makes the next lane undesirable with probability p; an incorrect intention makes that probability 1−p. Therefore we obtain an exact identity:
Substituting T=16, p=0.1 and εL=0.348148 gives 6.05629. The demonstrator is optimal under this example’s condition p below 0.5. If the actuator is more likely to flip than to obey, the control problem changes.
With equal label budgets, which states get visited?
The program uses only the Python standard library. After two initial expert episodes, it compares two expansion schemes. DAgger collects four mixed episodes per round, with β equal to 1, 1/2, 1/4, 1/8, 1/16 and 1/32. Expert augmentation instead collects four additional pure-expert episodes per round. The arms use corresponding actuator-noise streams and independent mixture randomness. Each fit uses all accumulated labels. Exact probability propagation evaluates policies without additional sampled environment episodes.
"""Original finite recovery task: tabular BC and data aggregation. Python 3.11+."""
import json
import random
def expert(state):
return state[1] # action 1 flips the lane; lane 0 is desired
def validate(horizon, noise):
if not isinstance(horizon, int) or horizon < 1 or not 0 <= noise <= 1:
raise ValueError('Positive integer horizon and noise in [0,1] required')
def fit(data, horizon):
"""Empirical 0-1 risk minimizer; ties/unseen states choose action 0."""
counts = [[[0, 0] for lane in range(2)] for t in range(horizon)]
for (t, lane), label in data:
if not 0 <= t < horizon or lane not in (0, 1) or label not in (0, 1):
raise ValueError('Invalid labeled state')
counts[t][lane][label] += 1
policy = [[int(row[1] > row[0]) for row in step] for step in counts]
return policy, counts
def collect(policy, episodes, noise, beta, env_rng, mix_rng):
"""Query every visited state; beta changes execution, never the label."""
horizon = len(policy)
validate(horizon, noise)
if not 0 <= beta <= 1 or not isinstance(episodes, int) or episodes < 1:
raise ValueError('Invalid collection budget or mixture')
data, trace = [], []
for episode in range(episodes):
lane = 0
for t in range(horizon):
state = (t, lane)
label = expert(state)
intended = label if mix_rng.random() < beta else policy[t][lane]
flipped = int(env_rng.random() < noise)
next_lane = lane ^ intended ^ flipped
data.append((state, label))
trace.append(dict(episode=episode, state=list(state), label=label,
intended=intended, actuator_flip=flipped, next_lane=next_lane))
lane = next_lane
return data, trace
def evaluate(policy, noise):
"""Exact forward probabilities, used only for diagnostics, never for fitting."""
validate(len(policy), noise)
occupancy = [1.0, 0.0]
cost = mistakes = 0.0
for t, actions in enumerate(policy):
next_occupancy = [0.0, 0.0]
for lane, mass in enumerate(occupancy):
if actions[lane] not in (0, 1):
raise ValueError('Binary action required')
mistakes += mass * (actions[lane] != expert((t, lane)))
for flip, chance in ((0, 1 - noise), (1, noise)):
next_occupancy[lane ^ actions[lane] ^ flip] += mass * chance
cost += next_occupancy[1]
occupancy = next_occupancy
return dict(cost=cost, learner_distribution_error=mistakes / len(policy))
def train(seed=0, horizon=16, noise=.1, rounds=6, episodes_per_round=4):
validate(horizon, noise)
if not isinstance(rounds, int) or rounds < 0:
raise ValueError('Nonnegative round count required')
zero = [[0, 0] for _ in range(horizon)]
initial, initial_trace = collect(zero, 2, noise, 1., random.Random(seed), random.Random(seed + 1000))
bc, initial_counts = fit(initial, horizon)
data = list(initial)
more_expert = list(initial)
dagger = bc
expert_augmented = bc
curve, traces = [], []
env_rng, mix_rng = random.Random(seed + 2000), random.Random(seed + 3000)
# The comparison uses equal per-round actuator noise streams and equal queries.
reference_env, reference_mix = random.Random(seed + 2000), random.Random(seed + 4000)
for i in range(rounds):
beta = .5 ** i
fresh, trace = collect(dagger, episodes_per_round, noise, beta, env_rng, mix_rng)
data.extend(fresh)
extra, reference_trace = collect(zero, episodes_per_round, noise, 1., reference_env, reference_mix)
more_expert.extend(extra)
dagger, counts = fit(data, horizon)
expert_augmented, _ = fit(more_expert, horizon)
curve.append(dict(round=i + 1, beta=beta, labels=len(data),
dagger=evaluate(dagger, noise), expert_augmented=evaluate(expert_augmented, noise)))
traces.append(dict(dagger=trace, expert_augmented=reference_trace))
expert_policy = [[0, 1] for _ in range(horizon)]
return dict(seed=seed, horizon=horizon, noise=noise,
bc=evaluate(bc, noise), dagger=evaluate(dagger, noise),
expert_augmented=evaluate(expert_augmented, noise), expert=evaluate(expert_policy, noise),
initial_labels=len(initial), final_labels=len(data),
training_transitions_per_arm=len(data), final_policy=dagger,
initial_policy=bc, initial_counts=initial_counts,
known_training_error=sum(dagger[t][lane] != label for (t, lane), label in data) / len(data),
curve=curve, initial_trace=initial_trace, traces=traces)
def experiment(seed=0):
return train(seed)
if __name__ == '__main__':
result = experiment()
print(json.dumps({k: v for k, v in result.items() if k not in ('initial_trace', 'traces', 'initial_counts')}, indent=2))
Inspect the recorded summary
{
"seed": 0,
"horizon": 16,
"noise": 0.1,
"bc": {
"cost": 6.0562949953421334,
"learner_distribution_error": 0.34814804651110415
},
"dagger": {
"cost": 1.680000000000001,
"learner_distribution_error": 0.00625
},
"expert_augmented": {
"cost": 1.920000000000001,
"learner_distribution_error": 0.02500000000000001
},
"expert": {
"cost": 1.6000000000000003,
"learner_distribution_error": 0.0
},
"initial_labels": 32,
"final_labels": 416,
"training_transitions_per_arm": 416,
"final_policy": [
[
0,
0
],
[
0,
0
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
]
],
"initial_policy": [
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
]
],
"known_training_error": 0.0,
"curve": [
{
"round": 1,
"beta": 1.0,
"labels": 96,
"dagger": {
"cost": 4.139832320000001,
"learner_distribution_error": 0.19842440000000008
},
"expert_augmented": {
"cost": 4.139832320000001,
"learner_distribution_error": 0.19842440000000008
}
},
{
"round": 2,
"beta": 0.5,
"labels": 160,
"dagger": {
"cost": 3.0594304000000014,
"learner_distribution_error": 0.11401800000000005
},
"expert_augmented": {
"cost": 3.2034304000000016,
"learner_distribution_error": 0.12526800000000007
}
},
{
"round": 3,
"beta": 0.25,
"labels": 224,
"dagger": {
"cost": 1.9040000000000012,
"learner_distribution_error": 0.02375000000000001
},
"expert_augmented": {
"cost": 2.064000000000001,
"learner_distribution_error": 0.03625000000000001
}
},
{
"round": 4,
"beta": 0.125,
"labels": 288,
"dagger": {
"cost": 1.680000000000001,
"learner_distribution_error": 0.00625
},
"expert_augmented": {
"cost": 1.920000000000001,
"learner_distribution_error": 0.02500000000000001
}
},
{
"round": 5,
"beta": 0.0625,
"labels": 352,
"dagger": {
"cost": 1.680000000000001,
"learner_distribution_error": 0.00625
},
"expert_augmented": {
"cost": 1.920000000000001,
"learner_distribution_error": 0.02500000000000001
}
},
{
"round": 6,
"beta": 0.03125,
"labels": 416,
"dagger": {
"cost": 1.680000000000001,
"learner_distribution_error": 0.00625
},
"expert_augmented": {
"cost": 1.920000000000001,
"learner_distribution_error": 0.02500000000000001
}
}
]
}Each arm finishes with 416 labels and 416 transitions, including 32 shared initial labels. Together they generate 800 transitions and expert queries. Each arm’s repeated fitting scans 32+96+160+224+288+352+416=1568 sample rows. Decreasing β does not automatically save labeling: every step still queries the expert. One tabular fit takes O(N+T), with O(N) dataset storage and an O(T) table. Exact evaluation takes O(T) by exploiting this known two-lane model; it says nothing about the evaluation cost of real driving.
All eight seeds are retained below. The metric is expected off-lane steps out of sixteen, so lower is better. These are complete probability calculations for learned policies, not noisy averages over a few test episodes.
| Seed | Initial BC | Final DAgger | Equal-budget expert augmentation | Expert |
|---|---|---|---|---|
| 0 | 6.05629 | 1.68 | 1.92 | 1.60 |
| 1 | 2.74240 | 1.60 | 1.60 | 1.60 |
| 2 | 3.43954 | 1.60 | 1.68 | 1.60 |
| 3 | 3.67258 | 1.68 | 1.68 | 1.60 |
| 4 | 3.83501 | 1.60 | 1.60 | 1.60 |
| 5 | 3.59885 | 1.60 | 1.60 | 1.60 |
| 6 | 3.31776 | 1.60 | 1.60 | 1.60 |
| 7 | 2.67840 | 1.60 | 1.60 | 1.60 |
DAgger misses the expert cost twice; adding pure-expert demonstrations often achieves the same result. The table supports inspecting the collection distribution, not claiming DAgger wins every equal-budget task. The experiment returns all trajectories; the CLI omits those long traces and initial counts to keep its summary readable.
Can the expert label a recovery state?
DAgger requires interaction and additional labels. Real experts may not know how to recover from dangerous learner-created states, and response latency can misalign a label with its state. With only offline logs, one cannot pretend that an expert remains callable. Actions with consequences also require controlled data collection; these two lanes are numeric states only.
If the expert sees information unavailable to the learner, the same learner observation can require different actions. More data cannot repair missing information. Inconsistent demonstrations, multiple demonstrator styles and multimodal actions can also defeat direct regression. Inspect observations and label meaning before merely increasing model size.
Our labels are noiseless and fully representable by a table. The example does not validate visual encoders, continuous control or a complex model’s no-regret property, and it does not reproduce the paper’s game results. The fixed reference implementation has entropy/L2 terms, batching and trajectory wrappers; this program does not claim to reproduce them line by line. Reference implementation scope
Predict first, then check
-
DAgger visits lane 1. The learner suggests staying with action 0, the expert suggests correcting with action 1, and the mixture chooses to execute 0. Which label should be stored?
Answer: Store expert action 1, paired with lane 1 before the action. Execution changes future states; it should not turn an incorrect action into the supervised target. The next state’s expert action must not be attached to the current state either.
-
With T=16 and p=0.1, a policy has action error 0.1 under its own state distribution. How many off-lane steps are expected? Does zero training error contradict this?
Answer: The cost is 1.6+0.8×16×0.1=2.88 steps. There is no contradiction: the finite training set can omit recovery states reached under deployment.
-
If β is zero in every round, can you claim there are zero expert queries?
Answer: No. β controls the chance of executing the expert action, not the labeling frequency. This program still asks for a label at every visited state. Selective querying is a separate algorithm change requiring its own accounting of missing labels and cost.
-
Each arm uses 416 labels and shares the first 32. How many environment transitions are needed in total, and how should you avoid selecting the best seed?
Answer: The total is 416+416−32=800. Fix all eight seeds in advance and retain every result, including seeds 0 and 3 where DAgger misses 1.6. Selecting iterates by validation requires a separate selection set and final evaluation; this table cannot simultaneously be tuning evidence and the final test.
From action prediction to data collection
BC turns demonstrations into a supervised problem and provides an inspectable first baseline. DAgger changes collection: what will the learner encounter? IRL changes the modeled quantity: which rewards can explain these choices? They are not a ladder of necessarily stronger replacements.
When reading DAgger, first distinguish dπ, expert labels and executed actions, then examine u and candidate selection in the cost guarantees. Original paper In the reference code, follow how the collector forwards actions, saves expert labels and passes accumulated data to the BC trainer; algorithm names alone do not establish those details. Fixed implementation
Make a prediction, then check
After executing a learner action in DAgger, which action should become the training label?
Learning objectives
- Distinguish demonstration and learner visitation distributions and identify the conditions linking action error to task cost.
- Implement BC and DAgger and compare equal-budget expert augmentation, separating executed actions, expert labels and evaluation costs.
Prerequisites & connections
Explore related knowledge →References
- A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning — scoped conference paper
Stephane Ross; Geoffrey Gordon; Drew Bagnell · 2011 - imitation — fixed BC, DAgger and maximum causal entropy implementation reading
HumanCompatibleAI/imitation contributors · 2025
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-24 · Single AI author. Scoped reading: Read physical pages2–4 of the official9-page PDF: expert/learner state distributions, conditions on quadratic and uT error bounds, mixed execution/expert labels/aggregation and validation selection. Later proofs and experiments not fully read; an existence guarantee is not a guarantee for any final iterate. Fixed2025-01-07 commit. Read122-line README,21-line MIT license, bc40–155, dagger210–291/425–459, mce_irl38–144/467–498. Execution versus expert labels and causal entropy distinguished. Reference only, no copying/execution or blanket verification of branches/terminal/discount conventions. 6 paired equations and four explained exercises. Expert/learner distributions, the conditional cost bounds, execution versus labels and equal-budget comparisons checked. Closed-form and exhaustive actuator calculations verify exact cost; evaluation replacement cannot alter fitting. All8seeds retain two final-iterate failures, and 416-per-arm/shared32/total800 queries are distinct. Not a neural BC or universal DAgger guarantee.
- Expert/learner distributions, the conditional cost bounds, execution versus labels and equal-budget comparisons checked. Closed-form and exhaustive actuator calculations verify exact cost; evaluation replacement cannot alter fitting. All8seeds retain two final-iterate failures, and 416-per-arm/shared32/total800 queries are distinct. Not a neural BC or universal DAgger guarantee.
- Four computed SVG variants per topic;9 numeric/geometry tests and12 current responsive cases passed. All six selected current captures directly viewed after correcting the retained initial transfer color-domain failure. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning — scoped conference paper · Read physical pages2–4 of the official9-page PDF: expert/learner state distributions, conditions on quadratic and uT error bounds, mixed execution/expert labels/aggregation and validation selection. Later proofs and experiments not fully read; an existence guarantee is not a guarantee for any final iterate.
- imitation — fixed BC, DAgger and maximum causal entropy implementation reading · Fixed2025-01-07 commit. Read122-line README,21-line MIT license, bc40–155, dagger210–291/425–459, mce_irl38–144/467–498. Execution versus expert labels and causal entropy distinguished. Reference only, no copying/execution or blanket verification of branches/terminal/discount conventions.
Related topics