Created
May 20, 2021 21:39
-
-
Save jmbr/a0813fcbc906a04214ebe201751e26c4 to your computer and use it in GitHub Desktop.
Sample from a simple mixture of Gaussians
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
import numpy as np | |
from scipy.stats import rv_continuous | |
import matplotlib.pyplot as plt | |
class double_well_gen(rv_continuous): | |
def _pdf(self, x, mu, sigma): | |
sigma2 = sigma**2 | |
return ((np.exp(-(x - mu)**2 / (2.0 * sigma2)) | |
+ np.exp(-(x + mu)**2 / (2.0 * sigma2))) | |
/ (2.0 * np.sqrt(2.0 * np.pi * sigma2))) | |
double_well = double_well_gen(name='double_well').freeze(mu=2, sigma=1/2) | |
x = np.linspace(-5, 5, 100) | |
y = double_well.pdf(x) | |
assert np.allclose(np.trapz(y, x=x), 1.0) | |
samples = double_well.rvs(size=100) | |
plt.plot(x, y) | |
plt.hist(samples, density=True) | |
plt.xlabel('$x$') | |
plt.ylabel('Probability density') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment