Skip to content

Instantly share code, notes, and snippets.

@jmbr
Created May 20, 2021 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmbr/a0813fcbc906a04214ebe201751e26c4 to your computer and use it in GitHub Desktop.
Save jmbr/a0813fcbc906a04214ebe201751e26c4 to your computer and use it in GitHub Desktop.
Sample from a simple mixture of Gaussians
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