Lecture 2

Imitation Learning

Learning from expert demonstrations: behavioral cloning, distribution shift, DAgger, and when imitation succeeds or fails.

Behavioral Cloning DAgger Distribution Shift Demonstrations
Original PDF slides

What Is Imitation Learning?

In the previous lecture we introduced the Markov Decision Process and the idea that an agent interacts with an environment by choosing actions according to a policy $\pi$. But where does that policy come from? Reinforcement learning derives it from a reward signal—a scalar feedback that the agent seeks to maximize. Imitation learning takes a fundamentally different approach: instead of defining a reward function, we provide the agent with demonstrations of desired behavior and ask it to mimic the demonstrator.

The appeal is immediate. Specifying a reward function that captures every nuance of a complex task (drive safely, smoothly, and efficiently) is notoriously difficult. But collecting examples of a skilled human performing the task is often straightforward—we simply record what they do. Imitation learning converts those recordings into a policy.

Definition
Imitation Learning. Given a dataset of expert demonstrations $\mathcal{D} := \{(s_1, a_1, \ldots, s_T)\}$ sampled from an unknown expert policy $\pi_{\text{expert}}$, the goal is to learn a policy $\pi_\theta$ that performs at the level of the expert by mimicking its behavior.

A canonical example is autonomous driving. A dataset of human drivers provides sensor readings (camera images, LIDAR scans) paired with steering commands (wheel angle, throttle, brake). The imitation learning agent trains on these state-action pairs and, at deployment time, maps new sensor observations to driving actions. No reward function is specified—the demonstrations implicitly define what good behavior looks like.

Notation Recap

We will use the notation established in Lecture 1 throughout:

Behavioral Cloning: The Simplest Approach

The most direct form of imitation learning is behavioral cloning (BC): treat the problem as supervised learning. We have inputs (states) and labels (expert actions), so we can train a neural network to map from one to the other using standard regression or classification losses.

Version 0: Deterministic Policy via Regression

The simplest behavioral cloning approach learns a deterministic policy $\hat{a} = \pi_\theta(s)$ by minimizing the mean squared error between the expert's actions and the policy's predictions:

Behavioral Cloning — Version 0 (Deterministic)
  1. Given: Demonstrations collected by an expert, $\mathcal{D} := \{(s_1, a_1, \ldots, s_T)\}$.
  2. Train: Minimize the $\ell_2$ regression loss over the dataset: $$\min_\theta \; \frac{1}{|\mathcal{D}|} \sum_{(s,a) \in \mathcal{D}} \|a - \hat{a}\|^2 \quad \text{where } \hat{a} = \pi_\theta(s)$$
  3. Deploy: Execute the learned policy $\pi_\theta$ in the environment.

This is precisely standard supervised regression. The neural network takes a state $s$ as input and outputs a predicted action $\hat{a}$. Training proceeds via stochastic gradient descent on the squared error, exactly as one would train a regression model on any tabular dataset. After training, the policy is deployed: the agent observes a state, queries the network, and executes the predicted action.

The Multimodality Problem

What goes wrong with $\ell_2$ regression? Consider an autonomous driving scenario where human drivers encounter a situation that admits two reasonable actions—for example, an obstacle in the road that can be avoided by steering either left or right. If the dataset contains demonstrations of both strategies, the $\ell_2$ loss will learn the mean of the two actions: steering straight ahead, which is precisely the worst thing to do.

Example
Averaging over modes. Suppose a dataset of driving demonstrations contains two clusters of steering commands for a particular observation: one cluster centered at "merge left" and another centered at "stay straight." The combined data distribution is bimodal. A policy trained with $\ell_2$ regression will predict the mean of these two modes—a steering command that falls between the two intended behaviors, potentially aiming the car directly at an obstacle. This happens frequently in practice, especially when data is collected from multiple demonstrators who have different strategies.

The fundamental issue is that $\ell_2$ regression outputs a single point prediction, which is the conditional mean $\E[a \mid s]$. When the true conditional distribution $p(a \mid s)$ is multimodal, this mean can lie in a region of low probability—an action that no expert would ever take. This problem is not merely theoretical; it arises constantly in real-world imitation learning, particularly when demonstrations are collected from multiple people with different preferences and habits.

Key Insight
The $\ell_2$ regression loss forces the policy to predict the conditional mean of the expert actions. When the expert's action distribution is multimodal (as is common with multiple demonstrators or inherently ambiguous situations), the mean can be a poor—even dangerous—action. This motivates learning distributions over actions rather than point predictions.

Learning Expressive Policy Distributions

The multimodality problem reveals that we need our policy to represent a distribution over actions, not just a single point. The question becomes: how do we parameterize $\pi_\theta(a \mid s)$ as an expressive distribution using a neural network?

Simple Parametric Distributions

For discrete actions (e.g., button presses in a video game), a neural network can output a categorical distribution directly. The network takes the state $s$ as input and outputs a probability for each action: $p(\text{up}), p(\text{down}), p(\text{left}), \ldots$ This representation is maximally expressive—it can represent any distribution over the finite action set, including multimodal ones.

For continuous actions (e.g., steering angle, joint torques), a common simple choice is a Gaussian distribution. The neural network outputs a mean $\mu$ and standard deviation $\sigma$, defining $\pi_\theta(a \mid s) = \mathcal{N}(\mu(s), \sigma(s)^2)$. While this is a valid probability distribution, it is unimodal—it can only represent a single bump. For the driving example above, a single Gaussian cannot capture the bimodal "go left or go right" structure. We need something more expressive.

Generative Models as Policies

The key insight of modern imitation learning is to borrow tools from generative modeling—the same family of techniques used for image generation and language modeling—and apply them to policy learning. In generative modeling, we learn complex distributions:

For imitation learning, our goal is analogous: learn $p(\text{action} \mid \text{observations})$. Three prominent families of generative models have been adapted for policy learning:

Mixture of Gaussians

A Gaussian Mixture Model (GMM) represents the action distribution as a weighted sum of $K$ Gaussian components:

$$\pi_\theta(a \mid s) = \sum_{k=1}^{K} w_k(s) \; \mathcal{N}\big(a \;\big|\; \mu_k(s),\, \sigma_k(s)^2\big)$$

The neural network takes $s$ as input and outputs the parameters of all components: means $\mu_1, \ldots, \mu_K$, standard deviations $\sigma_1, \ldots, \sigma_K$, and mixture weights $w_1, \ldots, w_K$ (with $\sum_k w_k = 1$). Each component captures a different mode of the expert's behavior. For the driving example, one component might represent "merge left" and another "stay straight."

Discretize + Autoregressive Prediction

For high-dimensional continuous action spaces (e.g., a robot arm with many joints), the action vector $a_t \in \R^d$ can be decomposed dimension by dimension. First, each continuous dimension is discretized into bins. Then an autoregressive model predicts each dimension conditioned on the previous ones:

$$\pi_\theta(a_t \mid s_t) = p(a_{t,1} \mid s_t) \cdot p(a_{t,2} \mid \hat{a}_{t,1}, s_t) \cdot p(a_{t,3} \mid \hat{a}_{t,1:2}, s_t) \cdots$$

Each factor is a categorical distribution over the discretized bins for that dimension. This approach can represent arbitrarily complex distributions over actions because the chain rule decomposition loses no information, and categorical distributions over bins are maximally expressive for each conditional. This is the same principle that makes autoregressive language models so powerful.

Diffusion Policies

A diffusion policy generates actions by iteratively denoising a sample of Gaussian noise. Starting from pure noise $a_t^{(N)} \sim \mathcal{N}(0, I)$, the model applies $N$ steps of learned denoising, each conditioned on the current state $s_t$:

$$a_t^{(n-1)} = a_t^{(n)} - \epsilon_\theta(a_t^{(n)}, s_t, n), \quad n = N, N-1, \ldots, 1$$

where $\epsilon_\theta$ is a neural network trained to predict the noise. At each step, the network takes as input the current noisy action $a_t^{(n)}$, the state $s_t$, and the denoising step index $n$, and outputs a noise estimate. After all $N$ steps, the resulting $a_t^{(0)}$ is the sampled action. Diffusion models can represent highly complex, multimodal distributions and have become a dominant approach in modern robot imitation learning.

Key Insight
Neural network expressivity is distinct from distribution expressivity. A large neural network with an $\ell_2$ loss is still constrained to output a unimodal prediction (the conditional mean), no matter how many parameters it has. Expressiveness of the distribution family—GMM, autoregressive, diffusion—is what determines whether the policy can capture multimodal behavior. Using a bigger network with the same $\ell_2$ loss does not solve the averaging problem.

Behavioral Cloning with Expressive Policies

Armed with expressive policy distributions, we can upgrade behavioral cloning. Instead of minimizing $\ell_2$ loss, we maximize the log-likelihood of the expert's actions under the policy distribution:

Behavioral Cloning — Version 1 (Expressive Policies)
  1. Given: Demonstrations collected by an expert, $\mathcal{D} := \{(s_1, a_1, \ldots, s_T)\}$.
  2. Train: Minimize the negative log-likelihood: $$\min_\theta \; -\E_{(s,a) \sim \mathcal{D}}\!\big[\log \pi_\theta(a \mid s)\big]$$ using an expressive distribution $\pi_\theta(\cdot \mid s)$ (GMM, autoregressive, or diffusion).
  3. Deploy: Execute the learned policy $\pi_\theta$, sampling actions from the learned distribution.

The training objective maximizes the log probability of the demonstration actions under the policy. This is equivalent to minimizing the KL divergence $D_{\text{KL}}(p_{\text{data}}(a \mid s) \| \pi_\theta(a \mid s))$ averaged over states in the dataset.

This objective is standard maximum likelihood estimation, the same principle that underlies training language models and image generation models. The key difference from Version 0 is that the policy $\pi_\theta$ is now an expressive distribution that can represent multiple modes, rather than a point prediction that can only capture the mean.

Empirical Evidence: Expressivity Matters

Experimental results consistently demonstrate the advantage of expressive policies, particularly with multimodal demonstration data:

The pattern is clear: when demonstration data comes from a single consistent demonstrator, even simple unimodal policies can work well. But when data is multimodal—whether from multiple demonstrators or from a single demonstrator facing ambiguous situations—expressive generative models are essential.

Case Studies in Industry

The combination of imitation learning with expressive policies has been adopted across robotics and autonomous driving:

Definition
Offline vs. Online. Two key terms that will recur throughout this course:
  • Offline: Learning using only a pre-existing dataset, with no new data collected from the learned policy.
  • Online: Learning using new data collected by executing the learned policy in the environment.
Behavioral cloning is a fully offline algorithm—it trains solely on the provided demonstrations without ever running the learned policy.

The advantages of offline behavioral cloning are significant: there is no need for data from the learned policy (which can be unsafe or expensive to collect) and no need to define a reward function. The primary disadvantage is that it may require a very large amount of demonstration data for reliable performance, due to a fundamental problem we address next.

Compounding Errors and Distribution Shift

Even with a perfectly expressive policy class, behavioral cloning faces a fundamental challenge that distinguishes it from standard supervised learning: compounding errors. Understanding this phenomenon is essential for appreciating both the limitations of behavioral cloning and the motivation for more sophisticated imitation learning algorithms.

Supervised Learning vs. Sequential Decision Making

In standard supervised learning, the inputs $x_1, x_2, x_3, \ldots$ are drawn i.i.d. from some fixed distribution $p(x)$, and the predicted labels $\hat{y}$ have no effect on what the next input will be. Even if the model makes an error on input $x_i$, the next input $x_{i+1}$ is drawn from the same distribution—errors do not propagate.

In sequential decision making, the situation is fundamentally different. The predicted action $\hat{a}_t$ directly influences the next state $s_{t+1}$ via the environment's dynamics. If the policy makes even a small error at time $t$, it may end up in a state $s_{t+1}$ that is slightly different from any state the expert visited. At this new state, the policy has less reliable training signal (it may be outside the training distribution), so it is more likely to make another error, leading to a state even further from the expert's experience. Errors cascade: each mistake pushes the agent further from the data distribution, where further mistakes become increasingly likely.

Key Insight
The core problem is covariate shift: the distribution of states visited by the learned policy $p_\pi(s)$ differs from the distribution of states visited by the expert $p_{\text{expert}}(s)$. The policy was trained on states from $p_{\text{expert}}(s)$ but is evaluated on states from $p_\pi(s)$. Unlike standard supervised learning, the agent's own predictions influence the distribution of future inputs.

Theoretical Analysis of Error Compounding

To make the compounding error problem precise, suppose the learned policy $\pi_\theta$ makes errors with probability $\epsilon$ at any given time step—that is, $\pi_\theta$ takes a different action from the expert with probability at most $\epsilon$ on states in the expert's distribution. How does the total error grow over a trajectory of length $T$?

In standard supervised learning (i.i.d. setting), the expected number of mistakes over $T$ inputs is simply $\epsilon T$—linear in the horizon. But in the sequential setting, errors compound. At time $t$, the probability of being in a state the expert would not have visited grows with each previous error. A careful analysis (Ross and Bagnell, 2010) shows that the total expected cost of the learned policy can be bounded as:

$$J(\pi_\theta) \leq J(\pi_{\text{expert}}) + O(\epsilon T^2)$$

where $J(\pi)$ denotes the expected total cost (negative reward) of policy $\pi$ over a horizon of length $T$. The key term is the quadratic dependence on $T$: errors grow as $T^2$, not $T$. For a long horizon—say, driving for 30 minutes at 10 decisions per second—this quadratic blowup can make behavioral cloning unacceptably fragile.

Intuition for the $O(\epsilon T^2)$ bound

Consider a trajectory of length $T$. At each time step, the policy either follows the expert's action (with probability $1 - \epsilon$) or deviates (with probability $\epsilon$). After the first deviation, the agent is in an unfamiliar state. From that point on, even if the per-step error rate were still $\epsilon$ on expert states, the agent is no longer on expert states, so the effective error rate could be much higher.

A simple counting argument: at time step $t$, the probability that the agent has made at least one mistake in the first $t$ steps is approximately $\epsilon t$ (for small $\epsilon$). Once a mistake has occurred, the agent may incur cost at every subsequent step. So the expected total extra cost is roughly:

$$\sum_{t=1}^{T} (\text{prob of first mistake by time } t) \times (\text{cost per step}) \approx \sum_{t=1}^{T} \epsilon t \cdot c = O(\epsilon T^2)$$

This is an informal argument; the formal proof by Ross and Bagnell (2010) uses a more sophisticated reduction to the online learning framework.

Practical Implications

The $O(\epsilon T^2)$ bound has two immediate practical consequences:

  1. Collect massive amounts of data. If we can drive $\epsilon$ down to a very small value through extensive demonstrations and powerful function approximation, the quadratic blowup may remain manageable. This is the approach taken by large-scale behavioral cloning systems that train on millions or even billions of demonstration trajectories.
  2. Collect corrective data. Instead of trying to make $\epsilon$ vanishingly small, we can collect data that specifically addresses the distribution shift problem. This is the idea behind DAgger, which we discuss next.

DAgger: Dataset Aggregation

The compounding error problem arises because the policy is trained on the expert's state distribution but deployed on its own. DAgger (Dataset Aggregation), introduced by Ross, Gordon, and Bagnell (2011), addresses this directly by iteratively collecting expert labels on the states the learned policy actually visits.

DAgger (Dataset Aggregation)
  1. Initialize: Collect initial demonstrations $\mathcal{D}$ from the expert. Train initial policy $\pi_\theta$ on $\mathcal{D}$.
  2. Repeat:
    1. Roll out the learned policy $\pi_\theta$ in the environment: $s'_1, \hat{a}_1, s'_2, \hat{a}_2, \ldots, s'_T$.
    2. Query the expert for the correct action at each visited state: $a^* \sim \pi_{\text{expert}}(\cdot \mid s')$.
    3. Aggregate the new labeled data with the existing dataset: $\mathcal{D} \leftarrow \mathcal{D} \cup \{(s', a^*)\}$.
    4. Retrain the policy: $\min_\theta \mathcal{L}(\pi_\theta, \mathcal{D})$.

The crucial insight is step (b): the expert provides labels not for the states it would visit, but for the states the learned policy visits. Over successive iterations, the training distribution converges to the distribution of states the policy actually encounters, eliminating the covariate shift problem. Ross et al. (2011) proved that DAgger achieves a regret bound of $O(\epsilon T)$—linear in the horizon, matching the standard supervised learning setting and eliminating the $T^2$ blowup.

Key Insight
DAgger converts the sequential prediction problem into a standard supervised learning problem by ensuring the training distribution matches the test distribution. The key requirement is interactive access to the expert: we must be able to ask the expert "what would you do in this state?" for arbitrary states, including states the expert would never have reached on its own.

The advantages of DAgger are clear: it is a data-efficient way to learn from an expert, directly addressing the compounding error problem. However, it has a significant practical limitation: querying the expert for actions at states visited by the learned policy can be challenging. The agent is in control of execution, and the expert must provide labels for potentially unusual or dangerous states that the agent has wandered into. In safety-critical domains like driving, this is problematic—the human expert must somehow specify the correct action from an awkward or dangerous situation that they would never have entered themselves.

Human-Gated DAgger: A Practical Variant

A more practical variant of DAgger is Human-Gated DAgger (HG-DAgger), which reverses the control structure. Instead of letting the learned policy execute fully and then querying the expert after the fact, HG-DAgger lets a human supervisor watch the policy execute and intervene whenever they judge the policy is about to make a mistake.

Human-Gated DAgger (HG-DAgger)
  1. Initialize: Collect initial demonstrations $\mathcal{D}$ from the expert. Train initial policy $\pi_\theta$ on $\mathcal{D}$.
  2. Repeat:
    1. Start rolling out the learned policy $\pi_\theta$: $s'_1, \hat{a}_1, \ldots, s'_t$.
    2. The expert intervenes at time $t$ when the policy is about to make a mistake.
    3. The expert provides a (partial) demonstration from the intervention point: $s'_t, a^*_t, s'_{t+1}, a^*_{t+1}, \ldots, s'_T$.
    4. Aggregate the new demonstrations: $\mathcal{D} \leftarrow \mathcal{D} \cup \{(s'_i, a^*_i)\}$ for $i \geq t$.
    5. Retrain the policy: $\min_\theta \mathcal{L}(\pi_\theta, \mathcal{D})$.

HG-DAgger has a much more practical interface than standard DAgger. The human watches the agent act and takes over when needed—exactly the paradigm of a driving instructor supervising a student driver. The expert provides full demonstrations from the intervention point onward, which is a natural and comfortable way to provide corrections. The downside is that it can be difficult to catch mistakes quickly in some application domains, especially when errors compound rapidly or the system operates at high speed.

Example
Learning to drive with HG-DAgger. Consider training an autonomous driving policy. The human supervisor sits in the car while the learned policy drives. When the policy begins to drift toward the edge of the lane, the human takes over the steering wheel and drives correctively for some period. This corrective driving data—collected precisely in the states where the policy struggles—is added to the training set. After several rounds of this process, the policy has been exposed to its own failure modes and has learned to correct them.

An interesting research question, noted on the slides, is whether one could automatically detect when intervention is needed—for instance, by training an uncertainty estimator that flags states where the policy is likely to fail, triggering expert intervention without requiring constant human supervision.

How to Collect Demonstrations

The quality and practicality of imitation learning depends critically on how demonstration data is gathered. The challenge varies significantly across domains.

Naturally Occurring Demonstrations

In some domains, people already routinely perform the task being automated, and their behavior can simply be recorded. Autonomous driving is the prime example: billions of miles of human driving data exist in the form of dashcam footage paired with vehicle telemetry (steering angle, speed, braking). Similarly, language models can be trained on the vast corpus of human-written text—every sentence ever written is a "demonstration" of language generation.

Robotics Demonstrations

Robotics presents a harder challenge because humans cannot directly "do" what a robot does—we have different bodies, different sensors, and different actuators. Three common approaches for collecting robot demonstrations are:

The Embodiment Gap

Could we avoid specialized data collection entirely by having robots learn from videos of humans or animals? This is an attractive idea—internet video data is plentiful and covers an enormous range of behaviors. However, the embodiment gap presents a fundamental obstacle:

While it is hard to directly imitate human or animal demonstrations across the embodiment gap, such data can potentially guide exploration in reinforcement learning. For example, Peng et al. (SFV, SIGGRAPH Asia 2018) used video of humans performing athletic movements to define reward functions for training simulated characters, achieving impressive backflips and other acrobatic skills.

Theoretical Perspective: When Does Imitation Learning Work?

Let us consolidate the theoretical picture of when imitation learning succeeds and when it fails.

Behavioral Cloning Guarantees

Behavioral cloning treats imitation learning as an i.i.d. supervised learning problem. If the policy achieves expected per-step loss $\epsilon$ on the expert's state distribution, the performance guarantee is:

$$J(\pi_\theta) \leq J(\pi_{\text{expert}}) + O(\epsilon T^2)$$

This quadratic dependence on horizon $T$ means that even small per-step errors can accumulate to produce catastrophic failure over long episodes. To achieve a total error of at most $\delta$, we need per-step error $\epsilon \leq O(\delta / T^2)$, which may require an impractically large number of demonstrations.

DAgger Guarantees

DAgger, by training on the policy's own state distribution, achieves a much stronger guarantee:

$$J(\pi_\theta) \leq J(\pi_{\text{expert}}) + O(\epsilon T)$$

The linear dependence on $T$ matches the i.i.d. supervised learning rate. To achieve total error at most $\delta$, we need only $\epsilon \leq O(\delta / T)$, which is dramatically more lenient than the $O(\delta / T^2)$ requirement of behavioral cloning. The cost is that DAgger requires interactive access to the expert during training.

Theorem
DAgger Regret Bound (Ross, Gordon, and Bagnell 2011). Under suitable regularity conditions, after $N$ rounds of DAgger, the best policy in the sequence achieves expected total cost at most: $$J(\pi_{\hat{\theta}}) \leq J(\pi_{\text{expert}}) + O\!\left(\frac{T}{\sqrt{N}}\right) + O(\epsilon_{\text{approx}} \cdot T)$$ where $\epsilon_{\text{approx}}$ is the approximation error of the policy class and $N$ is the number of DAgger iterations. As $N \to \infty$, the regret approaches $O(\epsilon_{\text{approx}} \cdot T)$—linear in the horizon.

Summary and Looking Ahead

This lecture covered the two main paradigms of imitation learning, along with the critical issues that arise in practice:

Part 1: Offline Behavioral Cloning. Train a policy to mimic expert demonstrations using supervised learning. The key design choice is the policy's distribution family: simple regression produces the conditional mean (problematic for multimodal data), while expressive generative models—mixtures of Gaussians, autoregressive models, diffusion models—can capture the full distribution of expert behavior. The algorithm is fully offline, requiring no interaction with the environment. Its main weakness is susceptibility to compounding errors ($O(\epsilon T^2)$ cost growth) due to distribution shift between expert states and policy states.

Part 2: Online Imitation with DAgger. Address compounding errors by iteratively collecting expert labels on states the learned policy visits. DAgger achieves linear error growth ($O(\epsilon T)$), matching the i.i.d. supervised learning rate. Human-Gated DAgger provides a more practical variant where a human supervisor intervenes when the policy errs. The cost is the requirement for interactive expert access during training.

The strengths and limitations of imitation learning can be summarized as:

Key Insight
Imitation learning is powerful but inherently limited: it can at best match the expert, never surpass it. For tasks where we want the agent to discover better-than-human strategies, or where we want the agent to improve autonomously through trial and error, we need reinforcement learning. In practice, many successful systems combine imitation learning (to bootstrap a reasonable initial policy) with reinforcement learning (to refine and improve beyond the demonstrations). This is the direction the course takes next.

In the next lecture, we begin our study of reinforcement learning algorithms, starting with policy gradient methods—techniques for directly optimizing a policy using reward signals from the environment, without any expert demonstrations.