All problems
Importance Sampling Estimate (Seeded)
Problem
Estimate E[X] for a discrete variable with the given values and target distribution using importance sampling from proposal. Draw n samples from the proposal with random.Random(seed) via inverse transform, weight sample i by target[i] / proposal[i], and return the average weight times value. Return 0.0 for n <= 0.
Hint
Use inverse transform sampling with cumsum of the proposal.
Test cases
case 1
in: [[1,2,3],[0.2,0.3,0.5],[0.3333333333333333,0.3333333333333333,0.3333333333333333],20000,42]
expected: 2.3056949999998686
case 2
in: [[1,2,3],[0.2,0.3,0.5],[0.3333333333333333,0.3333333333333333,0.3333333333333333],20000,7]
expected: 2.2922099999998724
case 3
in: [[1,2,3],[0.2,0.3,0.5],[0.5,0.3,0.2],10000,1]
expected: 2.3073200000001353
case 4
in: [[1,2,3],[0.2,0.3,0.5],[0.3333333333333333,0.3333333333333333,0.3333333333333333],0,5]
expected: 0
Starter codePython
import random
def importance_sampling_estimate(values, target, proposal, n, seed):
# Your code here
pass4 test cases · run your code against them in the editor