def test_hamiltonian_monte_carlo(): # This mostly tests consistency. Tolerance chosen by experiment # Do statistical tests on your own time. np.random.seed(1) neg_log_p = neg_log_normal(2, 0.1) samples = hamiltonian_monte_carlo(100, neg_log_p, np.array(0.0)) assert samples.shape[0] == 100 assert_allclose(2.0, np.mean(samples), atol=0.02) assert_allclose(0.1, np.std(samples), atol=0.007)
def test_hamiltonian_monte_carlo_mv(): np.random.seed(1) mu = np.arange(2) cov = 0.8 * np.ones((2, 2)) + 0.2 * np.eye(2) neg_log_p = AutogradPotential(neg_log_mvnormal(mu, cov)) samples = hamiltonian_monte_carlo(100, neg_log_p, np.zeros(mu.shape), path_len=2.0) assert samples.shape[0] == 100 assert_allclose(mu, np.mean(samples, axis=0), atol=0.3) assert_allclose(cov, np.cov(samples.T), atol=0.5)
def test_pymc3_interface(): np.random.seed(3) with pm.Model() as model: pm.Normal("x", mu=0.0, sigma=1.0, shape=10) potential = PyMC3Potential() initial_q = potential.bijection.map(model.test_point) samples = hamiltonian_monte_carlo(500, potential, initial_q) assert samples.shape[0] == 500 assert samples.shape[1] == 10 assert_allclose(0.0, np.mean(samples, axis=0), atol=0.13) assert_allclose(1.0, np.var(samples, axis=0), atol=0.17)
"font.family": "serif", "figure.facecolor": "#fffff8", "axes.facecolor": "#fffff8", "figure.constrained_layout.use": True, "font.size": 14.0, "hist.bins": "auto", "lines.linewidth": 3.0, "lines.markeredgewidth": 2.0, "lines.markerfacecolor": "none", "lines.markersize": 8.0, } ) ### Example 1 ### samples = hamiltonian_monte_carlo( 2000, AutogradPotential(neg_log_normal(0, 0.1)), initial_position=0.0 ) ### Plot 1 ### fig, ax = plt.subplots(figsize=FIGSIZE) ax.hist(samples, bins="auto") ax.axvline(0, color="C1", linestyle="--") ax.set_title("1D Gaussians!") plt.savefig(os.path.join(HERE, "plot1.png")) ### Example 2 ### samples, positions, momentums, accepted, p_accepts = hmc_slow( 50, AutogradPotential(neg_log_normal(0, 0.1)), 0.0, step_size=0.01 ) ### Plot 2 ###