The following code evaluates probability mass function for all possible states of a model.
def PDF(size):
b = np.random.randn(size)
J = np.random.randn(size, size)
density_func = np.zeros(2**size)
states = dec2bin(size)
for i in range(2**size):
density_func[i] = np.exp((np.dot(b, states[i,:]) + np.dot(np.dot(states[i],J),states[i])))
Z = np.sum(density_func)
density_func = density_func / Z
return density_func
utility functions
def bitfield(n,size):
x = [int(x) for x in bin(n) [ 2 :]]
x = [0] * (size - len(x)) + x
return x
def dec2bin(size):
states = []
for i in range(2**size):
binary = bitfield(i, size)
states.append(binary)
return np.array(states)
The model is grid graph Markov random field. Each node of the graph can have two states {0, 1}, so the total number of possible states of the model is 2total number of nodes. Each instance of the for
loop is calculating the probability of that state. At end I want to calculate the joint probability distribution of all the nodes. The joint probability distribution of this model is as follows
$$ p(\mathbf{x}) = \tfrac{1}{z} exp(\mathbf{b}\cdot\mathbf{x} + \mathbf{x}\cdot\mathbf{J}\cdot\mathbf{x}) $$
\$b\$ and \$J\$ are model parameters and \$x\$ is a vector of present states of the system.
\$Z\$ is the normalizing constant which is calculated by summing up 'values' of each possible state of the system to convert them into probabilities.
When the variable size
is greater than 25 the code takes long time to execute. Is there a way to vectorize this code and speed it up?