606. 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.
def off_policy_value(episodes, gamma)Example 1
Input: off_policy_value([[(1.0, 0.5, 0.25)], [(0.0, 0.5, 0.75)]], 1.0)
Output: (1.0, 0.75)
Example 2
Input: episodes = [[(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, 0.5)]], gamma = 0.9
Output: (3.108, 2.506452)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
rho is a product of probability ratios over the whole episode.
Hint 2
Accumulate G and rho in the same loop over steps.
Hint 3
ordinary is a plain mean; weighted is a ratio of sums.
Hint 4
Guard sum(rho) = 0.
Common mistakes
- Inverting the ratio.
- Using per-step ratios instead of the full product for the episode return.
- Dividing by the episode count in the weighted estimator.
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.
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.
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.
Topics
Companies1
- Microsoft the topic appears in interview reports Microsoft Senior Applied Scientist (L63) Interview Experience
From public interview reports and guides. Not affiliated with or endorsed by these companies.