Skip to content

Test a policy on old logs

Estimate how a new decision rule would have done from logs of the current one, using inverse propensity weights and doubly robust estimates.

Advanced ~13 min10 steps

What runs in CodeSplash

You will be able to

  • Say why logs alone can't show what a new policy would earn without propensities
  • Compute IPS and self-normalized IPS
  • Read effective sample size and weights as warnings

Read first

01

You only see what was shown

Read

You have logs from a system that chose offers: who saw what, and whether they converted. You've written a better rule, and you want to know how it would have done before you run it.

You can't observe that directly. You only saw the reward for the offer actually shown. That's the gap off-policy evaluationOff-policy evaluationEstimates how a new decision policy would have done, using only logs from the current policy. tries to close, and it needs one more column: the probability that the old system had of showing each offer, its propensity.

02

Why can't you average the matches?

Predict

Predict first

Take only rows where the old policy happened to choose what your new rule would. Average their rewards. Is that a fair estimate of the new rule?

Yes, that's unbiasedNo, the old policy's habits skew the sample
Reveal

No. The old policy shows some offers mostly to certain people, so the matched rows aren't a fair sample. Rare matches get too little say, and common ones too much. Weighting corrects that: each match counts by one over its propensity.

03

The estimators

Read

Inverse propensity scoring (IPS) reweights the matched rows:

V^IPS=1n∑i=1n1(ai=π(xi))pi ri\hat V_{\text{IPS}} = \frac{1}{n}\sum_{i=1}^{n} \frac{\mathbf{1}(a_i = \pi(x_i))}{p_i}\, r_i
  • IPS: unbiased when propensities are right and every offer had a chance. It's noisy.
  • Self-normalized IPS: divides by the sum of the weights. Slightly biased, usually steadier.
  • Direct method: predicts rewards with a model. Stable, and biased if the model is wrong.
  • Doubly robust: combines the model and the weights, and it's consistent if either one is right.
04

Compute it

Checkpoint

Check yourself

Four of 10 logged rows match the new policy. Their rewards and propensities are (1, 0.5), (0, 0.5), (1, 0.25) and (0, 0.25). What's the IPS estimate? Give one decimal.

Show the answer

Answer: 0.6

Weighted rewards: 1 / 0.5 = 2, then 0, then 1 / 0.25 = 4, then 0. They sum to 6. Divide by all 10 logged rows, not only the matches: 6 / 10 = 0.6.

05

Read a result

In the app
Off-policy evaluationRecorded · Python and R agreeRecorded 2026-11-17 · 30 values compared · largest relative difference 2.7e-15
R

The doubly robust estimate says the target policy would earn 0.406 per decision, 95% CI [0.365, 0.449], more than the 0.355 the logged policy earned (+0.050). 528 of 1,500 logged decisions agree with the target policy; the effective sample size of the importance weights is 512.

Target policy value (doubly robust)
0.4058
95% CI
[0.3648, 0.4489]
Logged policy value
0.3553
Effective sample size
512.15

Plots

Estimated value per decisionHow large are several estimates, how precise, and which exclude the null?
View data
ValueUpperEstimatorLower
0.42720.4795IPS0.3794
0.40770.4501Self-normalized IPS0.3681
0.42720.4795Clipped IPS0.3794
0.40480.4086Direct method0.4010
0.40580.4489Doubly robust0.3648
0.35530.3773Logged policy0.3327
Importance weights (rows where target = logged action)How is one numeric variable distributed?
View data
Weight
2.738
2.599
2.539
3.901
2.743
2.452
3.771
2.856
2.771
2.367
3.006
4.434
3.892
2.665
3.166
2.663
3.958
2.659
2.929
2.788
2.925
2.666
4.537
3.740
3.866
2.982
2.762
2.823
3.090
2.325
3.121
3.025
2.500
2.847
2.877
2.344
2.664
2.845
2.400
1.957
2.266
4.013
2.682
2.747
2.821
2.806
2.310
2.872
2.789
2.520
2.506
2.852
2.633
2.527
2.925
2.540
3.654
2.946
3.399
2.856

First 60 of 528 rows.

Estimated value of the target policy

EstimatorEstimateSE95% CI low95% CI highvs logged
IPS0.42720.02770.37940.47950.0719
Self-normalized IPS0.40770.02180.36810.45010.0524
Clipped IPS0.42720.02770.37940.47950.0719
Direct method0.40480.00220.40100.40860.0495
Doubly robust0.40580.02270.36480.44890.0505

Weight diagnostics

DiagnosticValue
Rows1,500
Rows where target = logged action528
Effective sample size512.15
Mean weight (≈ 1 if propensities are right)1.048
Largest weight4.986
Smallest propensity0.1504

Actions: logged vs target policy

offerLogged shareTarget share
A30.4%23.2%
B37.6%52.1%
C32.0%24.7%
  • Weights w = 1[target = logged action] / propensity. Reward model: linear in x1, spend ($), segment, cross-fitted over 2 folds; 400 bootstrap resamples of the per-row contributions (seed 42).
The exact R script · R R version 4.5.1 (2025-06-13)
# Off-policy evaluation of a decision policy
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.ope 1.0.1 · spec 7ba9eba7d39215ad
# Dataset: o2_logged (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_bandit_ope(): twin of codesplash.decide.ope (shared-RNG folds and bootstrap)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/o2_logged.parquet", col_select = c("offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment")))
n_input <- nrow(df)
df[["offer"]] <- factor(df[["offer"]], levels = c("A", "B", "C"))  # stored level order
df[["new policy"]] <- factor(df[["new policy"]], levels = c("A", "B", "C"))  # stored level order
df[["segment"]] <- factor(df[["segment"]], levels = c("new", "returning", "loyal"))  # stored level order
df <- df[stats::complete.cases(df[c("offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment"))  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
a_col <- "offer"
r_col <- "converted"
p_col <- "propensity"
t_col <- "new policy"
features <- c("x1", "spend ($)", "segment")
model <- "linear" # linear | mean
folds <- as.integer(2)
clip <- 10 # NULL = no clipped IPS
n_boot <- as.integer(400)
conf <- 0.95
seed <- 42
lv <- levels(df[[a_col]])
action <- as.character(df[[a_col]])
target <- as.character(df[[t_col]])
# Yes/no rewards count as 1/0.
reward <- if (is.factor(df[[r_col]])) as.numeric(as.character(df[[r_col]]) == "true") else as.numeric(df[[r_col]])
propensity <- as.numeric(df[[p_col]])
is_cat <- vapply(features, function(c) is.factor(df[[c]]), logical(1))
numeric_f <- features[!is_cat]
categorical_f <- lapply(stats::setNames(features[is_cat], features[is_cat]), function(c) levels(df[[c]]))
x <- if (length(features) && model == "linear") cs_bandit_design(df, numeric_f, categorical_f) else NULL

# Every action the target policy picks must be among the logged actions (first unknown one, in sorted order).
unknown <- sort(setdiff(unique(target), lv), method = "radix")
if (length(unknown)) cs_error("CS_E_NOT_A_LEVEL", level = unknown[1], column = a_col)

# %% Estimate
res <- cs_bandit_ope(action, reward, propensity, target, lv, x = x, model = if (length(features)) model else "mean", folds = folds,
                     clip = clip, boot = n_boot, conf = conf, seed = seed)
warnings <- c(warnings, as.list(res$warnings))
n <- res$n
if (abs(res$mean_weight - 1) > 0.1) {
  warnings <- c(warnings, sprintf("The importance weights average %.2f, not 1: the propensities may be wrong, or the logging policy rarely takes the target's actions.", res$mean_weight))
}
if (res$ess < 0.1 * n) {
  warnings <- c(warnings, sprintf("Effective sample size %.0f is under 10%% of the %d rows: IPS-type estimates are noisy; prefer the doubly robust estimate.", res$ess, n))
}
if (res$max_weight > 50) warnings <- c(warnings, sprintf("The largest weight is %.0f: a few rows dominate IPS; compare with clipped IPS and DR.", res$max_weight))
if (!length(features)) warnings <- c(warnings, "No context features: the direct method uses each action's mean reward.")

# %% Result
lab <- cs_bandit_ope_labels()
pct <- sprintf("%.0f%%", conf * 100)
dr <- res$estimate$dr
dr_ci <- res$ci$dr
logged <- res$logged
summary <- sprintf(
  "The doubly robust estimate says the target policy would earn %.3f per decision, %s CI [%.3f, %.3f], %s than the %.3f the logged policy earned (%+.3f). %s of %s logged decisions agree with the target policy; the effective sample size of the importance weights is %.0f.",
  dr, pct, dr_ci[1], dr_ci[2], if (dr > logged) "more" else "less", logged, dr - logged, format(res$matched, big.mark = ","),
  format(n, big.mark = ","), res$ess
)
rows <- do.call(rbind, lapply(res$estimators, function(e) {
  data.frame(estimator = lab[[e]], estimate = res$estimate[[e]], se = res$se[[e]], low = res$ci[[e]][1], high = res$ci[[e]][2],
             diff = res$estimate[[e]] - logged)
}))
values <- list(logged_value = logged, logged_ci_low = res$logged_ci[1], logged_ci_high = res$logged_ci[2], n = n,
               matched = res$matched, ess = res$ess, mean_weight = res$mean_weight, max_weight = res$max_weight,
               min_propensity = res$min_propensity, improvement_dr = dr - logged)
for (e in res$estimators) {
  values[[sprintf("value[%s]", e)]] <- res$estimate[[e]]
  values[[sprintf("se[%s]", e)]] <- res$se[[e]]
  values[[sprintf("ci_low[%s]", e)]] <- res$ci[[e]][1]
  values[[sprintf("ci_high[%s]", e)]] <- res$ci[[e]][2]
}
forest_labels <- c(unname(lab[res$estimators]), "Logged policy")
matched_w <- res$weights[res$weights > 0]
fit_note <- if (!is.null(x)) paste("linear in", paste(features, collapse = ", ")) else "mean reward per action"
cs_publish(list(
  method = "bandit.ope",
  methodVersion = "1.0.1",
  title = "Off-policy evaluation",
  engine = cs_engine_info("stats", "codesplashr"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "dr", label = "Target policy value (doubly robust)", value = dr),
    list(key = "ci", label = paste(pct, "CI"), value = dr_ci),
    list(key = "logged", label = "Logged policy value", value = logged),
    list(key = "ess", label = "Effective sample size", value = res$ess)
  ),
  tables = list(
    list(key = "estimates", title = "Estimated value of the target policy",
         columns = list(list(key = "estimator", label = "Estimator", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                        list(key = "se", label = "SE", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
                        list(key = "high", label = paste(pct, "CI high"), type = "number"), list(key = "diff", label = "vs logged", type = "number")),
         rows = rows),
    list(key = "diagnostics", title = "Weight diagnostics",
         columns = list(list(key = "metric", label = "Diagnostic", type = "string"), list(key = "value", label = "Value", type = "number")),
         rows = data.frame(metric = c("Rows", "Rows where target = logged action", "Effective sample size",
                                      "Mean weight (≈ 1 if propensities are right)", "Largest weight", "Smallest propensity"),
                           value = c(n, res$matched, res$ess, res$mean_weight, res$max_weight, res$min_propensity))),
    list(key = "actions", title = "Actions: logged vs target policy",
         columns = list(list(key = "action", label = a_col, type = "string"), list(key = "logged", label = "Logged share", type = "percent"),
                        list(key = "target", label = "Target share", type = "percent")),
         rows = data.frame(action = lv, logged = unname(res$logged_share[lv]), target = unname(res$target_share[lv])))
  ),
  warnings = warnings,
  notes = list(paste0("Weights w = 1[target = logged action] / propensity. Reward model: ", fit_note,
                      if (folds > 1) sprintf(", cross-fitted over %d folds", folds) else ", fit in-sample",
                      sprintf("; %d bootstrap resamples of the per-row contributions (seed %s).", n_boot, seed))),
  values = values,
  charts = list(
    cs_chart("estimates", "forest", "Estimated value per decision", list(
      label = cs_col("Estimator", forest_labels, levels = forest_labels),
      estimate = cs_col("Value", c(rows$estimate, logged)),
      low = cs_col("Lower", c(rows$low, res$logged_ci[1])),
      high = cs_col("Upper", c(rows$high, res$logged_ci[2]))
    ), controls = list(reference = logged)),
    cs_chart("weights", "histogram", "Importance weights (rows where target = logged action)", list(x = cs_col("Weight", matched_w)))
  )
))
Python

The doubly robust estimate says the target policy would earn 0.406 per decision, 95% CI [0.365, 0.449], more than the 0.355 the logged policy earned (+0.050). 528 of 1,500 logged decisions agree with the target policy; the effective sample size of the importance weights is 512.

Target policy value (doubly robust)
0.4058
95% CI
[0.3648, 0.4489]
Logged policy value
0.3553
Effective sample size
512.15

To keep this page light, the plots are shown once, under the R tab.

Estimated value of the target policy

EstimatorEstimateSE95% CI low95% CI highvs logged
IPS0.42720.02770.37940.47950.0719
Self-normalized IPS0.40770.02180.36810.45010.0524
Clipped IPS0.42720.02770.37940.47950.0719
Direct method0.40480.00220.40100.40860.0495
Doubly robust0.40580.02270.36480.44890.0505

Weight diagnostics

DiagnosticValue
Rows1,500
Rows where target = logged action528
Effective sample size512.15
Mean weight (≈ 1 if propensities are right)1.048
Largest weight4.986
Smallest propensity0.1504

Actions: logged vs target policy

offerLogged shareTarget share
A30.4%23.2%
B37.6%52.1%
C32.0%24.7%
  • Weights w = 1[target = logged action] / propensity. Reward model: linear in x1, spend ($), segment, cross-fitted over 2 folds; 400 bootstrap resamples of the per-row contributions (seed 42).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Off-policy evaluation of a decision policy
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.ope 1.0.1 · spec 7ba9eba7d39215ad
# Dataset: o2_logged (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.decide import ope  # twin of codesplashr::cs_bandit_ope (shared-RNG folds and bootstrap)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/o2_logged.parquet", columns=["offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment"])
n_input = len(df)
df["offer"] = pd.Categorical(df["offer"], categories=["A", "B", "C"])  # stored level order
df["new policy"] = pd.Categorical(df["new policy"], categories=["A", "B", "C"])  # stored level order
df["segment"] = pd.Categorical(df["segment"], categories=["new", "returning", "loyal"])  # stored level order
df = df.dropna(subset=["offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment"])  # listwise deletion over the analysis columns
df["offer"] = df["offer"].cat.remove_unused_categories()
df["new policy"] = df["new policy"].cat.remove_unused_categories()
df["segment"] = df["segment"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
a_col, r_col, p_col, t_col = "offer", "converted", "propensity", "new policy"
features = ["x1", "spend ($)", "segment"]
model = "linear"  # linear | mean
folds = int(2)
clip = 10  # None = no clipped IPS
n_boot = int(400)
conf = 0.95
seed = 42
levels = [str(x) for x in df[a_col].cat.categories]
action = df[a_col].astype(str).to_numpy()
target = df[t_col].astype(str).to_numpy()
# Yes/no rewards count as 1/0.
reward = (df[r_col].astype(str) == "true").astype(float).to_numpy() if isinstance(df[r_col].dtype, pd.CategoricalDtype) else df[r_col].to_numpy(dtype=float)
propensity = df[p_col].to_numpy(dtype=float)
numeric = [c for c in features if not isinstance(df[c].dtype, pd.CategoricalDtype)]
categorical = {c: [str(x) for x in df[c].cat.categories] for c in features if isinstance(df[c].dtype, pd.CategoricalDtype)}
x = ope.design(df, numeric, categorical) if features and model == "linear" else None

# Every action the target policy picks must be among the logged actions (first unknown one, in sorted order).
unknown = sorted(set(target) - set(levels))
if unknown:
    cs.cs_error("CS_E_NOT_A_LEVEL", level=unknown[0], column=a_col)

# %% Estimate
res = ope.ope(action, reward, propensity, target, levels, x=x, model=model if features else "mean", folds=folds, clip=clip,
              boot=n_boot, conf=conf, seed=seed)
warnings += res["warnings"]
n = res["n"]
if abs(res["mean_weight"] - 1) > 0.1:
    warnings.append(f"The importance weights average {res['mean_weight']:.2f}, not 1: the propensities may be wrong, or the logging policy rarely takes the target's actions.")
if res["ess"] < 0.1 * n:
    warnings.append(f"Effective sample size {res['ess']:.0f} is under 10% of the {n} rows: IPS-type estimates are noisy; prefer the doubly robust estimate.")
if res["max_weight"] > 50:
    warnings.append(f"The largest weight is {res['max_weight']:.0f}: a few rows dominate IPS; compare with clipped IPS and DR.")
if not features:
    warnings.append("No context features: the direct method uses each action's mean reward.")

# %% Result
lab = ope.LABELS
pct = f"{conf:.0%}"
dr, (dr_lo, dr_hi) = res["estimate"]["dr"], res["ci"]["dr"]
logged = res["logged"]
direction = "more" if dr > logged else "less"
summary = (
    f"The doubly robust estimate says the target policy would earn {dr:.3f} per decision, {pct} CI [{dr_lo:.3f}, {dr_hi:.3f}], "
    f"{direction} than the {logged:.3f} the logged policy earned ({dr - logged:+.3f}). {res['matched']:,} of {n:,} logged decisions agree with "
    f"the target policy; the effective sample size of the importance weights is {res['ess']:.0f}."
)
rows = [
    {"estimator": lab[e], "estimate": res["estimate"][e], "se": res["se"][e], "low": res["ci"][e][0], "high": res["ci"][e][1],
     "diff": res["estimate"][e] - logged}
    for e in res["estimators"]
]
values = {"logged_value": logged, "logged_ci_low": res["logged_ci"][0], "logged_ci_high": res["logged_ci"][1], "n": n,
          "matched": res["matched"], "ess": res["ess"], "mean_weight": res["mean_weight"], "max_weight": res["max_weight"],
          "min_propensity": res["min_propensity"], "improvement_dr": dr - logged}
for e in res["estimators"]:
    values[f"value[{e}]"] = res["estimate"][e]
    values[f"se[{e}]"] = res["se"][e]
    values[f"ci_low[{e}]"] = res["ci"][e][0]
    values[f"ci_high[{e}]"] = res["ci"][e][1]
forest_labels = [lab[e] for e in res["estimators"]] + ["Logged policy"]
matched_w = res["weights"][res["weights"] > 0]
cs.publish({
    "method": "bandit.ope",
    "methodVersion": "1.0.1",
    "title": "Off-policy evaluation",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "dr", "label": "Target policy value (doubly robust)", "value": dr},
        {"key": "ci", "label": f"{pct} CI", "value": [dr_lo, dr_hi]},
        {"key": "logged", "label": "Logged policy value", "value": logged},
        {"key": "ess", "label": "Effective sample size", "value": res["ess"]},
    ],
    "tables": [
        {"key": "estimates", "title": "Estimated value of the target policy",
         "columns": [{"key": "estimator", "label": "Estimator", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                     {"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
                     {"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "diff", "label": "vs logged", "type": "number"}],
         "rows": rows},
        {"key": "diagnostics", "title": "Weight diagnostics",
         "columns": [{"key": "metric", "label": "Diagnostic", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
         "rows": [{"metric": "Rows", "value": n}, {"metric": "Rows where target = logged action", "value": res["matched"]},
                  {"metric": "Effective sample size", "value": res["ess"]}, {"metric": "Mean weight (≈ 1 if propensities are right)", "value": res["mean_weight"]},
                  {"metric": "Largest weight", "value": res["max_weight"]}, {"metric": "Smallest propensity", "value": res["min_propensity"]}]},
        {"key": "actions", "title": "Actions: logged vs target policy",
         "columns": [{"key": "action", "label": a_col, "type": "string"}, {"key": "logged", "label": "Logged share", "type": "percent"},
                     {"key": "target", "label": "Target share", "type": "percent"}],
         "rows": [{"action": lv, "logged": res["logged_share"][lv], "target": res["target_share"][lv]} for lv in levels]},
    ],
    "warnings": warnings,
    "notes": [
        "Weights w = 1[target = logged action] / propensity. Reward model: " + f"{'linear in ' + ', '.join(features) if x is not None else 'mean reward per action'}"
        + (f", cross-fitted over {folds} folds" if folds > 1 else ", fit in-sample") + f"; {n_boot} bootstrap resamples of the per-row contributions (seed {seed}).",
    ],
    "values": values,
    "charts": [
        cs.chart("estimates", "forest", "Estimated value per decision", {
            "label": cs.col("Estimator", forest_labels, levels=forest_labels),
            "estimate": cs.col("Value", [r["estimate"] for r in rows] + [logged]),
            "low": cs.col("Lower", [r["low"] for r in rows] + [res["logged_ci"][0]]),
            "high": cs.col("Upper", [r["high"] for r in rows] + [res["logged_ci"][1]]),
        }, controls={"reference": logged}),
        cs.chart("weights", "histogram", "Importance weights (rows where target = logged action)", {"x": cs.col("Weight", matched_w)}),
    ],
})

The logged policy earned 0.355 per decision. The doubly robust estimate of the new policy is higher by 0.050.

Before you celebrate, look at how much of the log supports that. Of 1,500 decisions, 528 match the new policy. The intervals for each estimator are on the card. Do they exclude the logged value?

06

How much data is that really?

Predict

Predict first

Unequal weights mean some rows count more than others. The effective sample sizeEffective sample sizeHow many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count. says how many equally weighted rows the estimate is worth. With 528 matches and a largest weight of 5.0, what would you guess?

About 1,500About 500About 50
Reveal

512. That's reasonable here, since the smallest propensity is 0.15. If some propensities were tiny, a few rows would dominate, and the effective sample size would collapse. Clipped IPS caps the weights, trading a little bias for less noise.

07

A policy the logs barely tried

Reflect

Off-policy evaluation can only judge choices the old policy sometimes made. If it never showed an offer to a kind of user, no estimator can tell you how those users would respond, and a model would be extrapolating.

Logs from a randomized policy are the best material, since each option had a known chance: 0.33 per option in this example. Could your own system log its propensities, starting today?

08

Check your understanding

Checkpoint

Check yourself

Your old system was a fixed rule: VIP customers always saw offer A. What happens if the new rule shows them offer B?

Show the answer

Answer: b

A model can produce a number, but it's an extrapolation with nothing behind it. Run a small randomized test to create support.

Check yourself

What does "doubly robust" promise?

Show the answer

Answer: b

It gives two chances to get it right. If both are wrong, it can still be wrong.

Check yourself

Off-policy evaluation estimates a gain of 0.05, with an interval excluding zero. What's the right next step?

Show the answer

Answer: b

Off-policy evaluation is a cheap screen. It tells you which policies deserve a live test.

09

Try it

In the app

In Decisions & fairness, choose Evaluate a new policy on logs. The Off-policy evaluation panel needs the logged action, its reward, its propensity and the action your new policy would have taken.

Python
import pandas as pd

df = pd.read_csv("logged.csv")
weight = (df["offer"] == df["new policy"]) / df["propensity"]
reward = df["converted"]

ips = (weight * reward).mean()
snips = (weight * reward).sum() / weight.sum()
ess = weight.sum() ** 2 / (weight**2).sum()
print(round(ips, 4), round(snips, 4), round(ess, 1))
R
df <- read.csv("logged.csv", check.names = FALSE)
weight <- (df$offer == df[["new policy"]]) / df$propensity
reward <- df$converted

ips <- mean(weight * reward)
snips <- sum(weight * reward) / sum(weight)
ess <- sum(weight)^2 / sum(weight^2)
round(c(ips = ips, snips = snips, ess = ess), 4)
10

Recap

Recap
  • Without logged propensities, you can't correct for how the old policy chose.
  • IPS is unbiased but noisy. Doubly robust uses a model as well.
  • Effective sample size and the largest weight warn when a few rows dominate.
  • Confirm promising policies with a live test.

Concepts in this lesson