importance_sampler = DefaultMetropolis(ndim, target.pdf, channels)

# initialize the mixed sampler a.k.a. (MC)^3
# the sampler weights (beta parameter) can be tuned
sampler_weights = [0.5, 0.5]  # should sum to 1
sampler = MixingMarkovUpdate(ndim, [metropolis_sampler, importance_sampler],
                             sampler_weights)

# produce the samples
target.pdf.count = 0

t_start = timer()
sample = sampler.sample(nsamples, start)
t_end = timer()

n_target_calls = target.pdf.count

# print some statistics (can take a while if sample size is large!)
print('time: ', t_end - t_start)
print('pdf calls: ', n_target_calls)
print(sample)

# plot the results
if ndim == 1:
    plot_1d(sample.data, target.pdf, mapping_pdf=channels.pdf)
elif ndim == 2:
    plot_2d(sample.data, target.pdf)
else:
    plot_1d(sample.data[:, 0], target.pdf)
Esempio n. 2
0
import numpy as np

np.seterr(all='warn')
np.random.seed(1234)

ndim = 2
nsamples = 1000
nadapt = 500


def hmc_adapt_schedule(t):
    if t > nadapt:
        return False
    else:
        return True


target = densities.UnconstrainedCamel(ndim)
#sampler = StaticHMC(ndim, target.pdf, target.log_pdf_gradient, 0.01, 0.1, 10, 150)
sampler = hamiltonian.HamiltonianUpdate(
    target, densities.Gaussian(ndim), 20, 0.05)
start = np.full(ndim, 0.44)
#sampler = DualAveragingHMC(ndim, target.pdf, target.log_pdf_gradient, 1, start, hmc_adapt_schedule, momentum=IsotropicZeroMeanGaussian(ndim, 1))
#sampler = NUTS(ndim, target.pdf, target.log_pdf_gradient, start, hmc_adapt_schedule, momentum=IsotropicZeroMeanGaussian(ndim, 1))

samples = sampler.sample(nsamples, start).data
#samples = [sample[0] for sample in samples]
#print(samples)

plot_2d(samples, target.pdf)