Imitation Learning
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Policy and State-Action Representation () — covered in Lecture 1: Introduction to Reinforcement Learning and Lecture 4: Markov Decision Processes
- Markov Decision Processes, State Space and Action Space — covered in Lecture 4: Markov Decision Processes (4.5 The Elements of MDP; 4.5.2 State Space; 4.5.3 Action Space)
- Reward Hypothesis, Return and Reward Function — covered in Lecture 1: Introduction to Reinforcement Learning (1.8 From Reward to Return) and Lecture 4: Markov Decision Processes (4.5.4 Reward Function)
- State-Value and Action-Value Functions (, ) — covered in Lecture 2: Elements of RL and Multi-Armed Bandits and Lecture 5: Markov Decision Processes and Dynamic Programming
- The Recycling Robot Example (High/Low Battery, Search/Recharge) — covered in Lecture 4: Markov Decision Processes (4.8.3 Recycling Robot)
- Agent-Environment Interaction Loop — covered in Lecture 1: Introduction to Reinforcement Learning (1.3 The Interaction Loop)
17.1 What Imitation Learning Is and Why It Matters
17.1.1 Definition in Plain Words
Hook — Why would you copy instead of writing a reward? Imagine you are asked to write rules for "drive smoothly through a crowded market" — how do you score every tiny swerve, pause, and horn use? It is far easier to sit beside a good driver and record what they do. That shift from "write the reward" to "show the behavior" is the starting point for imitation learning.
Imitation learning — learning by copying an expert — is a way to teach an agent what to do by showing it what a good performer does, rather than by writing a reward by hand and letting the agent discover a policy through trial and error alone. The word imitation is common outside machine learning. We learn many skills by watching others, sometimes even picking up habits like how a manager handles a situation, and later we become our own best version — the lecture used the phrase "behave like your boss" to make this concrete: you observe a skilled manager, you copy responses to clients, to deadlines, to conflicts, and over time you distill your own style. The same idea applies here. The learner, the agent that needs to act, gets access to a demonstrator or to demonstrations, which are records of how that demonstrator behaved.
An expert is someone or something that is good at the task, and expert demonstrations are the data that expert leaves behind. A demonstration is not a single label — it is a set of state-action pairs logged while the expert acts. Access to the demonstrator can mean full trajectories, or just the ability to ask the expert what it would do in a given situation. When we have many such records, we can treat imitation as supervised learning on those records, at least as a first step.
Intuition — Copying as a shortcut. Think of learning a new dance. The instructor shows the steps; you mirror them. You do not first write a formula for "good dancing" and then search by random flailing. The mapping is direct: watch, copy, refine. In machines the instructor is a human driver, a game player, or a trained controller, and the steps are pairs . The analogy breaks where dance allows instant correction — a driving mistake changes the next camera view, so pure copying later needs more than the dance-studio mirror.
Formal framing of imitation. Let be the state space and the action space. An expert policy maps states to actions favored by the expert. Expert demonstrations are samples where or a noisy version of it. The learner seeks a policy from a class that mimics . No reward function is written at this stage — the reward is implicit in the expert choices. When it is hard to write the right reward but easy to show what good behavior looks like, imitation gives a direct path.
17.1.2 Two Roles: Learner and Expert
There are always two sides. One side is the learner that is trying to acquire a skill. The other side is the expert whose behavior is worth copying. We assume the expert is skilled, and we want the learner to become as close as possible to that skill level. This framing already hints why imitation is useful: when it is hard to write down the right reward, but it is easy to show what good behavior looks like, imitation gives a direct path.
Think of it like learning a sport or a workplace routine. At first you watch and copy, and that helps you get started. Over time you may need more than copying, but as a starting strategy copying is powerful. That is the core motivation that runs through the whole session.
To make the roles precise:
- Learner: the agent under training, with parameters that define . It starts weak and improves by minimizing a gap to the expert.
- Expert: the reference performer, denoted . The expert may be a human, an existing controller, or even a stronger RL agent. We do not need the expert's internal reward — only its surface decisions.
The learner's goal is not to memorize exact trajectories but to generalize the mapping so that for a new state it still picks an expert-like action. Imitation learning is therefore most valuable when expert data is cheaper than reward engineering — for example, asking a pilot to fly a demo is often cheaper than encoding "good flying" as numbers.
Assumptions & Scope — When copying makes sense. Imitation assumes (i) the expert is near-optimal for the intended task, (ii) states are observable enough to decide the action, and (iii) we can collect enough state-action pairs to cover important situations. If the expert is suboptimal or inconsistent, the learner inherits those flaws. If the task reward is easy to write and exploration is cheap, direct RL may be simpler. Imitation shines where reward design is hard and demo collection is easy.
Visual intuition: picture two columns. Left column lists expert states — a camera frame of a straight road, a frame of a left bend, a frame of a crowded crossing. Right column lists the expert's hands on the wheel for each frame. A line connects each frame to its action. The learner's job is to draw the same lines for new, unseen frames.
17.1.3 How This Topic Sits in the Course
Exam note: Earlier material on TPO loss functions and their numerical details was set aside as not in scope for this course and not needed for the exam. The focus instead is on topics that are part of the syllabus and will appear in the assessment, and imitation learning is one of those topics. The treatment here stays at the level needed for understanding the idea, its strengths, its failure modes, and the key algorithms, without going into low-level loss-function numericals that were covered only for completeness.
Real-world: The same shift happens in practice. Teams often start with a hand-tuned reward, then realize that showing examples from a human driver, a game player, or a pilot is far easier than writing the perfect reward. In warehouses, a hand-coded reward for "pick neatly" is brittle, but a few hours of human picking demos give a solid starting policy.
Pitfalls — What students mix up here. (1) Thinking imitation replaces reward design forever — it gives a start, but later refinement often needs interactive correction or reward inference. (2) Confusing demonstrations with labels that always cover the full state space — demos cover the expert's own distribution, not the whole space. (3) Assuming the learner will automatically improve beyond the expert by copying — copying caps you at expert level unless you add more learning.
Recap & Bridge. Imitation learning copies an expert's state-action behavior to avoid manual reward design. The expert shows what to do, the learner maps states to expert-like actions, and the "behave like your boss" idea captures the motivation. Next we turn those informal demonstrations into a concrete supervised dataset by looking at states, actions, and the racing-track picture of how many pairs a tiny track can produce.
17.2 From States and Actions to Supervised Examples — The Track Intuition
17.2.1 State-Action Pairs as the Basic Unit
A demonstration means watching someone act in a real environment and recording what happened. At each moment we note the state, written , which is the situation the agent faces, and the action, written , which is what the expert did in that state. A pair is a state-action pair. A collection of many such pairs is the training material.
The verbal idea in the lecture was "if someone is doing something right, you talk about state-action pairs — what does that expert do in each state." The reconstructed idea is that a trajectory is a sequence of states together with the expert's choices, and we treat each step as an example for supervised learning.
States, actions, and trajectories. Let denote a state, where is the set of all possible states, and let denote an action, where is the set of all possible actions. A trajectory of length is where each is the expert action at and each follows from the environment after . A state-action pair is one element of that sequence. The dataset for imitation is where is the expert's action and may be thousands to millions.
Intuition — States as snapshots, actions as captions. Think of a photo album where each photo is a state and the caption on the back is the action taken in that photo. Learning means: given a new photo you have not seen, write the right caption. The analogy breaks because in a real task the caption you write now chooses the next photo you will see — snapshots are linked, not independent pages.
A single demonstration already contains many pairs because the expert visits many consecutive states. The same state variable may represent a raw image, a sensor vector, or a board position, depending on the domain. The action may be a steering angle, a move, or a control command. What matters is the pairing: "in this situation, do this."
17.2.2 The Racing Track Thought Experiment
Picture a car on a small racing track. The task is to steer — go straight, turn slightly left, or turn slightly right — depending on where the car is on the road. If the whole expert drive were drawn on the track, there would be a line that shows where a skilled driver would place the car at each point. Each short segment of that line can be thought of as a state: the position and heading of the car at that moment. For each such state there is a correct steering action, drawn in the lecture as a mark in a different color — red for the state location, green for the action.
Even a small track generates many states. Each lane position, each slight shift in angle, is a different input. If we record enough of those states together with the expert's steering choice, we obtain millions of examples for a small track. We can then feed those examples to a deep neural network and ask it to learn the mapping: "given this track view, what should I do?"
Formally, a policy is a mapping from states to actions, written
where is the set of states, is the set of actions, and is the action the policy suggests when it sees state . The state variable lives in , the action variable lives in , is the function we want to learn, and is its output at .
The hope is simple: take state-action pairs from the expert, treat them as supervised labels, and train to reproduce them.
Policy as a lookup with generalization. The policy is not a table of memorized pairs; it is a function that must output a sensible action even for a state not in . In the track example, the input might be a camera image (so ) and the output a scalar steering angle in degrees (so ). Writing says: for every possible image, the policy proposes one angle.
Visual description: draw a top-down oval track. Mark the expert path as a continuous blue line along the center. At evenly spaced points along it, place a small red dot (the state) and a short green arrow (the action — straight arrow on straights, left-curved arrow before a left bend). The lecture used red for location and green for steering to separate "where you are" from "what to do." Zooming in, even a 10-meter straight yields dozens of slightly different camera views — each is a distinct , each needs its own green arrow.
Worked Example — Track steering states with expert actions degrees. Suppose the training set contains three canonical views: = "straight road ahead" with expert label , = "gentle left curve ahead" with (negative = left), = "gentle right curve ahead" with . We train so that , , . At test time a new view resembles but with a slightly sharper left bend; a well-generalizing network outputs about , close to what the expert would do, even though was never logged. The sense-check: outputs near the training labels for nearby inputs, and interpolates for mixtures (a view halfway between straight and left curve predicts about ).
Assumptions & Scope. This reduction assumes expert actions are available for many states and that the learner's class can represent the needed mapping (a deep net is usually assumed flexible enough). It also assumes IID-ish supervised learning applies, which is exactly the point that breaks next: states are sequential, not independent draws, so the IID assumption is only an approximation.
17.2.3 Why the Supervised Reduction Is Tempting and Incomplete
On the surface this reduces reinforcement learning to supervised learning: states become inputs, expert actions become targets, and a network learns to predict the target. That is attractive because supervised learning is well understood.
The limitation appears right after that. No matter how many pairs we collect, we cannot cover every possible state and every possible action. More importantly, supervised learning treats each state independently, as if the choice now has no effect on what state comes next. In a real task the choices form a sequence that achieves a goal. One steering decision changes the next camera view, which changes the next decision. When each prediction is made in isolation, the learner misses that sequential dependence.
Core gap — Sequential dependence vs independent prediction. Supervised training minimizes error per pair as if the next does not depend on the predicted . In reality the environment transitions as . A small error at moves you to a different distribution, which is not in the training set. This is the seed of the compounding-error failure discussed in 17.6. Knowing this limitation helps you see why behavior cloning later needs dataset aggregation.
This mismatch between "treat each example alone" and "actions form a sequence that creates the next state" is the seed of the failure that appears later with cloning.
Recap & Bridge. States and actions form pairs ; trajectories chain those pairs; the policy is the target function. The racing track shows how millions of such pairs arise even on a tiny circuit, with red state marks and green action arrows. The supervised view is tempting but incomplete because it ignores sequential dependence — a missing link that later causes distribution mismatch. Next we name the full ingredients needed to actually run this reduction.
17.3 What You Need to Run Imitation Learning
17.3.1 The Ingredients
If you want to learn imitation with a supervised network, you need several pieces working together:
- a policy class, which is the family of functions you allow — typically a deep neural network — written for the set of all permissible policies, and a specific learned policy inside that set with parameters ;
- a loss function that measures how far the learner is from the expert;
- a learning algorithm that updates to reduce that loss;
- a demonstrator or a set of demonstrations that supply state-action pairs;
- and a practice environment, either a simulator or the real world, where the learner can try its policy and gather new states.
Here denotes the network weights — the numbers the network learns — and is the action the network predicts at state when it uses those weights.
Policy class and parameterized policy . is the set of all policies realizable by the chosen architecture (for example, all convolutional nets with a given depth and width). The vector collects every weight and bias. Picking picks one member . Learning is search inside for the member that best matches the expert.
Everyday picture. Think of as a wardrobe and as the exact outfit you put on. The wardrobe limits style (you cannot wear what is not in it), but the outfit choice decides how well you match the dress code — here, the expert's style.
Other pieces in one line each:
- Loss : a number that is small when matches and large when they differ (squared error is the running example).
- Learning algorithm: usually gradient-based optimization, repeatedly stepping .
- Demonstrator / expert : the source of labels. Access may be offline (a fixed log) or interactive (you can query for a new ).
- Practice environment: where rollouts happen. Without it you cannot see what states your current would actually visit.
Assumptions & Scope. This stack assumes a differentiable policy class, a computable loss, and some way to obtain corrected labels for new states. If the environment is unsafe for live rollouts, a simulator must stand in. If the expert is not queryable after logging, you are limited to pure offline cloning and cannot fix distribution shift later — a limit that motivates DAgger.
17.3.2 Where These Pieces Meet
The network takes a scenario as input and produces an outcome . The expert recommendation for that same scenario is , where denotes the expert policy. The loss measures the gap between and . Learning means choosing so that gap is small on average over the states the expert visits.
In symbols, for a single state the gap is , and training aims for
where is the distribution of states encountered when the expert acts (defined formally in 17.5). The expectation says "average over the kinds of states the expert tends to visit."
Real-world: This is the same stack used when training a lane-keeping network from human drives. The network is a convolutional net, the loss is mean squared steering error, the optimizer is gradient descent, the demonstrator is a human driver, and the practice ground is either logged video or a driving simulator.
Mini-trace — How the pieces interact on one training step. Start with = image of straight road. (1) Policy class gives current ; forward pass yields . (2) Demonstrator label is for that . (3) Loss . (4) Learning algorithm computes gradient and nudges so next time is nearer . (5) Repeat over a minibatch sampled from . Over many batches the average loss over falls. Sense-check: if loss does not fall, check policy capacity, label noise, or optimizer step size.
Visual: imagine a block diagram with five boxes — Policy Class, Loss, Optimizer, Demonstrations, Environment — arrows show demonstrations feeding into loss, environment feeding new to the policy, and optimizer feeding updated back to the policy.
17.3.3 Scope for Assessment
Exam note: The focus for the exam is on understanding these blocks conceptually and on being able to walk through the algorithms that use them, not on reproducing low-level loss numericals. Slides that show detailed numbers exist for reference, but the assessment emphasis is on the ideas and their trade-offs.
Recap & Bridge. Running imitation needs a policy class , a loss, an optimizer, a demonstrator, and a practice environment; the policy maps scenarios to predicted actions and is tuned to match on the expert's state distribution. Knowing the ingredients sets you up to see early successes where this stack already worked and where it hit its limits — the story of NAVLAB, ghosting, and helicopters next.
17.4 Early Success Stories — Autonomous Driving, Ghosting in Games, and Helicopter Acrobatics
17.4.1 NAVLAB and the Earliest Autonomous Driving Work
One of the oldest examples in the field is the NAVLAB effort at Carnegie Mellon, where a simple neural network learned to drive by using an expert nearby. A truck or car learned to steer on a track from human steering examples, following the exact pattern described earlier: many state-action pairs, a network that maps track view to steering, and an expert who shows what to do. This was presented as a two-minute clip to convey how a very simple network, with an expert around to demonstrate, could already learn autonomous driving on a confined road. It is noted as one of the first works that can be called imitation learning in the reinforcement learning community.
Why NAVLAB mattered. Before end-to-end learning was fashionable, NAVLAB showed that a shallow network fed with camera-to-steering pairs could stay on a road, not by hand-coded lane detection but by copying a human. The contribution was not network depth but the data loop: human drives, log , train , steer.
Details that make the pattern concrete: the input was a downsampled road image, the target was a steering angle, the training set was a few minutes of human driving recorded as thousands of pairs. At test time the network ran live on the same road and produced steering in real time. Performance was limited to the road type seen, but on that road it stayed centered — an early proof that imitation can replace manual control rules.
Example — NAVLAB autonomous driving at Carnegie Mellon with simple neural network and human steering. Setup: Carnegie Mellon NAVLAB vehicle on a closed track; human driver provides steering demo. Data: sequence of road images paired with wheel angles (e.g., image of straight segment → , image approaching left bend → ). Model: small fully-connected or early convolutional net mapping image to angle. Result: after supervised training, the vehicle follows the track without hand-crafted lane features. Takeaway: even a simple network, with an expert nearby to supply , can achieve lane keeping on the demonstrated road. Sense-check: performance drops sharply on an unseen road texture — the policy only knows the distribution it saw.
Real-world: The same data pattern — camera view paired with human wheel angle — still powers modern lane-assist datasets, only with larger networks and much more data. Modern extensions add multiple cameras, lidar, and DAgger-style corrections, but the core logging remains.
17.4.2 Ghosting in Team Games
A second illustration comes from team sports such as soccer and basketball. Every past game is a trajectory: players move, the ball moves, and the sequence shows different ways to approach the same situation. If you record many games, you can study how an average player or a strong player moves when the ball is in a given spot.
Ghosting is a technique that uses that history. When a live game is underway, each dot or number on the display can be a ghost — a replay of how a typical or expert player moved from that same game situation. That ghost is superimposed on the live players. If the ghost behaves differently from what is actually happening, it signals that the current play is deviating from the historical norm. That deviation itself can be studied, and a policy can be learned from the actual moves that players took.
The lecture linked a short clip to make this concrete, noting that audio is not essential — the visual of ghost trajectories laid over live play already shows the idea: multiple trajectories from different players, many games, and a learned sense of what usually happens next.
Ghost trajectories as learned expectations. For a game state (positions of all players and the ball), the ghost policy predicts the next movement that a typical expert would make. Overlaying ghost trajectories on live play visualizes versus the actual . The gap flags unusual decisions — useful for coaching and opponent modeling.
Example — Ghosting overlay in soccer and basketball with trajectories superimposed on live players. Setup: database of many past soccer games; each game is a trajectory of player positions per second. At live state where the ball is near midfield with two defenders ahead, ghosts appear as translucent dots continuing forward along the historically most common run. If the live winger cuts inside while the ghost continues down the wing, the deviation is visible as diverging ghost trajectories superimposed on the same live frame. Analysts can then ask: was the inside cut better? A learned policy can be trained on the expert moves that historically led to goals. Sense-check: ghosts are averages — they show norms, not optimal play — so a deviating live move may be innovative, not wrong.
Real-world: Broadcast tools now overlay expected-run paths in soccer and expected movement in basketball for strategy review. The same learned trajectory models support opponent modeling and training planners that ask "what would a good player do here?" Clubs use these overlays to design pressing triggers and to spot players who consistently beat the ghost.
Scope — What ghosting can and cannot show. Ghosting needs many games to estimate a stable . With few games, ghosts are noisy and may not represent true expert behavior. Also, historical trajectories mix player skill levels; separating "average" from "expert" requires filtering demos by player quality.
17.4.3 Helicopter Acrobatics from Demonstrations
A third example is learning difficult helicopter maneuvers. Research from Stanford, including work co-authored by Andrew Ng, showed a helicopter learning acrobatic moves from expert demonstrations. The demonstrations contain the hard-to-engineer details of how to sequence controls for flips and sharp turns. Instead of writing the perfect reward for acrobatics, the system learns from traces of how a skilled pilot or an existing controller flew.
Example — Helicopter acrobatics from Stanford with Andrew Ng learning difficult maneuvers from demonstrations. Setup: Stanford helicopter platform; state includes pose, velocity, and rotor speeds; action is control inputs to cyclic, collective, and throttle. Expert demos are recorded flights of a skilled pilot performing flips and funnels — maneuvers where hand-crafting a reward for "good flip" is extremely hard. By training on traces, the learner acquires a policy that reproduces the maneuver timing and can then be refined. Notably, later work flipped the problem to learn the reward behind the demos (inverse RL) to generalize to new maneuvers. Sense-check: success hinged on many demos of the same maneuver family; a new maneuver type with no demo still fails without extra learning.
Real-world: This pattern appears wherever perfect reward design is hard — surgical robots that copy a surgeon's path, or robotic arms that learn assembly from human demonstrations. In each case the expert trace encodes timing and compliance that a hand-written reward would miss, and imitation bootstraps a viable policy before any RL fine-tuning.
Visual across all three: picture three panels side by side — left panel: road image with steering arrow (NAVLAB); middle panel: soccer field with translucent ghost dots over live players (ghosting); right panel: helicopter silhouette mid-flip with control traces below (acrobatics). The common arrow is "expert trace → supervised pairs → learned policy," with complexity rising from left to right.
Recap & Bridge. NAVLAB at Carnegie Mellon, ghosting in soccer and basketball, and Stanford helicopter acrobatics co-authored by Andrew Ng show the same pattern working at increasing difficulty: lane keeping on a fixed road, trajectory prediction from many games, and high-rate control of an unstable aircraft. Each success relied on an expert nearby and careful logging. The next step is to name the simplest algorithm that formalizes this pattern — behavior cloning — and to write its objective.
17.5 Behavior Cloning — Cloning an Expert with Supervised Learning
17.5.1 The Simplest Form of Imitation
The simplest form of imitation learning is behavior cloning. The name says it: clone someone's behavior by supervised learning. You collect state-action pairs from the expert and train a network to predict the expert's action whenever it sees the same state.
Formally, suppose you are given a distribution of states visited by the expert, written or , and for each such state the expert's action . You want to learn a policy that is close to on those states and that also generalizes to states you have not seen.
Hook — Why "cloning" is the right word. In biology a clone is a copy that should be indistinguishable in behavior, not just in looks. Behavior cloning aims for the same: an outside observer watching the learner should struggle to tell it apart from the expert on the training distribution.
Behavior cloning as supervised regression/classification. Given demo data with , treat as input and as target. For continuous actions (steering) this is regression; for discrete actions (left/straight/right) it is classification. The learner outputs and pays a loss when .
17.5.2 Mathematical Formulation
The lecture stated the goal as "learn the network parameters such that the expected loss is minimal, given state-action pairs as taken by the expert on those states the expert demonstrated, so the agent performs as good or as close to the expert and generalizes beyond seen states." The reconstructed math preserves that verbal description alongside the expression.
Let be a state, be the expert's action at that state, be the learner's prediction with parameters , and be a loss that compares two actions. Then the behavior cloning objective is
where is the expectation — the average — over states the expert visits, is that visit distribution, and is small when the two actions match. In words: pick weights that make the average gap between learner and expert, measured on expert states, as small as possible.
A common choice for mentioned as "pretty straightforward" and not to worry about, is squared error. The verbal description was "take the difference and square it; you might want to measure the squared distance or mean squared error between your action and the expert's action." That reconstructs to
or in the scalar steering case
where is the Euclidean norm — the straight-line length of a vector — and the square makes large errors count more than small ones. For discrete actions the same idea uses cross-entropy, but the squared-error form above is the one emphasized in the lecture.
At training time the network receives a scenario , produces , compares it to the expert label , computes the loss above, and updates to reduce it.
Symbol registry for this concept. : state; : action; : expert policy; : learner with weights ; : distribution over states when rolling out ; : action-matching loss; : average over expert-visited states; : Euclidean norm; : learner prediction; : expert label.
Derivation of the empirical loss: the expectation is not computed analytically; it is approximated by the sample average over the demo set
so minimizing the familiar mean squared error on the demo set approximates minimizing the population objective over . As grows, the sample average converges to the expectation under standard supervised-learning assumptions (IID samples from ). The gap between sample and population error is the usual generalization gap.
Assumptions & Scope. Behavior cloning assumes is well-covered by and that the loss faithfully captures task performance. Squared error is convenient for continuous steering but not the right choice for discrete or multimodal actions (where two good actions exist). Also, optimization is only over — no guarantee is made for states drawn from a different distribution, which is exactly the mismatch that appears in 17.6.
Visual: draw a 1D axis of states labeled by (a bump centered on the expert's track). The training loss is the area under . Cloning squeezes that area to near zero, but says nothing about states where is near zero (off-track states).
17.5.3 Worked Examples
Example 1 — Track steering as supervised labels. Suppose the training set has states for "straight road view," for "gentle left curve," for "gentle right curve," with expert labels degrees, degrees (left), degrees (right). The network learns that maps , , . At test time a new view that looks slightly like will produce a prediction near if the network generalizes. Check: training loss on is zero if the mapping is exact; test loss on depends on similarity to in feature space.
Example 2 — One training step in numbers (squared error versus gives loss ). Take one sample . The network predicts before the update. The squared error is The gradient of with respect to is , so a gradient step with learning rate moves the prediction by toward (since is nudged to reduce ). After the step, next prediction might be with loss , strictly smaller. Repeating over batches drives toward and the gap toward . Sense-check: perfect prediction gives loss ; symmetry means error sign does not matter, only magnitude.
Additional quick check: if the dataset had 10 copies of and the network averaged them, the optimum under squared error is the mean, , confirming that squared error pulls predictions toward the average expert action per state.
17.5.4 Student Questions and Answers
Q: Is imitation sufficient on its own in the long run?
A: Copying helps learning and is important, especially to get started, but it may not be sufficient forever. Over time you need to do more than mimic — you need to handle new states and to improve beyond the expert's traces. The lecture stressed this early to frame later sections: cloning is a bootstrap, not the final skill. Relying only on copying caps performance at the demo distribution and leaves you fragile to novel states, which is why interactive methods and reward inference are introduced later.
17.5.5 Industry Applications
Real-world: Behavior cloning is the baseline for many applied pipelines. A company collects human demonstrations for warehouse picking, trains a network with a simple squared-error loss on joint angles, and obtains a workable initial policy before adding more sophisticated correction. For example, collect 500 demos of a robot arm picking boxes (state = wrist camera view, action = 7-DOF joint targets), train with mean squared error, and get a policy that succeeds on typical box poses. Failures on unusual poses then motivate DAgger-style corrections.
Pitfalls — Common traps with behavior cloning. (1) Thinking more demos always fix generalization — quantity helps only if demos cover relevant variety, not just repeats of the same state. (2) Using squared error for discrete choices where cross-entropy is needed — squaring class labels is meaningless. (3) Evaluating only on held-out demo data — that tests performance but hides rollout performance under .
17.5.6 Exam Notes
Exam note: For behavior cloning, be ready to state the objective as "minimize expected loss on the expert's state distribution" and to write both the expectation form and the squared-error loss (or scalar). Define , , and . Expect conceptual or short-answer questions that ask why behavior cloning is efficient and simple, not long numerical drills on the loss. Reason for simplicity: it is pure supervised learning with no environment interaction at training time.
Recap & Bridge. Behavior cloning clones by minimizing with squared-error as the running example vs → loss . It is fast and needs no live rollouts to train. Its weakness is that it only optimizes on , so performance can collapse once the learner's own rollout distribution diverges — the distribution-mismatch story with the red and blue track next.
17.6 Why Naive Cloning Fails — Compounding Error and Distribution Mismatch
17.6.1 The Core Problem in Plain Words
Behavior cloning is simple and efficient, and it works when one-step deviation is not catastrophic and when expert trajectories cover the space well. If you make a small steering mistake but there are still nearby expert examples to pull you back, you stay safe. The trouble starts when the coverage is not that dense.
The key problem is a mismatch of data distribution — the states the learner sees at test time are not the same distribution it was trained on. Training saw states from (expert-visited). Testing with the learned policy generates states from (learner-visited). After the first mistake those two differ, and the gap compounds.
Hook — A copy that slowly drifts off script. Think of copying a parade: you follow the person ahead. A tiny step sideways puts you slightly out of line. The next instruction was written for someone still in line, so you guess, step further out, and soon you are on the sidewalk while the parade marches on. Each guess was small, but their effects stacked.
Assumptions & Scope — When cloning is actually fine. Cloning succeeds when (i) single-step error is small, (ii) the environment is forgiving (a small deviation does not move you to a novel state), and (iii) expert data blankets the region near the nominal trajectory. Highway lane keeping with dense center-line demos is an example; a narrow mountain track with no off-center demos is not.
17.6.2 The Red and Blue Track Story
Picture again the track with two lines. The blue line is the expert trajectory — where a good driver actually goes. The red line is the learner's path. Suppose the learner starts at the same spot as the expert and follows the blue line nicely for a while. At some point the supervised model suggests an action with a marginal deviation — a small steering error. That deviation alone is not serious; no one drives exactly on the center line.
What matters is what happens next. After that small shift, the car is now in a state that is slightly off the expert track. That exact off-track view may never have been encountered in any expert example. The network, which was only trained on on-track views, now has to guess. It often guesses poorly and produces an action that widens the gap. That new wider gap leads to an even more unfamiliar state, which leads to a larger mistake, and the error compounds.
The lecture walked this in steps: at the deviation point the red line is slightly off the blue line; feed that off-track state to the network; the expert may never have visited that precise state; the network gives some output; the error grows; soon the learner is in a region like a roadside strip it never saw during training but where it still assumes it can drive safely; the supervised network, learned only from the blue line, makes mistakes that pull it further away; eventually the car crashes. A small deviation leads to a new state, the new state leads to more mistakes, and the mistakes push the car further from the track.
This compounding is why the discussion notes that the network will actually try to give some output, so that error would slowly compound, and finally you will actually be crashing.
Error compounding intuition in one line. Let the per-step error on training states be . On expert states you err by . On learner-visited states you err by more, say , where grows as you drift. Stacked over steps this can yield total return loss scaling like in the worst case, not — quadratically worse because early drift poisons later decisions. The lecture kept this conceptual ("small → unseen → larger → crash"), not as a formula to memorize.
Visual: draw the oval track again. Blue line: smooth center loop. Red line: starts glued to blue, then a tiny kink outward at the top straight, then each segment bends further outward. Label the first kink "step : -error → off-track state," the next segment "step : state never seen → bigger error," and the final outward loop leaving the track "crash." Add two histograms below: left histogram tight around center; right histogram shifted and spread outward.
17.6.3 Distribution Mismatch Formalized
During training the loss is averaged over , the distribution of states the expert visits. At test time the learner generates its own distribution by acting. Once it drifts, the sequence of states it collects — the "new distribution" drawn in red — no longer aligns with the expert's distribution. The learner keeps seeing states outside its training set and keeps making errors on them. This is the distribution mismatch problem.
In symbols, training assumes
but deployment sees
and after the first mistake. The further the learner drifts, the larger the gap between the two distributions, and the larger the average test error. The gap can be measured by total variation or by the extra loss which is zero only if the two distributions coincide.
Notation for the mismatch. : probability (density) of being in state when rolling out the expert ; : same quantity under the learner . Both are induced by the environment dynamics and the policy. Behavior cloning matches actions where is high but says nothing where has mass and does not.
A useful mental model: training loss is a flashlight that only illuminates the blue line; deployment walks with a flashlight that quickly points off the line into darkness.
17.6.4 Worked Examples
Example 1 — One-step drift to meters off center predicts versus correct . Expert data contains states at lane center: positions . Learner drifts to meters off center. No training example had . The network's predicted steering at was never supervised, so it predicts (slightly right) when the correct correction to rejoin center is (left). Error . The car, instead of returning, moves to next step, where error is larger. Quantitatively, start at . Step 1 error moves . Step 2 predicted action error scaled to lateral move yields . Error roughly doubles each step until leaving the lane. Sense-check: if the dataset had contained , the prediction would have been near and drift would have been damped.
Example 2 — When cloning still works (dense coverage recovery when expert data includes off-center states ). If expert data already contains many off-center recoveries — states at all with correct recovery steering (e.g., , , ) — then a drift to is still within the training cloud. Interpolate: expected label near (since is of the way from to ). The network predicts , close enough to steer back toward center, so shrinks to next step and the error damps. This is the case where "expert trajectories cover the whole space pretty well," and cloning is acceptable. Sense-check: coverage must span the neighborhood the learner can drift into, not just the center line.
17.6.5 Student Questions and Answers
Q: Does behavior cloning always fail?
A: No. It is simple and efficient and can work well when a small mistake does not cause a catastrophe and when you have so many expert trajectories that they blanket the state space. If even after a deviation you remain inside a well-covered region, recovery is likely. The danger is when coverage is thin and errors lead you outside the demonstrated region. The takeaway for revision is to name the two conditions for success: forgiving dynamics plus dense coverage; absent those, compounding and distribution mismatch dominate.
17.6.6 Industry Applications
Real-world: Highway lane-keeping with dense center-line data can succeed with pure cloning. Off-road or narrow track driving, where leaving the center means encountering unseen terrain, quickly reveals compounding error and forces a more interactive data strategy. For instance, a highway lane-keeping demo set with millions of centered frames tolerates small errors because the next frame still looks centered; a quarry road with one narrow path offers no such forgiveness — a 20 cm drift shows rocks never seen in training, the network mis-steers, and drift accelerates.
Pitfalls — Misreading this failure. (1) Blaming the network size — bigger nets do not fix missing off-track data. (2) Thinking compounding is just "average error grows linearly" — it can grow quadratically with horizon because one error changes the state distribution. (3) Believing more epochs on the same data will help — it only sharpens the flashlight on the blue line, not the red region.
17.6.7 Exam Notes
Exam note: Be able to draw or describe the blue-expert versus red-learner diagram, explain "small deviation → unseen state → larger error → compounding → crash," and name the problem as distribution mismatch between and . State training distribution versus deployment and why after the first mistake. The story is the answer; heavy algebra is not required.
Recap & Bridge. Naive cloning fails not because the per-step loss is large on , but because deployment shifts to where loss is uncontrolled, and that shift compounds — the red track diverges from the blue. The fix must bring training data onto the learner's actual state distribution. That fix is an interactive expert that labels states the learner visits — the DAgger loop next.
17.7 Fixing the Mismatch with an Interactive Expert — DAgger
17.7.1 The Driving Instructor Analogy
The second major family fixes cloning by using an interactive demonstrator, much like learning to drive with an instructor beside you. At first you try to copy what the instructor says. With time you improve, but sometimes you deviate. When you do, the instructor takes control, adjusts the steering, and puts you back on track, helping you learn better. The instructor does not just give you a fixed log of examples; he intervenes when you make a mistake and gives you the correct action for the very state you just created.
That idea — let the learner act, and whenever it visits a new state, ask the expert what should have been done there — is the heart of the next algorithm.
Intuition — Instructor as a safety net and labeler. In a driving lesson the instructor does two jobs: (1) keep the car from crashing, (2) turn your mistake into a lesson ("in that off-center pose you should have steered "). The second job is the dataset trick: every mistake becomes a new labeled example where is exactly the state you created by erring. Over many lessons the logbook fills with recoveries, not just perfect driving.
Scope — What "interactive" requires. Interactive means the expert can be queried on states the learner visits during training. If you only have a fixed offline log and the expert is gone, this method does not apply. In practice the instructor may be a human watching the simulator, or a trained expert policy that can be run on any .
17.7.2 DAgger in One Sentence
DAgger, short for Dataset Aggregation, alternates between collecting demonstrations, training a policy, letting the learner drive (partly on its own, partly with expert help), labeling the states the learner visited with the expert's correct actions, adding those new labeled states to the dataset, and retraining. The dataset grows so that it increasingly covers the states the learner actually encounters, not just the states the expert would have visited alone.
The lecture emphasized: collect demonstrations, learn from the expert via supervised learning, get a policy ready, go drive with it, let the interactive demonstrator make corrections, update the learner, and repeat. The loss itself remains the same simple gap between your action and the expert's action, often squared error, so the new idea is about what data you train on and how you mix control.
17.7.3 Mathematical Formulation
Let be the aggregated dataset of state-action pairs, initially empty, written
Let be the policy class — all policies the network could represent — and let be the first policy, initialized arbitrarily. In words, the instruction was to "initialize a policy Pi one to any policy; Pi is the space of all policies and Pi one is one policy within that space" which reconstructs to chosen at random from .
DAgger runs in a loop over iterations . At iteration it uses a mixed policy that blends the expert and the current learner via a parameter . The verbal description was "this beta is a parameter that instructor uses as to how much to intervene; when you begin this beta will be pretty high, meaning the policy would be largely by whatever your instructor gives; with time he will slowly decrease his involvement to ensure you become autonomous." That reconstructs to
Interpreted as a stochastic mixture: at each step, follow with probability and follow with probability . In the lecture's words, " is so time follow your instructor and time follow yours — you still have two physical policies and then you choose between them randomly." A deterministic blend is also possible in some tasks, but the randomized mixture is the typical implementation noted.
A second form that makes the mixing explicit is
where is the action taken, is the current state, is the expert's suggestion, is the learner's suggestion, and controls how often the expert is in charge.
Once is fixed, sample a trajectory using . A trajectory means a sequence of states generated by rolling out in the environment. Those states are still unlabeled for learning purposes, so for each visited state attach the expert's correct action . This creates a new batch
Then aggregate
and train a new classifier or regressor on the enlarged to obtain the next policy
With experience is decreased, so the learner becomes independent. Early on it relies mostly on the expert; later it drives more on its own and the dataset already contains many of the off-track corrections it will need.
Symbols: is the growing dataset, is the batch from iteration , is the mixing weight at iteration in , is the expert, is the learner at iteration , and is the mixed rollout policy.
Why aggregation matters algebraically. At iteration the training distribution is the mixture of all past rollout distributions, not just the current one. So minimizing approximates minimizing loss under the distribution induced by the learner's own future rollouts, closing the vs gap. In words, the flashlight now sweeps the red region where the learner actually goes.
Assumptions & Scope. DAgger assumes you can roll out safely and query for every visited (the expert is not harmed by showing the label even when the state is poor). It also assumes retraining on aggregated is feasible as grows. Early near 1 keeps rollouts safe; late near 0 gives realism but risks larger drift if the learner is still weak — hence the gradual decay.
17.7.4 The Algorithm Step by Step
- Start with . Choose an initial at random from .
- For to :
a. Form the mixed policy and roll it out to get states visited under . b. For each visited state , query the expert for and form pairs into . c. Aggregate . d. Train a new policy on with the simple loss . e. Reduce so the learner takes more control.
- Return the best on a held-out check or the final one.
Each step has a reason: the mixture creates states the learner would actually see, the expert label turns those states into supervised examples, aggregation remembers all past corrections so the learner does not forget, and decaying pushes autonomy.
Visual: a loop diagram with four boxes — "Roll out " → "Label visited with " → "Aggregate " → "Train " — with an outer arrow labeled "" showing the instructor stepping back each round.
17.7.5 Worked Examples
Example 1 — First two iterations on the track (beta then and relabeling off-center state). Iteration 1: , so the car is expert-guided. It stays near the blue line and contains mostly on-track states labeled by the expert, e.g., . Train on — it mimics the center. Iteration 2: . Now half the decisions come from . The car drifts slightly, visits an off-center state at meters, and the expert labels it with the correct recovery steering . So contains , and now explicitly teaches recovery. Train on the enlarged ; it steers back from off-center states better because those states are now supervised. After 10 iterations with decaying toward 0, contains a dense cloud around and off the track, and handles both. Sense-check: never shrinks — forgetting is prevented by the union.
Example 2 — Why aggregation matters. Suppose we discarded old data and trained only on with its off-center recoveries. The new policy would learn at but could forget at , drifting on straights. By keeping the union , the loss encourages on center and off-center jointly, so the policy must do well on both old and new states, which stabilizes learning. Numerically, training only on gives low loss on but high loss on ; training on the union balances both to moderate loss everywhere.
17.7.6 Student Questions and Answers
Q: Is there a lot of numerical calculation in DAgger that will be tested?
A: The numbers are not the point and they are hard to make into a meaningful exam numerical. Slides with numbers exist for reference, but the idea is better understood without heavy calculation. The key is to know the algorithm in your head — every piece, how the dataset grows, how the mixing parameter controls intervention, and how the learner becomes independent — and to be able to use it conceptually. Technically the approach should give confidence even if a small question is asked. For revision, memorize the loop and the role of decay, not arithmetic.
17.7.7 Industry Applications
Real-world: DAgger-style correction is used when a safety driver can intervene. In data collection for autonomous driving, the car runs its current network, the human takes over at the edge of an error, and that takeover frame is logged as for the next training round. Similarly, in robotic grasping the robot attempts a grasp, a human corrects the wrist pose when it fails, and that corrected pose becomes a new pair on an otherwise rare failure state.
17.7.8 Exam Notes
Exam note: Be ready to write the DAgger loop from memory: empty , random , mixture with decay, rollout of , expert relabeling to form , aggregation , retraining, and decay. Also know the stochastic mixture form with probability for the expert. Do not expect a long numerical exercise; expect to explain why each line helps with distribution mismatch — mixing creates learner-like states, relabeling supervises them, aggregation remembers them.
Recap & Bridge. DAgger fixes distribution mismatch by aggregating datasets from mixtures with dataset update and . The instructor starts hands-on and lets go as the learner's state distribution becomes well-covered. Where DAgger corrects actions on the learner's states, the next family corrects the underlying intent itself — learning the reward behind the behavior with inverse reinforcement learning.
17.8 Inverse Reinforcement Learning — Learning the Reward Behind the Behavior
17.8.1 Why "Inverse"
The phrase "inverse" can be confusing. In a typical, or forward, reinforcement learning setup you start with states, actions, often transition dynamics , and a reward function , and your goal is to learn an optimal policy . In short
So you assume access to the world model and the reward, and you compute how to act.
Inverse reinforcement learning flips that. You are given states, actions, transitions, and many samples — demonstrations — but you do not know the reward. Your target is to learn the reward function itself. In words from the session: "your target is to learn the reward function; you will be given states and actions, you will be given transitions, and many samples, so you understand why it is coming under imitation learning — when it comes to imitation, you try to learn the policy from demonstrations, but here the primary objective is to learn the reward function, not the policy directly."
Once you recover a good reward, you can then use standard reinforcement learning to obtain a policy from it. So the chain becomes
where is the learned reward and is the policy that optimizes it. The arrow is just ordinary RL with the inferred reward.
Forward vs inverse in one picture. Forward RL: reward known, policy unknown, demonstrations optional — solve for actions. Inverse RL: policy demos known, reward unknown — solve for intent. The output of inverse RL is not an action but a scalar function or that scores every state-action pair; high score means "the expert would like this."
Hook — Why infer reward instead of copying actions? Copying actions ties you to streets the expert drove. Knowing why they drove that way lets you navigate a new city. Reward is portable; a trajectory is not.
Visual: two opposite arrows. Top row: box with plus an arrow to . Bottom row: box with demos plus plus a backward curved arrow labeled "inverse" pointing to , then a forward arrow to .
17.8.2 The Intuition: What Is the Expert Trying to Maximize
The motivation is that an expert's behavior is governed by some internal reward. Ask: why does the person do what they do? What would they gain? They are maximizing some reward function, even if they never write it down. If you can learn that reward, you understand their intent, not just their surface actions.
The lecture put it as "there is a reward function that he internally uses that governs his behavior, so what you try to learn is what he tries to maximize or minimize." In certain problems this is called reward modeling. If you crack the reward, you can reuse it to learn a policy that generalizes to new settings where the expert never demonstrated, because you now know what to optimize.
This is also the lens for interaction with language models. When you chat with a model, the model tries to understand what kind of response gives you higher satisfaction — what your internal reward is. It builds a picture of your preferences and then produces outputs that score well under that model of your reward. That problem is fundamentally a reward-modeling problem, and it draws on inverse reinforcement learning ideas.
Everyday analogy — Taste vs menu choice. Watching someone order at a restaurant shows choices (actions). Inferring their taste (sweet vs salty, spicy vs mild) is the reward. Once you know taste, you can predict orders at a new restaurant, even though the menu is different. The analogy breaks where taste alone does not determine choice — budget and allergies (constraints) also matter, just as transition dynamics shape RL.
The key property of inverse RL is transfer: the learned lets you act well where no demo exists, because you optimize there. Pure cloning has no such transfer.
17.8.3 Mathematical Formulation
You still model the reward with a parametric form that takes state and action as input and predicts a scalar score. The session illustrated the linear case first, saying "assume you are extracting many features from state and action — feature one, feature two, feature three, feature four — and you are trying to learn the weight of each feature."
Let be a feature vector extracted from , where each is a hand-designed or learned feature such as distance to a wall or speed, and let be learnable weights plus a bias . Then the linear reward model is
In vector form
where is the predicted reward at , is the transpose of the weight vector, and is the feature column. A nonlinear model replaces the dot product with a network, written , where is a neural net with parameters . The learning goal is to choose so that the observed demonstrations look near-optimal under — the reward that best justifies the behavior you saw.
Symbol registry. : feature vector (here ); : -th feature (e.g., = negative travel time, = negative jerk); : weights; : bias term; : scalar reward; : nonlinear alternative implemented as a neural net.
How is chosen? Conceptually, pick so that expert trajectories score higher than alternative trajectories under . Different algorithms make this precise by maximizing the gap between expert return and non-expert return, or by matching feature expectations to . The session kept scope conceptual: know what inverse reinforcement learning is and how it differs from forward reinforcement learning, rather than reproducing a full solver.
For the linear model the return of a trajectory is
so learning is learning how to weight summed features along a trajectory. The bias sets a baseline offset and does not affect comparison between trajectories of equal length.
Assumptions & Scope. Linear assumes the true expert reward is roughly a weighted sum of the chosen features. If key features are missing, the inferred reward will be wrong. Nonlinear is more flexible but needs more data and can be less interpretable. In both cases demos must cover enough variation to identify trade-offs — if the expert always takes the same road you cannot learn whether they value speed or smoothness.
Visual: picture a table with four feature columns to and a weight column to . Each row is a state-action pair; the reward is the weighted sum across the row. Learning tilts the weight column so that rows from expert trajectories sum high and other rows sum low.
17.8.4 Worked Examples
Example 1 — Linear reward delivery task smoothness versus travel time with weights and . Suppose demonstrations in a delivery task show a driver always preferring a slightly longer but smoother road. Features are travel time (more negative when slower), jerk (more negative when rougher). Two candidate routes: Route A (fast but jerky): min, ; Route B (slower but smooth): min, . Fitting to make chosen routes (here Route B) score higher requires solving larger for B. With learned and : , . Indeed , so the model explains the preference: smoothness weight outweighs pure speed weight . That learned reward then predicts future choices on new roads — e.g., it will again favor smooth over fast. Sense-check: swapping weights to would rank A higher, contradicting demos, so the fitted weights are identifiable.
Example 2 — Why policy alone is not enough. Two different reward weightings can produce the same observed short trajectory, but they suggest different behavior in a new city. City X demos show the driver taking Main Street; both weighting and could rationalize it given that street's features. In a new city where Main Street is rough and Side Street is smooth, the two rewards predict opposite choices. Learning the reward (if possible from richer demos) lets you transfer intent, while copying actions alone ties you to the old streets and gives no rule for the new map. This shows the portability advantage of over cloned directly.
17.8.5 Student Questions and Answers
Q: Can you give a real life example where inverse reinforcement learning is used?
A: Take a soccer game. A player can approach the same situation in multiple ways, sometimes with misleading feints, but the intent behind the sequence matters — what reward is that player actually trying to maximize over many moves? If you watch many games and learn the reward function that makes that player's long sequences look good, you understand the player beyond the single action you just saw. That lets you predict future behavior and, if you need to play against him, craft a strategy that counters how he trades off risk, space, and chance of scoring. The same idea powers reward modeling for broader interactive systems that try to maximize your satisfaction rather than the machine's own score — for instance, a language model that learns from human feedback which style of answer you find helpful and then generates responses that score high under that learned satisfaction model.
17.8.6 Industry Applications
Real-world: In game analysis, ghosting plus inverse reinforcement learning estimates a player's hidden preferences — for example, how a striker weights a quick shot versus a safer pass — which feeds coaching and opposing-team planning. In language models, reward models are trained from human feedback and then used to fine-tune the assistant to fit what users actually find helpful. A reward model where is a prompt and is a response learns to score responses by human preference; the assistant is then optimized to produce high- responses. Both are direct applied uses of inverse reinforcement learning ideas where the reward is about user satisfaction and helpfulness.
Pitfalls — Overclaiming what IRL gives you. (1) Thinking IRL finds a unique reward — many rewards can rationalize the same demos; extra assumptions or regularization are needed. (2) Confusing reward learning with policy learning — IRL output is , not ; you still need RL to get a policy from it. (3) Ignoring that language-model reward modeling is RLHF-style — it learns satisfaction from preferences, not from full trajectories, so it is a cousin of IRL with its own data quirks.
17.8.7 Exam Notes
Exam note: Expect to contrast forward versus inverse reinforcement learning: forward learns a policy from a known reward, inverse learns a reward from demonstrations and then can learn a policy from that reward. Diagram: versus . Be ready to write the linear form and to define each symbol , , , and . Also be ready to give a real-life example such as player intent in soccer or reward modeling for interactive language models that maximize user satisfaction, which is the bridge to the next illustration of why reward quality matters.
Recap & Bridge. Inverse RL learns — often or — that makes expert demos look near-optimal, then derives from . This flips forward RL and enables transfer to new settings where surface actions do not repeat. The quality of is decisive: a small misspecification can flip the optimal policy, as the recycling-robot illustration next makes concrete.
17.9 A Small Concrete Illustration — The Recycling Robot and Poor Reward Design
17.9.1 The Setup
A compact example that was shown uses a recycling robot with two battery states, and , and two actions, and . The expert's preferred behavior is simple to state: when the battery is high, search; when the battery is low, recharge. The learner's initial attempt does the opposite in one state — it searches when it should recharge or vice versa — so there is a visible mismatch.
Let and be the expert's choices, and let but be a learner that is lazy about recharging. On state "high" the pair matches, on state "low" it does not. The training loss counts that misalignment as for the mismatched state and for the matched one, so the gap is visible and can be improved by adding demonstrator examples.
Tabular policy comparison. Write the state in the left column and the action in the next two columns: Mismatch indicator is for high and for low. Average 0-1 loss over the two states is . Adding a demo and retraining drives toward recharge, pushing the loss toward .
Intuition — The lazy student. Think of a student who studies when energetic but keeps studying when exhausted instead of resting. One wrong rule ("always search") looks industrious but burns out. The expert rule ("recharge when low") encodes the trade-off between immediate work and future capacity — the same trade-off that a correct reward must capture.
17.9.2 Reward Misspecification in Numbers
Now change the lens to reward. Suppose the world gives the agent reward each time step it waits, and each time it searches while battery is high, but also some cost if it searches while low. If the reward model is poorly learned and the agent believes waiting gives for free with no risk, it may reason: why sweat to search? Sit back and collect every minute — over many steps that sums to a large total. That learned reward makes the lazy policy look optimal when it is not. The point of the example is that small mistakes in reward modeling change the optimal behavior completely. A correct reward makes searching when able the best choice; a weak reward model makes idling look attractive.
Concretely, over steps, waiting yields under the flawed model, while correctly search-and-recharge might yield a higher true return but is never discovered because the flawed reward never encourages it. The lecture flagged this as the kind of trouble poor reward modeling causes, not as a lengthy calculation to memorize.
How a small reward error flips the policy. Let true rewards be , but enables future 's, and with no future cost in the flawed model. Under the flawed , the value of always waiting from any state is Under the true task, the optimal search-recharge cycle might yield, say, 70 cans worth each minus recharge time, still beating 50, but removes the penalty for not recharging, so waiting dominates. The fix is to learn that includes the future cost of low battery.
Assumptions & Scope. This two-state robot is deliberately tiny so the effect is visible; real tasks have larger state spaces where the same misspecification is harder to spot. The numbers and are illustrative, not calibrated — the lesson is the direction of the effect, not the exact totals. Also, the illustration assumes the learner optimizes exactly; in practice optimization is approximate, so reward error and search error compound.
Visual: draw two timelines of 10 steps. Top timeline: "wait" every step, reward each, cumulative with flat line. Bottom timeline: "search when high, recharge when low" with rewards cumulative and rising faster. Label the flawed model's view where the flat line is drawn as if it ends higher.
17.9.3 Worked Examples
Example 1 — Loss on the robot table (high search match versus low recharge mismatch, loss ). Build a table with rows "high" and "low" and columns "expert action" and "learner action." Row high: expert search, learner search → match count . Row low: expert recharge, learner search → mismatch count . Total mismatch loss out of states. Adding a corrected demonstration at and retraining moves the learner toward matching that row. After retraining, both rows match and total loss drops to . Sense-check: with only two states the loss is integer, so improvement is discrete and visible.
Example 2 — Effect of fixed reward error (waiting every step versus searching causing lazy policy). Keep the reward for "wait" at and for "search when high" at . An agent that learns but underestimates the future cost of not recharging will prefer wait repeatedly. Concretely, over steps waiting gives under the flawed model. A correct model knows that waiting while low still leaves you low, while recharging resets to high and enables future 's, so a search-recharge cycle averaging per step yields over steps and is truly better. The expert's policy, derived from the true reward, would recharge at low battery and then search again, achieving higher long-term return than the lazy waiter once the horizon is long. The error persists until is corrected to penalize stuck-in-low.
17.9.4 Industry Applications
Real-world: In warehouse robots, a reward that only counts short-term pick count can produce a policy that never charges, leading to mid-shift failures. Correct reward design adds a term for battery health, learned from expert demonstrations of when a good operator chooses to charge. Concretely, if the dispatcher's demos show charging at 30% battery even though picks are pending, an inverse-RL reward that includes will learn a negative weight for "search while low," reproducing the expert's charging behavior and avoiding the lazy wait-like failure.
Pitfalls — Misreading the robot lesson. (1) Thinking the numbers vs are universal — they are example values showing the mechanism. (2) Concluding that waiting is always bad — in some tasks waiting is optimal; the point is the model must reflect the true cost. (3) Assuming more demos of searching automatically fix a misspecified reward — if reward features lack a battery term, no amount of search demos will teach recharging; the feature set must include the relevant signal.
17.9.5 Exam Notes
Exam note: This illustration is meant to give intuition for "deviation between your behavior and the expert's behavior is minimal" and for "what happens if reward modeling is not good." No detailed numerical exam question is built around it; the takeaway is the conceptual link between the reward you learn and the policy that follows. Be able to state the two-state table, point out the mismatch at , and explain how a flawed with for waiting can make a lazy policy look attractive while the expert's recharge-when-low rule is optimal under the true reward.
Recap & Bridge. The recycling robot with high/low battery and actions search/recharge makes two ideas tangible: behavior alignment is measured as mismatch count per state, and reward misspecification — waiting at seeming to beat searching at — can flip the optimal policy. Both illustrate the broader lecture arc: imitation starts by copying actions, but lasting skill requires either interactive state coverage (DAgger) or intent inference (inverse RL) that respects true task costs.
Exam Guidance Summary
This session contained several explicit signals about what matters for assessment and what does not:
- The numerical depth on TPO loss functions covered previously is not in scope for this course and was skipped for exam preparation.
- Imitation learning itself is in scope. Be able to define it, explain expert demonstrations as state-action pairs, and describe the supervised reduction.
- Behavior cloning: know the objective "minimize expected loss on the expert's state distribution," write with definitions of each symbol, and write the squared-error loss . Know why it is simple and when it works. Expect conceptual questions, not long numerical drills.
- Distribution mismatch and compounding error: be able to narrate the blue-expert versus red-learner drift, define versus , and explain "small deviation to unseen state to larger error to crash." Be ready to write for training and for deployment and note .
- DAgger: memorize and reproduce the full loop — , random , mixture with decay, rollout of , expert relabeling to form , aggregation , retraining. Know the stochastic form with probability . Explain why each line helps. No heavy numerical is expected; the slides attributed to a teaching assistant contain numbers for reference only and are not the focus.
- Inverse reinforcement learning: contrast forward with inverse . Write the linear reward and explain that it learns the intent behind behavior. Be ready to give a real-life example such as player intent in soccer or reward modeling for interactive language models that learn user satisfaction.
- Recycling robot: treat it as intuition for behavior alignment and for "poor reward gives poor policy, e.g., waiting at looks better than searching at when the model is wrong," not as a calculation drill. Know the high/low table and the mismatch count.
- Optional topics listed in the shared notes should be ignored. Study from the instructor's notes using the guidance from the class, paying attention to the motivation with which the notes were written in elaborate form.
Real-world exam advice that was shared: write all assumptions explicitly, present work in a table when the problem is tabular so grading is easier, and focus revision on the concepts emphasized live rather than on optional numerical appendices.
Exam note: Prioritize definitions, objectives with expectations, the red/blue drift story, the DAgger loop with decay and , and the forward/inverse contrast with . Practice writing each formula with symbol definitions and a one-line intuition. That set covers the majority of likely questions.
Key Industry Applications
- Autonomous driving lane-keeping (NAVLAB pattern): Camera view plus human steering logged as pairs; a network maps view to wheel angle; behavior cloning provides the baseline, DAgger-style human takeovers enrich the dataset with recovery states. Carnegie Mellon NAVLAB showed this works even with a simple network on a confined road.
- Game ghosting and strategy: Soccer and basketball trajectories from many past games create ghost overlays of "what an average or expert player would do here"; deviation detection and learned trajectory models feed coaching, opponent modeling, and play design; the same multi-trajectory learning extends to any setting with many recorded human plays. Ghost trajectories superimposed on live play make the expected policy visible.
- Helicopter acrobatics and robotics: Difficult maneuvers that are hard to encode as a reward are learned from demonstrations, as shown in Stanford helicopter work co-authored by Andrew Ng; similarly, surgical or assembly robots copy skilled operator traces. The demo trace carries timing that manual reward writing misses.
- Reward modeling for interactive systems: Language-model interaction is framed as learning the user's hidden reward — what kind of answer the user values — so that the system can produce responses that maximize that inferred reward; this is a direct applied use of inverse reinforcement learning ideas, where the learned scores prompt-response pairs by satisfaction and helpfulness.
- Warehouse and field robots: The recycling-robot intuition generalizes to battery-aware policies; a misspecified reward that rewards idling at can make a lazy wait-loop look optimal, so learning a reward that reflects true expert trade-offs — for example, weighting battery health alongside pick count — is essential for long-horizon performance.
Takeaway — Where imitation fits in practice. Use behavior cloning for a fast baseline where demos are plentiful, add DAgger-style aggregation where the learner's own states diverge from demo states, and use inverse RL / reward modeling where intent must transfer to new settings. The three families cover "copy the action," "cover the state's you will actually see," and "learn why the expert acts."
DRL Lecture 17 notes · Imitation Learning
Sections Breakdown
Imitation copies an expert via state-action demos to avoid hand-crafting rewards; learner vs expert roles and the behave-like-your-boss motivation define the problem.
States and actions form pairs (s,a); the racing track turns expert driving into millions of supervised examples for a policy pi: S->A, but the IID supervised view ignores sequential dependence.
Running imitation needs a policy class Pi, loss, optimizer, demonstrator, and practice environment; the gap hat_a vs a* averaged over expert states is the training objective.
NAVLAB at Carnegie Mellon, ghosting in soccer/basketball, and Stanford helicopter with Andrew Ng illustrate imitation from simple lane keeping to trajectory ghosts to acrobatic control.
Behavior cloning minimizes expected loss over rho_pi* with objective argmin E[L(hat_pi_theta(s), pi*(s))] and squared-error instantiation; track labels and a single-step with loss 4 illustrate it.
Naive cloning drifts: small error puts the learner off the blue expert track into unseen red states where errors compound, formalized as s~rho_pi* at training vs s~rho_hat_pi at deployment.
DAgger aggregates datasets from mixtures pi_i = beta_i pi* + (1-beta_i) hat_pi_i with beta decay and relabeling D_i, so training covers learner-visited states.
Forward RL: (S,A,P,R)->pi*; inverse RL: demos+(S,A,P)->hat_R->hat_pi; linear reward R_theta(s,a)=theta^T phi+bias and nonlinear f_theta model intent for transfer, e.g., soccer intent and language-model satisfaction.
Two-state recycling robot (high/low, search/recharge) shows behavior mismatch loss 1/2 and how flawed reward 0.5 for waiting beats 1 for searching and flips the optimal policy.
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
What Imitation Learning Is and Why It Matters
Must-know: Imitation = copy expert state-action behavior when reward is hard to write but demos are easy to get.
⚠️ Top pitfall: Thinking copying alone suffices forever; it caps at expert level and misses novel states.
Self-check: When is imitation preferred over reward writing?
Connects to: 17.2, 17.5
From States and Actions to Supervised Examples — The Track Intuition
Must-know: Policy pi: S->A maps states to actions; track shows many (s,a) pairs yet supervised treatment misses that actions create next states.
⚠️ Top pitfall: Assuming independent predictions suffice; they miss sequential dependence where one action shapes the next state.
Self-check: Write the policy mapping and explain red vs green marks on the track diagram.
Connects to: 17.5, 17.6
What You Need to Run Imitation Learning
Must-know: Five ingredients: Pi, loss, optimizer, demonstrator, environment; training matches hat_pi to pi* on rho_pi*
⚠️ Top pitfall: Forgetting the practice environment or assuming a fixed log suffices for interactive correction.
Self-check: Name the five ingredients and what distribution the loss averages over.
Connects to: 17.5, 17.7
Early Success Stories — Autonomous Driving, Ghosting in Games, and Helicopter Acrobatics
Must-know: NAVLAB = simple net copies human steering; ghosting = expected trajectories overlaid on live play; Stanford helicopter copies pilot for flips.
⚠️ Top pitfall: Thinking ghosts show optimal play; they show historical norms and need filtering by skill.
Self-check: Name the three early examples and the (s,a) pattern in each.
Connects to: 17.5, 17.8
Behavior Cloning — Cloning an Expert with Supervised Learning
Must-know: BC objective: hat_theta = argmin E_{s~rho_pi*}[L(hat_pi_theta(s), pi*(s))]; squared loss ||hat_pi-pi*||^2 or (hat_a-a*)^2
⚠️ Top pitfall: Evaluating only on rho_pi* held-out data and thinking it predicts rollout performance.
Self-check: Write the BC objective and compute loss for hat_a=-3 vs a*=-5.
Connects to: 17.6, 17.7
Why Naive Cloning Fails — Compounding Error and Distribution Mismatch
Must-know: Distribution mismatch: train on rho_pi*, test on rho_hat_pi; small deviation -> unseen state -> larger error -> crash; quadratic in horizon.
⚠️ Top pitfall: Blaming network size; missing off-track data is the cause, not capacity.
Self-check: Draw the blue vs red track and name the two distributions.
Connects to: 17.7
Fixing the Mismatch with an Interactive Expert — DAgger
Must-know: Loop: D empty, random hat_pi1, mixture pi_i with beta_i, rollout pi_i, relabel with pi* into D_i, aggregate D<-D U D_i, retrain, beta decay.
⚠️ Top pitfall: Training only on latest D_i and forgetting via discarding old data; aggregation prevents forgetting.
Self-check: Write the DAgger mixture and the aggregation update.
Connects to: 17.6, 17.8
Inverse Reinforcement Learning — Learning the Reward Behind the Behavior
Must-know: Inverse RL learns hat_R from demos; linear form theta^T phi + theta0; forward vs inverse contrast and transfer advantage.
⚠️ Top pitfall: Thinking IRL output is a policy; it is a reward, still needs RL to get pi; reward is not unique.
Self-check: Contrast forward (R->pi) vs inverse (demos->R->pi) and write the linear reward.
Connects to: 17.9, 17.5
A Small Concrete Illustration — The Recycling Robot and Poor Reward Design
Must-know: Table high->search vs low->recharge; mismatch 1; 100 steps waiting 0.5 gives 50 but true optimum needs recharge to harvest future 1s.
⚠️ Top pitfall: Treating 0.5 vs 1 as universal numbers; they illustrate reward misspecification direction.
Self-check: Fill the high/low table and explain why waiting looks better under the flawed reward.
Connects to: 17.8, 17.6
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.