Inverse reinforcement learning: what can choices tell us about rewards?
逆强化学习
Move from reward ambiguity to maximum-entropy feature matching, learn preferences from four routes, and test a changed map.
inverse-rlThe same route can have different reasons
Someone takes a longer route through a park every day. Do they like shade, dislike crowds, or simply not know the shortcut? The route supplies behavioral evidence, not a reward function. Inverse reinforcement learning (IRL) models the environment and decision maker, then seeks rewards that explain observed behavior. Planning or reinforcement learning can produce a policy from an inferred reward.
Ordinary RL takes rewards as given and asks how to act. IRL takes behavior as given and asks which rewards are compatible with it. Behavior cloning can imitate actions directly without inferring rewards. The extra reward model in IRL may support reusing preferences, but it adds assumptions about dynamics, features and decisions. The problem and its ambiguities
Our explicitly fictional example has a two-step route graph. Each segment has shade score, crowding score and step count as features. The four route totals are (0,0,2), (0,1,2), (1,1,2) and (2,0,2). A demonstrator prefers shade and avoids crowds but chooses stochastically. The program learns the first two weights from 128 demonstrations, then encounters a map with one segment’s features changed.
Before asking whether the recovered reward is exactly correct, notice that every route has two steps. Adding the same reward constant at each step adds the same total score to all four routes, leaving their probabilities unchanged. No amount of data from these equal-length routes can identify that constant.
Behavior constrains rewards without specifying them uniquely
Start with an idealized setting: finite states, known transitions, a completely observed deterministic expert policy, state-only rewards and discount strictly between zero and one. Let Pπ be the policy’s transition matrix and Pa the matrix for any alternative action. Optimality requires the expert action to be no worse than deviating once and following the expert thereafter. The Bellman equation gives: Equation 4 for finite MDPs
The actions have the same immediate state reward, which cancels; the positive discount also divides out. These are linear inequalities in R. Zero rewards satisfy them for every policy, and constant rewards create ambiguity too. Finite demonstrations, stochastic experts, action-dependent rewards or unknown transitions require changes to this formulation. Our main program instead models stochastic choice over finite deterministic routes; it does not solve this linear program.
A maximum-entropy route model matches expected demonstration features while adding as little further preference as possible. Let F sum features along a route. The constraints require probabilities to sum to one and expected features to match specified values. Differentiating entropy with Lagrange multipliers gives log probability equal to a linear feature score plus a constant. Normalization yields: The deterministic-path model
The initial state is fixed, the candidate set contains all legal finite deterministic paths, and temperature is fixed at one. This is not scoring demonstrations and normalizing only over observed routes: legal unobserved routes also belong in Z. A finite candidate set makes Z finite; our example has no convergence problem involving infinitely many looping paths.
Write the empirical mean feature vector as F with a bar. Maximizing demonstration likelihood is equivalent to minimizing the following objective. The program adds L2 regularization on the first two coordinates; the constant third weight is fixed at zero.
Differentiating log Z gives model-expected features. Differentiating again gives their covariance, supplying both the optimization direction and a convexity check:
Covariance is positive semidefinite, so negative log-likelihood is convex and log-likelihood is concave. Page 3 of the author’s corrected copy uses “convex” after defining a maximized L; we follow the signs derived above rather than copying that wording. Without regularization, a finite interior optimum matches model and empirical moments. With regularization they differ by λMθ, so exact feature matching is no longer the right claim. Original gradient and version scope
Distinguish two ambiguities. At fixed length, adding a constant leaves probabilities unchanged. If temperature is also unknown, only the ratio between score and temperature determines preferences. If only optimal actions are known, without selection frequencies, positive reward scaling also preserves action rankings.
When temperature is fixed at one, scaling θ alone generally sharpens the distribution rather than preserving all choice probabilities. Regularization or fixing a constant selects a representative; it does not reveal an additional true motive.
Route enumeration is easy to verify, but the number of paths can grow exponentially with the horizon. In a deterministic acyclic graph, work backward from the terminal state to accumulate weights of possible continuations. Let V be their log total and rθ the edge reward; the terminal has no extra action:
Products of these local action probabilities equal global path probabilities. Applying softmax only to immediate rewards would omit future alternatives. With stochastic dynamics, one must also avoid treating uncontrollable lucky outcomes as selectable behavior. Finite-horizon maximum causal entropy control at temperature one uses the expected future soft value:
Expected V and log expected exp(V) generally differ. Suppose there is just one action and the environment awards either zero or two with equal probability. The controller cannot change those one-half probabilities. Reweighting outcomes by exponentiated reward would assign the good outcome probability about 0.880797, creating nonexistent control. The 2008 author copy adds an approximation assumption for stochastic paths, and the causal-entropy implementation has separate horizon conventions; they are not interchangeable. Stochastic-path assumptions, fixed causal-entropy implementation
Rewards can also have dynamics-dependent equivalences. Adding a potential difference makes the discounted sum telescope:
With a fixed start and zero terminal potential, every policy return shifts by the same amount, preserving rankings. The terminal condition matters; variable-length tasks and unequal terminal potentials need a fresh analysis. This is an independently checked arithmetic counterexample here; the main fit still uses fixed, undiscounted two-step routes.
Learn four routes, then change one edge
The program uses only the Python standard library. Demonstrator weights (0.7,−0.5,0) are used for data generation and evaluation only; the fitting function cannot access them. Training uses 128 demonstrations. Another 512, generated from an independent random stream, are held out solely for evaluation. Training fixes 800 gradient steps, learning rate 0.15 and L2 coefficient 0.01, without using held-out results to select a budget or seed.
"""Original finite deterministic MaxEnt IRL. Enumerated paths; Python 3.11+."""
import json
import math
import random
# Each edge is (next state, three additive features). State 3 is terminal.
GRAPH = {0: [(1, (0., 0., 1.)), (2, (1., 0., 1.))],
1: [(3, (0., 0., 1.)), (3, (0., 1., 1.))],
2: [(3, (0., 1., 1.)), (3, (1., 0., 1.))]}
TRUE_WEIGHTS = (.7, -.5, 0.) # used only by the demonstrator and evaluation
def dot(a, b):
if len(a) != len(b):
raise ValueError('Feature dimensions differ')
return sum(x * y for x, y in zip(a, b))
def logsumexp(values):
if not values or not all(math.isfinite(x) for x in values):
raise ValueError('Nonempty finite scores required')
maximum = max(values)
return maximum + math.log(sum(math.exp(x - maximum) for x in values))
def paths(graph=GRAPH, state=0, visited=()):
if state == 3:
return [((), (0., 0., 0.))]
if state in visited or state not in graph or not graph[state]:
raise ValueError('Acyclic graph ending in terminal state 3 required')
output = []
for action, (next_state, features) in enumerate(graph[state]):
if len(features) != 3 or not all(math.isfinite(x) for x in features):
raise ValueError('Three finite edge features required')
for actions, rest in paths(graph, next_state, visited + (state,)):
output.append(((action,) + actions, tuple(x + y for x, y in zip(features, rest))))
return output
def distribution(weights, features):
scores = [dot(weights, f) for f in features]
normalizer = logsumexp(scores)
return [math.exp(x - normalizer) for x in scores], normalizer
def objective_gradient(weights, observed, features, l2=.01):
if not observed or not math.isfinite(l2) or l2 < 0:
raise ValueError('Nonempty demonstrations and nonnegative regularizer required')
if any(not isinstance(i, int) or not 0 <= i < len(features) for i in observed):
raise ValueError('Invalid demonstrated path')
probabilities, normalizer = distribution(weights, features)
empirical = [sum(features[i][k] for i in observed) / len(observed) for k in range(3)]
expected = [sum(p * f[k] for p, f in zip(probabilities, features)) for k in range(3)]
# The constant feature is fixed to zero, not recovered from demonstrations.
penalty = .5 * l2 * sum(x * x for x in weights[:2])
loss = normalizer - dot(weights, empirical) + penalty
gradient = [expected[k] - empirical[k] + (l2 * weights[k] if k < 2 else 0.) for k in range(3)]
return loss, gradient, empirical, expected
def fit(observed, features, steps=800, rate=.15, l2=.01):
if not isinstance(steps, int) or steps < 1 or not math.isfinite(rate) or rate <= 0:
raise ValueError('Positive optimization budget required')
weights, history = [0., 0., 0.], []
for i in range(steps):
loss, gradient, _, _ = objective_gradient(weights, observed, features, l2)
if i % 100 == 0:
history.append(dict(step=i, loss=loss))
for k in range(2):
weights[k] -= rate * gradient[k]
loss, gradient, empirical, expected = objective_gradient(weights, observed, features, l2)
history.append(dict(step=steps, loss=loss))
return dict(weights=weights, loss=loss, gradient=gradient, empirical=empirical,
expected=expected, history=history, gradient_steps=steps)
def soft_plan(weights, graph=GRAPH):
"""Independent backward dynamic programming; deterministic DAG only."""
paths(graph) # validate acyclicity and edge dimensions before recursion
values, policy = {3: 0.}, {}
def backward(state):
if state not in values:
q = [dot(weights, f) + backward(nxt) for nxt, f in graph[state]]
values[state] = logsumexp(q)
policy[state] = [math.exp(x - values[state]) for x in q]
return values[state]
backward(0)
return values, policy
def sample(probabilities, n, rng):
if not isinstance(n, int) or n < 1 or any(x < 0 for x in probabilities) or not math.isclose(sum(probabilities), 1.):
raise ValueError('Positive sample count and normalized probabilities required')
return rng.choices(range(len(probabilities)), weights=probabilities, k=n)
def experiment(seed=0):
items = paths()
features = [f for _, f in items]
true_p, _ = distribution(TRUE_WEIGHTS, features)
observed = sample(true_p, 128, random.Random(seed))
heldout = sample(true_p, 512, random.Random(seed + 1000))
learned = fit(observed, features)
estimated, _ = distribution(learned['weights'], features)
_, policy = soft_plan(learned['weights'])
changed = {s: list(edges) for s, edges in GRAPH.items()}
changed[1][1] = (3, (3., 1., 1.))
new_features = [f for _, f in paths(changed)]
choice = max(range(4), key=lambda i: dot(learned['weights'], new_features[i]))
new_rewards = [dot(TRUE_WEIGHTS, f) for f in new_features]
return dict(seed=seed, actions=[list(a) for a, _ in items], features=features,
demo_counts=[observed.count(i) for i in range(4)], true_probabilities=true_p,
estimated_probabilities=estimated, root_policy=policy[0], fit=learned,
heldout_nll=-sum(math.log(estimated[i]) for i in heldout) / len(heldout),
uniform_nll=math.log(4), exact_kl=sum(p * math.log(p / q) for p, q in zip(true_p, estimated)),
transfer_choice=choice, transfer_true_rewards=new_rewards,
transfer_regret=max(new_rewards) - new_rewards[choice],
demonstrations=128, heldout_demonstrations=512, enumerated_paths=4)
if __name__ == '__main__':
print(json.dumps(experiment(), indent=2))
Inspect the recorded summary
{
"seed": 0,
"actions": [
[
0,
0
],
[
0,
1
],
[
1,
0
],
[
1,
1
]
],
"features": [
[
0.0,
0.0,
2.0
],
[
0.0,
1.0,
2.0
],
[
1.0,
1.0,
2.0
],
[
2.0,
0.0,
2.0
]
],
"demo_counts": [
13,
6,
20,
89
],
"true_probabilities": [
0.1452826705669086,
0.08811839402376027,
0.1774486545432975,
0.5891502808660336
],
"estimated_probabilities": [
0.09858227756262193,
0.05712916218008818,
0.15145162807439086,
0.692836932182899
],
"root_policy": [
0.1557114397427101,
0.8442885602572898
],
"fit": {
"weights": [
0.9749515798481871,
-0.5455767972283652,
0.0
],
"loss": 0.9257967592560096,
"gradient": [
8.238670794191716e-09,
2.2282195385678327e-08,
0.0
],
"empirical": [
1.546875,
0.203125,
2.0
],
"expected": [
1.537125492440189,
0.20858079025447904,
2.0
],
"history": [
{
"step": 0,
"loss": 1.3862943611198906
},
{
"step": 100,
"loss": 0.9258526920335607
},
{
"step": 200,
"loss": 0.9257986242006041
},
{
"step": 300,
"loss": 0.9257968212471186
},
{
"step": 400,
"loss": 0.9257967613154878
},
{
"step": 500,
"loss": 0.9257967593244208
},
{
"step": 600,
"loss": 0.9257967592582793
},
{
"step": 700,
"loss": 0.9257967592560824
},
{
"step": 800,
"loss": 0.9257967592560096
}
],
"gradient_steps": 800
},
"heldout_nll": 1.099143178098365,
"uniform_nll": 1.3862943611198906,
"exact_kl": 0.027128098811312874,
"transfer_choice": 1,
"transfer_true_rewards": [
0.0,
1.5999999999999996,
0.19999999999999996,
1.4
],
"transfer_regret": 0.0,
"demonstrations": 128,
"heldout_demonstrations": 512,
"enumerated_paths": 4
}The program enumerates four paths for the partition function and separately checks route probabilities with backward recursion. Each gradient calculation rescans N demonstrations and M candidate paths: K steps with d-dimensional features cost O(K(N+M)d). It does not optimize this by caching empirical moments. soft_plan also calls complete path enumeration to validate its input, so the whole function cannot claim linear graph-traversal cost. Its backward recursion reuses subproblems; a large-graph implementation should validate without enumerating paths.
At seed 0, demonstration counts are 13, 6, 20 and 89. Learned weights are approximately 0.97495 and −0.54558, rather than the generating values 0.7 and −0.5. Estimated route probabilities are about 0.09858, 0.05713, 0.15145 and 0.69284; root action probabilities are about 0.15571 and 0.84429. Finite data and L2 regularization both affect the fit.
Now change the final edge on route 01 from features (0,1,1) to (3,1,1), leaving other edges unchanged. The four true route scores become 0, 1.6, 0.2 and 1.4, so the optimal route changes from 11 to 01. Feature meanings and true reward weights stay fixed; only known map features change. Those are explicit assumptions of this transfer test.
| Seed | Shade weight | Crowding weight | Exact old-map KL | New-map choice | True regret |
|---|---|---|---|---|---|
| 0 | 0.97495 | −0.54558 | 0.02713 | 01 | 0.0 |
| 1 | 0.69902 | −0.75802 | 0.00618 | 11 | 0.2 |
| 2 | 0.71817 | −0.49724 | 0.00011 | 01 | 0.0 |
| 3 | 0.78629 | −0.67945 | 0.00829 | 01 | 0.0 |
| 4 | 0.57619 | −0.29846 | 0.01428 | 01 | 0.0 |
| 5 | 0.58390 | −0.65259 | 0.00390 | 11 | 0.2 |
| 6 | 0.82363 | −0.28815 | 0.00469 | 01 | 0.0 |
| 7 | 0.54421 | −0.64699 | 0.00674 | 11 | 0.2 |
The KL direction is from the true demonstrator distribution to the learned distribution. It is exactly available only because we know the generating mechanism. All eight runs beat the uniform log4 baseline on held-out negative log-likelihood, but seeds 1, 5 and 7 choose incorrectly on the new graph. Route 01’s advantage over 11 depends on the sum of the two weights, so a small change can reverse the ranking. A good fit to old behavior is not reliable transfer decision-making.
The inferred preferences depend on assumptions
Identifiability, sample size and model error are separate issues. The constant third coordinate remains unidentified even with unlimited data from this task. The first two coordinates affect choice distributions but remain sensitive to finite sampling. If shade and crowding omit something the expert values, exact optimization can still fit the wrong explanation.
Reward inference also depends on assumptions about the expert’s information and rationality. An unknown map, habits, mistakes or different goals can produce similar behavior. Treating every action as optimal under a stable reward may just fit the wrong decision model. Our stochastic exponential-family demonstrator is a testable teaching assumption, not a universal psychological law.
Rewards equivalent in one environment may cease to be equivalent in another. If task preferences change, reusing old weights is unsupported. Changing feature units changes weight values and regularization effects. Behavioral fit, reward ambiguity and observed transfer are more informative than merely reporting that a reward was learned.
This program does not reproduce the Ng/Russell linear program, the paper’s road-navigation system or a complete causal-entropy library. Stochastic dynamics appear only in an uncontrollable-outcome counterexample, not a trained stochastic IRL experiment. Demonstrator identities and synthetic true rewards must not be smuggled into fitting.
What is identified, and what is still missing?
-
Every route has length two. If each step reward increases by seven, what happens to MaxEnt path probabilities? Does fixing the constant weight to zero identify its true value?
Answer: Every total score increases by fourteen. Numerators and the partition function are multiplied by exp14, leaving probabilities unchanged. Zero fixes a representative rather than identifying the true constant. Unequal route lengths invalidate this particular argument.
-
For one coordinate, the empirical feature mean is 1.2, the model mean is 0.9, θ=0.5 and λ=0.1. What is the regularized NLL gradient, and the weight after a step of size 0.2?
Answer: The gradient is 0.9−1.2+0.1×0.5=−0.25. Gradient descent gives 0.5−0.2×(−0.25)=0.55, increasing preference for routes with that feature. Regularized optima do not generally have zero moment mismatch.
-
There is one action, with a fair random reward of zero or two. Why is the approximately 0.880797 good-outcome probability obtained by exponentiated-reward reweighting not executable?
Answer: There is no alternative action, so the environment fixes that probability at one-half. Global reweighting changes uncontrollable outcomes as if the decision maker could select them. Causal control must preserve the transition probabilities.
-
Routes 01 and 11 on the changed map have features (3,1,2) and (2,0,2). Which does weight vector (0.69902,−0.75802,0) select, and what is lost under true weights (0.7,−0.5,0)?
Answer: The estimated advantage is the shade-plus-crowding weight, −0.059, so it selects 11. The true advantage is 0.7−0.5=0.2, giving regret 0.2. This is finite-data error near a decision boundary, not an effect of the unidentified third-coordinate constant.
Follow constraints, probabilities and control separately
The Ng/Russell finite-MDP characterization shows how behavior constrains rewards and why zero reward is a degenerate solution. Author archive The MaxEnt model shows how feature constraints yield path probabilities, why the partition function matters and why gradients compare moments. Author-corrected copy The author’s landing page identifies AAAI2008 and an algorithm correction. A 2010 PDF copyright line should not replace the conference year or be treated as a verified correction date.
When comparing implementations, follow causal entropy’s soft Bellman recursion and occupancy calculation, stating terminal, final-action and discount conventions explicitly. Fixed implementation More elaborate methods can change features, reward parameterization and fitting, but still need to say what is controllable, what data identify and what is selected only by modeling assumptions.
Make a prediction, then check
If all candidate routes have equal length, can their selection frequencies identify a constant added to every step reward?
Learning objectives
- Explain how behavior constrains rewards without uniquely determining them, and derive a finite-path MaxEnt objective, gradient and unidentifiable direction.
- Verify enumeration against backward planning, retain finite-sample transfer failures and distinguish deterministic-path MaxEnt from causal control with stochastic dynamics.
Prerequisites & connections
Explore related knowledge →References
- Algorithms for Inverse Reinforcement Learning — author archive, visual reading
Andrew Y. Ng; Stuart Russell · 2000 - Maximum Entropy Inverse Reinforcement Learning — author-corrected copy
Brian D. Ziebart; Andrew Maas; J. Andrew Bagnell; Anind K. Dey · 2008 - imitation — fixed BC, DAgger and maximum causal entropy implementation reading
HumanCompatibleAI/imitation contributors · 2025
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-24 · Single AI author. Scoped reading: ICML2000 author archive,8 pages. Text extraction is corrupted by font encoding; read rendered pages1–3. Known finite MDP, complete deterministic policy, state-only rewards, Equation4 for0<gamma<1 and zero/constant ambiguities. Remaining5 pages unread; no LP reproduction. Author landing page identifies AAAI2008 and an off-by-one correction; linked6-page copy has a2010 copyright line but no stated correction date. Read2–3 and viewed3. Finite deterministic paths, feature gradients and stochastic approximation; independently checked concave log-likelihood/convex NLL rather than copying page3 wording. No infinite-path convergence or later experimental audit. Fixed2025-01-07 commit. Read122-line README,21-line MIT license, bc40–155, dagger210–291/425–459, mce_irl38–144/467–498. Execution versus expert labels and causal entropy distinguished. Reference only, no copying/execution or blanket verification of branches/terminal/discount conventions. 8 paired equations and four explained exercises. Known-policy constraints, finite deterministic MaxEnt gradients/covariance Hessian, fixed constant/temperature and terminal shaping conditions independently checked. Enumeration agrees with backward planning; stochastic reweighting does not invent control. All8seeds retain three changed-map failures. True reward is absent from fitting, and author-copy convexity wording is corrected by derivation.
- Known-policy constraints, finite deterministic MaxEnt gradients/covariance Hessian, fixed constant/temperature and terminal shaping conditions independently checked. Enumeration agrees with backward planning; stochastic reweighting does not invent control. All8seeds retain three changed-map failures. True reward is absent from fitting, and author-copy convexity wording is corrected by derivation.
- Four computed SVG variants per topic;9 numeric/geometry tests and12 current responsive cases passed. All six selected current captures directly viewed after correcting the retained initial transfer color-domain failure. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- Algorithms for Inverse Reinforcement Learning — author archive, visual reading · ICML2000 author archive,8 pages. Text extraction is corrupted by font encoding; read rendered pages1–3. Known finite MDP, complete deterministic policy, state-only rewards, Equation4 for0<gamma<1 and zero/constant ambiguities. Remaining5 pages unread; no LP reproduction.
- Maximum Entropy Inverse Reinforcement Learning — author-corrected copy · Author landing page identifies AAAI2008 and an off-by-one correction; linked6-page copy has a2010 copyright line but no stated correction date. Read2–3 and viewed3. Finite deterministic paths, feature gradients and stochastic approximation; independently checked concave log-likelihood/convex NLL rather than copying page3 wording. No infinite-path convergence or later experimental audit.
- imitation — fixed BC, DAgger and maximum causal entropy implementation reading · Fixed2025-01-07 commit. Read122-line README,21-line MIT license, bc40–155, dagger210–291/425–459, mce_irl38–144/467–498. Execution versus expert labels and causal entropy distinguished. Reference only, no copying/execution or blanket verification of branches/terminal/discount conventions.
Related topics