Imitation Learning for Drone Control
Instead of designing reward functions, imitation learning lets drones learn by watching expert demonstrations. Think of it like teaching a child to ride a bike â they learn by observing and imitating, not by mathematical optimization.
For flight control specifically, the appeal is practical. Expert pilots and well-tuned classical controllers already produce competent behavior on the aircraft you actually fly, and converting that behavior into a policy is a supervised problem with stable training dynamics â no reward shaping, no exploration crashes, no reward-hacking an objective that was never quite what you meant. The cost arrives at deployment, where a learned policy must cope with states the expert never had to visit because the expert never made the mistakes that lead there.
Why Imitation Learning?
Traditional RL requires careful reward engineering. Imitation learning bypasses this by learning directly from expert behavior. For drones, experts can be human pilots, classical controllers, or other RL-trained agents â each choice brings different data. A human supplies intent and smoothness but flies inconsistently between sessions; a classical controller supplies perfectly repeatable labels but inherits every assumption baked into its gains; a trained agent supplies whatever its reward actually rewarded, which may not be what you wanted.
Whatever the source, three questions determine whether the resulting policy flies: does the demonstration state space cover where the policy will be deployed, does the recorded action space match the actuator interface the policy will command, and is the temporal structure of the expert's behavior preserved â actions sampled at the right rate, with the right smoothing â rather than treated as independent snapshots.
Imitation Learning Pipeline
The pipeline that converts footage into a controller has four stages, and each can fail independently. Collection records state and action together with timestamps from a source that already behaves acceptably; bad source behavior is not fixed by the learning algorithm afterward. Curation aligns the streams, removes segments where the expert was recovering from their own error or where telemetry glitched, and normalizes both observations and commands into consistent units â centimeters versus meters, degrees versus radians, stick positions versus body rates â because a scaling mismatch between training and deployment shows up as confident, wrong output. Fitting trains a policy mapping states to actions with a held-out split by episode rather than by frame, so near-duplicate consecutive frames do not leak across the split and make validation look better than reality. Finally, deployment runs the policy closed-loop against the real vehicle, where the first rollout is a test of the collection assumptions as much as of the network.
Behavior Cloning (BC)
Behavior cloning is the simplest form of imitation learning â just supervised learning on state-action pairs from expert demonstrations.
Behavior Cloning Implementation
from typing import List, Tuple
class BehaviorCloningNetwork(nn.Module):
def __init__(self, state_dim: int, action_dim: int, hidden_size: int = 256):
super().__init__()
self.network = nn.Sequential(
nn.Linear(state_dim, hidden_size),
nn.ReLU(),
nn.BatchNorm1d(hidden_size),
nn.Dropout(0.1),
nn.Linear(hidden_size, hidden_size),
nn.ReLU(),
nn.BatchNorm1d(hidden_size),
nn.Dropout(0.1),
nn.Linear(hidden_size, hidden_size // 2),
nn.ReLU(),
nn.Linear(hidden_size // 2, action_dim)
)
def forward(self, state):
return self.network(state)
class BehaviorCloningTrainer:
def __init__(self, model: nn.Module, lr: float = 1e-3):
self.model = model
self.optimizer = torch.optim.Adam(model.parameters(), lr=lr)
self.loss_fn = nn.MSELoss()
def train_epoch(self, dataloader) -> float:
self.model.train()
total_loss = 0
for states, actions in dataloader:
predicted_actions = self.model(states)
loss = self.loss_fn(predicted_actions, actions)
self.optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)
self.optimizer.step()
total_loss += loss.item()
return total_loss / len(dataloader)
def evaluate(self, dataloader) -> float:
self.model.eval()
total_loss = 0
with torch.no_grad():
for states, actions in dataloader:
predicted_actions = self.model(states)
loss = self.loss_fn(predicted_actions, actions)
total_loss += loss.item()
return total_loss / len(dataloader)
class DemonstrationDataset:
def __init__(self):
self.states = []
self.actions = []
def add_trajectory(self, states: np.ndarray, actions: np.ndarray):
self.states.extend(states)
self.actions.extend(actions)
def to_tensors(self) -> Tuple[torch.Tensor, torch.Tensor]:
states = torch.FloatTensor(np.array(self.states))
actions = torch.FloatTensor(np.array(self.actions))
return states, actions
def __len__(self):
return len(self.states)
def __getitem__(self, idx):
return self.states[idx], self.actions[idx]
Designing the Demonstration Set
Two numbers dominate the quality of a behavior cloning dataset: how many distinct episodes you have, and how much of the flight envelope each one touches. Consecutive frames from one sortie are almost the same sample repeated â thousands of them add less than a dozen genuinely different situations â so splitting validation by frame instead of by episode produces leakage and optimism. Ten short sorties covering the maneuvers you care about beat one exhaustive sortie for this reason alone.
Normalization deserves its own pass before training. State channels expressed in mixed units across log sources are the most common silent defect: a policy trained with altitude in centimeters and evaluated with meters will output commands scaled wrong by a factor of one hundred while its validation loss looks perfect. The same applies to actions â stick deflection in [-1, 1] and motor commands in microseconds cannot share a network head without an explicit mapping, and the mapping must be identical on both sides of the training/deployment boundary.
Coverage gaps show up later as confident failure. A dataset without recovery from disturbance teaches nothing about disturbance rejection, so include episodes where the expert corrected a gust or a position error rather than only segments where everything went well; the corrections are precisely the labels a deployed policy will need when reality supplies the disturbance first. Labeling each episode with the maneuver it contains turns this into something you can audit as a table before any training begins.
Distribution Shift Problem
Behavior cloning suffers from distribution shift â the trained policy encounters states not seen during training, leading to compounding errors. The mechanism deserves to be stated precisely, because it explains why offline accuracy and flight performance disagree so violently. The expert's data covers states reached by expert actions. The learned policy's small deviation from those actions lands it in a slightly different state â one that was never labeled â and at that state the network is extrapolating. Its next output deviates further, and the deviation grows with every control cycle rather than being pulled back.
The classical bound on this effect grows quadratically with episode length: if the per-step error is small but nonzero, the probability of leaving the demonstrated distribution over time compounds until trajectory error scales with the square of the horizon rather than its first power. A two-minute flight at 50 Hz is six thousand chances to drift, which is why a policy with one percent action error on a held-out frame split can still diverge at the first waypoint it attempts. The analyzer in the code above makes the gap visible by rolling expert and learner from identical initial states and plotting divergence over time instead of reporting a single aggregate loss.
from typing import Optional
class DistributionShiftAnalyzer:
def __init__(self, expert_policy, learned_policy):
self.expert = expert_policy
self.learned = learned_policy
def analyze_drift(self, initial_states: np.ndarray, n_steps: int = 50):
expert_trajectories = []
learned_trajectories = []
for state in initial_states:
expert_traj = self._rollout(self.expert, state, n_steps)
learned_traj = self._rollout(self.learned, state, n_steps)
expert_trajectories.append(expert_traj)
learned_trajectories.append(learned_traj)
# Compute state distribution divergence
drift = self._compute_drift(learned_trajectories, expert_trajectories)
return {
'expert_states': expert_trajectories,
'learned_states': learned_trajectories,
'state_drift': drift
}
def _rollout(self, policy, initial_state, n_steps):
states = [initial_state]
state = initial_state
for _ in range(n_steps):
action = policy.predict(state)
state = self._sim_step(state, action)
states.append(state)
return np.array(states)
def _sim_step(self, state, action):
# Simple simulation
next_state = state.copy()
next_state[:3] += action[:3] * 0.1
return next_state
def _compute_drift(self, learned_trajs, expert_trajs):
drifts = []
for learned, expert in zip(learned_trajs, expert_trajs):
for t in range(min(len(learned), len(expert))):
distance = np.linalg.norm(learned[t] - expert[t])
drifts.append(distance * t) # Weight by time step
return np.mean(drifts)
DAgger (Dataset Aggregation)
DAgger addresses distribution shift by iteratively collecting new data from the learned policy and labeling it with expert actions.
DAgger Algorithm
The dataset aggregation idea is one sentence long: let the learner fly, then ask the expert to label the states the learner actually visited, and add those labels to the training set. Iterating that loop converts the learner's own mistakes into supervision instead of hoping supervised accuracy on someone else's trajectories transfers to closed-loop flight. The first iteration usually looks like a distribution of near-expert states; by the fifth, the collected states cluster exactly where the learner previously failed, and retraining there removes the failure rather than the symptom.
A subtlety that separates working DAgger from wasted sorties: the expert must label states, not trajectories. When the pilot overrides the learner mid-run, you record what the expert commanded at that moment, not how the combined run finished â the label belongs to the state, and discarding the remainder of the episode throws away the most informative samples in the dataset. Implementation-wise this means the expert interface stays available at full rate during collection even while the learner's actions are what drive the vehicle.
DAgger Implementation
from typing import Callable
class DAgger:
def __init__(self, expert_policy: Callable, student_model: nn.Module,
env, lr: float = 1e-3, beta: float = 0.5):
self.expert = expert_policy
self.student = student_model
self.env = env
self.beta = beta # Interpolation factor for expert data
self.optimizer = torch.optim.Adam(student_model.parameters(), lr=lr)
self.dataset = {'states': [], 'expert_actions': []}
# Initial training with expert demonstrations
self._initial_dataset = None
def initial_train(self, expert_states, expert_actions, n_epochs=50):
"""Train on initial expert demonstrations."""
self._initial_dataset = (expert_states, expert_actions)
states = torch.FloatTensor(expert_states)
actions = torch.FloatTensor(expert_actions)
for epoch in range(n_epochs):
pred = self.student(states)
loss = nn.MSELoss()(pred, actions)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def dagger_iteration(self, n_episodes=5, n_steps=200):
"""Run one DAgger iteration."""
new_states = []
new_expert_actions = []
for _ in range(n_episodes):
state = self.env.reset()
for step in range(n_steps):
# Student chooses action
state_tensor = torch.FloatTensor(state).unsqueeze(0)
with torch.no_grad():
student_action = self.student(state_tensor).numpy()[0]
# With probability (1-beta), use expert action
if np.random.random() < (1 - self.beta):
expert_action = self.expert(state)
else:
expert_action = student_action
new_states.append(state)
new_expert_actions.append(expert_action)
# Step environment
state, done, _ = self.env.step(student_action)
if done:
break
# Add new data to dataset
self.dataset['states'].extend(new_states)
self.dataset['expert_actions'].extend(new_expert_actions)
# Retrain on aggregated dataset
self._retrain()
return len(new_states)
def _retrain(self, n_epochs=30):
states = torch.FloatTensor(np.array(self.dataset['states']))
actions = torch.FloatTensor(np.array(self.dataset['expert_actions']))
for epoch in range(n_epochs):
indices = torch.randperm(len(states))
for i in range(0, len(states), 32):
batch_idx = indices[i:i+32]
batch_states = states[batch_idx]
batch_actions = actions[batch_idx]
pred = self.student(batch_states)
loss = nn.MSELoss()(pred, batch_actions)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def train(self, n_iterations=10, n_episodes_per_iter=5):
"""Run full DAgger training."""
for i in range(n_iterations):
n_samples = self.dagger_iteration(n_episodes_per_iter)
print(f"Iteration {i+1}: Added {n_samples} samples, "
f"Total dataset: {len(self.dataset['states'])}")
Choosing the DAgger Schedule
DAgger's two parameters â how many aggregation iterations to run and how much expert versus learner control each iteration uses â deserve an explicit schedule rather than defaults carried over from a tutorial.
The mixing schedule answers who flies. Flying pure learner throughout and labeling afterward gives the true deployment distribution but risks repeated crashes before the labels ever get applied; flying pure expert gives safe data that barely differs from the original demonstrations and therefore teaches little. Annealing from mostly-expert to mostly-learner across iterations is the standard compromise: early rounds stay safe while the network's worst outputs are still frequent, later rounds expose it to its own errors as those become rarer and less catastrophic. Concretely, starting near 0.9 expert fraction and decaying toward 0.1 by the final iteration works well when each iteration's learner episodes are automatically terminated on a safety predicate â the predicate, not the schedule, is what makes aggressive learner control affordable.
Stopping criteria should be measured on closed-loop rollouts, not dataset loss. The right metric is task success rate over repeated runs from varied initial conditions, with a patience rule: if two consecutive iterations do not improve success, stop and inspect the failure cases rather than adding more of the same data. Expect the gains to flatten after roughly three to six iterations for a well-specified task; continued aggregation past that point mostly grows the dataset while teaching the policy to recover from failures it will rarely be allowed to reach.
Bookkeeping matters too. Each iteration's samples should be tagged with the aggregator index so later analysis can tell whether residual failures concentrate in early (rare) or late (common) states â and because mixing ratios differ per iteration, keep evaluation fixed on a held-out set of expert episodes throughout, otherwise the reported improvement partly reflects an easier evaluation distribution.
Learning from Human Pilots
Human pilots provide natural, intuitive demonstrations that capture complex flying behaviors.
What the human supplies that a scripted controller cannot is anticipation: a skilled pilot begins braking before the corner, shifts stick gently rather than stepping it, and corrects drift long before it becomes an error worth logging. Those are exactly the behaviors that are tedious to hand-code and valuable to clone. What the human also supplies is variability â different pilots hold different conventions for rate versus angle mode, deadband usage, and how aggressively they command yaw â so choosing whether you want one pilot's style or a consensus across several is a product decision that shapes the whole dataset.
The recording interface constrains what can be learned. State and command streams must share a timestamp base accurate to within a frame period, because a 50 ms offset at 20 Hz puts each action label against the wrong state and degrades the policy in ways no architecture change will fix. Commands should be recorded at the rate the controller consumes them, not merely on change, so hover segments contain evidence of active station-keeping rather than appearing as frozen values the network learns to copy verbatim.
from datetime import datetime
from typing import List, Dict
class HumanDemonstrationCollector:
def __init__(self, control_interface):
self.interface = control_interface
self.recordings = []
self.current_recording = None
self.is_recording = False
def start_recording(self, metadata: Dict = None):
self.current_recording = {
'timestamp': datetime.now().isoformat(),
'metadata': metadata or {},
'states': [],
'actions': [],
'timestamps': []
}
self.is_recording = True
print("Recording started...")
def record_step(self, state: np.ndarray, action: np.ndarray):
if self.is_recording and self.current_recording:
self.current_recording['states'].append(state.tolist())
self.current_recording['actions'].append(action.tolist())
self.current_recording['timestamps'].append(
datetime.now().timestamp()
)
def stop_recording(self):
self.is_recording = False
if self.current_recording:
self.recordings.append(self.current_recording)
print(f"Recording saved: {len(self.current_recording['states'])} steps")
self.current_recording = None
def save_demonstrations(self, filepath: str):
data = {
'demonstrations': self.recordings,
'total_demos': len(self.recordings),
'total_steps': sum(len(r['states']) for r in self.recordings)
}
with open(filepath, 'w') as f:
json.dump(data, f, indent=2)
print(f"Saved {len(self.recordings)} demonstrations to {filepath}")
def load_demonstrations(self, filepath: str):
with open(filepath, 'r') as f:
data = json.load(f)
self.recordings = data['demonstrations']
print(f"Loaded {len(self.recordings)} demonstrations")
def filter_by_quality(self, min_steps=50, max_jerk=10.0):
filtered = []
for recording in self.recordings:
if len(recording['states']) < min_steps:
continue
# Compute smoothness
actions = np.array(recording['actions'])
if len(actions) > 1:
jerk = np.mean(np.abs(np.diff(actions, axis=0)))
if jerk > max_jerk:
continue
filtered.append(recording)
self.recordings = filtered
print(f"Kept {len(filtered)} demonstrations after quality filter")
class DataAugmentation:
"""Augment drone demonstration data."""
@staticmethod
def add_noise(states, actions, noise_std=0.05):
noisy_states = states + np.random.normal(0, noise_std, states.shape)
return noisy_states, actions
@staticmethod
def time_warp(states, actions, warping_factor=0.2):
n = len(states)
warp = 1 + np.random.uniform(-warping_factor, warping_factor)
indices = np.clip((np.arange(n) * warp).astype(int), 0, n - 1)
return states[indices], actions[indices]
@staticmethod
def rotate_demonstration(states, actions, max_angle=15):
angle = np.random.uniform(-max_angle, max_angle) * np.pi / 180
cos_a, sin_a = np.cos(angle), np.sin(angle)
rotation = np.array([[cos_a, -sin_a], [sin_a, cos_a]])
augmented_states = states.copy()
augmented_states[:, :2] = states[:, :2] @ rotation.T
augmented_states[:, 5] += angle # Yaw
return augmented_states, actions
Cleaning and Augmenting What the Pilot Recorded
Raw pilot logs contain three classes of content the policy should never see taught: segments where the human was fighting a recording setup rather than flying the task, recovery maneuvers that belong to a mistake the learner will not repeat, and stretches of idle hover that would let the network learn "do nothing" as the dominant strategy. Curation is therefore subtractive before it is additive â drop the segments that do not represent the skill, then augment what remains.
Augmentation for flight data must respect physics. Rotating horizontal position and yaw together, as in the code above, synthesizes a heading the pilot never flew while keeping the geometry consistent; scaling altitude or horizontal extent simulates different operating envelopes as long as the action labels remain valid at the new scale. What does not survive augmentation is any transformation that would change the correct command: mirroring left and right is only legal if your vehicle is symmetric in both mass and actuator authority, and time-warping a trajectory invalidates rate-derived labels.
A useful audit before training counts samples per maneuver class and per flight phase after cleaning. If one class exceeds roughly half the dataset, the policy's loss will look excellent while minority behaviors â typically takeoff, landing, and aborts â arrive undertrained. Undersample the dominant class or collect targeted episodes for the sparse ones; this check costs a minute and prevents the most common post-flight surprise in imitation projects, a policy that is superb until the moment it must do the rare thing.
Generative Adversarial Imitation Learning (GAIL)
GAIL uses adversarial training to match the state-action distribution of the expert without requiring paired state-action labels.
That last property is the entire reason to reach for it. Behavior cloning needs the expert's action at every recorded state â which means an instrumented expert producing synchronized commands. GAIL needs only trajectories: states visited by the expert are enough, because the discriminator scores state-action pairs and the policy learns to produce actions the discriminator cannot distinguish from whatever the expert's behavior implies. A reference dataset of flight logs with states but imperfect or unavailable stick traces still works.
The training dynamic is genuinely adversarial, with the usual consequences. If the discriminator wins too easily, its reward signal saturates and the policy's gradient disappears; if the policy wins too easily, it has found a distribution that fools the discriminator without resembling competent flight. Normalizing the discriminator loss and capping its update rate relative to the policy are the standard stabilizers, and both should be monitored â a discriminator accuracy pinned near 100 percent or 50 percent tells you the game has stopped being informative. Expect training to cost an order of magnitude more environment interaction than behavior cloning, and budget the compute honestly before committing the schedule to it.
class GAILDiscriminator(nn.Module):
def __init__(self, state_dim, action_dim, hidden_size=128):
super().__init__()
self.network = nn.Sequential(
nn.Linear(state_dim + action_dim, hidden_size),
nn.LeakyReLU(0.2),
nn.Linear(hidden_size, hidden_size),
nn.LeakyReLU(0.2),
nn.Linear(hidden_size, 1),
nn.Sigmoid()
)
def forward(self, state_action):
return self.network(state_action)
class GAIL:
def __init__(self, policy, expert_states, expert_actions,
state_dim, action_dim, lr=1e-3):
self.policy = policy
self.discriminator = GAILDiscriminator(state_dim, action_dim)
self.disc_optimizer = torch.optim.Adam(self.discriminator.parameters(), lr=lr)
# Expert data
self.expert_states = torch.FloatTensor(expert_states)
self.expert_actions = torch.FloatTensor(expert_actions)
self.expert_sa = torch.cat([self.expert_states, self.expert_actions], dim=-1)
def train_discriminator(self, policy_states, policy_actions, n_epochs=10):
policy_sa = torch.cat([policy_states, policy_actions], dim=-1)
for _ in range(n_epochs):
# Expert: label 1, Policy: label 0
expert_pred = self.discriminator(self.expert_sa)
policy_pred = self.discriminator(policy_sa.detach())
expert_loss = -torch.mean(torch.log(expert_pred + 1e-8))
policy_loss = -torch.mean(torch.log(1 - policy_pred + 1e-8))
loss = (expert_loss + policy_loss) / 2
self.disc_optimizer.zero_grad()
loss.backward()
self.disc_optimizer.step()
def compute_reward(self, state, action):
sa = torch.FloatTensor(np.concatenate([state, action]))
with torch.no_grad():
D = self.discriminator(sa.unsqueeze(0))
reward = -torch.log(1 - D + 1e-8)
return reward.item()
When Each Method Earns Its Place
The decision between the three approaches is less about benchmark results and more about what you possess going in.
Choose behavior cloning when demonstrations are abundant, actions are reliably recorded, and the deployment distribution will not stray far from where the expert flew â for example, repeating a survey route that a classical controller already flies well. It is the cheapest path to a working policy and the first thing to get into closed-loop testing, with the understanding that its ceiling is the coverage of the data you collected.
Choose DAgger when the task is long-horizon or precision-sensitive enough that the compounding drift of pure cloning shows up as systematic misses. It costs flight or simulation time every iteration and demands an expert interface available at runtime, but it is the only one of the three that directly optimizes the closed-loop quantity you care about, and it needs no architectural changes on top of the clone.
Choose GAIL when actions are the missing ingredient â when you have rich trajectories but no trustworthy command stream â or when the expert's inputs are continuous and high-dimensional in a way that makes exact labels unrealistic to align. Pay for that flexibility with training instability and much heavier compute, and keep a behavior cloning baseline running alongside it: a well-curated clone that stays competitive with a struggling GAIL run is a result worth believing.
Hands-On Project: Complete Imitation Learning System
from typing import List, Tuple
class CompleteImitationLearningSystem:
def __init__(self, state_dim, action_dim):
self.state_dim = state_dim
self.action_dim = action_dim
# Models
self.bc_model = BehaviorCloningNetwork(state_dim, action_dim)
self.dagger_model = BehaviorCloningNetwork(state_dim, action_dim)
# Trainers
self.bc_trainer = BehaviorCloningTrainer(self.bc_model)
self.dagger = DAgger(
expert_policy=self._expert_policy,
student_model=self.dagger_model,
env=None # Set during training
)
# Data
self.demonstrations = DemonstrationDataset()
def _expert_policy(self, state):
"""Simulated expert policy (PD controller)."""
target = np.array([10.0, 10.0, 5.0])
error = target - state[:3]
kp = 1.0
kd = 0.5
action = kp * error - kd * state[3:6]
return np.clip(action, -1, 1)
def collect_demonstrations(self, n_trajectories=100):
print(f"Collecting {n_trajectories} expert demonstrations...")
for i in range(n_trajectories):
states = []
actions = []
state = np.random.uniform(-5, 5, self.state_dim)
for step in range(200):
action = self._expert_policy(state)
states.append(state)
actions.append(action)
# Simulate step
state = self._sim_step(state, action)
self.demonstrations.add_trajectory(
np.array(states),
np.array(actions)
)
print(f"Collected {len(self.demonstrations)} state-action pairs")
def _sim_step(self, state, action):
next_state = state.copy()
next_state[:3] += state[3:6] * 0.1 + 0.5 * action * 0.01
next_state[3:6] += action * 0.1
return next_state
def train_behavior_cloning(self, epochs=50):
print("\nTraining Behavior Cloning...")
states, actions = self.demonstrations.to_tensors()
dataset = torch.utils.data.TensorDataset(states, actions)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)
for epoch in range(epochs):
loss = self.bc_trainer.train_epoch(dataloader)
if epoch % 10 == 0:
print(f" Epoch {epoch}: Loss = {loss:.4f}")
def train_dagger(self, n_iterations=5, env=None):
print("\nTraining with DAgger...")
self.dagger.env = env
for i in range(n_iterations):
n_samples = self.dagger.dagger_iteration(n_episodes=5)
print(f" Iteration {i+1}: Added {n_samples} samples")
def evaluate(self, test_states, use_dagger=True):
model = self.dagger_model if use_dagger else self.bc_model
model.eval()
states_tensor = torch.FloatTensor(test_states)
with torch.no_grad():
predicted_actions = model(states_tensor).numpy()
expert_actions = np.array([self._expert_policy(s) for s in test_states])
mse = np.mean((predicted_actions - expert_actions) ** 2)
return mse
def _sim_step(self, state, action):
next_state = state.copy()
next_state[:3] += state[3:6] * 0.1 + 0.5 * action * 0.01
next_state[3:6] += action * 0.1
return next_state
# Usage example
def main():
system = CompleteImitationLearningSystem(state_dim=6, action_dim=3)
# Collect expert demonstrations
system.collect_demonstrations(n_trajectories=50)
# Train behavior cloning
system.train_behavior_cloning(epochs=50)
# Evaluate
test_states = np.random.uniform(-5, 5, (100, 6))
mse_bc = system.evaluate(test_states, use_dagger=False)
print(f"\nBehavior Cloning MSE: {mse_bc:.4f}")
if __name__ == "__main__":
main()
Key Takeaways
- Behavior cloning is simple but suffers from distribution shift
- DAgger iteratively improves by labeling learner's own trajectories
- GAIL enables imitation without explicit action labels
- Data quality matters more than quantity for imitation learning
- Combining multiple methods often yields best results
- Human demonstrations capture intuitive flying skills hard to code
Common Mistakes
Splitting train and validation by frame instead of by episode
Fix: Hold out entire episodes; consecutive near-identical frames otherwise leak across the split and inflate offline accuracy.
Mixing units or action conventions between collection and deployment
Fix: Normalize states and commands into one documented convention and assert identical scaling on both sides of the boundary.
Reporting behavior cloning loss as evidence the policy will fly
Fix: Evaluate closed-loop success from varied initial states â trajectory error compounds with horizon, frame loss does not reveal it.
Running DAgger without a safety predicate on learner control
Fix: Terminate runaway learner episodes automatically and anneal expert control from mostly-expert toward mostly-learner across iterations.
Letting hover and dominant maneuvers crowd out rare behaviors
Fix: Audit samples per maneuver class before training and collect targeted episodes for takeoff, landing, and abort cases.