Skip to main content

6  Random vectors and multivariate models

The output of a measurement system is rarely a single number. A feature vector may contain latency, energy consumption and measurement error. Multiple components can respond to shared conditions and carry information about each other. Linear algebra provides an efficient language for their joint behavior.

6.1 Means and covariance matrices

Let \(\mathbf X=(X_1,\ldots,X_d)^\top\). Its mean vector is \(\boldsymbol\mu=\operatorname{E}\mathbf X\), and, with finite second moments, its covariance matrix is

\[ \boxed{\Sigma=\operatorname{E}\left[ (\mathbf X-\boldsymbol\mu)(\mathbf X-\boldsymbol\mu)^\top \right]}. \]

The \((i,j)\) entry is \(\operatorname{Cov}(X_i,X_j)\). Diagonal entries are variances; the matrix is symmetric. For any deterministic vector \(\mathbf a\),

\[ \mathbf a^\top\Sigma\mathbf a =\operatorname{E}\left[(\mathbf a^\top(\mathbf X-\boldsymbol\mu))^2\right] =\operatorname{Var}(\mathbf a^\top\mathbf X)\ge0. \]

Hence every covariance matrix is positive semidefinite (PSD). If there is no nonzero linear combination of the variables that is constant almost surely, \(\Sigma\) is positive definite. A PSD matrix may be singular: the variables can obey exact linear constraints.

For a deterministic \(m\times d\) matrix \(A\) and vector \(\mathbf b\), let \(\mathbf Y=A\mathbf X+\mathbf b\). Linearity gives

\[ \operatorname{E}\mathbf Y=A\boldsymbol\mu+\mathbf b,\qquad \operatorname{Cov}(\mathbf Y)=A\Sigma A^\top. \]

For the second equality, expand \(\mathbf Y-\operatorname{E}\mathbf Y=A(\mathbf X-\boldsymbol\mu)\) inside the expected outer product and move the deterministic matrices outside the expectation.

6.1.1 Worked example: combining two sensors

Two unbiased measurements have errors with covariance matrix

\[ \Sigma=\begin{pmatrix}4&1\\1&1\end{pmatrix}. \]

An estimate combining the two sensors with weights \((w,1-w)\) has error variance

\[ V(w)=4w^2+2w(1-w)+(1-w)^2=3w^2+1. \]

Its minimum is at \(w=0\): use the second sensor alone. Although averaging independent sensors can reduce uncertainty, these errors are correlated and the first measurement adds no precision in this example. With independent errors of the same individual variances, the variance would instead be \(4w^2+(1-w)^2\), minimized at \(w=1/5\).

The off-diagonal entries determine whether combining measurements reduces uncertainty. It is not enough to know the separate standard deviations.

6.2 Multinomial counts

Generalize a Bernoulli trial to a trial with \(k\) mutually exclusive categories, having probabilities \(p_1,\ldots,p_k\) with \(\sum p_i=1\). Among \(n\) independent such trials, the count vector \(\mathbf C=(C_1,\ldots,C_k)\) has \(\sum_i C_i=n\). The multinomial probability mass function is

\[ \Pr(\mathbf C=\mathbf c) =\frac{n!}{\prod_{i=1}^k c_i!}\prod_{i=1}^k p_i^{c_i}, \qquad c_i\ge0,\ \sum_i c_i=n. \]

Derivation. Every particular ordered sequence containing \(c_i\) occurrences of category \(i\) has mass \(\prod p_i^{c_i}\) by independence. The number of distinct arrangements of this multiset is \(n!/(c_1!\cdots c_k!)\). Different sequences are disjoint.

Each \(C_i\) is a sum of Bernoulli indicators for its category, so \(C_i\sim\operatorname{Bin}(n,p_i)\). For a single trial, one-hot indicators satisfy \(I_iI_j=0\) for \(i\ne j\), giving covariance \(-p_i p_j\). Indicators from different trials are independent. Summing over trials,

\[ \begin{aligned} \operatorname{E}C_i &= np_i,\\ \operatorname{Var}(C_i)&=np_i(1-p_i),\\ \operatorname{Cov}(C_i,C_j)&=-np_i p_j\quad (i\ne j). \end{aligned} \]

In matrix notation, \(\operatorname{Cov}(\mathbf C)= n(\operatorname{diag}(\mathbf p)-\mathbf p\mathbf p^\top)\). Multiplying by the all-ones vector gives zero: \(\Sigma\mathbf1=\mathbf0\). The fixed-sum constraint makes the covariance matrix singular, regardless of the sample size.

6.2.1 Worked example: three request types

Suppose 40 requests independently belong to the small, medium and large classes with probabilities \((0.5,0.3,0.2)\). The mean count vector is \((20,12,8)\). The covariance of medium and large counts is \(-40(0.3)(0.2)=-2.4\). It is negative because adding a request to one category leaves fewer of the 40 requests for other categories.

6.3 The multivariate normal distribution

Let \(\mathbf Z\) have independent \(N(0,1)\) components. Its density factorizes:

\[ f_{\mathbf Z}(\mathbf z)=(2\pi)^{-d/2} \exp\left(-\frac12\mathbf z^\top\mathbf z\right). \]

A multivariate normal vector with mean \(\boldsymbol\mu\) and covariance \(\Sigma\) can be constructed as \(\mathbf X=\boldsymbol\mu+L\mathbf Z\), where \(LL^\top=\Sigma\). If \(\Sigma\) is positive definite, its Cholesky factor \(L\) is nonsingular and lower triangular. The affine transformation has inverse \(\mathbf z=L^{-1}(\mathbf x-\boldsymbol\mu)\) and changes volume by \(|\det L|\) (the change-of-variables theorem is developed in Chapter 7). Consequently,

\[ \boxed{ f_{\mathbf X}(\mathbf x) =\frac{\exp\{-\tfrac12(\mathbf x-\boldsymbol\mu)^\top \Sigma^{-1}(\mathbf x-\boldsymbol\mu)\}} {(2\pi)^{d/2}|\Sigma|^{1/2}} }. \]

Here \(\det\Sigma=(\det L)^2\) and \(\|L^{-1}(\mathbf x-\boldsymbol\mu)\|^2 =(\mathbf x-\boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x-\boldsymbol\mu)\).

The exponent is half a squared Mahalanobis distance: it measures displacement relative to the covariance structure. Density contours are ellipses in two dimensions, with axes along the eigenvectors of \(\Sigma\). Larger eigenvalues correspond to larger variation along the associated directions.

Two bivariate-normal density contour plots tilted in opposite directions for correlations 0.75 and minus 0.75.

Two normal distributions with the same marginals but opposite correlations.

For numerical work, avoid explicitly computing \(\Sigma^{-1}\). Solve linear systems involving \(\Sigma\) or its Cholesky factor. This is both more efficient and usually more stable.

6.3.1 Linear combinations and marginals

Every linear combination \(\mathbf a^\top\mathbf X\) is normally distributed, with mean \(\mathbf a^\top\boldsymbol\mu\) and variance \(\mathbf a^\top\Sigma\mathbf a\). To see this, write the combination as a linear combination of independent standard normals and use the normal MGF (Chapter 8), or use rotational invariance of the standard normal density.

Every subvector of a multivariate normal vector is multivariate normal. Select the corresponding components of \(\boldsymbol\mu\) and the principal submatrix of \(\Sigma\). If \(\Sigma\) is singular, the construction \(\boldsymbol\mu+L\mathbf Z\) with a rectangular factor still defines a Gaussian vector; the distribution is supported on a lower-dimensional affine subspace and does not have a full-dimensional density of the displayed form.

For jointly Gaussian variables, zero cross-covariance implies independence. A block-diagonal covariance matrix has block-diagonal inverse and determinant equal to the product of block determinants; the joint density therefore factorizes. The property is special to the joint Gaussian family, not a general rule about correlations.

6.4 Conditional normal distributions

Partition a jointly normal vector into two blocks:

\[ \begin{pmatrix}\mathbf X\\\mathbf Y\end{pmatrix} \sim N\left( \begin{pmatrix}\boldsymbol\mu_X\\\boldsymbol\mu_Y\end{pmatrix}, \begin{pmatrix} \Sigma_{XX}&\Sigma_{XY}\\ \Sigma_{YX}&\Sigma_{YY} \end{pmatrix} \right). \]

Assume \(\Sigma_{XX}\) is invertible. Set \(B=\Sigma_{YX}\Sigma_{XX}^{-1}\) and define the residual \(\mathbf R=\mathbf Y-\boldsymbol\mu_Y-B(\mathbf X-\boldsymbol\mu_X)\). Because it is an affine transformation of a Gaussian vector, \((\mathbf R,\mathbf X)\) is jointly Gaussian. Its cross-covariance is

\[ \operatorname{Cov}(\mathbf R,\mathbf X)= \Sigma_{YX}-B\Sigma_{XX}=0, \]

so the residual is independent of \(\mathbf X\). Its covariance, by expanding the matrix of the centered linear combination, is

\[ \begin{aligned} \Sigma_{RR} &=\Sigma_{YY}-B\Sigma_{XY}-\Sigma_{YX}B^\top +B\Sigma_{XX}B^\top\\ &=\Sigma_{YY}-\Sigma_{YX}\Sigma_{XX}^{-1}\Sigma_{XY}. \end{aligned} \]

Thus conditioning on \(\mathbf X=\mathbf x\) simply shifts the independent Gaussian residual:

\[ \begin{aligned} \mathbf Y\mid \mathbf X=\mathbf x\ \sim\ N\big(& \boldsymbol\mu_Y+\Sigma_{YX}\Sigma_{XX}^{-1} (\mathbf x-\boldsymbol\mu_X),\\ &\Sigma_{YY}-\Sigma_{YX}\Sigma_{XX}^{-1}\Sigma_{XY}\big). \end{aligned} \]

The conditional covariance is the Schur complement of \(\Sigma_{XX}\). Notice that it does not depend on the observed value \(\mathbf x\) in this Gaussian model.

6.4.1 Worked example: predict one measurement from another

Let \(X\) and \(Y\) have means 10 and 25, standard deviations 2 and 3, and correlation \(\rho=0.6\). The covariance is \(3.6\). Observing \(X=13\) gives

\[ \operatorname{E}[Y\mid X=13]=25+\frac{3.6}{4}(13-10)=27.7,\qquad \operatorname{Var}(Y\mid X)=9-\frac{3.6^2}{4}=5.76. \]

So \(Y\mid X=13\sim N(27.7,2.4^2)\). Knowing \(X\) changes the expected \(Y\) and reduces its variance relative to the marginal distribution. A correlation of zero would have produced no change in either quantity in this Gaussian model.

6.5 Python experiment: create a correlated normal sample

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(606)
mu = np.array([10.,25.])
Sigma = np.array([[4.,3.6],[3.6,9.]])
L = np.linalg.cholesky(Sigma)
assert np.allclose(L@L.T,Sigma)
z = rng.standard_normal((100_000,2))
x = mu + z @ L.T
print("Empirical mean:",x.mean(axis=0))
print("Empirical covariance:\n",np.cov(x,rowvar=False))
assert np.allclose(np.cov(x,rowvar=False),Sigma,atol=.14)
xx = np.linspace(3,17,200)
conditional_mean = mu[1] + Sigma[1,0]/Sigma[0,0]*(xx-mu[0])
plt.scatter(x[:2000,0],x[:2000,1],s=9,alpha=.25)
plt.plot(xx,conditional_mean,color="tab:red",lw=2,label="Conditional mean")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.show()

The fitted conditional-mean line falls through the center of the conditional vertical distributions. The spread about that line is a different uncertainty from the marginal spread of \(Y\).

6.6 Practice problems

Work in your browser with Google Colab, or download the notebooks for Jupyter.

Practice notebook

Open in Colab Download .ipynb

Worked solutions

Open in Colab Download .ipynb

6.6.1 Exercise 1: Is this a possible covariance matrix?

Decide whether \(\begin{pmatrix}1&2\\2&1\end{pmatrix}\) can be a covariance matrix. Demonstrate the failure using a linear combination and using the determinant.

For \(\mathbf a=(1,-1)^\top\), \(\mathbf a^\top\Sigma\mathbf a=1+1-4=-2\), an impossible variance. Also \(\det\Sigma=1-4=-3<0\); a symmetric PSD matrix has nonnegative eigenvalues and hence nonnegative determinant.

6.6.2 Exercise 2: Multinomial moments

For \(n=100\) observations from categories with probabilities \((.2,.5,.3)\), calculate the mean vector, covariance matrix, and variance of \(C_1+C_3\).

The mean vector is \((20,50,30)^\top\). Diagonal variances are 16, 25 and 21, and the pairwise covariances are \(-10,-6,-15\) for pairs \((1,2),(1,3),(2,3)\). Thus

\[ \Sigma=\begin{pmatrix}16&-10&-6\\-10&25&-15\\-6&-15&21\end{pmatrix}. \]

The sum \(C_1+C_3=100-C_2\) has variance 25. Directly, \(16+21+2(-6)=25\).

6.6.3 Exercise 3: A Gaussian conditional law

Suppose \(X\) and \(Y\) are jointly normal with means zero, variances 4 and 16, and covariance \(-4\). Find the distribution of \(Y\mid X=2\) and the variance of \(X+Y\).

The conditional mean is \((-4/4)(2)=-2\) and conditional variance is \(16-16/4=12\). So \(Y\mid X=2\sim N(-2,12)\). The variance of the sum is \(4+16+2(-4)=12\).

6.6.4 Exercise 4: Python — sample and transform a three-dimensional normal

Let \(\boldsymbol\mu=(1,2,3)^\top\) and \(\Sigma=\begin{pmatrix}4&1&0.5\\1&2&0.4\\0.5&0.4&1\end{pmatrix}\). Verify positive definiteness numerically, construct a Cholesky sampler, and simulate 120,000 observations. For \(A=\begin{pmatrix}1&-1&0\\0&1&1\end{pmatrix}\), calculate the theoretical mean and covariance of \(A\mathbf X\) and check them empirically.

The eigenvalues must be positive before a nonsingular Cholesky factorization is appropriate. The target covariance is computed from \(A\Sigma A^\top\), not by multiplying elementwise.

import numpy as np

rng = np.random.default_rng(613)
mu = np.array([1.,2.,3.])
S = np.array([[4.,1.,.5],[1.,2.,.4],[.5,.4,1.]])
A = np.array([[1.,-1.,0.],[0.,1.,1.]])
assert np.all(np.linalg.eigvalsh(S)>0)
L = np.linalg.cholesky(S)
x = mu+rng.standard_normal((120_000,3))@L.T
y = x@A.T
print("Theoretical mean:", A@mu)
print("Theoretical covariance:\n", A@S@A.T)
print("Empirical covariance:\n",np.cov(y,rowvar=False,ddof=0))
assert np.allclose(y.mean(axis=0),A@mu,atol=.03)
assert np.allclose(np.cov(y,rowvar=False,ddof=0),A@S@A.T,atol=.1)

For samples stored as rows, right multiplication by \(A^\top\) represents the same linear transformation as left multiplication of a column vector by \(A\).

6.6.5 Exercise 5: Python — predict a conditional distribution

For the Gaussian model in Exercise 3, simulate a large joint sample. Compare the distribution of \(Y\) for observations with \(1.95<X<2.05\) to the exact conditional distribution at \(X=2\). Estimate its mean and variance and check them as the interval becomes wider or narrower.

For a narrow bin, the conditional law approaches \(N(-2,12)\). A very narrow bin has fewer observations and larger simulation noise.

import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt

rng = np.random.default_rng(618)
S = np.array([[4.,-4.],[-4.,16.]])
x,y = rng.multivariate_normal([0,0],S,1_000_000).T
for half_width in [.5,.15,.05]:
    sub = y[np.abs(x-2)<half_width]
    print(half_width,sub.size,sub.mean(),sub.var())
sub = y[np.abs(x-2)<.05]
t = np.linspace(-14,10,400)
plt.hist(sub,bins=50,density=True,alpha=.45,label="Narrow conditioning bin")
plt.plot(t,norm.pdf(t,loc=-2,scale=np.sqrt(12)),lw=2,label="Exact conditional")
plt.legend()
plt.xlabel("Y")
plt.show()

Conditioning on a point is computed from the joint model, whereas a simulation approximates it through a neighborhood of positive mass.

6.6.6 Exercise 6: Python — diagnose a singular covariance

Draw 70,000 multinomial vectors with \(n=20\) and probabilities \((.25,.35,.4)\). Calculate the theoretical covariance, compare it with the empirical covariance, and use eigenvalues to identify the fixed-sum constraint.

import numpy as np

rng = np.random.default_rng(619)
p = np.array([.25,.35,.4])
n = 20
cov = n*(np.diag(p)-np.outer(p,p))
draws = rng.multinomial(n,p,size=70_000)
emp = np.cov(draws,rowvar=False,ddof=0)
print("Eigenvalues:",np.linalg.eigvalsh(cov))
print(emp)
assert np.all(draws.sum(axis=1)==n)
assert np.allclose(cov@np.ones(3),0)
assert np.allclose(emp,cov,atol=.12)

The smallest eigenvalue is zero up to floating-point roundoff. The corresponding direction is proportional to \((1,1,1)^\top\): there is no variation in the sum of counts.