Created
August 17, 2020 09:00
-
-
Save vene/53d2cacef08db60694789b33c28c1542 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# linearity of expectation under mixture model | |
# license: mit | |
# author: vlad niculae | |
from scipy.stats import norm | |
import numpy as np | |
def main(): | |
rng = np.random.RandomState(42) | |
centers = rng.randn(3) | |
w = np.array([.8, .1, .1]) | |
stds = np.array([.5, 1., 1.]) | |
dists = [norm(loc=c, scale=s) for c, s in zip(centers, stds)] | |
def psi(t): | |
# return (1 / 3) * t ** 3 | |
return np.sin(t / 3) | |
# mc sampling | |
n_samples = 100000 | |
mean_mc = 0 | |
for _ in range(n_samples): | |
h = rng.choice(3, p=w) | |
t = dists[h].rvs(random_state=rng) | |
mean_mc += psi(t) | |
mean_mc /= n_samples | |
print(mean_mc) | |
# closed form: | |
means = np.array([d.expect(psi) for d in dists]) | |
print(w @ means) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment