Show code cell source
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib_inline
matplotlib_inline.backend_inline.set_matplotlib_formats('svg')
import seaborn as sns
sns.set_context("paper")
sns.set_style("ticks");
The Multivariate Normal - Marginalization#
Consider the \(N\)-dimensional multivariate normal:
where \(\boldsymbol{\mu}\) is a \(N\)-dimensional vector, \(\boldsymbol{\Sigma}\) is a positive-definite matrix. Let’s look at a component of \(\mathbf{X}\), say \(X_1\). What is its PDF? We can find it by marginalizing over the other components of \(\mathbf{X}\):
If you really do the integrals, you will find that the marginal PDF of \(X_1\) is a Gaussian with mean \(\mu_1\) and variance \(\Sigma_{11}\):
Similarly, the marginal PDF of \(X_2\) is a Gaussian with mean \(\mu_2\) and variance \(\Sigma_{22}\). And so on.
Let’s demonstrate this by sampling in the random vector \(\mathbf{X}\) and making the histogram of its \(X_1\) component.
Show code cell source
import numpy as np
import scipy.stats as st
# The mean vector
mu = np.array([1.0, 2.0])
# The covariance matrix
Sigma = np.array(
[
[2.0, 0.9],
[0.9, 4.0]
]
)
# The multivariate normal random vector
X = st.multivariate_normal(
mean=mu,
cov=Sigma
)
# Take some samples
num_samples = 10000
x_samples = X.rvs(size=num_samples)
# Now, just take the X1 components of these samples:
x1_samples = x_samples[:, 0]
# And draw their histogram
fig, ax = plt.subplots()
ax.hist(
x1_samples,
density=True,
bins=100,
alpha=0.5,
label="Histogram of $X_1$ samples"
)
# Compare to the theoretical marginal with mean:
mu1 = mu[0]
# And variance:
Sigma11 = Sigma[0, 0]
X1_theory = st.norm(
loc=mu1,
scale=np.sqrt(Sigma11)
)
x1s = np.linspace(
x1_samples.min(),
x1_samples.max(),
100
)
ax.plot(
x1s,
X1_theory.pdf(x1s),
label="Theoretical marginal"
)
ax.set_xlabel(r"$x_1$")
ax.set_ylabel(r"$p(x_1)$")
plt.legend(loc="best", frameon=False)
sns.despine(trim=True);
Questions#
Expand the code so that you produce the figure that gives you the marginal of the \(X_2\) component of \(\mathbf{X}\).
Getting the joint PDF of a subset of components of a multivariate Gaussian#
Take the same multivariate Gaussian as in the previous exercise, but now we are interested in the joint PDF of the first two components, \(X_1\) and \(X_2\). The joint PDF of \(X_1\) and \(X_2\) is given by the following expression:
If we do the integration, we get that \((X_1, X_2)\) is a bivariate Gaussian with mean vector \((\mu_1,\mu_2)\) and covariance matrix:
This sort of marginalization extends to any subset of components of a multivariate Gaussian.