Estimate a policy's return from another policy's episodes with importance sampling

Why it matters Off-policy evaluation lets teams test a new recommendation or agent policy on logged data before an online launch.

You have episodes collected by a behaviour policy b and want the expected return of a different target policy pi without running it.

Write off_policy_value(episodes, gamma). Each episode is a list of (reward, pi_prob, b_prob) where pi_prob and b_prob are the probabilities both policies gave to the action actually taken. For each episode compute G = discounted return from the start and rho = product of pi_prob / b_prob over its steps. Return (ordinary, weighted):
- ordinary = mean over episodes of rho * G
- weighted = sum(rho * G) / sum(rho), or 0.0 if sum(rho) is 0.
Both as floats; return (0.0, 0.0) for no episodes.

Signaturedef off_policy_value(episodes, gamma)

Example

off_policy_value([[(1.0, 0.5, 0.25)], [(0.0, 0.5, 0.75)]], 1.0) gives (1.0, 0.75).

Understand the idea

Suppose your logged data came from an old policy, but you want to know how a new policy would do. Importance sampling reweights each logged episode by how much more (or less) likely the new policy was to produce it. If the new policy is twice as likely to take the logged actions, that episode counts twice.

Example: episode A got return 1 and the new policy likes its action twice as much (0.5 vs 0.25), so rho = 2. Episode B got 0 with rho = 0.5 / 0.75 = 0.667. Ordinary IS: (2 * 1 + 0.667 * 0) / 2 = 1.0. Weighted IS: 2 / (2 + 0.667) = 0.75.

Rules: rho = prod_t pi(a_t|s_t) / b(a_t|s_t); OIS = mean(rho * G); WIS = sum(rho * G) / sum(rho).

Weighted IS is the usual choice in practice because a single huge rho cannot blow up the estimate.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleoff_policy_value([[(1.0, 0.5, 0.25)], [(0.0, 0.5, 0.75)]], 1.0)
  • Sample 2: multi stepoff_policy_value([[(1, 0.9, 0.5), (2, 0.8, 0.5)], [(0, 0.1, 0.5), (5, 0.3, 0.5)], [(1, 0.9, 0.5), (0, 0.2, ...