Off-policy evaluation: estimate a policy before running it
离策略评估
Compute importance weights, doubly robust estimates and effective sample size from logged behavior probabilities, retaining actual small-sample errors.
off-policy-evaluationA log from a cautious policy can mislead an adventurous one
Suppose an old policy usually exits a two-stage task early. A proposed policy continues much more often and frequently chooses an action the old policy rarely took. Averaging the old returns answers how the old behavior performed, not how the proposed policy would perform.
Off-policy evaluation (OPE) estimates the return of a target policy from data collected by another behavior. It is a question about a specified policy, not itself a method for discovering a better one. The target can be learned on other data, but using the evaluation sample repeatedly to select it changes the statistical problem. Fixed-policy evaluation and independence
Our original finite example has a true target return of −0.752 and behavior return of 0.4945. These truths are available because we constructed the simulator. The estimators only receive logs, their recorded action probabilities and a value model fit on separate logs. Some finite samples look reassuring while missing the rare harmful action entirely.
Reweight actions without changing the environment
Assume independent complete trajectories, the same initial-state distribution and environment law, sufficient recorded state, and known behavior probabilities . The target and any fitted nuisance models are fixed relative to the evaluation sample. Whenever the target can take an action at a reachable history, the behavior must give that action positive probability. Under these assumptions, environment factors cancel from the trajectory likelihood ratio:
For a finite common horizon, early terminal paths can be padded by zero rewards and absorbing-state ratios of one. In our code they are simply stopped at their true terminal transition. Changed initial distributions would require an additional correction; hidden information used by the behavior can also invalidate the stated cancellation. Positive probabilities on observed actions alone do not prove coverage of actions that never appear. Importance sampling setup Finite-horizon assumptions
With trajectories, trajectory importance sampling and per-decision importance sampling (PDIS) use different weights:
An early reward does not depend on later sampled actions. PDIS removes those later factors from that reward’s weight. Both estimators are unbiased under the fixed-target and correct-probability assumptions, but products of ratios can make variance very large. “Unbiased” describes an expectation over datasets, not the accuracy of this particular estimate. IS and step-wise IS
Weighted or self-normalized IS divides by the observed total weight:
It is generally biased at finite . If there is one trajectory and its weight is positive, the weight cancels and WIS equals that trajectory’s observed return. In this example its expectation is then 0.4945 rather than −0.752. Normalization can stabilize estimates, but stability is not unbiasedness. A zero denominator must be reported, not replaced with a fabricated zero estimate. WIS
A direct method instead fits an approximate value function. Its state value is the target-policy average of its action values, and its estimate averages initial-state predictions:
Time-to-go must be part of the state or value index when a finite-horizon problem revisits the same physical state at different times. A direct method can be wrong because of model misspecification or missing data even when its output barely varies between datasets. Regression estimators
Doubly robust does not mean immune to two errors. In a one-step contextual problem, let be the true conditional mean reward, an independently fitted reward model, and a positive propensity model. Conditional on the context, the bias of the DR combination is:
This identity shows why an exact propensity model or exact reward model cancels the bias in this fixed-nuisance setting. Estimated functions are not automatically exact; consistency statements need their own conditions. Correlation with the evaluation sample can also invalidate this simple calculation. The cited sequential paper distinguishes the unknown-propensity asymptotic motivation from its known-probability variance analysis. Bandit DR and independence
For sequential decisions, correct each predicted action value with a weighted temporal residual:
With correct ratios, the predicted-value terms cancel in expectation even if the independent Q-model is inaccurate. With an exact target Q-function, the residuals have conditional mean zero even under a fixed incorrect positive propensity model. Those observations do not recover an unknown action’s reward from a structurally unsupported log. The equivalent backward recursion, with zero continuation at the terminal boundary, is:
Setting makes DR equal PDIS. A good Q-model can reduce action-selection variance, but cannot remove all transition or reward randomness. Independent exact-path checks for our stochastic task give single-trajectory variances of about 17.0981 for DR with the true Q-function and 84.6596 for PDIS. These are analytic finite-distribution calculations, not variances estimated from eight runs. Sequential DR and variance
Two diagnostics answer narrower questions than “is the estimate trustworthy?” For final trajectory weights, and for per-trajectory IS, PDIS or DR values :
ESS measures concentration among observed weights; it does not inspect unseen actions. The standard error is a sample estimate under the independence assumptions. Heavy weights and a small sample make an automatic normal confidence interval unreliable; rigorous bounds also need bounds or tail assumptions on the estimator itself. Counting correlated transitions as independent trajectories would shrink an error bar without creating information. Confidence intervals and remaining variance
Fit the value model on different trajectories
The target action probabilities are [0.2, 0.8] at the entrance and [0.3, 0.7] at the second decision. The behavior uses [0.7, 0.3] and [0.95, 0.05]. Exiting earns 0.4. Unlike the deterministic example in the offline-RL article, continuing costs 0.05, and the final reward is a mean of 1 or −2 plus equiprobable noise −1 or +1. Discount is 0.9.
These numbers give target value . The rare final action has ratio ; after the continuing entrance action its trajectory weight is . A single such trajectory can dominate 64 samples.
Each run fits a tabular target Q-model on 256 independently generated trajectories, then evaluates on a separate set of 64. Two backward fitting passes suffice for this two-stage graph. An unobserved pair retains a declared zero prior, not a claim that its true value is zero. The target is fixed throughout; the evaluation set does not choose the model or policy.
The program calculates DM, IS, PDIS, DR, WIS, trajectory ESS, plug-in standard errors, and an IS variant that caps the final weight at 5. Capping changes the estimator and generally introduces bias. Full per-trajectory values remain in experiment(); the CLI omits them from its summary. The check of population overlap uses the simulator’s known behavior table. Real logs cannot always certify that condition merely from their observed propensities.
For trajectories of length at most and a supplied Q-model, these estimators use time and stored per-trajectory summaries. This small implementation’s value fitting repeatedly scans the logged transitions for each table cell, so its cost also includes the number of states and actions; it is not a scalable fitting library. No new target-policy rollout is used to produce an estimate. exact_value is a separate teaching oracle for comparison.
"""Original finite-trajectory off-policy estimators with independent model fitting.
Known logged propensities, two-stage Markov task, NumPy only; no deployment claim.
"""
import json
import numpy as np
GAMMA=.9
TARGET=np.array([[.2,.8],[.3,.7]])
def policy(p):
p=np.asarray(p,dtype=float)
if p.shape!=(2,2) or not np.isfinite(p).all() or np.any(p<0) or not np.allclose(p.sum(1),1,rtol=0,atol=1e-12):
raise ValueError('Two finite action distributions required')
return p
def overlap(target,behavior):
target,behavior=policy(target),policy(behavior)
if np.any((target>0)&(behavior==0)):raise ValueError('Target action lacks behavior support')
def generate(seed,n=64,behavior=None):
mu=policy(np.array([[.7,.3],[.95,.05]]) if behavior is None else behavior)
if isinstance(n,bool) or not isinstance(n,(int,np.integer)) or n<1:raise ValueError('Positive trajectory count required')
rng=np.random.default_rng(seed);data=[]
for _ in range(n):
state=0;episode=[]
while state!=2:
action=int(rng.random()<mu[state,1]);prob=float(mu[state,action])
if state==0:
nxt,reward,done=(2,.4,True) if action==0 else (1,-.05,False)
else:
nxt,done=2,True
reward=(1. if action==0 else -2.)+rng.choice([-1.,1.])
episode.append((state,action,float(reward),nxt,done,prob));state=nxt
data.append(episode)
return data
def validate_episode(episode):
if not episode or len(episode)>2:raise ValueError('Complete one/two-step episode required')
expected=0
for i,row in enumerate(episode):
if len(row)!=6:raise ValueError('Malformed transition')
s,a,r,nxt,done,p=row
if s!=expected or s not in (0,1) or a not in (0,1) or not np.isfinite(r):raise ValueError('Invalid state/action/reward')
if done not in (False,True) or bool(done)!=(nxt==2) or bool(done)!=(i==len(episode)-1):raise ValueError('Invalid true terminal boundary')
if nxt not in (1,2) or not np.isfinite(p) or not 0<p<=1:raise ValueError('Invalid transition or logged probability')
if nxt!=(1 if s==0 and a==1 else 2):raise ValueError('Transition violates the two-stage task')
expected=nxt
def fit_q(data,target=TARGET):
pi=policy(target)
if not data:raise ValueError('Need separate fitting data')
rows=[]
for ep in data:validate_episode(ep);rows.extend(ep)
q=np.zeros((3,2))
for _ in range(2):
values=np.r_[np.sum(pi*q[:2],axis=1),0.];new=q.copy()
for s in (0,1):
for a in (0,1):
observed=[r+GAMMA*(0. if done else values[nxt]) for st,ac,r,nxt,done,p in rows if st==s and ac==a]
if observed:new[s,a]=np.mean(observed)
q=new
return q # Unobserved pairs retain a declared zero prior, not a proof of value0.
def per_episode(episode,target,q,propensity_model=None,clip=5.):
validate_episode(episode);pi=policy(target);q=np.asarray(q,dtype=float)
if q.shape!=(3,2) or not np.isfinite(q).all() or np.any(q[2]!=0):raise ValueError('Finite value table with terminal zeros required')
if not np.isfinite(clip) or clip<=0:raise ValueError('Positive weight cap required')
mu_hat=policy(propensity_model) if propensity_model is not None else None
values=np.r_[np.sum(pi*q[:2],axis=1),0.]
weight=1.;discount=1.;ret=0.;pdis=0.;dr=float(values[0])
for s,a,r,nxt,done,logged in episode:
denominator=logged if mu_hat is None else mu_hat[s,a]
if denominator<=0:raise ValueError('Zero modeled probability for a logged action')
weight*=pi[s,a]/denominator;ret+=discount*r;pdis+=discount*weight*r
residual=r+GAMMA*(0. if done else values[nxt])-q[s,a]
dr+=discount*weight*residual;discount*=GAMMA
return dict(dm=float(values[0]),is_value=float(weight*ret),pdis=float(pdis),dr=float(dr),
weight=float(weight),observed_return=float(ret),clipped_is=float(min(weight,clip)*ret))
def estimate(data,target,q,behavior,propensity_model=None):
if not data:raise ValueError('Need evaluation trajectories')
overlap(target,behavior) # A simulator-known check; logs alone cannot certify all missing actions.
rows=[per_episode(ep,target,q,propensity_model) for ep in data]
weights=np.array([r['weight'] for r in rows]);total=float(weights.sum())
means={k:float(np.mean([r[k] for r in rows])) for k in ('dm','is_value','pdis','dr','clipped_is','observed_return')}
se={k:float(np.std([r[k] for r in rows],ddof=1)/np.sqrt(len(rows))) if len(rows)>1 else None for k in ('is_value','pdis','dr')}
return dict(**means,wis=float(sum(r['weight']*r['observed_return'] for r in rows)/total) if total>0 else None,
effective_sample_size=float(total**2/(weights@weights)) if total>0 else 0.,
weight_mean=float(weights.mean()),max_weight=float(weights.max()),standard_errors=se,
trajectories=len(rows),rows=rows)
def exact_value(target=TARGET):
pi=policy(target)
return float(pi[0,0]*.4+pi[0,1]*(-.05+GAMMA*(pi[1,0]*1.+pi[1,1]*-2.)))
def experiment(seed=0):
mu=np.array([[.7,.3],[.95,.05]])
training=generate(10000+seed,256,mu);evaluation=generate(seed,64,mu)
q=fit_q(training);result=estimate(evaluation,TARGET,q,mu)
counts=np.zeros((2,2),dtype=int)
for ep in evaluation:
for s,a,*_ in ep:counts[s,a]+=1
return dict(seed=seed,target=TARGET.tolist(),behavior=mu.tolist(),
fitting_trajectories=256,fitting_transitions=sum(map(len,training)),
evaluation_transitions=sum(map(len,evaluation)),evaluation_counts=counts.tolist(),
q_fitted=q.tolist(),true_target_value=exact_value(),true_behavior_value=exact_value(mu),estimates=result)
if __name__=='__main__':
result=experiment();result['estimates'].pop('rows')
print(json.dumps(result,indent=2))
Inspect the recorded summary
{
"seed": 0,
"target": [
[
0.2,
0.8
],
[
0.3,
0.7
]
],
"behavior": [
[
0.7,
0.3
],
[
0.95,
0.05
]
],
"fitting_trajectories": 256,
"fitting_transitions": 337,
"evaluation_transitions": 78,
"evaluation_counts": [
[
50,
14
],
[
13,
1
]
],
"q_fitted": [
[
0.3999999999999999,
-0.7199999999999999
],
[
0.8888888888888888,
-1.4444444444444444
],
[
0.0,
0.0
]
],
"true_target_value": -0.7519999999999998,
"true_behavior_value": 0.49449999999999994,
"estimates": {
"dm": -0.496,
"is_value": -1.4050125313283208,
"pdis": -1.3964598997493738,
"dr": -1.3310877192982458,
"clipped_is": -0.015689614661654125,
"observed_return": 0.4,
"wis": -1.4372055760294822,
"effective_sample_size": 2.7820460052313094,
"weight_mean": 0.9776002506265666,
"max_weight": 37.333333333333336,
"standard_errors": {
"is_value": 1.6080179928194722,
"pdis": 1.5805962063616592,
"dr": 0.8174603131914269
},
"trajectories": 64
}
}All eight runs use the same fixed target and behavior, with new fitting and evaluation streams. The true target value is −0.752 in every row; displayed numbers are rounded to five decimals.
| Seed | IS | DR | WIS | ESS |
|---|---|---|---|---|
| 0 | −1.40501 | −1.33109 | −1.43721 | 2.78205 |
| 1 | −0.23490 | −0.21931 | −0.22248 | 3.23222 |
| 2 | 0.30714 | −0.89656 | 0.69458 | 48.48364 |
| 3 | −1.34862 | −1.32063 | −1.30964 | 3.07861 |
| 4 | 0.26466 | −0.75230 | 0.62301 | 48.42475 |
| 5 | −2.94724 | −1.80166 | −1.86234 | 3.66020 |
| 6 | 0.29323 | −0.70742 | 0.71972 | 48.53207 |
| 7 | −2.45320 | −0.22622 | −1.13499 | 4.56001 |
In seed 0, PDIS is −1.39646, while capped IS is −0.01569; the smoother-looking capped result is far from the truth. The logged entrance counts are 50/14 and final-action counts 13/1. Seeds 2, 4 and 6 see no rare harmful final action, yet their empirical ESS values are near 48. The absence of a large observed weight does not prove the absence of a coverage problem.
The independent tests enumerate all five possible paths and their probabilities, including reward noise. They verify exact expectations with deliberately wrong Q-models, correct Q with wrong propensities, failure when both are wrong, residual variance, normalization bias and clipping bias. Eight random runs illustrate finite-sample behavior; they cannot by themselves prove unbiasedness.
An estimate and a deployment decision are different objects
The example has known propensities, complete short trajectories, a fixed initial state and a stable fully observed environment. In practice, action probabilities may not be recorded, observations may omit variables used by the behavior, and logging conditions may change. Replacing a missing propensity with an empirical frequency does not automatically restore the likelihood-ratio assumptions.
Separate model fitting, policy selection and final evaluation. Cross-fitting nuisance models can help use data efficiently while holding the target fixed. If each fold instead evaluates a different newly trained target, the average need not estimate the final policy trained on all data. Repeatedly picking the best noisy OPE score also creates selection bias.
WIS and clipping trade variance against bias; DR can still have enormous variance with good nuisance models. Report the estimand, overlap assumptions, data split, weight distribution and uncertainty method together. A plausible score or narrow heuristic error bar is not a guarantee of safe deployment.
Which part of the estimate deserves doubt?
-
The target takes a rare action with probability 0.7 and the behavior with probability 0.05. The preceding action has target/behavior probabilities 0.8/0.3. What weight applies to the final reward, and why should an earlier reward use less history?
Answer: The final prefix weight is . PDIS uses only on the preceding reward because that reward arrives before the second action. Multiplying by the later ratio adds irrelevant sampling variation to it.
-
With a single trajectory and a positive target weight, WIS gives its observed return. Is it unbiased for the new policy in this experiment?
Answer: No. The ratio cancels, so its expectation is the behavior value 0.4945 rather than target value −0.752. This is an explicit finite-sample counterexample; consistency as sample size grows is a different statement.
-
An estimated Q-function is exactly correct. Must every DR sample equal the true policy value? What does Q equal to zero produce?
Answer: No. Real rewards here still fluctuate by ±1; their weighted residuals do not vanish sample by sample. Exact enumeration gives positive DR variance about 17.0981. With Q identically zero, the DR expression reduces to PDIS, not to an accurate direct model.
-
A run has ESS near 48 out of 64, but no rare harmful action in its evaluation set. Can it establish good target-policy performance? What should happen when every final target weight is zero?
Answer: The ESS only describes the weights that appeared, so it cannot certify coverage or performance; this pattern actually occurs in seeds 2, 4 and 6. When all final weights are zero, WIS is undefined: the code reports
Noneand ESS zero. More relevant data or explicitly justified assumptions are needed, not a fabricated estimate of zero.
The correction is statistical, not a substitute for evidence
The 2016 paper extends the bandit DR idea to sequential decisions and makes the independence requirement explicit. The offline-RL tutorial places these estimators alongside other ways of using a fixed dataset. Their mathematical statements apply under the assumptions actually supplied; neither source makes finite logged data reveal every unobserved consequence. Sequential DR paper Offline tutorial
Read importance sampling for the basic change of distribution, policy evaluation for Bellman-based values, and offline reinforcement learning for the separate problem of learning a policy. The two teaching programs share a two-stage structure but intentionally differ in continuing cost and reward noise.
Make a prediction, then check
Does a relatively high effective sample size prove that the target policy’s important actions have been covered?
Learning objectives
- Compute trajectory and prefix-weighted IS and state the overlap and stable-environment assumptions.
- Derive sequential DR with independent fitting/evaluation data and distinguish unbiasedness, variance, ESS and confidence claims.
Prerequisites & connections
Explore related knowledge →References
- Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems — arXiv v3
Sergey Levine; Aviral Kumar; George Tucker; Justin Fu · 2020 - Doubly Robust Off-policy Value Evaluation for Reinforcement Learning — scoped ICML paper
Nan Jiang; Lihong Li · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Selected v3 dated2020-11-01, first submitted2020-05-04. Read pages7/9/10/18/19 of43 and650 identity characters on page1. Fixed data, distribution shifts, IS/WIS and unseen-action backups; neither the2020 sufficiency footnote nor unverified original imitation bounds are current universal conclusions. Not a full-paper audit. ICML2016, PMLR48:652–661. Read2–4 of10 pages and650 identity characters on page1, viewed4. IS/PDIS/WIS, bandit/sequential DR, independent evaluation data and reward-noise variance. Unknown-propensity asymptotics separated from known-probability unbiasedness; no full appendix/benchmark audit or DR-v2 reproduction. 8 paired equations and four explained exercises. Fixed target and independent fitted-Q/evaluation logs. Five-path exact enumeration checks IS/PDIS/DR expectations, correct-Q/wrong-propensity robustness, both-wrong bias, normalization and clipping bias, and residual reward variance. All8seeds retained; high empirical ESS does not certify rare-action coverage. Zero WIS denominator is undefined, not zero value; no deployment guarantee.
- Fixed target and independent fitted-Q/evaluation logs. Five-path exact enumeration checks IS/PDIS/DR expectations, correct-Q/wrong-propensity robustness, both-wrong bias, normalization and clipping bias, and residual reward variance. All8seeds retained; high empirical ESS does not certify rare-action coverage. Zero WIS denominator is undefined, not zero value; no deployment guarantee.
- Four computed SVG variants per topic;9 numeric/geometry tests and12 current responsive cases passed. All six selected current captures directly viewed; no figure failure or post-capture asset edit in this group. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems — arXiv v3 · Selected v3 dated2020-11-01, first submitted2020-05-04. Read pages7/9/10/18/19 of43 and650 identity characters on page1. Fixed data, distribution shifts, IS/WIS and unseen-action backups; neither the2020 sufficiency footnote nor unverified original imitation bounds are current universal conclusions. Not a full-paper audit.
- Doubly Robust Off-policy Value Evaluation for Reinforcement Learning — scoped ICML paper · ICML2016, PMLR48:652–661. Read2–4 of10 pages and650 identity characters on page1, viewed4. IS/PDIS/WIS, bandit/sequential DR, independent evaluation data and reward-noise variance. Unknown-propensity asymptotics separated from known-probability unbiasedness; no full appendix/benchmark audit or DR-v2 reproduction.
Related topics