I discovered this useful trick while I was recently working on an assignment question for Christfried Webers’ excellent Introduction to Statistical Machine Learning course. The idea is to simplify implementations of the belief propagation algorithm on acyclic factor graphs, using NumPy’s Einstein summation API.
- 2016-11-28: Add references.
The Einstein summation notation is a really convenient way to represent operations on multidimensional matrices. It’s primarily used when manipulating tensors in differential geometry and in relativistic field theories in physics, but we’ll be using it to do operations on discrete joint distributions, which are basically big normalized matrices. The distinction between a tensor and a matrix is that the tensor has to behave in a certain way under coordinate transformations; for our purposes, this (physically motivated) constraint is lifted.
All expressions are in terms of the elements of multidimensional objects. If an object is -dimensional, it must have distinct indices. For example, if is an matrix of real numbers, it is a -dimensional object (which we will call rank-2 from now on), and we write it down as .
If an index occurs both as a subscript and as a superscript in an expression, then it is summed over.
Following these rules, we can look at some simple examples. The inner product of two vectors is given by the shorthand
This kind of operation is called a contraction, since the result has lower rank than its inputs (in the case of the inner product, these are 0 and 1, respectively). Notice that we can construct objects of higher rank out of lower rank ones quite easily. The outer product
is an matrix whose element is given by the product . Note that the dual vectors and are in general related by the metric tensor: . In our case, the metric is the identity, so they are element-wise equal, and the only distinction is that one is a column vector and the other is a row vector. Hence, in this context, the matrices and are equal, since to get from one to the other we left-multiply by the identity.
Matrix-vector multiplication looks like
Here’s where the power of the notation starts to become apparent: note that in the above example, is a rank-3 matrix. By summing over the index, we are rotating in such a way that it is being multiplied with in the first dimension. To illustrate this further, consider the multiplication of two matrices and ; clearly the product is well-defined but is not. With the Einstein notation, the indices tell us explicitly which dimensions to sum over. Hence
is well defined, since it sums over the ‘slot’, whereas
is not well-defined. Note that flipping the order of two indices amounts to taking the transpose. As we will see, this feature is really helpful when it comes to marginalizing a multidimensional distribution.
Some final examples: we can compute the trace of a matrix by contracting with the Kronecker delta:
Given a vector whose entries are functions on some basis set , we can write down the Jacobian simply as
where we identify . Bonus: if you’re a statistician or a computer scientist, you now have all the tools you need to parse quantum field-theoretic Lagrangians:
Ok, back to the task at hand. I hope I’ve convinced you that the set of permissible operations with with these rules (more formally known as the Ricci calculus) generalize matrix algebra. Let’s see how we can use these to make marginalization cleaner when doing belief propagation.
Discrete distributions and marginalization in numpy
Before we get to belief propagation, let’s talk about the standard set-up: we have a discrete multi-dimensional probability mass function over a bunch of random variables , where each of the has its own finite sample space , and in general if . For example, we could have , etc.
The two most basic operations on are conditioning and marginalization. To marginalize, we wish to compute, for example,
In NumPy, we represent the probability mass function as a matrix of real numbers in the interval . To compute the sums above ‘by brute force’, we would sum over all the dimensions except the first. Similar to Matlab, this operation is most efficient in NumPy if it is vectorized. The best way to accomplish a simple sum like this is with
numpy.sum(...), specifying the dimensions to sum over. We can also do this with
import numpy as np A = np.random.rand(3,5,4,3,9,7,2) # make a random 7-dimensional array A /= np.sum(A) # normalize np.einsum('abcdefg->d',A) # marginalize :)
Note that repetition of indices does not necessarily imply a summation if they’re both super/subscripts. This lets us easily define element-wise products. For example:
B = np.random.rand(3,2) C = np.random.rand(3,5) A = np.einsum('ij,ik->ijk',B,C) # A has shape (3,2,5)
As long as the shapes match up, then we have combined two rank-2 tensors to make a rank 3 tensor without contracting, i.e. without summation. This is key when we want to compute the product of messages in belief propagation. More tips and tricks can be found at the einsum documentation page.
Following Bishop , We have a graphical model of discrete variables that induces some factorisation of the joint distribution where the factors are functions of the variable subsets . When it comes to marginalisation:
where is the product of factors in the subtree annexed by , and we interpret the subtree marginals as “messages”, which satisfy the mutually recursive relations:
where for all leaf factors and nodes we set and , respectively. Given a joint distribution corresponding to a graphical model, we can efficiently marginalise by evaluating the messages in equations (1) and (2). The subject of this post is the details of the implementation of these messages and their evaluation. Since we are dealing with discrete variables each factor is represented by a array, where is the size of the domain of .
Putting it together
Note that each of the messages is a marginal distribution with respect to , and so is a vector of size . The multiplication in equations and then corresponds to a bunch of elementwise matrix-vector products. This makes them amenable to the Einstein treatment. Rewriting equation with the Einstein notation, we have
Similarly for equation :
A short demo on a simple Bayesian network can be found here.
 C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006