GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — DeepLearningTutorials/code/hmc/test_hmc.py at master · oftensmile/DeepLearningTutorials Expand file tree/ Copy pathtest_hmc.pyMore file actions 69 lines (52 loc) · 2.36 KB / Copy pathtest_hmc.pyFile metadata and controls69 lines (52 loc) · 2.36 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 from __future__ import print_function import numpy import theano try: from hmc import HMC_sampler except ImportError as e: # python 3 compatibility # http://stackoverflow.com/questions/3073259/python-nose-import-error from hmc.hmc import HMC_sampler def sampler_on_nd_gaussian(sampler_cls, burnin, n_samples, dim=10): batchsize = 3 rng = numpy.random.RandomState(123) # Define a covariance and mu for a gaussian mu = numpy.array(rng.rand(dim) * 10, dtype=theano.config.floatX) cov = numpy.array(rng.rand(dim, dim), dtype=theano.config.floatX) cov = (cov + cov.T) / 2. cov[numpy.arange(dim), numpy.arange(dim)] = 1.0 cov_inv = numpy.linalg.inv(cov) # Define energy function for a multi-variate Gaussian def gaussian_energy(x): return 0.5 * (theano.tensor.dot((x - mu), cov_inv) * (x - mu)).sum(axis=1) # Declared shared random variable for positions position = rng.randn(batchsize, dim).astype(theano.config.floatX) position = theano.shared(position) # Create HMC sampler sampler = sampler_cls(position, gaussian_energy, initial_stepsize=1e-3, stepsize_max=0.5) # Start with a burn-in process garbage = [sampler.draw() for r in range(burnin)] # burn-in Draw # `n_samples`: result is a 3D tensor of dim [n_samples, batchsize, # dim] _samples = numpy.asarray([sampler.draw() for r in range(n_samples)]) # Flatten to [n_samples * batchsize, dim] samples = _samples.T.reshape(dim, -1).T print('****** TARGET VALUES ******') print('target mean:', mu) print('target cov:\n', cov) print('****** EMPIRICAL MEAN/COV USING HMC ******') print('empirical mean: ', samples.mean(axis=0)) print('empirical_cov:\n', numpy.cov(samples.T)) print('****** HMC INTERNALS ******') print('final stepsize', sampler.stepsize.get_value()) print('final acceptance_rate', sampler.avg_acceptance_rate.get_value()) return sampler def test_hmc(): sampler = sampler_on_nd_gaussian(HMC_sampler.new_from_shared_positions, burnin=1000, n_samples=1000, dim=5) assert abs(sampler.avg_acceptance_rate.get_value() - sampler.target_acceptance_rate) < .1 assert sampler.stepsize.get_value() >= sampler.stepsize_min assert sampler.stepsize.get_value() <= sampler.stepsize_max |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |