DAgger and interactive imitation learning
Ask an expert to label learner-visited states with DAgger, connect the method to online no-regret learning, and examine human intervention, noise injection and distribution shift.
After this lesson you can
- Implement DAgger with policy mixing and data aggregation.
- Explain the online-learning reduction and the conditions behind an O(Tε) bound.
- Compare DAgger, HG-DAgger and DART by expert-query cost, safety and human usability.
- Measure success against expert-label count and compare with behavior cloning.
- Recognize related ideas in on-policy LLM distillation and scheduled sampling.
Before you start
Label where the learner fails
A cloner can be accurate on demonstrations and fail after a small deviation. If the expert can respond in those new states, we can record what they would do there and retrain. Interaction changes the data distribution, but also introduces query costs and collection risks.
Aggregate rather than replace
DAgger means Dataset Aggregation. Begin with demonstrations and a trained policy; each round executes a mixture of learner and expert, asks the expert for actions on visited states, adds those pairs to the previous dataset and retrains. If is the probability of executing the expert in round , a common mixture starts with more help and reduces it. The label must be the expert’s action in the observed state even if the learner reached it.
The first figure runs this loop on scalar state with expert . Initial data contain only ; collection has a disturbance of per step. It fits a regularized least-squares line to all accumulated labels. Each step executes the expert with probability and otherwise the learner; the expert is queried in both cases. Shown coverage is maximum labelled , not a full distribution. Results depend on this idealized expert and are not robot data.
With , the expert keeps the system near its own trajectory and the learner may receive little information about its errors. With , learner states are observed, but it can reach difficult or unsafe situations. In practice also record state, executed action, label, source of control and episode endings. Discarding previous rounds can cause forgetting; aggregation is part of the algorithm, not merely a way to grow the file.
Consider one transition: the learner moves the end effector one centimetre sideways, observes a new image and the expert says what they would do from that image. Saving the action the expert would have given in the previous state would produce a misaligned pair. Label and executed action can differ too: when the learner controls, the expert recommendation is saved even though the next transition depends on the learner’s action. In simulation the oracle can inspect full state; on hardware decide what the human sees and whether the label arrives in time.
From online learning to a bound
The reduction to online learning treats each round as a loss evaluated on states visited by that round’s policy. Average regret compares chosen losses with the best fixed policy in the class over the same sequence:
A no-regret learner makes tend to zero under its assumptions. If the best policy in the class has average loss on the generated distributions, average policy loss is bounded by , plus terms for finite samples and mixing with the expert. This does not imply the last model is necessarily best: the original guarantee may select a policy or use a mixture. Ross, Gordon and Bagnell (2011) develop the reduction.
Each round’s loss changes when the data-generating policy changes. Comparing a single fixed validation set is therefore insufficient: the regret comparator is evaluated over the entire loss sequence. The definition also does not make a neural network trained by any optimizer automatically no-regret. The reduction separates three questions: whether the class can imitate the expert in those states, whether the algorithm optimizes accumulated losses well, and whether enough samples exist to estimate them.
The linear bound follows if imitation loss on policy-induced states is at most and the harm of taking a wrong action, compared with following the expert afterwards, is bounded by . The performance-difference identity sums that disadvantage over steps; bounding it by per disagreement gives . If grows with , the expression can again be quadratic. Small MSE is not automatically a 0/1 error rate and does not certify .
For example, with , and , the expression bounds additional cost by 5 units, provided those values satisfy the assumptions. If a wrong action causes an irreversible fall, the disadvantage may span the rest of the episode and is no longer a small constant. DAgger helps obtain labels on visited states, but does not make an irreversible task recoverable or remove measurement uncertainty by itself.
In the second figure, an error in the absorbing model keeps cost 1 until the end; in the recoverable model it produces exactly bad steps and then returns to the good state. Expectations are calculated by probability recursion, with error per good step. The displayed bounds are and . This chain illustrates recovery assumptions; it does not prove a DAgger-trained system achieved that error.
Interventions and disturbances
Human-gated imitation reduces the burden of continuous labelling: in HG-DAgger the human decides when to take control and supplies examples in those regions; Kelly and colleagues describe this scheme. SafeDAgger learns a signal to request help when the learner is expected to be unreliable; Zhang and Cho study efficient queries. A threshold on known error, as in the third figure, is only a toy making the gate visible: in a real task error and uncertainty are not perfect oracles.
In the game, press Advance to use the learner or Intervene to apply and save the expert action. In automatic mode intervention occurs when reaches the threshold. Each label updates an accumulated linear fit; New round resets the state and retains labels. Observe the number of interventions and learned slope. The game does not model human delay or establish safety. A human may not know the correct action in an impossible state, and labelling video afterwards can lose force, velocity or intention available live.
Query cost is not measured by label count alone. Include monitoring time, control handover, delay, fatigue and the conditions under which a person can correct. An uncertainty detector can fail precisely out of distribution; evaluate false negatives and test it first in simulation. Retain each intervention’s time and duration too, since a long correction is not necessarily equivalent to an isolated decision.
DART seeks another demonstration distribution by perturbing actions during expert execution so the expert demonstrates recovery. The method of Laskey and colleagues (2017) adjusts perturbations to approximate learner errors; the lab uses fixed noise and is only a simplified version. Injecting noise can be costly or unsafe and is not equivalent to querying the expert in every state of an arbitrary policy.
Distribution-shift regimes help select a strategy. Spencer and colleagues distinguish a realizable regime where BC can work, an intermediate regime with limited model but sufficient expert coverage, and a difficult regime where learner-visited states fall outside demonstration support. In the intermediate regime, corrections using stored demonstrations and a simulator may help under coverage assumptions; in the difficult regime information about relevant states is missing and interaction may be necessary. These are theoretical conditions, not an automatic task classification.
A bounded density ratio expresses intermediate-regime coverage: learner states must have positive probability under the expert distribution, with a ratio that does not explode. If the expert never visits a region and different actions are needed there, a finite sample of demonstrations does not reveal the correction. Simulation can show that the learner reaches it but does not always provide the expert label. Before choosing interaction, noise or offline correction, compare that coverage with what the expert can actually supply.
In text, scheduled sampling mixes corpus context with own predictions; in on-policy distillation a teacher can label contexts generated by the student. Both analogies share concern about the induced distribution, but their objectives, expert access and guarantees are not identical to DAgger.
Lab: BC, DAgger and expert noise
In a scalar corridor, the ideal expert specifies . BC collects examples without disturbance; DAgger queries learner rollouts with a decreasing mixture; the DART-inspired variant executes the expert with fixed noise and saves the clean action. Each method receives exactly 80 labels per round for five rounds. Evaluation introduces disturbance and uses 100 shared seeds. The comparison deliberately favours a problem where BC sees only : it illustrates coverage, not a general ranking of methods.
import numpy as np
import matplotlib.pyplot as plt
def expert(e):return -.6*e
def train(data):
x=np.array([[1.,e] for e,a in data]);y=np.array([a for e,a in data])
return np.linalg.solve(x.T@x+.001*np.eye(2),x.T@y)
def policy(w,e):return np.clip(w[0]+w[1]*e,-.3,.3)
def collect(method,w,n,rng,beta):
data=[]
while len(data)<n:
e=0.
for _ in range(20):
label=expert(e);data.append((e,label))
if method=='BC':action=label;disturbance=0.
elif method=='DART':action=label+rng.normal(0,.1);disturbance=0.
else:action=label if rng.random()<beta else policy(w,e);disturbance=.035+rng.normal(0,.01)
e=np.clip(e+action+disturbance,-1,1)
if len(data)==n:break
return data
def evaluate(w,seeds=100):
success=0
for seed in range(seeds):
r=np.random.default_rng(10000+seed);e=0.;safe=True
for _ in range(40):
e=np.clip(e+policy(w,e)+.035+r.normal(0,.01),-1,1);safe &= abs(e)<.4
success+=int(safe)
return success/seeds
curves={}
for method in ['BC','DAgger','DART']:
rng=np.random.default_rng(7);data=[];w=np.zeros(2);rows=[]
for iteration in range(5):
beta=max(0,.5-.1*iteration)
data.extend(collect(method,w,80,rng,beta));w=train(data)
coverage=np.quantile(np.abs(np.array(data)[:,0]),.95);score=evaluate(w)
rows.append((len(data),score,coverage));print(method,'etiquetas',len(data),'éxito',round(score,3),'cobertura q95',round(coverage,3),'pendiente',round(w[1],3))
curves[method]=np.array(rows)
fig,axes=plt.subplots(1,2,figsize=(9,3))
for method,rows in curves.items():
axes[0].plot(rows[:,0],rows[:,1],marker='o',label=method);axes[1].plot(rows[:,0],rows[:,2],marker='o',label=method)
axes[0].set(xlabel='etiquetas expertas',ylabel='éxito en 100 semillas',ylim=(-.05,1.05));axes[1].set(xlabel='etiquetas expertas',ylabel='cuantil 95% de |e| etiquetado');axes[0].legend();plt.tight_layout();plt.show()Coverage is the 95th percentile of among labelled states. Success requires remaining within for 40 steps. The 100 seeds vary evaluation disturbances while each method is trained once; they do not estimate variation between training sets. The baseline receives no recoveries by construction. For a fair comparison in another environment, equalize labels and also report expert-executed actions, intervention time and scenario distribution.
Local lab: queryable pushing expert
You need MuJoCo, Gymnasium 1.1 or later, PyTorch, NumPy and Matplotlib. The code reproduces lesson six’s pushing environment and a residual policy with 32×32 images and proprioception. The expert uses privileged block state. BC trains on 100 demonstrations; DAgger starts with the first 10, trains, runs five rollouts per round and adds labels for visited states. The initial policy and five rounds are evaluated on 20 held-out seeds; the first round whose successes exceed BC is printed, or the code reports it was not reached. A difference of one episode does not establish statistical superiority.
import os, time
import numpy as np
import gymnasium as gym
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env
import mujoco
XML='''<mujoco model="push"><option timestep="0.002"/><worldbody>
<light pos="0 0 2"/><camera name="top" pos="0 0 .5" xyaxes="1 0 0 0 1 0"/>
<geom name="table" type="plane" size="1 1 .1" friction="1 .005 .0001"/>
<body name="pusher" pos="-.15 0 .025"><joint name="px" type="slide" axis="1 0 0" damping="5"/><joint name="py" type="slide" axis="0 1 0" damping="5"/><geom type="sphere" size=".015" mass="1" rgba=".2 .4 .8 1"/><site name="tip" size=".005"/></body>
<body name="block" pos="0 0 .025"><freejoint name="blockjoint"/><geom type="box" size=".025 .025 .025" mass=".1" rgba=".8 .3 .2 1"/></body>
</worldbody><actuator><velocity joint="px" kv="100" ctrlrange="-.2 .2"/><velocity joint="py" kv="100" ctrlrange="-.2 .2"/></actuator></mujoco>'''
class PushBlockEnv(gym.Env):
metadata={'render_modes':['rgb_array'], 'render_fps':10}
def __init__(self,render_mode='rgb_array',max_steps=100):
self.model=mujoco.MjModel.from_xml_string(XML);self.data=mujoco.MjData(self.model);self.render_mode=render_mode;self.max_steps=max_steps;self.renderer=None;self.capture=True
self.action_space=spaces.Box(-1.,1.,shape=(2,),dtype=np.float32)
self.observation_space=spaces.Dict({'rgb':spaces.Box(0,255,(64,64,3),dtype=np.uint8),'proprio':spaces.Box(-np.inf,np.inf,(4,),dtype=np.float32),'task':spaces.Box(-np.inf,np.inf,(4,),dtype=np.float32)})
self.tip=mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_SITE,'tip');self.block=mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_BODY,'block')
self.goal=np.array([.15,0.]);self.count=0
def _obs(self):
if self.capture:
if self.renderer is None:self.renderer=mujoco.Renderer(self.model,64,64)
self.renderer.update_scene(self.data,camera='top');img=self.renderer.render().copy()
else:img=np.zeros((64,64,3),dtype=np.uint8)
return {'rgb':img,'proprio':np.r_[self.data.qpos[:2],self.data.qvel[:2]].astype(np.float32),'task':np.r_[self.data.xpos[self.block,:2],self.goal].astype(np.float32)}
def reset(self,*,seed=None,options=None):
super().reset(seed=seed);mujoco.mj_resetData(self.model,self.data);self.data.qpos[3]=self.np_random.uniform(-.015,.015);self.count=0;mujoco.mj_forward(self.model,self.data)
return self._obs(),{}
def step(self,action):
a=np.clip(np.asarray(action,dtype=np.float32),-1,1);mujoco.mj_forward(self.model,self.data)
jp=np.zeros((3,self.model.nv));jr=np.zeros_like(jp);mujoco.mj_jacSite(self.model,self.data,jp,jr,self.tip)
desired=.2*a;J=jp[:2,:2];[email protected]([email protected]+1e-4*np.eye(2),desired)
self.data.ctrl[:]=np.clip(vel,-.2,.2)
for _ in range(50):mujoco.mj_step(self.model,self.data)
mujoco.mj_forward(self.model,self.data)
self.count+=1;distance=np.linalg.norm(self.data.xpos[self.block,:2]-self.goal);terminated=bool(distance<.035);truncated=bool(self.count>=self.max_steps and not terminated)
return self._obs(),float(-distance),terminated,truncated,{'distance':float(distance),'success':terminated}
def render(self):return self._obs()['rgb']
def close(self):
if self.renderer is not None:self.renderer.close();self.renderer=None
def expert(obs):
p=obs['proprio'];tip=np.array([-.15,0])+p[:2];block=obs['task'][:2];goal=obs['task'][2:];direction=goal-block;direction/=max(np.linalg.norm(direction),1e-8);behind=block-.045*direction
target=behind if np.linalg.norm(tip-behind)>.025 and tip[0]<block[0]-.02 else goal
return np.clip(6*(target-tip),-1,1).astype(np.float32)
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(2);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.manual_seed(41);rng=np.random.default_rng(41)
def compress(obs):return {'rgb':obs['rgb'][::2,::2].copy(),'proprio':obs['proprio'].copy()}
class Residual(nn.Module):
def __init__(self,c):
super().__init__();self.net=nn.Sequential(nn.Conv2d(c,c,3,padding=1),nn.ReLU(),nn.Conv2d(c,c,3,padding=1))
def forward(self,x):return F.relu(x+self.net(x))
class Policy(nn.Module):
def __init__(self,head):
super().__init__();assert head=='mse'
self.vision=nn.Sequential(nn.Conv2d(3,16,5,stride=2,padding=2),nn.ReLU(),Residual(16),nn.Conv2d(16,32,3,stride=2,padding=1),nn.ReLU(),Residual(32),nn.AdaptiveAvgPool2d(1),nn.Flatten())
self.mlp=nn.Sequential(nn.Linear(36,64),nn.ReLU(),nn.Linear(64,2))
def forward(self,images,proprio):return self.mlp(torch.cat([self.vision(images),proprio/.2],dim=1))
def predict(model,obs,unused):
c=compress(obs);im=torch.from_numpy(c['rgb']).permute(2,0,1).float()[None].to(device)/255;pr=torch.from_numpy(c['proprio'])[None].to(device)
with torch.no_grad():return model(im,pr)[0].clamp(-1,1).cpu().numpy().astype(np.float32)
def wilson(s,n):
z=1.96;p=s/n;den=1+z*z/n;mid=(p+z*z/(2*n))/den;half=z*np.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
return mid-half,mid+half
import matplotlib.pyplot as plt
torch.manual_seed(17);rng=np.random.default_rng(17)
def demo(env,seed):
env.capture=True;obs,_=env.reset(seed=seed);data=[];t=0
while True:
label=expert(obs)
if t%5==0:data.append((compress(obs),label.copy()))
t+=1;env.capture=(t%5==0);obs,_,term,trunc,_=env.step(label)
if term or trunc:break
return data,t
env=PushBlockEnv();demos=[demo(env,i) for i in range(100)];env.close()
print('demostraciones de experto:',len(demos),'etiquetas guardadas:',sum(len(ep[0]) for ep in demos),'pasos del experto:',sum(ep[1] for ep in demos))
def fit_policy(data,seed):
images=np.stack([x['rgb'] for x,a in data]);proprio=np.stack([x['proprio'] for x,a in data]);actions=np.stack([a for x,a in data]);torch.manual_seed(seed)
model=Policy('mse').to(device);opt=torch.optim.Adam(model.parameters(),lr=.001);model.train()
for _ in range(200):
i=rng.integers(0,len(data),64);im=torch.from_numpy(images[i]).permute(0,3,1,2).float().to(device)/255;pr=torch.from_numpy(proprio[i]).to(device);a=torch.from_numpy(actions[i]).to(device)
loss=F.mse_loss(model(im,pr),a);opt.zero_grad();loss.backward();opt.step()
model.eval();return model
def evaluate(model):
env=PushBlockEnv();success=0
for seed in range(20):
obs,_=env.reset(seed=10000+seed)
for _ in range(env.max_steps):
obs,_,term,trunc,_=env.step(predict(model,obs,None))
if term or trunc:success+=int(term);break
env.close();lo,hi=wilson(success,20);return success,lo,hi
baseline_data=[item for samples,steps in demos for item in samples];baseline=fit_policy(baseline_data,42);baseline_score,lo,hi=evaluate(baseline)
print('BC con 100 demos:',baseline_score,'/20, Wilson',round(lo,3),round(hi,3))
data=[item for samples,steps in demos[:10] for item in samples];expert_calls=sum(steps for samples,steps in demos[:10]);scores=[];queries=[];first=None
for iteration in range(6):
model=fit_policy(data,50+iteration);score,lo,hi=evaluate(model);scores.append(score/20);queries.append(len(data))
print('DAgger ronda',iteration,'etiquetas guardadas',len(data),'consultas totales',expert_calls,'éxitos',score,'/20, Wilson',round(lo,3),round(hi,3))
if first is None and score>baseline_score:first=iteration
if iteration==5:break
beta=max(0,.5-.1*iteration);env=PushBlockEnv()
for episode in range(5):
obs,_=env.reset(seed=20000+100*iteration+episode)
for t in range(env.max_steps):
action=predict(model,obs,None);use_expert=rng.random()<beta;query=(t%5==0 or use_expert)
if query:
label=expert(obs);expert_calls+=1;data.append((compress(obs),label.copy()))
executed=label if use_expert else action
obs,_,term,trunc,_=env.step(executed)
if term or trunc:break
env.close()
print('primera ronda con éxito observado mayor que BC:',first if first is not None else 'no alcanzado en las rondas ensayadas')
fig,ax=plt.subplots();ax.plot(queries,scores,marker='o',label='DAgger');ax.axhline(baseline_score/20,color='black',linestyle='--',label='BC 100 demos');ax.set(xlabel='etiquetas expertas acumuladas',ylabel='éxito en 20 episodios',ylim=(-.05,1.05));ax.legend();plt.show()npm run lab and open the connection link.Demonstrations save images and actions only every five steps, although the expert acts at every step; DAgger queries the expert at those steps and whenever the mixture executes their action. All those queries are saved. The code separately counts saved labels and expert calls, including unsaved demonstration actions. BC uses ten times more initial demonstrations, but total query budgets are unequal: the comparison measures that trade-off rather than attributing the result exclusively to the algorithm.
Practice
Step 1 of 3. What does average regret compare?
reset() returns (obs, info), step(a) returns Gymnasium's five values; train_fn(data) returns a callable policy. Query and add one label per visited state, mix actions with probability beta_schedule(i), train after each episode and return (policy, data). Use a generator seeded 0.import numpy as np
def dagger(env, expert, train_fn, n_iters, beta_schedule):
pass