Skip to main content
Notice removed Authoritative reference needed by mjake
Bounty Ended with Alex I's answer chosen by mjake
implemented code
Source Link
mjake
  • 117
  • 7

Edit:

I've implemented in some code based on my understanding of the algorithm. It works for a gaussian with mu=0, sigma=1. But if I change sigma it breaks. Any insights would be appreciated.

import numpy as np
import random
import scipy.stats as st
import matplotlib.pyplot as plt
from autograd import grad

def normal(x,mu,sigma):
    numerator = np.exp((-(x-mu)**2)/(2*sigma**2))
    denominator = sigma * np.sqrt(2*np.pi)
    return numerator/denominator

def neg_log_prob(x,mu,sigma):
    num = np.exp(-1*((x-mu)**2)/2*sigma**2)
    den = sigma*np.sqrt(np.pi*2)
    return -1*np.log(num/den)

def HMC(mu=0.0,sigma=1.0,path_len=1,step_size=0.25,initial_position=0.0,epochs=1_000):
    # setup
    steps = int(path_len/step_size) -1 # path_len and step_size are tricky parameters to tune...
    samples = [initial_position]
    momentum_dist = st.norm(0, 1) 
    # generate samples
    for e in range(epochs):
        q0 = np.copy(samples[-1])
        q1 = np.copy(q0)
        p0 = momentum_dist.rvs()        
        p1 = np.copy(p0) 
        dVdQ = -1*(q0-mu)/(sigma**2) # gradient of PDF wrt position (q0) aka momentum wrt position

        # leapfrog integration begin
        for s in range(steps):
            p1 += step_size*dVdQ/2 # as potential energy increases, kinetic energy decreases
            q1 += step_size*p1 # position increases as function of momentum 
            p1 += step_size*dVdQ/2 # second half "leapfrog" update to momentum    
        # leapfrog integration end        
        p1 = -1*p1 #flip momentum for reversibility    
        
        #metropolis acceptance
        q0_nlp = neg_log_prob(x=q0,mu=mu,sigma=sigma)
        q1_nlp = neg_log_prob(x=q1,mu=mu,sigma=sigma)        

        p0_nlp = neg_log_prob(x=p0,mu=0,sigma=1)
        p1_nlp = neg_log_prob(x=p1,mu=0,sigma=1)
        
        # Account for negatives AND log(probabiltiies)...
        target = q0_nlp - q1_nlp # P(q1)/P(q0)
        adjustment = p1_nlp - p0_nlp # P(p1)/P(p0)
        acceptance = target + adjustment 
        
        event = np.log(random.uniform(0,1))
        if event <= acceptance:
            samples.append(q1)
        else:
            samples.append(q0)
    
    return samples

Now it works here:

mu, sigma = 0,1
trial = HMC(mu=mu,sigma=sigma,path_len=2,step_size=0.25)

# What the dist should looks like
lines = np.linspace(-6,6,10_000)
normal_curve = [normal(x=l,mu=mu,sigma=sigma) for l in lines]

# Visualize
plt.plot(lines,normal_curve)
plt.hist(trial,density=True,bins=20)
plt.show()

HMC_1

But it breaks when I change sigma to 2.

# Generate samples
mu, sigma = 0,2
trial = HMC(mu=mu,sigma=sigma,path_len=2,step_size=0.25)

# What the dist should looks like
lines = np.linspace(-6,6,10_000)
normal_curve = [normal(x=l,mu=mu,sigma=sigma) for l in lines]

# Visualize
plt.plot(lines,normal_curve)
plt.hist(trial,density=True,bins=20)
plt.show()

HMC_sampler2

Any ideas? I feel like I'm close to "getting it".

Edit:

I've implemented in some code based on my understanding of the algorithm. It works for a gaussian with mu=0, sigma=1. But if I change sigma it breaks. Any insights would be appreciated.

import numpy as np
import random
import scipy.stats as st
import matplotlib.pyplot as plt
from autograd import grad

def normal(x,mu,sigma):
    numerator = np.exp((-(x-mu)**2)/(2*sigma**2))
    denominator = sigma * np.sqrt(2*np.pi)
    return numerator/denominator

def neg_log_prob(x,mu,sigma):
    num = np.exp(-1*((x-mu)**2)/2*sigma**2)
    den = sigma*np.sqrt(np.pi*2)
    return -1*np.log(num/den)

def HMC(mu=0.0,sigma=1.0,path_len=1,step_size=0.25,initial_position=0.0,epochs=1_000):
    # setup
    steps = int(path_len/step_size) -1 # path_len and step_size are tricky parameters to tune...
    samples = [initial_position]
    momentum_dist = st.norm(0, 1) 
    # generate samples
    for e in range(epochs):
        q0 = np.copy(samples[-1])
        q1 = np.copy(q0)
        p0 = momentum_dist.rvs()        
        p1 = np.copy(p0) 
        dVdQ = -1*(q0-mu)/(sigma**2) # gradient of PDF wrt position (q0) aka momentum wrt position

        # leapfrog integration begin
        for s in range(steps):
            p1 += step_size*dVdQ/2 # as potential energy increases, kinetic energy decreases
            q1 += step_size*p1 # position increases as function of momentum 
            p1 += step_size*dVdQ/2 # second half "leapfrog" update to momentum    
        # leapfrog integration end        
        p1 = -1*p1 #flip momentum for reversibility    
        
        #metropolis acceptance
        q0_nlp = neg_log_prob(x=q0,mu=mu,sigma=sigma)
        q1_nlp = neg_log_prob(x=q1,mu=mu,sigma=sigma)        

        p0_nlp = neg_log_prob(x=p0,mu=0,sigma=1)
        p1_nlp = neg_log_prob(x=p1,mu=0,sigma=1)
        
        # Account for negatives AND log(probabiltiies)...
        target = q0_nlp - q1_nlp # P(q1)/P(q0)
        adjustment = p1_nlp - p0_nlp # P(p1)/P(p0)
        acceptance = target + adjustment 
        
        event = np.log(random.uniform(0,1))
        if event <= acceptance:
            samples.append(q1)
        else:
            samples.append(q0)
    
    return samples

Now it works here:

mu, sigma = 0,1
trial = HMC(mu=mu,sigma=sigma,path_len=2,step_size=0.25)

# What the dist should looks like
lines = np.linspace(-6,6,10_000)
normal_curve = [normal(x=l,mu=mu,sigma=sigma) for l in lines]

# Visualize
plt.plot(lines,normal_curve)
plt.hist(trial,density=True,bins=20)
plt.show()

HMC_1

But it breaks when I change sigma to 2.

# Generate samples
mu, sigma = 0,2
trial = HMC(mu=mu,sigma=sigma,path_len=2,step_size=0.25)

# What the dist should looks like
lines = np.linspace(-6,6,10_000)
normal_curve = [normal(x=l,mu=mu,sigma=sigma) for l in lines]

# Visualize
plt.plot(lines,normal_curve)
plt.hist(trial,density=True,bins=20)
plt.show()

HMC_sampler2

Any ideas? I feel like I'm close to "getting it".

Notice added Authoritative reference needed by mjake
Bounty Started worth 50 reputation by mjake
Updated graphic
Source Link
mjake
  • 117
  • 7

I'm tryingI made the below graphic to self educate onexplain how I currently understand the inner working of HMC algorithm. I'd like verification that I'm on the right trackfrom a subject matter expert if this understanding is or isn't correct. The text in the below slide is copied below for ease of access:

 

I understand thatHamiltonian Monte Carlo: A satellite orbits a planet. The closer the biggest idea with "old school" methods, like Metropolis-Hastings,satellite is that they explore the probability space based on random proposals; ifto the proposal looks appealingplanet, the algorithm moves and appeandsgreater the location to an arrayeffects of gravity. This means, otherwise it says and appends the same (unchangedA) location to the array.

But as dimensionality increases, movements away from the central tendencies of the distribution look progressively lesshigher potential energy and less appealing - so much so that some areas never get explored (i.e. the sampler's approximation deviates too much from the actual distribution.B)

So HMC doesn't randomly propose new locations higher kinetic energy needed to sustain orbit. Rather, it views the central tendency asThat same kinetic energy at a further distance from the planet that a satellite orbits and views likelihood as energy levels, composed of kinetic and potential energy. Random momentum "kicks" causewould eject the satellite to jump up/down energy levels (and this is key to exploring different areas of the distributionout from orbit.)

If a The satellite can take x pictures/min, speed will directly affect how many pictures can be takenis tasked with collecting photos of a given geographical area before the satellite is too far along its orbital path to take another picturespecific geographic region. The closer tothe satellite orbits the planet, the faster it ismoves in orbit, the slowermore times it passes over the speedregion, and the more picturesphotographs it collects. TheConversely, the further ita satellite is from the planet, the higher speed andslower it moves in orbit, the less picturestimes it passes over the region, the less photographs it collects. (Where photo-count translates to In the numbercontext of observations in a given regionsampling, distance from the planet represents distance from the expectation of the distribution.)

I'm not a physicist, so there's a good chance I'm totally wrong!

Here's a graphic that I made An area of low likelihood is far from the expectation; when “orbiting this likelihood, and hopefully it's” lower kinetic energy means less samples collected over a decent representationfixed interval of how HMC works ontime, whereas when orbiting a conceptual levelhigher likelihood means more samples collected given the same fixed time interval.

pic2

First In a given orbit, I'd like to know: Am I on the right track? My second question is (if so) is total energy (potential +, kinetic) constant? And third and potential, if sois constant; however, does the algorithm randomly convert some potential energy into kinetic energy (and vice versa)relationship between the two is not simple. Hamiltonian equations relate changes in orderone to cause the "satellite"other. Namely, the gradient of position with respect to jump energy levels?

I've based my understanding on Betancourt's paper https://arxiv.org/pdf/1701.02434.pdf which goes a decent bit over my head!

Edit1: Someone pointed outtime equals momentum. And the gradient of momentum with respect to me thattime equals the closergradient of potential energy with respect to position. To compute how far a satellite will have traveled along its orbital path, leapfrog integration must be used, iteratively updating momentum and position vectors. In the context of sampling, likelihood is analogous to adistance from the planet, and the strongergradient of potential energy with respect to position is the effectsgradient of gravitythe probability density function with respect to its input parameter, x. The strongerThis information allows the effects of gravityorbital path around various inputs, X, corresponding to the more kinetic energy neededsame likelihood, y, to maintain orbitbe explored. So
However, I had it backwardswe’re not simply interested in exploring one likelihood, we must explore multiple orbital paths. To accomplish this, the satellite will orbitmomentum must randomly be augmented, bringing the planet more faster when it'ssatellite closer toor further away from the planet. However, the relationship between distance and samples collected remains the sameThese random “momentum kicks” allow for different likelihoods to be orbited. The faster a satellite movesFortunately, the more frequently it "passes by"hamiltonian equations ensure that no matter the geographic regionlikelihood, and the morenumber of samples it collects. The further a satellitecollected is, proportionate to the slower it moveslikelihood, the lessthus samples it collectscollected follow the shape of the target distribution.

 

Edit2: Updated graphic https://imgur.com/gallery/OBIE4xOMy question is - Is this an accurate way to think about how Hamiltonian Monte Carlo works?

HMC_updated

I'm trying to self educate on the inner working of HMC. I'd like verification that I'm on the right track.

I understand that the biggest idea with "old school" methods, like Metropolis-Hastings, is that they explore the probability space based on random proposals; if the proposal looks appealing, the algorithm moves and appeands the location to an array, otherwise it says and appends the same (unchanged) location to the array.

But as dimensionality increases, movements away from the central tendencies of the distribution look progressively less and less appealing - so much so that some areas never get explored (i.e. the sampler's approximation deviates too much from the actual distribution.)

So HMC doesn't randomly propose new locations. Rather, it views the central tendency as a planet that a satellite orbits and views likelihood as energy levels, composed of kinetic and potential energy. Random momentum "kicks" cause the satellite to jump up/down energy levels (and this is key to exploring different areas of the distribution.)

If a satellite can take x pictures/min, speed will directly affect how many pictures can be taken of a given geographical area before the satellite is too far along its orbital path to take another picture. The closer to the planet it is, the slower the speed, and the more pictures. The further it is from the planet, the higher speed and less pictures. (Where photo-count translates to the number of observations in a given region of the distribution.)

I'm not a physicist, so there's a good chance I'm totally wrong!

Here's a graphic that I made, and hopefully it's a decent representation of how HMC works on a conceptual level.

pic2

First, I'd like to know: Am I on the right track? My second question is (if so) is total energy (potential + kinetic) constant? And third, if so, does the algorithm randomly convert some potential energy into kinetic energy (and vice versa) in order to cause the "satellite" to jump energy levels?

I've based my understanding on Betancourt's paper https://arxiv.org/pdf/1701.02434.pdf which goes a decent bit over my head!

Edit1: Someone pointed out to me that the closer a satellite is to a planet, the stronger the effects of gravity. The stronger the effects of gravity, the more kinetic energy needed to maintain orbit. So, I had it backwards, the satellite will orbit the planet more faster when it's closer to the planet. However, the relationship between distance and samples collected remains the same. The faster a satellite moves, the more frequently it "passes by" the geographic region, and the more samples it collects. The further a satellite is, the slower it moves, the less samples it collects.

Edit2: Updated graphic https://imgur.com/gallery/OBIE4xO

I made the below graphic to explain how I currently understand the HMC algorithm. I'd like verification from a subject matter expert if this understanding is or isn't correct. The text in the below slide is copied below for ease of access:

 

Hamiltonian Monte Carlo: A satellite orbits a planet. The closer the satellite is to the planet, the greater the effects of gravity. This means, (A) higher potential energy and (B) higher kinetic energy needed to sustain orbit. That same kinetic energy at a further distance from the planet, would eject the satellite out from orbit. The satellite is tasked with collecting photos of a specific geographic region. The closer the satellite orbits the planet, the faster it moves in orbit, the more times it passes over the region, the more photographs it collects. Conversely, the further a satellite is from the planet, the slower it moves in orbit, the less times it passes over the region, the less photographs it collects. In the context of sampling, distance from the planet represents distance from the expectation of the distribution. An area of low likelihood is far from the expectation; when “orbiting this likelihood,” lower kinetic energy means less samples collected over a fixed interval of time, whereas when orbiting a higher likelihood means more samples collected given the same fixed time interval. In a given orbit, the total energy, kinetic and potential, is constant; however, the relationship between the two is not simple. Hamiltonian equations relate changes in one to the other. Namely, the gradient of position with respect to time equals momentum. And the gradient of momentum with respect to time equals the gradient of potential energy with respect to position. To compute how far a satellite will have traveled along its orbital path, leapfrog integration must be used, iteratively updating momentum and position vectors. In the context of sampling, likelihood is analogous to distance from the planet and the gradient of potential energy with respect to position is the gradient of the probability density function with respect to its input parameter, x. This information allows the orbital path around various inputs, X, corresponding to the same likelihood, y, to be explored.
However, we’re not simply interested in exploring one likelihood, we must explore multiple orbital paths. To accomplish this, the momentum must randomly be augmented, bringing the satellite closer or further away from the planet. These random “momentum kicks” allow for different likelihoods to be orbited. Fortunately, hamiltonian equations ensure that no matter the likelihood, the number of samples collected is proportionate to the likelihood, thus samples collected follow the shape of the target distribution.

 

My question is - Is this an accurate way to think about how Hamiltonian Monte Carlo works?

HMC_updated

added 61 characters in body
Source Link
mjake
  • 117
  • 7

I'm trying to self educate on the inner working of HMC. I'd like verification that I'm on the right track.

I understand that the biggest idea with "old school" methods, like Metropolis-Hastings, is that they explore the probability space based on random proposals; if the proposal looks appealing, the algorithm moves and appeands the location to an array, otherwise it says and appends the same (unchanged) location to the array.

But as dimensionality increases, movements away from the central tendencies of the distribution look progressively less and less appealing - so much so that some areas never get explored (i.e. the sampler's approximation deviates too much from the actual distribution.)

So HMC doesn't randomly propose new locations. Rather, it views the central tendency as a planet that a satellite orbits and views likelihood as energy levels, composed of kinetic and potential energy. Random momentum "kicks" cause the satellite to jump up/down energy levels (and this is key to exploring different areas of the distribution.)

If a satellite can take x pictures/min, speed will directly affect how many pictures can be taken of a given geographical area before the satellite is too far along its orbital path to take another picture. The closer to the planet it is, the slower the speed, and the more pictures. The further it is from the planet, the higher speed and less pictures. (Where photo-count translates to the number of observations in a given region of the distribution.)

I'm not a physicist, so there's a good chance I'm totally wrong!

Here's a graphic that I made, and hopefully it's a decent representation of how HMC works on a conceptual level.

pic2

First, I'd like to know: Am I on the right track? My second question is (if so) is total energy (potential + kinetic) constant? And third, if so, does the algorithm randomly convert some potential energy into kinetic energy (and vice versa) in order to cause the "satellite" to jump energy levels?

I've based my understanding on Betancourt's paper https://arxiv.org/pdf/1701.02434.pdf which goes a decent bit over my head!

EditEdit1: Someone pointed out to me that the closer a satellite is to a planet, the stronger the effects of gravity. The stronger the effects of gravity, the more kinetic energy needed to maintain orbit. So, I had it backwards, the satellite will orbit the planet more faster when it's closer to the planet. However, the relationship between distance and samples collected remains the same. The faster a satellite moves, the more frequently it "passes by" the geographic region, and the more samples it collects. The further a satellite is, the slower it moves, the less samples it collects.

Edit2: Updated graphic https://imgur.com/gallery/OBIE4xO

I'm trying to self educate on the inner working of HMC. I'd like verification that I'm on the right track.

I understand that the biggest idea with "old school" methods, like Metropolis-Hastings, is that they explore the probability space based on random proposals; if the proposal looks appealing, the algorithm moves and appeands the location to an array, otherwise it says and appends the same (unchanged) location to the array.

But as dimensionality increases, movements away from the central tendencies of the distribution look progressively less and less appealing - so much so that some areas never get explored (i.e. the sampler's approximation deviates too much from the actual distribution.)

So HMC doesn't randomly propose new locations. Rather, it views the central tendency as a planet that a satellite orbits and views likelihood as energy levels, composed of kinetic and potential energy. Random momentum "kicks" cause the satellite to jump up/down energy levels (and this is key to exploring different areas of the distribution.)

If a satellite can take x pictures/min, speed will directly affect how many pictures can be taken of a given geographical area before the satellite is too far along its orbital path to take another picture. The closer to the planet it is, the slower the speed, and the more pictures. The further it is from the planet, the higher speed and less pictures. (Where photo-count translates to the number of observations in a given region of the distribution.)

I'm not a physicist, so there's a good chance I'm totally wrong!

Here's a graphic that I made, and hopefully it's a decent representation of how HMC works on a conceptual level.

pic2

First, I'd like to know: Am I on the right track? My second question is (if so) is total energy (potential + kinetic) constant? And third, if so, does the algorithm randomly convert some potential energy into kinetic energy (and vice versa) in order to cause the "satellite" to jump energy levels?

I've based my understanding on Betancourt's paper https://arxiv.org/pdf/1701.02434.pdf which goes a decent bit over my head!

Edit: Someone pointed out to me that the closer a satellite is to a planet, the stronger the effects of gravity. The stronger the effects of gravity, the more kinetic energy needed to maintain orbit. So, I had it backwards, the satellite will orbit the planet more faster when it's closer to the planet. However, the relationship between distance and samples collected remains the same. The faster a satellite moves, the more frequently it "passes by" the geographic region, and the more samples it collects. The further a satellite is, the slower it moves, the less samples it collects.

I'm trying to self educate on the inner working of HMC. I'd like verification that I'm on the right track.

I understand that the biggest idea with "old school" methods, like Metropolis-Hastings, is that they explore the probability space based on random proposals; if the proposal looks appealing, the algorithm moves and appeands the location to an array, otherwise it says and appends the same (unchanged) location to the array.

But as dimensionality increases, movements away from the central tendencies of the distribution look progressively less and less appealing - so much so that some areas never get explored (i.e. the sampler's approximation deviates too much from the actual distribution.)

So HMC doesn't randomly propose new locations. Rather, it views the central tendency as a planet that a satellite orbits and views likelihood as energy levels, composed of kinetic and potential energy. Random momentum "kicks" cause the satellite to jump up/down energy levels (and this is key to exploring different areas of the distribution.)

If a satellite can take x pictures/min, speed will directly affect how many pictures can be taken of a given geographical area before the satellite is too far along its orbital path to take another picture. The closer to the planet it is, the slower the speed, and the more pictures. The further it is from the planet, the higher speed and less pictures. (Where photo-count translates to the number of observations in a given region of the distribution.)

I'm not a physicist, so there's a good chance I'm totally wrong!

Here's a graphic that I made, and hopefully it's a decent representation of how HMC works on a conceptual level.

pic2

First, I'd like to know: Am I on the right track? My second question is (if so) is total energy (potential + kinetic) constant? And third, if so, does the algorithm randomly convert some potential energy into kinetic energy (and vice versa) in order to cause the "satellite" to jump energy levels?

I've based my understanding on Betancourt's paper https://arxiv.org/pdf/1701.02434.pdf which goes a decent bit over my head!

Edit1: Someone pointed out to me that the closer a satellite is to a planet, the stronger the effects of gravity. The stronger the effects of gravity, the more kinetic energy needed to maintain orbit. So, I had it backwards, the satellite will orbit the planet more faster when it's closer to the planet. However, the relationship between distance and samples collected remains the same. The faster a satellite moves, the more frequently it "passes by" the geographic region, and the more samples it collects. The further a satellite is, the slower it moves, the less samples it collects.

Edit2: Updated graphic https://imgur.com/gallery/OBIE4xO

Adjusted physics.
Source Link
mjake
  • 117
  • 7
Loading
corrected slide
Source Link
mjake
  • 117
  • 7
Loading
Used advice from comments.
Source Link
mjake
  • 117
  • 7
Loading
Tweeted twitter.com/StackStats/status/1296416712930275328
Source Link
mjake
  • 117
  • 7
Loading