Module contents
Lesson 12 of 24Core 100 min

Probabilistic PCA and factor analysis

Probabilistic PCA, linear Gaussian latent models, factor analysis and expectation-maximization.

After this lesson you can

  • Derive marginal and posterior distributions of linear Gaussian latent models.
  • Connect probabilistic PCA maximum likelihood to principal components.
  • Explain factor analysis and rotational ambiguity.
  • Apply EM and missing-data inference.

Before you start

Motivation: PCA gives a subspace, not a model

PCA answers a geometric question: which kk-dimensional subspace retains most variance or, equivalently, leaves least reconstruction error (the reconstruction view)? It is a powerful, inexpensive answer, but says nothing about how data were generated. There is no density on Rd\R^d, no noise model, and five concrete limitations follow:

  • No likelihood. You cannot say how likely a new observation is, compare k=5k=5 with k=8k=8 using a measure penalizing poor fit, or detect anomalies in a calibrated way.
  • Missing values are unresolved. Classical PCA has no criterion for jointly estimating the subspace and missing entries.
  • It cannot be mixed or composed. A density model combines with others (mixtures of local models, dynamic models, hierarchies); a subspace does not.
  • Noise is implicit. PCA measures error by Euclidean norm, treating all variables as equally reliable. A much noisier variable can pull PCA toward it.
  • Scores have vague meaning. What statistically are subspace coordinates?

The solution is familiar from Gaussian mixtures: write a generative model with latent variables and fit by maximum likelihood using EM. Here the latent variable is not a group label but a low-dimensional continuous vector z∈Rk\vb{z} \in \R^k, and data are a linear function of it plus noise. With isotropic noise this recipe is probabilistic PCA (PPCA), whose maximum-likelihood solution turns out to be ordinary PCA. With distinct diagonal noise per variable it is factor analysis (FA), an older model (Spearman proposed it in 1904 to measure intelligence) with qualitatively different behavior.

This lesson derives model marginal and posterior distributions, proves Tipping and Bishop’s (1999) closed-form solution, implements EM with missing data, studies factor analysis and rotational ambiguity, and ends with an application to returns, probabilistic canonical correlation analysis, and bridges to ICA and variational autoencoders.

The linear Gaussian latent-variable model

Identity covariance for z\vb{z} loses no generality: if z∼N(0,Σz)\vb{z} \sim \Normal(\vb{0}, \mat{\Sigma}_z), the model with WΣz1/2\mat{W}\mat{\Sigma}_z^{1/2} and z′=Σz−1/2z\vb{z}' = \mat{\Sigma}_z^{-1/2}\vb{z} is the same. The assumption k<dk < d makes the model useful: data covariance has a rank-kk part plus noise.

Proof

The pair (z,x−μ)(\vb{z}, \vb{x} - \vb{\mu}) is a linear transformation of Gaussian (z,ε)(\vb{z}, \vb{\varepsilon}), hence jointly Gaussian (Gaussian marginalization). By independence, E[x]=μ\E[\vb{x}] = \vb{\mu}, Cov⁡(x)=WCov⁡(z)W⊤+Cov⁡(ε)=C\Cov(\vb{x}) = \mat{W}\Cov(\vb{z})\mat{W}\T + \Cov(\vb{\varepsilon}) = \mat{C} and Cov⁡(x,z)=WCov⁡(z)=W\Cov(\vb{x}, \vb{z}) = \mat{W}\Cov(\vb{z}) = \mat{W}. This proves point 1.

For conditioning, the Gaussian conditioning formula gives E[z∣x]=W⊤C−1(x−μ)\E[\vb{z} \given \vb{x}] = \mat{W}\T\mat{C}\inv(\vb{x} - \vb{\mu}) and Cov⁡(z∣x)=I−W⊤C−1W\Cov(\vb{z} \given \vb{x}) = \mat{I} - \mat{W}\T\mat{C}\inv\mat{W}: point 3. To obtain point 2 use the Woodbury identity, C−1=Ψ−1−Ψ−1WGW⊤Ψ−1\mat{C}\inv = \mat{\Psi}\inv - \mat{\Psi}\inv\mat{W}\mat{G}\mat{W}\T\mat{\Psi}\inv, and define A=W⊤Ψ−1W\mat{A} = \mat{W}\T\mat{\Psi}\inv\mat{W}, so G=(I+A)−1\mat{G} = (\mat{I} + \mat{A})\inv:

W⊤C−1=W⊤Ψ−1−AGW⊤Ψ−1=(I−A(I+A)−1)W⊤Ψ−1=GW⊤Ψ−1,\mat{W}\T\mat{C}\inv = \mat{W}\T\mat{\Psi}\inv - \mat{A}\mat{G}\mat{W}\T\mat{\Psi}\inv = (\mat{I} - \mat{A}(\mat{I} + \mat{A})\inv)\mat{W}\T\mat{\Psi}\inv = \mat{G}\mat{W}\T\mat{\Psi}\inv,

because I−A(I+A)−1=(I+A−A)(I+A)−1\mat{I} - \mat{A}(\mat{I} + \mat{A})\inv = (\mat{I} + \mat{A} - \mat{A})(\mat{I} + \mat{A})\inv. Likewise, I−W⊤C−1W=I−GA=I−(I+A)−1A=G\mat{I} - \mat{W}\T\mat{C}\inv\mat{W} = \mat{I} - \mat{G}\mat{A} = \mat{I} - (\mat{I} + \mat{A})\inv\mat{A} = \mat{G}. PPCA follows with Ψ=σ2I\mat{\Psi} = \sigma^2\mat{I}: G=(I+W⊤W/σ2)−1=σ2M−1\mat{G} = (\mat{I} + \mat{W}\T\mat{W}/\sigma^2)\inv = \sigma^2\mat{M}\inv.

∎

Notice what you gain. Data covariance goes from d(d+1)/2d(d+1)/2 free parameters to “low rank plus diagonal” structure. Likelihood can be evaluated without inverting a d×dd \times d matrix: with Woodbury and the determinant lemma, det⁡C=det⁡Ψ det⁡(Ik+W⊤Ψ−1W)\det \mat{C} = \det\mat{\Psi}\,\det(\mat{I}_k + \mat{W}\T\mat{\Psi}\inv\mat{W}), each observation costs O(dk+k2)\bigO(dk + k^2) after O(dk2+k3)\bigO(dk^2 + k^3) work shared by all. The first cell checks all formulas numerically.

[ ]Marginal, posterior and inexpensive likelihood in numbersBrowser
import numpy as np
from scipy.stats import multivariate_normal

rng = np.random.default_rng(0)
d, k, n = 6, 2, 200_000
W = rng.normal(size=(d, k))
mu = rng.normal(size=d)
psi = np.array([0.3, 0.5, 0.2, 0.8, 0.4, 0.6])            # unicidades: ruido diagonal

Z = rng.normal(size=(n, k))
X = Z @ W.T + mu + np.sqrt(psi) * rng.normal(size=(n, d))
C = W @ W.T + np.diag(psi)
print("covarianza empírica menos (W W' + Psi), error máximo:", round(np.abs(np.cov(X.T) - C).max(), 4))

# posterior de un dato: fórmula de la lección frente a condicionar la gaussiana conjunta
x = X[0]
G = np.linalg.inv(np.eye(k) + (W.T / psi) @ W)
m_formula = G @ (W.T @ ((x - mu) / psi))
m_bruto = W.T @ np.linalg.solve(C, x - mu)
V_bruto = np.eye(k) - W.T @ np.linalg.solve(C, W)
print("media posterior, diferencia entre las dos vías:", np.abs(m_formula - m_bruto).max())
print("covarianza posterior, diferencia:", np.abs(G - V_bruto).max())

def logpdf_woodbury(x, mu, W, psi):
    """log N(x; mu, W W' + diag(psi)) en O(d k^2): Woodbury y lema del determinante."""
    d, k = W.shape
    r = x - mu
    a = W.T @ (r / psi)
    A = np.eye(k) + (W.T / psi) @ W
    quad = r @ (r / psi) - a @ np.linalg.solve(A, a)
    logdet = np.log(psi).sum() + np.linalg.slogdet(A)[1]
    return -0.5 * (d * np.log(2 * np.pi) + logdet + quad)

print("log p(x): Woodbury", round(logpdf_woodbury(x, mu, W, psi), 8), "| scipy (inversión directa)", round(multivariate_normal(mu, C).logpdf(x), 8))

PPCA: a pancake around a subspace

With Ψ=σ2I\mat{\Psi} = \sigma^2\mat{I} the geometry is easy to see. Probabilistic PCA (PPCA) is the linear Gaussian model with isotropic noise, x=Wz+μ+ε\vb{x} = \mat{W}\vb{z} + \vb{\mu} + \vb{\varepsilon} with ε∼N(0,σ2Id)\vb{\varepsilon} \sim \Normal(\vb{0}, \sigma^2\mat{I}_d). The plane {Wz+μ}\{\mat{W}\vb{z} + \vb{\mu}\} is the batter and noise gives thickness: the data cloud is a pancake, σ\sigma thick in each direction perpendicular to the plane, with Gaussian distribution N(0,WW⊤)\Normal(\vb{0}, \mat{W}\mat{W}\T) inside it.

For intuition let W=US\mat{W} = \mat{U}\mat{S} with orthonormal columns in U\mat{U} and S=diag⁡(s1,…,sk)\mat{S} = \diag(s_1, \dots, s_k). Then M=S2+σ2I\mat{M} = \mat{S}^2 + \sigma^2\mat{I} is diagonal and the posterior of z\vb{z} given x\vb{x} has mean and covariance

E[z∣x]j=sj2sj2+σ2⋅uj⊤(x−μ)sj,Var⁡(zj∣x)=σ2sj2+σ2.\begin{gathered} \E[\vb{z} \given \vb{x}]_j = \frac{s_j^2}{s_j^2 + \sigma^2}\cdot\frac{\vb{u}_j\T(\vb{x} - \vb{\mu})}{s_j}, \\ \Var(z_j \given \vb{x}) = \frac{\sigma^2}{s_j^2 + \sigma^2}. \end{gathered}

Look at the first factor: uj⊤(x−μ)/sj\vb{u}_j\T(\vb{x} - \vb{\mu})/s_j is the coordinate of the orthogonal projection of x\vb{x} onto the plane, expressed in z\vb{z} units. The posterior multiplies it by sj2/(sj2+σ2)<1s_j^2/(s_j^2 + \sigma^2) < 1: posterior mean shrinks toward the origin, more for weaker directions and noisier data, leaving residual uncertainty σ2/(sj2+σ2)\sigma^2/(s_j^2 + \sigma^2) ignored by orthogonal projection. Only as σ2→0\sigma^2 \to 0 does the posterior mean become the PCA projection and the posterior collapse to a point.

InteractiveThe PPCA pancake and its posterior
Data space R3\mathbb{R}^3: x=Wz+ε\mathbf{x} = \mathbf{W}\mathbf{z} + \boldsymbol\varepsilon
  • data
  • selected point
  • orthogonal projection (PCA)
  • reconstruction Wm\mathbf{W}\mathbf{m} (posterior mean)
Latent space R2\mathbb{R}^2: prior N(0,I)\mathcal{N}(\mathbf{0}, \mathbf{I}) and posterior of the selected point
  • circles of radius 1 and 2 (prior)
  • S−1U⊤x\mathbf{S}^{-1}\mathbf{U}^\top\mathbf{x} (orthogonal projection)
  • posterior mean m\mathbf{m} and two-standard-deviation ellipse
  • zi\mathbf{z}_i that generated this point
0.70
131
Noise variance σ2\sigma^20.4900.490
Shrinkage s12/(s12+σ2)s_1^2/(s_1^2+\sigma^2) (strong direction)0.8800.880
Shrinkage s22/(s22+σ2)s_2^2/(s_2^2+\sigma^2) (weak direction)0.6710.671
Distance between Wm\mathbf{W}\mathbf{m} and the orthogonal projection1.034
Distance from point to plane1.136
At σ2=0.49\sigma^2 = 0.49, the weak direction (s2=1s_2 = 1) shrinks by 33% and the strong direction by 12%. The posterior mean differs from the orthogonal projection, and the posterior ellipse has standard deviations 0.350.35 and 0.570.57.
Model x=Wz+ε\vb{x} = \mat{W}\vb{z} + \vb{\varepsilon} with W=U diag(1.9,1.0)\mat{W} = \mat{U}\,\mathrm{diag}(1.9, 1.0) in R3\R^3 and 150 points generated with z∼N(0,I2)\vb{z} \sim \Normal(\vb{0}, \mat{I}_2) (the same z\vb{z} and noise samples for every σ\sigma). Left: cloud and plane of W\mat{W}; red is the selected point, orange its orthogonal projection (PCA), teal reconstruction from posterior mean. Right: latent plane, prior radius-1 and radius-2 circles and the selected point's posterior. Lower σ\sigma nearly to 0 and watch the cloud flatten and the two points coincide; raise it to 1.5 and compare how much the weak-direction coordinate approaches the origin versus the strong one.

Tipping and Bishop’s closed-form solution

You have nn observations x1,…,xn\vb{x}_1, \dots, \vb{x}_n and seek maximum-likelihood (μ,W,σ2)(\vb{\mu}, \mat{W}, \sigma^2) (maximum likelihood estimator). With S=1n∑i(xi−xˉ)(xi−xˉ)⊤\mat{S} = \frac1n\sum_i(\vb{x}_i - \bar{\vb{x}})(\vb{x}_i - \bar{\vb{x}})\T the sample covariance with divisor nn, log-likelihood after substituting μ=xˉ\vb{\mu} = \bar{\vb{x}} (the sample mean maximizes over μ\vb{\mu} because C−1≻0\mat{C}\inv \succ 0 and (xˉ−μ)⊤C−1(xˉ−μ)(\bar{\vb{x}} - \vb{\mu})\T\mat{C}\inv(\bar{\vb{x}} - \vb{\mu}) only adds cost) is

ℓ(W,σ2)=−n2[dlog⁡2π+log⁡det⁡C+tr⁡(C−1S)],C=WW⊤+σ2I.\begin{gathered} \ell(\mat{W}, \sigma^2) = -\frac{n}{2}\Big[d\log 2\pi + \log\det\mat{C} + \tr(\mat{C}\inv\mat{S})\Big], \\ \mat{C} = \mat{W}\mat{W}\T + \sigma^2\mat{I}. \end{gathered}
Proof

Gradient in W\mat{W}. With  ⁣dlog⁡det⁡C=tr⁡(C−1 ⁣dC)\dd\log\det\mat{C} = \tr(\mat{C}\inv\dd\mat{C}),  ⁣dtr⁡(C−1S)=−tr⁡(C−1  ⁣dC C−1S)\dd\tr(\mat{C}\inv\mat{S}) = -\tr(\mat{C}\inv\,\dd\mat{C}\,\mat{C}\inv\mat{S}) and  ⁣dC= ⁣dW W⊤+W  ⁣dW⊤\dd\mat{C} = \dd\mat{W}\,\mat{W}\T + \mat{W}\,\dd\mat{W}\T we obtain ∂ℓ∂W=n(C−1SC−1W−C−1W)\pd{\ell}{\mat{W}} = n(\mat{C}\inv\mat{S}\mat{C}\inv\mat{W} - \mat{C}\inv\mat{W}). Since C\mat{C} is invertible, the point is stationary if and only if SC−1W=W\mat{S}\mat{C}\inv\mat{W} = \mat{W}.

Structure of W\mat{W}. Write the thin SVD W=ULV⊤\mat{W} = \mat{U}\mat{L}\mat{V}\T of rank q≤kq \le k, with U∈Rd×q\mat{U} \in \R^{d \times q} and V∈Rk×q\mat{V} \in \R^{k \times q} having orthonormal columns and diagonal L≻0\mat{L} \succ 0. Then CU=U(L2+σ2I)\mat{C}\mat{U} = \mat{U}(\mat{L}^2 + \sigma^2\mat{I}), so C−1U=U(L2+σ2I)−1\mat{C}\inv\mat{U} = \mat{U}(\mat{L}^2 + \sigma^2\mat{I})\inv. Substituting into SC−1W=W\mat{S}\mat{C}\inv\mat{W} = \mat{W} and simplifying LV⊤\mat{L}\mat{V}\T gives SU=U(L2+σ2I)\mat{S}\mat{U} = \mat{U}(\mat{L}^2 + \sigma^2\mat{I}): columns of U\mat{U} are eigenvectors of S\mat{S} with eigenvalues λj=lj2+σ2>σ2\lambda_j = l_j^2 + \sigma^2 > \sigma^2. This is the stated form of W\mat{W}.

Equation for σ2\sigma^2. In an eigenbasis of S\mat{S} containing UJ\mat{U}_J, C\mat{C} is diagonal with λj\lambda_j for j∈Jj \in J and σ2\sigma^2 elsewhere. Then ∂ℓ∂σ2=−n2[tr⁡C−1−tr⁡(C−1SC−1)]=−n2σ4∑j∉J(σ2−λj)\pd{\ell}{\sigma^2} = -\frac n2[\tr\mat{C}\inv - \tr(\mat{C}\inv\mat{S}\mat{C}\inv)] = -\frac{n}{2\sigma^4}\sum_{j \notin J}(\sigma^2 - \lambda_j), which vanishes exactly when σ2\sigma^2 is the mean discarded eigenvalue. This proves point 1.

Value at each stationary point. With log⁡det⁡C=∑Jlog⁡λj+(d−q)log⁡σ2\log\det\mat{C} = \sum_J\log\lambda_j + (d-q)\log\sigma^2 and tr⁡(C−1S)=q+∑j∉Jλj/σ2=d\tr(\mat{C}\inv\mat{S}) = q + \sum_{j \notin J}\lambda_j/\sigma^2 = d, we obtain ℓJ=−n2[dlog⁡2π+Φ(J)+d]\ell_J = -\frac n2[d\log 2\pi + \Phi(J) + d] with Φ(J)=∑j∈Jlog⁡λj+(d−q)log⁡σJ2\Phi(J) = \sum_{j \in J}\log\lambda_j + (d-q)\log\sigma^2_J. This is point 3 for J={1,…,k}J = \{1, \dots, k\}.

Comparison. Since ℓ→−∞\ell \to -\infty at the parameter boundary (when S≻0\mat{S} \succ 0), a maximum is attained and is stationary; show that J={1,…,k}J = \{1, \dots, k\} minimizes Φ\Phi among admissible JJ. (a) Exchange. Let a∈Ja \in J, b∉Jb \notin J with λb>λa\lambda_b > \lambda_a, J′=J∖{a}∪{b}J' = J \setminus \{a\} \cup \{b\} and δ=λb−λa\delta = \lambda_b - \lambda_a. Then σJ′2=σJ2−δ/(d−q)\sigma^2_{J'} = \sigma^2_J - \delta/(d-q), J′J' remains admissible (its noise variance decreases), and using log⁡(1+u)≤u\log(1+u) \le u, log⁡(1−u)≤−u\log(1-u) \le -u and λa>σJ2\lambda_a > \sigma^2_J,

Φ(J′)−Φ(J)=log⁡ ⁣(1+δλa)+(d−q)log⁡ ⁣(1−δ(d−q)σJ2)≤δ(1λa−1σJ2)<0.\Phi(J') - \Phi(J) = \log\!\Big(1 + \tfrac{\delta}{\lambda_a}\Big) + (d-q)\log\!\Big(1 - \tfrac{\delta}{(d-q)\sigma^2_J}\Big) \le \delta\Big(\tfrac{1}{\lambda_a} - \tfrac{1}{\sigma_J^2}\Big) < 0.

(b) Add. If q<kq < k, add to JJ the largest eigenvalue λb\lambda_b outside JJ: new σ′2\sigma^{\prime 2} is the mean of the rest, at most λb\lambda_b, and log concavity (log⁡σ2≥1d−qlog⁡λb+d−q−1d−qlog⁡σ′2\log\sigma^2 \ge \frac{1}{d-q}\log\lambda_b + \frac{d-q-1}{d-q}\log\sigma^{\prime 2}, since (d−q)σ2=λb+(d−q−1)σ′2(d-q)\sigma^2 = \lambda_b + (d-q-1)\sigma^{\prime 2}) gives Φ(J∪{b})≤Φ(J)\Phi(J \cup \{b\}) \le \Phi(J), with equality only if all eigenvalues outside JJ are equal (then adding makes no difference). Neither move worsens the objective and exchange strictly improves it, so the optimum is J={1,…,k}J = \{1, \dots, k\}. Admissibility holds because σML2\sigma^2_{\text{ML}} is the average of eigenvalues at most λk+1≤λk\lambda_{k+1} \le \lambda_k.

∎

Three interpretations of this result are worth understanding.

PPCA invents nothing. Its maximum-likelihood subspace is PCA’s, so everything you knew about PCA (covariance eigenvectors, explained variance) still holds. What is new is a meaningful σ2\sigma^2: the mean discarded variance, σML2=1d−k∑j>kλj\sigma^2_{\text{ML}} = \frac{1}{d-k}\sum_{j>k}\lambda_j.

Rotation R\mat{R} is a real freedom. WML\mat{W}_{\text{ML}} is not unique: WR\mat{W}\mat{R} gives the same C\mat{C} and likelihood for any orthogonal R\mat{R}. PPCA identifies the subspace, not coordinates within it. Factor analysis returns to this thread.

Reconstruction shrinks. With WML\mat{W}_{\text{ML}} (taking R=I\mat{R} = \mat{I}) and sj2=λj−σ2s_j^2 = \lambda_j - \sigma^2, the previous section’s factor is sj2/(sj2+σ2)=(λj−σ2)/λj=1−σ2/λjs_j^2/(s_j^2 + \sigma^2) = (\lambda_j - \sigma^2)/\lambda_j = 1 - \sigma^2/\lambda_j, and posterior reconstruction is x^=μ+Uk(I−σ2Λk−1)Uk⊤(x−μ)\hat{\vb{x}} = \vb{\mu} + \mat{U}_k(\mat{I} - \sigma^2\mat{\Lambda}_k\inv)\mat{U}_k\T(\vb{x} - \vb{\mu}). Each component shrinks by σ2/λj\sigma^2/\lambda_j: weak ones more, strong ones less. As σ2→0\sigma^2 \to 0 you recover orthogonal projection, what PCA does.

The next cell checks this on the 1797 load_digits digits (8×8 pixels), with k=10k = 10. Practical detail: sklearn.decomposition.PCA already implements this model (its score method is mean PPCA log-likelihood and noise_variance_ is σML2\sigma^2_{\text{ML}}), but estimates covariance with divisor n−1n-1, so values differ from the maximum-likelihood estimator by factor n/(n−1)n/(n-1).

[ ]Closed-form PPCA on digits versus scikit-learn PCABrowser
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

X, y = load_digits(return_X_y=True)
n, d = X.shape
k = 10

def loglik(X, mu, W, s2):
    """Media por dato de log N(x; mu, W W' + s2 I), con Woodbury: no forma ninguna matriz d x d."""
    n, d = X.shape
    k = W.shape[1]
    Xc = X - mu
    M = W.T @ W + s2 * np.eye(k)
    A = Xc @ W
    quad = ((Xc ** 2).sum(1) - np.einsum('ij,ij->i', A @ np.linalg.inv(M), A)) / s2
    logdet = (d - k) * np.log(s2) + np.linalg.slogdet(M)[1]
    return -0.5 * (d * np.log(2 * np.pi) + logdet + quad).mean()

def ppca_cerrada(X, k):
    """Solución de máxima verosimilitud de Tipping y Bishop (con R = I)."""
    n, d = X.shape
    mu = X.mean(axis=0)
    Xc = X - mu
    lam, U = np.linalg.eigh(Xc.T @ Xc / n)
    lam, U = lam[::-1], U[:, ::-1]
    s2 = lam[k:].mean()
    W = U[:, :k] * np.sqrt(lam[:k] - s2)
    return mu, W, s2, lam, U

mu, W, s2, lam, U = ppca_cerrada(X, k)
pca = PCA(n_components=k).fit(X)
print(f"sigma^2 de la PPCA (divisor n):        {s2:.4f}")
print(f"noise_variance_ de scikit-learn:        {pca.noise_variance_:.4f}  (divisor n-1; por n/(n-1) da {pca.noise_variance_ * (n - 1) / n:.4f})")

# el subespacio de W es el de PCA: cosenos de los ángulos principales
Q, _ = np.linalg.qr(W)
cos = np.linalg.svd(Q.T @ pca.components_.T, compute_uv=False)
print("menor coseno entre los subespacios:", round(cos.min(), 12))

print(f"log-verosimilitud media: PPCA {loglik(X, mu, W, s2):.5f} | PCA.score de scikit-learn {pca.score(X):.5f}")
Rm = np.linalg.qr(np.random.default_rng(1).normal(size=(k, k)))[0]
print(f"con W rotada por una R ortogonal al azar: {loglik(X, mu, W @ Rm, s2):.5f}")

# la reconstrucción de la PPCA no es la proyección ortogonal: encoge cada componente
Xc = X - mu
M = W.T @ W + s2 * np.eye(k)
rec_ppca = Xc @ W @ np.linalg.solve(M, W.T)
rec_pca = (Xc @ U[:, :k]) @ U[:, :k].T
print("norma de la reconstrucción PPCA / norma de la proyección PCA:", round(np.linalg.norm(rec_ppca) / np.linalg.norm(rec_pca), 4))
print("factor (lambda_j - s2)/lambda_j de las componentes 1, 5 y 10:", np.round((lam[[0, 4, 9]] - s2) / lam[[0, 4, 9]], 4))
print("autovalores 1, 10, 11 y 64:", np.round(lam[[0, 9, 10, 63]], 3), "| media de los 54 descartados:", round(s2, 3))

The last eigenvalue is 0, and not the only one: three pixels (top-left corner and both ends of the fifth row) are always zero in this dataset, so S\mat{S} has rank 61 and is not positive definite. The theorem required S≻0\mat{S} \succ 0 only to guarantee a maximum exists, and rank⁡S>k\rank\mat{S} > k suffices: any C\mat{C} with σ2→0\sigma^2 \to 0 then leaves part of data variance outside its rank-kk subspace and tr⁡(C−1S)→∞\tr(\mat{C}\inv\mat{S}) \to \infty. The average of 54 discarded values absorbs the three zeros and remains positive. Also PPCA reconstruction norm is 93.5% of PCA projection norm: shrinkage is small for strong components (factor 0.967 for first) and greater for weak ones (0.843 for tenth). This also answers “how many components?” with a measure: ℓ⋆(k)\ell^\star(k) or its penalized version. PCA(n_components='mle') chooses kk using Minka’s (2000) Bayesian approximation to this model’s evidence.

EM for PPCA: linear cost and missing data

Diagonalizing S\mat{S} costs O(nd2+d3)\bigO(nd^2 + d^3), prohibitive when dd is thousands and only k=10k = 10 components are needed. The alternative is the previous lesson’s EM algorithm applied to this model (Tipping and Bishop, 1999; Roweis, 1998), with z\vb{z} latent (EM lower bound). For each observation, the E-step is the theorem’s posterior:

E[zi]=M−1W⊤(xi−μ),E[zizi⊤]=σ2M−1+E[zi]E[zi]⊤.\begin{gathered} \E[\vb{z}_i] = \mat{M}\inv\mat{W}\T(\vb{x}_i - \vb{\mu}), \\ \E[\vb{z}_i\vb{z}_i\T] = \sigma^2\mat{M}\inv + \E[\vb{z}_i]\E[\vb{z}_i]\T. \end{gathered}

Expected complete log-likelihood is Q=−∑iE[d2log⁡σ2+12σ2∥xi−μ−Wzi∥2+12tr⁡(zizi⊤)]+constQ = -\sum_i\E\big[\frac d2\log\sigma^2 + \frac{1}{2\sigma^2}\norm{\vb{x}_i - \vb{\mu} - \mat{W}\vb{z}_i}^2 + \frac12\tr(\vb{z}_i\vb{z}_i\T)\big] + \text{const}. Differentiating:

∑i(xi−μ) E[zi]⊤=W∑iE[zizi⊤]\begin{aligned} & \sum_i(\vb{x}_i - \vb{\mu})\,\E[\vb{z}_i]\T \\ & \quad = \mat{W}\sum_i\E[\vb{z}_i\vb{z}_i\T] \end{aligned}
This is condition ∂Q∂W=0\pd{Q}{\mat{W}} = \mat{0}. The term E∥x−μ−Wz∥2\E\norm{\vb{x} - \vb{\mu} - \mat{W}\vb{z}}^2 is quadratic in W\mat{W} with coefficients E[z]\E[\vb{z}] and E[zz⊤]\E[\vb{z}\vb{z}\T].
1/3

Substitution expresses the M-step in one line with S\mat{S}: Wnew=SW(σ2I+M−1W⊤SW)−1\mat{W}_{\text{new}} = \mat{S}\mat{W}(\sigma^2\mat{I} + \mat{M}\inv\mat{W}\T\mat{S}\mat{W})\inv and σnew2=1dtr⁡(S−SWM−1Wnew⊤)\sigma^2_{\text{new}} = \frac1d\tr(\mat{S} - \mat{S}\mat{W}\mat{M}\inv\mat{W}_{\text{new}}\T). But the point is not to form S\mat{S}: with centered data matrix X∈Rn×d\mat{X} \in \R^{n \times d}, the E-step needs XW\mat{X}\mat{W} and M-step X⊤E[Z]\mat{X}\T\E[\mat{Z}], two products costing O(ndk)\bigO(ndk); the rest are k×kk \times k matrices. One iteration costs O(ndk)\bigO(ndk) versus O(nd2)\bigO(nd^2) to form covariance, and can process data too large to fit in memory. Fixed points are the theorem’s stationary points and, according to Tipping and Bishop, stationary points other than the global maximum are saddles, so EM usually reaches PCA from almost any start, though in the basis W\mat{W} determined by initialization (not the eigenbasis).

[ ]EM for PPCA: monotonicity and convergence to the PCA subspaceBrowser
def ppca_em(X, k, iters=60, seed=0):
    """EM para PPCA. Nunca forma la covarianza d x d: solo productos con X, de coste O(n d k)."""
    n, d = X.shape
    mu = X.mean(axis=0)
    Xc = X - mu
    rng = np.random.default_rng(seed)
    W = rng.normal(size=(d, k))
    s2 = 1.0
    ll = []
    for _ in range(iters):
        Mi = np.linalg.inv(W.T @ W + s2 * np.eye(k))
        Ez = Xc @ W @ Mi                                   # E[z_i | x_i], n x k
        Szz = n * s2 * Mi + Ez.T @ Ez                      # suma de E[z z'], k x k
        W = (Xc.T @ Ez) @ np.linalg.inv(Szz)               # paso M para W
        s2 = (np.sum(Xc ** 2) - 2 * np.sum((Xc @ W) * Ez) + np.trace(Szz @ W.T @ W)) / (n * d)
        ll.append(loglik(X, mu, W, s2))
    return mu, W, s2, np.array(ll)

_, W_em, s2_em, ll = ppca_em(X, k, 60)
print("monótona (menor incremento de la log-verosimilitud):", f"{np.diff(ll).min():.2e}")
print(f"log-verosimilitud tras 1, 5, 20 y 60 iteraciones: {ll[0]:.3f}, {ll[4]:.3f}, {ll[19]:.5f}, {ll[59]:.5f}  | óptimo {loglik(X, mu, W, s2):.5f}")
print(f"sigma^2: EM {s2_em:.4f} | cerrada {s2:.4f}")
for t in (3, 6, 10, 20, 40):
    Wt = ppca_em(X, k, t)[1]
    Qt, _ = np.linalg.qr(Wt)
    c = np.linalg.svd(Qt.T @ U[:, :k], compute_uv=False).min()
    print(f"tras {t:2d} iteraciones: 1 - menor coseno con el subespacio de PCA = {1 - c:.2e}")

Output shows both predicted properties: ℓ\ell never decreases and W\mat{W} converges to the PCA subspace, not a particular W\mat{W} (the result depends on random initialization because of freedom R\mat{R}).

Missing data

What makes EM special here is that the same structure permits missing data without changing methods. If only coordinates OiO_i of row ii are observed, the observed vector follows N(μOi,WOiWOi⊤+σ2I)\Normal(\vb{\mu}_{O_i}, \mat{W}_{O_i}\mat{W}_{O_i}\T + \sigma^2\mat{I}), where WOi\mat{W}_{O_i} are rows of W\mat{W} for observed pixels. The E-step uses only those rows, Mi=σ2I+WOi⊤WOi\mat{M}_i = \sigma^2\mat{I} + \mat{W}_{O_i}\T\mat{W}_{O_i} and E[zi]=Mi−1WOi⊤(xOi−μOi)\E[\vb{z}_i] = \mat{M}_i\inv\mat{W}_{O_i}\T(\vb{x}_{O_i} - \vb{\mu}_{O_i}); the M-step works pixel by pixel: (μj,wj)(\mu_j, \vb{w}_j) is regression of xijx_{ij} on (1,zi)(1, \vb{z}_i) over rows observing pixel jj, using posterior moments; σ2\sigma^2 averages observed-pixel error plus wj⊤Cov⁡(zi)wj\vb{w}_j\T\Cov(\vb{z}_i)\vb{w}_j. Once fitted, a missing pixel’s prediction is E[xij∣xOi]=μj+wj⊤E[zi]\E[x_{ij} \given \vb{x}_{O_i}] = \mu_j + \vb{w}_j\T\E[\vb{z}_i].

Factor analysis in the next section works similarly: each row’s posterior uses only observed variables, Gi=(I+WOi⊤ΨOi−1WOi)−1\mat{G}_i = (\mat{I} + \mat{W}_{O_i}\T\mat{\Psi}_{O_i}\inv\mat{W}_{O_i})\inv with mean GiWOi⊤ΨOi−1(xOi−μOi)\mat{G}_i\mat{W}_{O_i}\T\mat{\Psi}_{O_i}\inv(\vb{x}_{O_i} - \vb{\mu}_{O_i}), and the M-step proceeds variable by variable, with (μj,wj)(\mu_j, \vb{w}_j) obtained by regression on (1,zi)(1, \vb{z}_i) and ψj\psi_j equal to the average over rows observing xjx_j of (xij−μj−wj⊤E[zi])2+wj⊤Giwj(x_{ij} - \mu_j - \vb{w}_j\T\E[\vb{z}_i])^2 + \vb{w}_j\T\mat{G}_i\vb{w}_j.

This EM maximizes observed-data likelihood, hence is the correct maximum-likelihood estimator under MCAR or MAR missingness (EM with missing data); if pixels are missing because of their values (MNAR), the result is biased even if EM converges.

InteractiveFilling pixels with EM-PPCA
Original (hidden from EM)
Observed, with missing pixels in red
Per-pixel mean imputation
EM-PPCA after 30 iterations
Error on missing pixels by EM iteration
  • EM-PPCA
  • per-pixel mean
40 %
5
EM iteration 30
Missing pixels6244 of 15360
Mean imputation error (RMSE)4.367
EM-PPCA error (RMSE), iteration 303.480
Reduction relative to mean imputation20.3 %
Lowest error on the curve (iteration)3.437 (5)
Change in ℓobs\ell_{\text{obs}} at this iteration+0.01+0.01
EM-PPCA achieves an error of 3.48 versus 4.37 for the mean after 30 iterations, with ℓobs\ell_{\text{obs}} increasing at every step.
240 load_digits digits (24 per class; labels unused) with a random fraction of pixels erased. EM-PPCA actually runs in the browser for 30 iterations, and the plot measures mean squared error on erased pixels against their true values (never seen by the model). Play from iteration 0: each step jointly estimates components and pixels. The orange line imputes each pixel's mean. Raise missing fraction to 80% and increase components: find where more components stop helping, and note which iteration minimizes the curve.

The next cell is the same algorithm, vectorized in NumPy, on 600 digits. For each missing-pixel fraction it compares mean-per-pixel imputation against EM-PPCA and checks that observed log-likelihood always rises.

[ ]EM-PPCA with missing data versus mean imputationBrowser
def ppca_em_faltantes(X, k, iters=25, seed=0):
    """EM para PPCA con NaN en X (MAR). Cada fila usa solo sus píxeles observados."""
    n, d = X.shape
    O = ~np.isnan(X)
    Of = O.astype(float)
    X0 = np.where(O, X, 0.0)
    rng = np.random.default_rng(seed)
    mu = X0.sum(0) / Of.sum(0)
    W = 0.1 * rng.normal(size=(d, k))
    s2 = np.var(X[O])
    I = np.eye(k)
    ll = []
    for _ in range(iters):
        # paso E, fila a fila con sus observados: M_i = s2 I + W_o' W_o
        R = (X0 - mu) * Of
        WW = (W[:, :, None] * W[:, None, :]).reshape(d, k * k)
        M = (Of @ WW).reshape(n, k, k) + s2 * I
        Mi = np.linalg.inv(M)
        b = R @ W
        Ez = np.einsum('ikl,il->ik', Mi, b)
        Ezz = s2 * Mi + Ez[:, :, None] * Ez[:, None, :]
        no = Of.sum(1)
        logdet = (no - k) * np.log(s2) + np.linalg.slogdet(M)[1]
        quad = ((R ** 2).sum(1) - np.einsum('ik,ik->i', b, Ez)) / s2
        ll.append(-0.5 * np.sum(no * np.log(2 * np.pi) + logdet + quad))   # log-verosimilitud observada
        # paso M, píxel a píxel: regresión de x_ij sobre [1, z_i] con las filas que lo observan
        T = np.zeros((n, k + 1, k + 1))
        T[:, 0, 0] = 1.0
        T[:, 0, 1:] = Ez
        T[:, 1:, 0] = Ez
        T[:, 1:, 1:] = Ezz
        A = (Of.T @ T.reshape(n, -1)).reshape(d, k + 1, k + 1)
        rhs = X0.T @ np.hstack([np.ones((n, 1)), Ez])
        sol = np.linalg.solve(A, rhs[:, :, None])[:, :, 0]
        mu, W = sol[:, 0], sol[:, 1:]
        res = (X0 - mu - Ez @ W.T) * Of
        WW = (W[:, :, None] * W[:, None, :]).reshape(d, k * k)
        s2 = float((res ** 2).sum() + ((Of @ WW) * (s2 * Mi).reshape(n, -1)).sum()) / Of.sum()
    return mu, W, s2, np.array(ll)

def imputar(X, mu, W, s2):
    """E[x_falta | x_obs] = mu + W E[z | x_obs]; los observados se dejan como están."""
    n, d = X.shape
    k = W.shape[1]
    O = ~np.isnan(X)
    Of = O.astype(float)
    R = (np.where(O, X, 0.0) - mu) * Of
    WW = (W[:, :, None] * W[:, None, :]).reshape(d, k * k)
    M = (Of @ WW).reshape(n, k, k) + s2 * np.eye(k)
    Ez = np.einsum('ikl,il->ik', np.linalg.inv(M), R @ W)
    return np.where(O, X, mu + Ez @ W.T)

rng = np.random.default_rng(3)
Xd = X[:600]                                             # 600 dígitos de 64 píxeles
print(f"{'faltan':>7} {'k':>3} {'RMSE media':>11} {'RMSE EM-PPCA':>13} {'¿l_obs monótona?':>17}")
for frac, kk in [(0.1, 8), (0.3, 8), (0.6, 8)]:
    falta = rng.random(Xd.shape) < frac
    Xm = np.where(falta, np.nan, Xd)
    mu_f, W_f, s2_f, ll_f = ppca_em_faltantes(Xm, kk)
    err_em = np.sqrt(np.mean((imputar(Xm, mu_f, W_f, s2_f)[falta] - Xd[falta]) ** 2))
    err_media = np.sqrt(np.mean((np.broadcast_to(np.nanmean(Xm, 0), Xm.shape)[falta] - Xd[falta]) ** 2))
    print(f"{frac:7.0%} {kk:3d} {err_media:11.3f} {err_em:13.3f} {str(bool(np.all(np.diff(ll_f) > 0))):>17}")

Three readings of the table and interactive. First, mean-imputation error barely depends on fraction (a pixel mean is well estimated from 540 or 240 observations), while EM-PPCA error rises with fraction because fewer observations per pixel estimate the subspace worse and each row contributes less to locating itself within it. Second, overfitting matters: with few rows per pixel, more components can worsen imputation even while ℓobs\ell_{\text{obs}} rises (in the interactive, at 70% or more, compare k=12k = 12 with k=5k = 5). Third, inspect the interactive curve’s shape: error falls in early iterations, reaches a minimum early (with 40% or more missing, between iterations four and seven), then rises while ℓobs\ell_{\text{obs}} continues increasing each step. With 70% missing and k=8k = 8, the rise is so strong that final imputation is worse than the mean, though halfway it was better. Early iterations learn common digit structure; later ones fit the few observed values of each pixel. Maximum likelihood does not protect against overfitting; use cross-validation on hidden pixels (also for early stopping) or the criteria in the section on choosing kk.

Factor analysis: different noise per variable

PPCA assumes all variables have equal noise, a strong assumption: height in meters and weight in grams are not measured with equal absolute precision. Factor analysis (FA) relaxes this in the same model, but with Ψ=diag⁡(ψ1,…,ψd)\mat{\Psi} = \diag(\psi_1, \dots, \psi_d) diagonal and different per variable:

xj=μj+wj⊤z+εj,εj∼N(0,ψj),Σ=WW⊤+Ψ.\begin{gathered} x_j = \mu_j + \vb{w}_j\T\vb{z} + \varepsilon_j, \quad \varepsilon_j \sim \Normal(0, \psi_j), \\ \mat{\Sigma} = \mat{W}\mat{W}\T + \mat{\Psi}. \end{gathered}

Each row wj∈Rk\vb{w}_j \in \R^k of W\mat{W} contains loadings of variable jj, hj2=∥wj∥2h_j^2 = \norm{\vb{w}_j}^2 is its communality (variance explained by common factors), and ψj\psi_j its uniqueness (its own part). Diagonal Ψ\mat{\Psi} is a modeling assumption: factors must explain all cross-variable correlations, and what remains in each variable is noise or its own traits, unconditionally independent across variables.

A difference in approach appears in covariance. PCA approximates S\mat{S} with a rank-kk matrix and therefore also tries to explain diagonal variances; FA only requires WW⊤\mat{W}\mat{W}\T to explain off-diagonal entries, absorbing the rest into Ψ\mat{\Psi}. Another consequence is scale equivariance: changing units of variable jj (multiplying by cj>0c_j > 0) changes the FA maximum-likelihood solution by W→DW\mat{W} \to \mat{D}\mat{W}, Ψ→D2Ψ\mat{\Psi} \to \mat{D}^2\mat{\Psi} (with D=diag⁡(cj)\mat{D} = \diag(c_j)), and mean log-likelihood per observation changes only by the variable-change Jacobian constant −∑jlog⁡cj-\sum_j\log c_j (the factor-analysis cell below checks this). Covariance PCA is not equivariant: converting weight from grams to kilograms changes components. In FA there is no need to decide whether to standardize (though often done to make loadings readable).

Why a noisy variable fools PCA

The effect appears with five variables and one factor, where the fifth barely depends on the factor (w5=0.35w_5 = 0.35) and its own noise ψ5\psi_5 increases. Here known truth (the simulation model described in the caption) lets us measure both solutions.

InteractiveA noisy variable fools PCA
Loadings of each variable on one factor
  • truth (wjw_j)
  • PCA (λ1 v1\sqrt{\lambda_1}\,\mathbf{v}_1)
  • factor analysis (w^j\hat w_j)
Cosine similarity to true loadings as ψ5\psi_5 increases
  • PCA
  • factor analysis
  • current ψ5\psi_5
3.00
Variable scale
X5X_5 loading in the first principal component1.581.58
X5X_5 loading in factor analysis0.310.31
True value (unstandardized)0.35
Cosine with true loadings: PCA0.676
Cosine with true loadings: factor analysis0.999
Estimated uniqueness ψ^5\hat\psi_52.972.97
PCA makes variable five dominate the first component (loading 1.58 versus true 0.35). Factor analysis estimates 0.31, treating its unique variance as noise.
Five variables, one factor, 500 observations simulated as xj=wjz+ψj ej\vb{x}_j = w_j z + \sqrt{\psi_j}\,e_j, loadings w=(0.9,0.8,0.7,0.6,0.35)\vb{w} = (0.9, 0.8, 0.7, 0.6, 0.35) and ψj=1−wj2\psi_j = 1 - w_j^2 for j≤4j \le 4. Only ψ5\psi_5 changes (same normals for all values). Bars compare true loading (gray), first PCA component loading (orange) and EM-fitted factor analysis (blue). Right: cosine between each estimate and true loadings as ψ5\psi_5 rises. Start at 3: PCA has made the fifth variable the first component axis. Then try 'Standardized': does standardization fix the problem?

The previous section explains this. The first principal component maximizes projected variance without distinguishing its origin: a high-uniqueness-variance variable attracts it even when uncorrelated with others. FA models that variance as uniqueness and excludes it from WW⊤\mat{W}\mat{W}\T. Standardizing fixes most of the deviation: the noisy variable has variance one like the others and no longer dominates. With the model’s population covariance and ψ5=3\psi_5 = 3, the first correlation-matrix component has cosine 0.997 with true standardized loadings. But the model is unchanged: PCA still tries to reproduce the diagonal with the low-rank part, so slightly overestimates the noisy variable’s loading (0.28 versus 0.20 in standardized units in that population calculation), while FA does not because it puts that variance in ψ5\psi_5. Standardizing does not replace modeling noise, but is a cheap mitigation, hence the figure’s comparison.

EM for factor analysis

As in PPCA, the E-step is the theorem’s posterior, now with nonscalar Ψ−1\mat{\Psi}\inv. With G=(I+W⊤Ψ−1W)−1\mat{G} = (\mat{I} + \mat{W}\T\mat{\Psi}\inv\mat{W})\inv and B=GW⊤Ψ−1\mat{B} = \mat{G}\mat{W}\T\mat{\Psi}\inv, we have E[zi]=B(xi−μ)\E[\vb{z}_i] = \mat{B}(\vb{x}_i - \vb{\mu}) and E[zizi⊤]=G+E[zi]E[zi]⊤\E[\vb{z}_i\vb{z}_i\T] = \mat{G} + \E[\vb{z}_i]\E[\vb{z}_i]\T. The EM algorithm for factor analysis (Rubin and Thayer, 1982; Ghahramani and Hinton, 1996) alternates that E-step with

Wnew=[∑i(xi−μ) E[zi]⊤][∑iE[zizi⊤]]−1,Ψnew=diag⁡(S−WnewBS).\begin{gathered} \mat{W}_{\text{new}} = \Big[\sum_i(\vb{x}_i - \vb{\mu})\,\E[\vb{z}_i]\T\Big]\Big[\sum_i\E[\vb{z}_i\vb{z}_i\T]\Big]\inv, \\ \mat{\Psi}_{\text{new}} = \diag\Big(\mat{S} - \mat{W}_{\text{new}}\mat{B}\mat{S}\Big). \end{gathered}

The W\mat{W} update is the same regression as PPCA. The Ψ\mat{\Psi} update follows by differentiating QQ with respect to each ψj\psi_j: ψj=1n∑iE[(xij−μj−wj⊤zi)2]\psi_j = \frac1n\sum_i\E[(x_{ij} - \mu_j - \vb{w}_j\T\vb{z}_i)^2], and since Wnew\mat{W}_{\text{new}} solves its normal equations, the quadratic term in wj\vb{w}_j simplifies against the cross term to 1n∑i[(xij−μj)2−wj⊤E[zi](xij−μj)]\frac1n\sum_i[(x_{ij} - \mu_j)^2 - \vb{w}_j\T\E[\vb{z}_i](x_{ij} - \mu_j)], the diagonal of S−WnewBS\mat{S} - \mat{W}_{\text{new}}\mat{B}\mat{S}. Each iteration works with S\mat{S} and k×kk \times k matrices, and likelihood never decreases.

[ ]Factor analysis by EM from scratch versus scikit-learn, equivariance and varimaxBrowser
from sklearn.decomposition import FactorAnalysis

def em_af(X, k, iters=1000, tol=1e-9, seed=0):
    """Análisis factorial por EM. Devuelve mu, W (d x k), psi (d,) y la historia de la log-verosimilitud media."""
    n, d = X.shape
    mu = X.mean(axis=0)
    Xc = X - mu
    S = Xc.T @ Xc / n
    rng = np.random.default_rng(seed)
    W = rng.normal(size=(d, k)) * np.sqrt(np.diag(S).mean() / k)
    psi = np.diag(S).copy()
    hist = []
    for it in range(iters):
        G = np.linalg.inv(np.eye(k) + (W.T / psi) @ W)       # covarianza posterior de z
        B = G @ (W.T / psi)                                    # E[z | x] = B (x - mu)
        Ezz = G + B @ S @ B.T                                  # media de E[z z']
        W = S @ B.T @ np.linalg.inv(Ezz)                       # paso M para W
        psi = np.diag(S - W @ B @ S).copy()                    # paso M para Psi
        C = W @ W.T + np.diag(psi)
        hist.append(-0.5 * (d * np.log(2 * np.pi) + np.linalg.slogdet(C)[1] + np.trace(np.linalg.solve(C, S))))
        if it and abs(hist[-1] - hist[-2]) < tol:
            break
    return mu, W, psi, np.array(hist)

# datos con tres factores y estructura "casi simple"; unicidades distintas por variable
rng = np.random.default_rng(7)
d, k, n = 10, 3, 2000
W0 = np.zeros((d, k))
W0[0:4, 0] = [0.9, 0.8, 0.7, 0.6]
W0[3:7, 1] = [0.5, 0.8, 0.7, 0.6]
W0[6:10, 2] = [0.4, 0.7, 0.8, 0.9]
W0[[4, 5, 9], 0] += [0.2, 0.1, 0.1]
psi0 = 1 - (W0 ** 2).sum(1)
Xf = rng.normal(size=(n, k)) @ W0.T + np.sqrt(psi0) * rng.normal(size=(n, d))

mu_f, W_f, psi_f, h = em_af(Xf, k)
fa = FactorAnalysis(n_components=k, tol=1e-8, max_iter=2000, random_state=0).fit(Xf)
print(f"EM propio: {len(h)} iteraciones, log-verosimilitud {h[-1]:.6f}, menor incremento {np.diff(h).min():.1e}")
print(f"scikit-learn: score {fa.score(Xf):.6f} ({fa.n_iter_} iteraciones)")
C_mia = W_f @ W_f.T + np.diag(psi_f)
C_sk = fa.components_.T @ fa.components_ + np.diag(fa.noise_variance_)
print("diferencia máxima entre las covarianzas modelo:", f"{np.abs(C_mia - C_sk).max():.1e}", "| entre unicidades:", f"{np.abs(psi_f - fa.noise_variance_).max():.1e}")
print("diferencia máxima entre las cargas sin rotar:", round(float(np.abs(W_f - fa.components_.T).max()), 3), "(son rotaciones una de otra)")
print("unicidades estimadas:", np.round(psi_f, 2))
print("unicidades verdaderas:", np.round(psi0, 2))

# equivarianza de escala: multiplicar variables por D multiplica W por D y Psi por D^2
D = np.array([1, 2, 1, 1, 3, 1, 1, 0.5, 1, 1])
_, W_D, psi_D, h_D = em_af(Xf * D, k)
print("psi(DX) / (D^2 psi(X)):", np.round(psi_D / (D ** 2 * psi_f), 3))
print("cambio de la log-verosimilitud media:", round(float(h_D[-1] - h[-1]), 6), "| -sum(log d_j):", round(float(-np.log(D).sum()), 6))

def varimax(W, iters=500, tol=1e-12):
    """Rotación varimax ortogonal (algoritmo de SVD sobre cargas sin normalizar)."""
    d, k = W.shape
    R = np.eye(k)
    crit = 0.0
    for _ in range(iters):
        L = W @ R
        u, s, vt = np.linalg.svd(W.T @ (L ** 3 - L @ np.diag((L ** 2).sum(0)) / d))
        R = u @ vt
        if s.sum() < crit * (1 + tol):
            break
        crit = s.sum()
    return W @ R, R

Wv, Rv = varimax(W_f)
Wsk = FactorAnalysis(n_components=k, rotation="varimax", tol=1e-8, max_iter=2000, random_state=0).fit(Xf).components_.T
perm = np.argmax(np.abs(Wv.T @ Wsk), axis=0)               # empareja columnas (el orden y el signo son arbitrarios)
print("diferencia con rotation='varimax' de scikit-learn:", f"{np.abs(np.abs(Wv[:, perm]) - np.abs(Wsk)).max():.1e}")
Sf = np.cov(Xf.T, bias=True)

def ll_af(W, psi):
    C = W @ W.T + np.diag(psi)
    return -0.5 * (d * np.log(2 * np.pi) + np.linalg.slogdet(C)[1] + np.trace(np.linalg.solve(C, Sf)))

print("log-verosimilitud antes y después de rotar:", round(ll_af(W_f, psi_f), 10), round(ll_af(Wv, psi_f), 10))
print("criterio varimax antes y después:", round(float((W_f ** 2).var(0).sum()), 4), round(float((Wv ** 2).var(0).sum()), 4))
np.set_printoptions(precision=2, suppress=True)
print("cargas tras varimax (columnas ordenadas por el emparejamiento):\n", Wv[:, perm])

Our EM and scikit-learn’s (which uses Barber’s SVD-based algorithm for the same likelihood) reach the same log-likelihood and model covariance, but not the same loadings: the next section explains why. The cell’s last three blocks (equivariance, varimax, log-likelihood before and after rotation) anticipate it.

Heywood cases

FA likelihood can reach its maximum at the parameter-space boundary with some uniqueness ψj=0\psi_j = 0: a Heywood case. Algebraically, the fit “wants” negative uniqueness variance, which is forbidden, and sticks at ψj=0\psi_j = 0 (the variable is completely explained by common factors: its communality equals variance). This is not a programming error: it signals model misspecification or excess flexibility. Common causes are few observations, too many factors, factors with only two or three variables, or a near-duplicate variable. Treat it by bounding ψj≥ε\psi_j \ge \varepsilon (scikit-learn uses 10−1210^{-12}), reducing kk, reviewing variables, or placing a prior on uniquenesses. The kk-selection cell below includes a minimal example where no real factor can reproduce correlations.

Rotational non-identifiability and varimax

PPCA had an arbitrary orthogonal R\mat{R}. The same occurs in FA, becoming an interpretation problem.

The proof is one line: (WR)(WR)⊤=WRR⊤W⊤=WW⊤(\mat{W}\mat{R})(\mat{W}\mat{R})\T = \mat{W}\mat{R}\mat{R}\T\mat{W}\T = \mat{W}\mat{W}\T, so C\mat{C} is unchanged (exercise 2 completes it). Consequently data cannot distinguish a factor from an orthogonal combination of factors: if factor 1 is “verbal ability,” an equally good rotated solution may call factor 1 “verbal ability plus 30% mathematics.” Both solutions are identical for all model statistics; only labels differ.

Parameter count: WW⊤\mat{W}\mat{W}\T retains only dk−k(k−1)/2dk - k(k-1)/2 degrees of freedom (subtract k(k−1)/2k(k-1)/2 rotations), so FA covariance structure has d(k+1)−k(k−1)/2d(k+1) - k(k-1)/2 free parameters, compared to d(d+1)/2d(d+1)/2 for full covariance. The difference

gl=d(d+1)2−[d(k+1)−k(k−1)2]=12[(d−k)2−(d+k)]\mathrm{gl} = \frac{d(d+1)}{2} - \Big[d(k+1) - \frac{k(k-1)}{2}\Big] = \frac12\Big[(d - k)^2 - (d + k)\Big]

is the number of covariance constraints imposed by the model. Requiring gl≥0\mathrm{gl} \ge 0, that is (d−k)2≥d+k(d-k)^2 \ge d + k, gives the Ledermann bound (1937) on factor count; for a testable model (more restrictive than full covariance), gl>0\mathrm{gl} > 0 is needed. With d=10d = 10 and k=3k = 3 there are 3737 parameters and gl=55−37=18\mathrm{gl} = 55 - 37 = 18. To fix a solution add a convention: W⊤Ψ−1W\mat{W}\T\mat{\Psi}\inv\mat{W} diagonal with decreasing entries (classical maximum-likelihood convention), or W\mat{W} zeros in predefined positions (confirmatory factor analysis).

Varimax rotation

Since any R\mat{R} works, choose one helping read factors: make each factor have a few large loadings and the rest nearly zero. Kaiser (1958) formalized this with varimax: among orthogonal rotations, maximize

V(W)=∑f=1k[1d∑j=1dwjf4−(1d∑j=1dwjf2)2],V(\mat{W}) = \sum_{f=1}^{k}\Big[\frac1d\sum_{j=1}^{d}w_{jf}^4 - \Big(\frac1d\sum_{j=1}^{d}w_{jf}^2\Big)^2\Big],

the sum over factors of variance of squared loadings. Maximizing pushes each column toward an unequal distribution: a few large squares and many near zero. Since ∑fwjf2=hj2\sum_f w_{jf}^2 = h_j^2 is communality, unchanged by rotation, VV cannot be inflated by growing all loadings: only by redistributing them. (Kaiser also proposed normalizing each row by communality before rotation to give variables equal weight; the version above is raw.)

With two factors there is a closed form. Write each variable as complex number cj=wj1+i wj2c_j = w_{j1} + \mathrm{i}\,w_{j2}; rotation by angle θ\theta is cj↦cje−iθc_j \mapsto c_j e^{-\mathrm{i}\theta}. With uj=wj12−wj22u_j = w_{j1}^2 - w_{j2}^2 and vj=2wj1wj2v_j = 2w_{j1}w_{j2}, the number cj2=uj+i vjc_j^2 = u_j + \mathrm{i}\,v_j rotates by 2θ2\theta and yields ∑f(1d∑jwjf4)=12d∑j(hj4+uj′2)\sum_f\big(\frac1d\sum_j w_{jf}^4\big) = \frac{1}{2d}\sum_j(h_j^4 + u_j'^2) and ∑f(1d∑jwjf2)2=12d2(H2+U′2)\sum_f(\frac1d\sum_j w_{jf}^2)^2 = \frac{1}{2d^2}(H^2 + U'^2), with uj′=ujcos⁡2θ+vjsin⁡2θu'_j = u_j\cos 2\theta + v_j\sin 2\theta, U′=∑juj′U' = \sum_j u'_j and constant H=∑jhj2H = \sum_j h_j^2. Thus

V(θ)=constant+12Var⁡j(ujcos⁡2θ+vjsin⁡2θ),V(\theta) = \text{constant} + \tfrac12\Var_j\big(u_j\cos2\theta + v_j\sin2\theta\big),

the variance of the projection of point cloud {cj2}\{c_j^2\} onto direction 2θ2\theta. It is maximal along the cloud’s principal axis, and VV has period 90∘90^\circ in θ\theta (hence four equivalent maxima: permute factors and flip signs). With centered u~,v~\tilde u, \tilde v, θ⋆=14atan2⁡(2 u~v~‾, u~2‾−v~2‾)\theta^\star = \frac14\operatorname{atan2}\big(2\,\overline{\tilde u\tilde v},\ \overline{\tilde u^2} - \overline{\tilde v^2}\big). For more than two factors rotate pairs of columns until convergence, or use the previous cell’s SVD algorithm, used by FactorAnalysis(rotation='varimax').

InteractiveRotations invisible to likelihood
Loading plane with each variable at (wj1,wj2)(w_{j1}, w_{j2})
  • X1 to X4 (load on the same factor in the simulation)
  • X5 to X8 (load on the other factor)
Loadings by variable and factor
  • factor 1
  • factor 2
Varimax criterion V(θ)V(\theta) with a 90° period
Log-likelihood ℓ(θ)\ell(\theta) in a window of ±1 around its value
0.0°
Log-likelihood ℓ(Wθ,Ψ)\ell(\mathbf{W}_\theta, \boldsymbol\Psi)−3834.699492−3834.699492
Largest deviation in ℓ\ell across the 181 angles1.4e-12
Varimax criterion V(Wθ)V(\mathbf{W}_\theta)0.03060.0306
Maximum of VV0.1472
Variables with a loading above 0.3 on both factors7
The rotation fits the data as well as any other (same ℓ\ell), but 7 variable(s) load on both factors, obscuring the structure. Click “Apply varimax”.
Eight variables and two factors; 400 simulated observations with simple structure (X1–X4 load on one factor, X5–X8 on the other). EM's solution from a random start is an arbitrary rotation of that structure. Rotate loadings with the slider: log-likelihood (actually recomputed at every angle, with a ±1 lower-plot window) does not move, while varimax has maxima every 90°. Press 'Apply varimax' and watch loadings become sparse, with almost each variable on one factor. At intermediate angles some variables load equally on both.
[ ]Varimax with two factors: closed form versus searchBrowser
# Dos factores: el ángulo varimax tiene forma cerrada. Con c_j = a_j + i b_j, rotar es c_j -> c_j e^{-i theta}
# y V(theta) = constante + (1/2) Var_j( Re[c_j^2 e^{-2 i theta}] ).
def angulo_varimax_2f(W):
    a, b = W[:, 0], W[:, 1]
    u, v = a ** 2 - b ** 2, 2 * a * b
    u, v = u - u.mean(), v - v.mean()
    return np.degrees(np.arctan2(2 * (u * v).mean(), (u ** 2).mean() - (v ** 2).mean()) / 4)

def rotar(W, grados):
    t = np.radians(grados)
    return W @ np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])

def V(W):
    return (W ** 4).mean(0).sum() - ((W ** 2).mean(0) ** 2).sum()

# cargas de dos factores con estructura simple, giradas 33 grados
W2 = np.array([[.85, .1], [.8, .05], [.75, -.1], [.7, .15], [.05, .8], [-.1, .75], [.1, .7], [.15, .65]])
Wg = rotar(W2, 33)
th = angulo_varimax_2f(Wg)
grid = np.arange(-45, 45, 0.01)
th_grid = grid[np.argmax([V(rotar(Wg, g)) for g in grid])]
print(f"ángulo varimax: fórmula cerrada {th:.3f} grados | búsqueda en rejilla {th_grid:.2f} grados")
print(f"V antes {V(Wg):.4f} | tras rotar por la fórmula {V(rotar(Wg, th)):.4f} | cargas verdaderas {V(W2):.4f}")
print("diferencia máxima entre |cargas| rotadas y las de partida:", np.abs(np.abs(rotar(Wg, th)) - np.abs(W2)).max().round(3))

Varimax recovers the structure we planted because true structure was simple. This is no theorem about the world: it is a readability criterion. If true factors correlate, an orthogonal rotation cannot represent that; use oblique rotations (promax, oblimin). And if you want an identifiable rotation, a statistical criterion is needed, not an aesthetic one: factor non-Gaussianity (ICA).

Choosing the number of factors

Factor count is a hyperparameter; cross-check four approaches.

  • Likelihood-ratio test. With Σ^k\hat{\mat{\Sigma}}_k the kk-factor fit, S\mat{S} sample covariance (the saturated model) and ℓ(Σ)\ell(\mat{\Sigma}) total sample log-likelihood at covariance Σ\mat{\Sigma}, statistic 2[ℓ(S)−ℓ(Σ^k)]=n[log⁡det⁡Σ^k−log⁡det⁡S+tr⁡(Σ^k−1S)−d]2[\ell(\mat{S}) - \ell(\hat{\mat{\Sigma}}_k)] = n\big[\log\det\hat{\mat{\Sigma}}_k - \log\det\mat{S} + \tr(\hat{\mat{\Sigma}}_k\inv\mat{S}) - d\big] is compared with χgl2\chi^2_{\mathrm{gl}}; Bartlett’s correction multiplies by (n−1−(2d+5)/6−2k/3)/n(n - 1 - (2d+5)/6 - 2k/3)/n. Null: kk factors suffice. Increase kk until non-rejection. This is a chain of tests on the same data and depends on normality.
  • BIC =−2ℓ+(parameters)log⁡n= -2\ell + (\text{parameters})\log n and AIC =−2ℓ+2(parameters)= -2\ell + 2(\text{parameters}), with d(k+1)−k(k−1)/2d(k+1) - k(k-1)/2 parameters.
  • Validation-data likelihood, the most reliable measure when data are plentiful.
  • Eigenvalue criteria (scree plot, Kaiser rule of eigenvalues above one): these are for correlation-matrix PCA and do not follow from the factor model.
[ ]Choosing k using BIC, Bartlett test and validation, and a Heywood caseBrowser
from scipy.stats import chi2

def em_af_cov(S, k, iters=3000, tol=1e-12, floor=1e-6, seed=0):
    """EM del análisis factorial sobre la covarianza S, con cota inferior floor para las unicidades."""
    d = S.shape[0]
    rng = np.random.default_rng(seed)
    W = rng.normal(size=(d, k)) * np.sqrt(np.diag(S).mean() / k)
    psi = np.diag(S).copy()
    prev = -np.inf
    for it in range(iters):
        G = np.linalg.inv(np.eye(k) + (W.T / psi) @ W)
        B = G @ (W.T / psi)
        W = S @ B.T @ np.linalg.inv(G + B @ S @ B.T)
        psi = np.maximum(np.diag(S - W @ B @ S), floor)
        C = W @ W.T + np.diag(psi)
        ll = -0.5 * (d * np.log(2 * np.pi) + np.linalg.slogdet(C)[1] + np.trace(np.linalg.solve(C, S)))
        if abs(ll - prev) < tol:
            break
        prev = ll
    return W, psi, ll, it + 1

def ll_gauss(C, S):
    d = len(C)
    return -0.5 * (d * np.log(2 * np.pi) + np.linalg.slogdet(C)[1] + np.trace(np.linalg.solve(C, S)))

# Elegir k: tres factores verdaderos, 500 datos para ajustar y 500 para validar
rng = np.random.default_rng(11)
d, k0, n = 10, 3, 500
W3 = np.zeros((d, k0))
W3[0:4, 0] = [.9, .8, .7, .6]
W3[3:7, 1] = [.5, .8, .7, .6]
W3[6:10, 2] = [.4, .7, .8, .9]
psi3 = 1 - (W3 ** 2).sum(1)

def simular(n):
    return rng.normal(size=(n, k0)) @ W3.T + np.sqrt(psi3) * rng.normal(size=(n, d))

Xa, Xv = simular(n), simular(n)
mu_a = Xa.mean(0)
Sa = (Xa - mu_a).T @ (Xa - mu_a) / n
Sv = (Xv - mu_a).T @ (Xv - mu_a) / n
print(f"{'k':>2} {'parám.':>6} {'gl':>3} {'ll ajuste':>10} {'ll validación':>13} {'BIC':>9} {'AIC':>9} {'p Bartlett':>10}")
for k in range(0, 7):
    if k == 0:
        C = np.diag(np.diag(Sa))
    else:
        Wk, pk, _, _ = em_af_cov(Sa, k)
        C = Wk @ Wk.T + np.diag(pk)
    npar = d * (k + 1) - k * (k - 1) // 2
    gl = d * (d + 1) // 2 - npar
    ll = ll_gauss(C, Sa)
    T = 2 * n * (ll_gauss(Sa, Sa) - ll)
    Tb = (n - 1 - (2 * d + 5) / 6 - 2 * k / 3) * T / n
    p = chi2.sf(Tb, gl) if gl > 0 else float("nan")
    print(f"{k:2d} {npar:6d} {gl:3d} {ll:10.3f} {ll_gauss(C, Sv):13.3f} {-2 * n * ll + npar * np.log(n):9.1f} {-2 * n * ll + 2 * npar:9.1f} {p:10.3f}")

# Un caso de Heywood: tres variables, un factor y correlaciones que ningún factor real puede reproducir
R = np.array([[1, .9, .9], [.9, 1, .7], [.9, .7, 1.]])
Wh, ph, llh, its = em_af_cov(R, 1)
print(f"\nHeywood: cargas {np.round(Wh.ravel(), 3)}, unicidades {np.round(ph, 6)} tras {its} iteraciones")
print(f"log-verosimilitud {llh:.4f}; con la matriz saturada (imposible aquí) sería {ll_gauss(R, R):.4f}")
w1 = np.sqrt(.9 * .9 / .7)
print(f"el sistema exacto da w1^2 = {w1 ** 2:.2f} > 1, es decir, psi_1 = {1 - w1 ** 2:.2f} < 0: fuera del espacio de parámetros")

Four output observations. On fit data, log-likelihood rises with kk and cannot select it; BIC and AIC are minimized at k=3k = 3, the true count; validation log-likelihood stops improving at k=3k = 3; and Bartlett’s test stops rejecting at k=3k = 3 (p≈0.56p \approx 0.56), clearly rejecting k=0,1,2k = 0, 1, 2. For k≥4k \ge 4, gains on seen data are negligible. The final part is a Heywood case: with three variables and one factor the model exactly reproduces three correlations (df =0= 0), but exact solution requires ψ1<0\psi_1 < 0; EM crawls toward the boundary: after 3000 iterations ψ1≈7×10−5\psi_1 \approx 7 \times 10^{-5} keeps falling (still above our 10−610^{-6} floor because EM converges very slowly near the boundary), loading w1=0.987w_1 = 0.987 approaches 1, the other two uniquenesses remain at 0.190.19, and likelihood remains below the saturated covariance, unattainable here.

Application: a factor model of returns

In finance, a factor model explains returns of dd assets using kk common risk factors plus asset-specific risk: rt=μ+Bft+εt\vb{r}_t = \vb{\mu} + \mat{B}\vb{f}_t + \vb{\varepsilon}_t, with Cov⁡(rt)=BΣfB⊤+Ψ\Cov(\vb{r}_t) = \mat{B}\mat{\Sigma}_f\mat{B}\T + \mat{\Psi}. This is exactly this lesson’s model (with W=BΣf1/2\mat{W} = \mat{B}\mat{\Sigma}_f^{1/2}), with two practical benefits. Estimation shrinks from d(d+1)/2d(d+1)/2 covariances to d(k+1)−k(k−1)/2d(k+1) - k(k-1)/2 parameters, and resulting covariance is invertible even with fewer dates than assets, needed for a minimum-variance portfolio (w∝Σ−11\mat{w} \propto \mat{\Sigma}\inv\vb{1}). Statistical factors (unobserved, estimated by PCA or FA) come from arbitrage pricing theory (Ross, 1976) and approximate factor structures (Chamberlain and Rothschild, 1983). The platform’s quantitative finance area revisits this with observed factors and risk estimation.

The lab simulates a market with known truth: 30 assets, three factors (the first with exposures near 1, like a market factor; the other two with variable-sign exposures), and idiosyncratic volatility varying greatly across assets. With T=250T = 250 days it fits four covariance estimates and evaluates them out of sample using three measures: log-likelihood on 5000 new days, relative Frobenius error against true covariance, and true risk of each estimate’s minimum-variance portfolio divided by that built using true covariance (1 is the unattainable optimum).

[ ]Returns with three factors: sample, PPCA, PCA plus diagonal and factor analysisBrowser
import numpy as np

# Mercado sintético: 30 activos, 3 factores y ruido idiosincrático con volatilidades muy distintas
rng = np.random.default_rng(2024)
d, k = 30, 3
B = np.column_stack([rng.normal(1.0, 0.25, d), rng.normal(0, 0.6, d), rng.normal(0, 0.6, d)])   # exposiciones
vol_f = np.array([0.010, 0.006, 0.005])                                                           # volatilidad diaria de los factores
vol_e = np.exp(rng.normal(np.log(0.010), 0.5, d))                                                 # volatilidad idiosincrática diaria
Sigma = B @ np.diag(vol_f ** 2) @ B.T + np.diag(vol_e ** 2)
print(f"volatilidad idiosincrática: mínima {vol_e.min():.4f}, máxima {vol_e.max():.4f} (cociente de varianzas {(vol_e.max() / vol_e.min()) ** 2:.0f})")
print("autovalores de la parte factorial B S_f B' (x1e-4):", np.round(np.sort(np.linalg.eigvalsh(B @ np.diag(vol_f ** 2) @ B.T))[::-1][:3] * 1e4, 2))
print("mayores varianzas idiosincráticas (x1e-4):", np.round(np.sort(vol_e ** 2)[::-1][:3] * 1e4, 2))
print("autovalores de la covarianza verdadera (x1e-4):", np.round(np.sort(np.linalg.eigvalsh(Sigma))[::-1][:4] * 1e4, 2))

def simular(T):
    return rng.normal(size=(T, k)) * vol_f @ B.T + rng.normal(size=(T, d)) * vol_e

def estimadores(R, k):
    """Cuatro estimaciones de la covarianza con k factores, y los subespacios de factores de PCA y AF."""
    T = len(R)
    Rc = R - R.mean(0)
    S = Rc.T @ Rc / T
    lam, U = np.linalg.eigh(S)
    lam, U = lam[::-1], U[:, ::-1]
    s2 = lam[k:].mean()
    Wp = U[:, :k] * np.sqrt(lam[:k] - s2)
    out = {"muestral": S, "PPCA": Wp @ Wp.T + s2 * np.eye(d)}
    low = (U[:, :k] * lam[:k]) @ U[:, :k].T
    out["PCA + diagonal"] = low + np.diag(np.diag(S - low))
    W, psi = Wp.copy(), np.full(d, s2)                       # EM del AF, arrancando de la solución de PPCA
    prev = -np.inf
    for _ in range(500):
        G = np.linalg.inv(np.eye(k) + (W.T / psi) @ W)
        Bm = G @ (W.T / psi)
        W = S @ Bm.T @ np.linalg.inv(G + Bm @ S @ Bm.T)
        psi = np.maximum(np.diag(S - W @ Bm @ S), 1e-8)
        C = W @ W.T + np.diag(psi)
        ll = -0.5 * (np.linalg.slogdet(C)[1] + np.trace(np.linalg.solve(C, S)))
        if abs(ll - prev) < 1e-8:
            break
        prev = ll
    out["factorial (AF)"] = C
    return out, {"PCA": U[:, :k], "AF": W}

def ll_gauss(C, S):
    return -0.5 * (len(C) * np.log(2 * np.pi) + np.linalg.slogdet(C)[1] + np.trace(np.linalg.solve(C, S)))

uno = np.ones(d)
def min_var(C):
    w = np.linalg.solve(C, uno)
    return w / w.sum()
w_or = min_var(Sigma)
sd_or = np.sqrt(w_or @ Sigma @ w_or)

T, reps = 250, 12
res = {}
ang = {"PCA": [], "AF": []}
QB = np.linalg.qr(B)[0]
for _ in range(reps):
    R, Rt = simular(T), simular(5000)
    Ste = Rt.T @ Rt / len(Rt)
    covs, subs = estimadores(R, k)
    for nombre, sub in subs.items():                        # menor coseno entre el subespacio estimado y el verdadero
        ang[nombre].append(np.linalg.svd(np.linalg.qr(sub)[0].T @ QB, compute_uv=False).min())
    for nombre, C in covs.items():
        w = min_var(C)
        res.setdefault(nombre, []).append([ll_gauss(C, Ste), np.linalg.norm(C - Sigma) / np.linalg.norm(Sigma), np.sqrt(w @ Sigma @ w) / sd_or])
print(f"\nT = {T} días, {reps} repeticiones; media (desviación) por método")
print(f"{'método':<16} {'log-ver. fuera':>15} {'error relativo':>15} {'riesgo cartera/óptimo':>22}")
for nombre, v in res.items():
    v = np.array(v)
    m, s = v.mean(0), v.std(0)
    print(f"{nombre:<16} {m[0]:8.2f} ({s[0]:.2f}) {m[1]:8.3f} ({s[1]:.3f}) {m[2]:12.3f} ({s[2]:.3f})")

print("menor coseno entre el subespacio de factores estimado y el verdadero:", {n: round(float(np.mean(v)), 3) for n, v in ang.items()})

# con menos días que activos, la covarianza muestral es singular y el modelo factorial no
Rs = simular(20)
est = estimadores(Rs, k)[0]
print("\nT = 20 < 30 activos: rango de la covarianza muestral =", np.linalg.matrix_rank(est["muestral"]), "| menor autovalor del modelo factorial =", f"{np.linalg.eigvalsh(est['factorial (AF)']).min():.2e}")

The output, subject to the caveats of one synthetic experiment, says FA is best of four on all three measures and PPCA worst (even worse than sample covariance for portfolio risk): idiosyncratic variances differ by a factor of 124 between most and least noisy assets, so one σ2\sigma^2 is a badly misspecified noise model, penalized especially in minimum-variance portfolios depending on inverse covariance. Factor recovery tells the same story: the two weak factors contribute eigenvalues 3.4×10−43.4 \times 10^{-4} and 1.4×10−41.4 \times 10^{-4} to covariance, less than noise variance of the two most volatile assets (10.2×10−410.2 \times 10^{-4} and 9.5×10−49.5 \times 10^{-4}). In true covariance, second and third principal components are those noisy assets, not factors, and PCA mixes noise directions into its subspace (lower mean cosine with true subspace: 0.366 versus FA’s 0.856). “PCA plus diagonal” (completing PCA’s low-rank covariance with residual diagonal) fixes part of the problem, but does not jointly estimate W\mat{W} and Ψ\mat{\Psi}. FA’s advantage over sample covariance is moderate with T=250T = 250 and 30 assets; this is no universal recipe (other factors, heavy tails or weak factors may change ordering), but illustrates why the noise model matters. The last output line shows another practical advantage: with T=20<30T = 20 < 30 sample covariance has rank 19 and cannot be inverted, while factor-model covariance is positive definite.

Two views of the same data: canonical correlation

So far there was one view x\vb{x}. With two sets of variables measured on the same cases, x∈Rp\vb{x} \in \R^p and y∈Rq\vb{y} \in \R^q (for example an image and its description, or a patient’s symptoms and lab results), canonical correlation analysis (CCA) seeks directions a∈Rp\vb{a} \in \R^p and b∈Rq\vb{b} \in \R^q whose projections a⊤x\vb{a}\T\vb{x} and b⊤y\vb{b}\T\vb{y} are maximally correlated, then subsequent ones uncorrelated with earlier ones. With covariances Σxx,Σyy,Σxy\mat{\Sigma}_{xx}, \mat{\Sigma}_{yy}, \mat{\Sigma}_{xy}:

ρ1=max⁡a,ba⊤Σxyba⊤Σxxab⊤Σyyb.\rho_1 = \max_{\vb{a}, \vb{b}}\frac{\vb{a}\T\mat{\Sigma}_{xy}\vb{b}}{\sqrt{\vb{a}\T\mat{\Sigma}_{xx}\vb{a}}\sqrt{\vb{b}\T\mat{\Sigma}_{yy}\vb{b}}}.

Changing variables to u=Σxx1/2a\vb{u} = \mat{\Sigma}_{xx}^{1/2}\vb{a} and v=Σyy1/2b\vb{v} = \mat{\Sigma}_{yy}^{1/2}\vb{b} gives max⁡ u⊤Kv\max\ \vb{u}\T\mat{K}\vb{v} with ∥u∥=∥v∥=1\norm{\vb{u}} = \norm{\vb{v}} = 1 and K=Σxx−1/2ΣxyΣyy−1/2\mat{K} = \mat{\Sigma}_{xx}^{-1/2}\mat{\Sigma}_{xy}\mat{\Sigma}_{yy}^{-1/2}: the maximum is K\mat{K}‘s largest singular value and canonical correlations ρ1≥ρ2≥…\rho_1 \ge \rho_2 \ge \dots are all its singular values (SVD after whitening each view). The same solution is the generalized eigenvalue problem

(0ΣxyΣyx0)(ab)=ρ(Σxx00Σyy)(ab),\begin{pmatrix} \mat{0} & \mat{\Sigma}_{xy} \\ \mat{\Sigma}_{yx} & \mat{0} \end{pmatrix}\begin{pmatrix} \vb{a} \\ \vb{b} \end{pmatrix} = \rho\begin{pmatrix} \mat{\Sigma}_{xx} & \mat{0} \\ \mat{0} & \mat{\Sigma}_{yy} \end{pmatrix}\begin{pmatrix} \vb{a} \\ \vb{b} \end{pmatrix},

whose eigenvalues appear in pairs ±ρi\pm\rho_i: substituting a=Σxx−1/2u\vb{a} = \mat{\Sigma}_{xx}^{-1/2}\vb{u} and b=Σyy−1/2v\vb{b} = \mat{\Sigma}_{yy}^{-1/2}\vb{v} gives (0KK⊤0)(uv)=ρ(uv)\begin{pmatrix}\mat{0} & \mat{K} \\ \mat{K}\T & \mat{0}\end{pmatrix}\begin{pmatrix}\vb{u} \\ \vb{v}\end{pmatrix} = \rho\begin{pmatrix}\vb{u} \\ \vb{v}\end{pmatrix}, whose eigenvalues are ±\pm the singular values of K\mat{K}.

Probabilistic version (Bach and Jordan, 2005). Model both views with the same latent variables: z∼N(0,Im)\vb{z} \sim \Normal(\vb{0}, \mat{I}_m), x∣z∼N(Wxz+μx,Ψx)\vb{x} \given \vb{z} \sim \Normal(\mat{W}_x\vb{z} + \vb{\mu}_x, \mat{\Psi}_x) and y∣z∼N(Wyz+μy,Ψy)\vb{y} \given \vb{z} \sim \Normal(\mat{W}_y\vb{z} + \vb{\mu}_y, \mat{\Psi}_y), with Ψx,Ψy⪰0\mat{\Psi}_x, \mat{\Psi}_y \succeq 0 full covariance matrices (without FA’s diagonal restriction: noise within each view can correlate). This is factor analysis on joint (x,y)(\vb{x}, \vb{y}) with block-diagonal noise. According to that work its maximum-likelihood solution is Wx=ΣxxUxMx\mat{W}_x = \mat{\Sigma}_{xx}\mat{U}_x\mat{M}_x and Wy=ΣyyUyMy\mat{W}_y = \mat{\Sigma}_{yy}\mat{U}_y\mat{M}_y, with Ux,Uy\mat{U}_x, \mat{U}_y the first mm normalized canonical directions (Ux⊤ΣxxUx=I\mat{U}_x\T\mat{\Sigma}_{xx}\mat{U}_x = \mat{I}), MxMy⊤=Pm=diag⁡(ρ1,…,ρm)\mat{M}_x\mat{M}_y\T = \mat{P}_m = \diag(\rho_1, \dots, \rho_m) and spectral norms of Mx\mat{M}_x, My\mat{M}_y below one (again rotational freedom). Posterior mean E[z∣x]=Mx⊤Ux⊤(x−μx)\E[\vb{z} \given \vb{x}] = \mat{M}_x\T\mat{U}_x\T(\vb{x} - \vb{\mu}_x) is a rescaled canonical projection. The views are linked because WxWy⊤=ΣxxUxPmUy⊤Σyy\mat{W}_x\mat{W}_y\T = \mat{\Sigma}_{xx}\mat{U}_x\mat{P}_m\mat{U}_y\T\mat{\Sigma}_{yy} reproduces rank-mm cross-covariance Σxy\mat{\Sigma}_{xy}: what views share is exactly what common factors explain.

[ ]CCA by SVD, generalized eigenproblem and shared latentsBrowser
from scipy.linalg import eigh, sqrtm

rng = np.random.default_rng(5)
n, p, q, dz = 5000, 6, 5, 2
Wx, Wy = rng.normal(size=(p, dz)), rng.normal(size=(q, dz))
Z = rng.normal(size=(n, dz))                                   # factores compartidos
Xv = Z @ Wx.T + rng.normal(size=(n, p))                        # vista 1
Yv = Z @ Wy.T + rng.normal(size=(n, q))                        # vista 2
Sxx, Syy = np.cov(Xv.T), np.cov(Yv.T)
Sxy = (Xv - Xv.mean(0)).T @ (Yv - Yv.mean(0)) / (n - 1)

# (a) CCA por SVD de K = Sxx^{-1/2} Sxy Syy^{-1/2}
Sxx_mh, Syy_mh = np.linalg.inv(sqrtm(Sxx)).real, np.linalg.inv(sqrtm(Syy)).real
Ua, rho, Vta = np.linalg.svd(Sxx_mh @ Sxy @ Syy_mh)
print("correlaciones canónicas (SVD):", np.round(rho, 4))

# (b) lo mismo como problema de autovalores generalizado A v = rho B v
A = np.block([[np.zeros((p, p)), Sxy], [Sxy.T, np.zeros((q, q))]])
B = np.block([[Sxx, np.zeros((p, q))], [np.zeros((q, p)), Syy]])
vals = np.sort(eigh(A, B, eigvals_only=True))[::-1]
print("mayores autovalores generalizados:", np.round(vals[:5], 4), "| menores:", np.round(vals[-2:], 4), "(vienen en pares ±rho)")

# (c) la correlación de la primera pareja de proyecciones, medida directamente
a1, b1 = Sxx_mh @ Ua[:, 0], Syy_mh @ Vta[0]
print("corr(a1'x, b1'y) medida directamente:", round(float(np.corrcoef((Xv - Xv.mean(0)) @ a1, (Yv - Yv.mean(0)) @ b1)[0, 1]), 4))

# (d) ingredientes de la CCA probabilística: con dz latentes compartidas y M1 = M2 = P^{1/2}
U1, U2 = Sxx_mh @ Ua[:, :dz], Syy_mh @ Vta[:dz].T
Pm = np.diag(rho[:dz])
W1, W2 = Sxx @ U1 @ np.sqrt(Pm), Syy @ U2 @ np.sqrt(Pm)
U1f, U2f = Sxx_mh @ Ua[:, :q], Syy_mh @ Vta.T
print("con todas las parejas, Sxx U1 P U2' Syy = Sxy:", np.allclose(Sxx @ U1f @ np.diag(rho) @ U2f.T @ Syy, Sxy))
print("con solo dz parejas, error relativo ||Sxy - W1 W2'|| / ||Sxy|| =", round(float(np.linalg.norm(Sxy - W1 @ W2.T) / np.linalg.norm(Sxy)), 4))
print("menor autovalor de Psi1 = Sxx - W1 W1':", round(float(np.linalg.eigvalsh(Sxx - W1 @ W1.T).min()), 4), "(>= 0)")

# (e) con pocos datos CCA ve correlación perfecta entre variables independientes
m = 30
Xs, Ys = rng.normal(size=(m, 40)), rng.normal(size=(m, 40))
Xs, Ys = Xs - Xs.mean(0), Ys - Ys.mean(0)
Qx, Qy = np.linalg.qr(Xs)[0], np.linalg.qr(Ys)[0]
print("n = 30, 40 + 40 variables independientes: primera correlación canónica =", round(float(np.linalg.svd(Qx.T @ Qy, compute_uv=False)[0]), 4))

With two shared factors and independent noise in each view, only the first two canonical correlations are large (0.847 and 0.648); the rest, below 0.06, are sample noise. The two projection pairs reproduce cross-covariance with 0.9% relative error, and remaining Ψx\mat{\Psi}_x is positive definite as required. The last line is a practical warning: with nn below p+qp + q, covariances Σxx\mat{\Sigma}_{xx}, Σyy\mat{\Sigma}_{yy} are singular and CCA finds correlation one between independent variables, so regularize (add λI\lambda\mat{I} to covariances) or first reduce with PCA.

Bridges: ICA and variational autoencoders

This lesson leaves three bridges to cross later in the course.

Toward ICA. Rotational ambiguity exists because a standard Gaussian vector is rotation invariant: R⊤z\mat{R}\T\vb{z} has the same law as z\vb{z}. If factors are non-Gaussian and mutually independent, that invariance disappears and loadings are identified up to permutation and scale. Independent component analysis chooses rotation by non-Gaussianity rather than readability as in varimax.

Toward variational autoencoders. A VAE with linear Gaussian decoder p(x∣z)=N(Wz+μ,σ2I)p(\vb{x} \given \vb{z}) = \Normal(\mat{W}\vb{z} + \vb{\mu}, \sigma^2\mat{I}) and Gaussian approximate posterior is PPCA; maximizing its lower bound (the same as EM’s, now with qq parameterized by a network) recovers the PCA subspace (Lucas et al., 2019, study it as a toy model of posterior collapse). A nonlinear decoder retains the generative model but loses the closed-form solution and exact posterior.

Toward richer models. Mixtures of factor analyzers (Ghahramani and Hinton, 1996) and PPCA models (Tipping and Bishop, 1999) combine this model with discrete latent variables to approximate curved manifolds with linear pieces. Factor analysis with time-evolving factors under linear dynamics is the state-space model solved by the Kalman filter; extending to causal relationships among factors gives structural equation models.

Which to choose: PCA, PPCA or factor analysis

The choice concerns noise, not the algorithm:

  • PCA if you only want a maximum-variance subspace or compression and will not use likelihood. It is cheapest and has PPCA’s solution.
  • PPCA if you need a density (score new data, detect anomalies, compare kk, mix models, impute) and noise is reasonably homogeneous across variables, such as pixels of one sensor.
  • Factor analysis if variables have different precision or scales, or the correlation structure matters rather than their variances. It is the default candidate in psychometrics and finance and requires choosing a rotation to interpret factors.
  • If uncertain between PPCA and FA, fit both and compare validation likelihood: their difference tells you the value of modeling variable-specific noise for your problem.

Common mistakes

Exercises

ProofThe model's marginal and posterior
Prove: In x=Wz+μ+ε\vb{x} = \mat{W}\vb{z} + \vb{\mu} + \vb{\varepsilon} with independent z∼N(0,Ik)\vb{z} \sim \mathcal{N}(\vb{0}, \mat{I}_k) and ε∼N(0,Ψ)\vb{\varepsilon} \sim \mathcal{N}(\vb{0}, \mat{\Psi}), we have x∼N(μ,WW⊤+Ψ)\vb{x} \sim \mathcal{N}(\vb{\mu}, \mat{W}\mat{W}^\top + \mat{\Psi}) and z∣x∼N(GW⊤Ψ−1(x−μ),G)\vb{z} \mid \vb{x} \sim \mathcal{N}(\mat{G}\mat{W}^\top\mat{\Psi}^{-1}(\vb{x} - \vb{\mu}), \mat{G}) with G=(I+W⊤Ψ−1W)−1\mat{G} = (\mat{I} + \mat{W}^\top\mat{\Psi}^{-1}\mat{W})^{-1}. In PPCA (Ψ=σ2I\mat{\Psi} = \sigma^2\mat{I}), posterior mean is M−1W⊤(x−μ)\mat{M}^{-1}\mat{W}^\top(\vb{x} - \vb{\mu}) and covariance is σ2M−1\sigma^2\mat{M}^{-1} with M=W⊤W+σ2I\mat{M} = \mat{W}^\top\mat{W} + \sigma^2\mat{I}.
0
Let C=WW⊤+Ψ\mat{C} = \mat{W}\mat{W}^\top + \mat{\Psi}.

Step 1 of 4. How do you obtain the joint distribution of (z,x)(\vb{z}, \vb{x}) and its covariances?

ProofLikelihood cannot see rotations
Prove: For any orthogonal R∈Rk×k\mat{R} \in \mathbb{R}^{k \times k}, the log-likelihood of model x=Wz+μ+ε\vb{x} = \mat{W}\vb{z} + \vb{\mu} + \vb{\varepsilon} at (μ,WR,Ψ)(\vb{\mu}, \mat{W}\mat{R}, \mat{\Psi}) equals that at (μ,W,Ψ)(\vb{\mu}, \mat{W}, \mat{\Psi}) for any sample. Moreover, likelihood maxima are never isolated when k≥2k \ge 2 and W≠0\mat{W} \neq 0.
0
Let θ=(μ,W,Ψ)\theta = (\vb{\mu}, \mat{W}, \mat{\Psi}) and θR=(μ,WR,Ψ)\theta_R = (\vb{\mu}, \mat{W}\mat{R}, \mat{\Psi}).

Step 1 of 4. Which parameters determine log-likelihood of a sample x1,…,xn\vb{x}_1, \dots, \vb{x}_n?

NumericFree parameters in factor analysis
How many free parameters does covariance structure WW⊤+Ψ\mat{W}\mat{W}^\top + \mat{\Psi} of factor analysis have with d=10d = 10 variables and k=3k = 3 factors (excluding the mean)?
NumericPPCA parameters for digits
PPCA with d=64d = 64 pixels and k=10k = 10 components: how many free parameters does covariance WW⊤+σ2I\mat{W}\mat{W}^\top + \sigma^2\mat{I} have (excluding mean)?
NumericHow many factors?
With d=12d = 12 variables, what is the largest number of factors kk for which Ledermann degrees of freedom 12[(d−k)2−(d+k)]\frac12[(d-k)^2 - (d+k)] remain nonnegative?
NumericHow much does PPCA shrink?
A sample covariance in R5\mathbb{R}^5 has eigenvalues 10,6,2,1.5,0.510, 6, 2, 1.5, 0.5. Fit maximum-likelihood PPCA with k=2k = 2 and reconstruct each observation using posterior mean, W E[z∣x]\mathbf{W}\,\mathbb{E}[\mathbf{z} \mid \mathbf{x}]. Relative to orthogonal PCA projection, by what factor is the coordinate on the second principal component multiplied? (Three decimals.)
CodeFactor analysis by EM
Implement em_factor_analysis(X, k, max_iter=2000, tol=1e-10), accepting an (n, d) matrix X and returning (W, psi) with W shape (d, k) and psi shape (d,): maximum-likelihood loadings and uniquenesses for x=Wz+μ+ε\mathbf{x} = \mathbf{W}\mathbf{z} + \boldsymbol\mu + \boldsymbol\varepsilon with diagonal noise. Center data by their mean and use covariance with divisor nn. Initialize small random W\mathbf{W} (with a fixed seed) and ψj\psi_j as each variable’s variance, stopping when mean log-likelihood changes by less than tol. Tests compare likelihood with scikit-learn and scale equivariance.
import numpy as np

def em_factor_analysis(X, k, max_iter=2000, tol=1e-10):
  X = np.asarray(X, dtype=float)
  n, d = X.shape
  Xc = X - X.mean(axis=0)
  S = Xc.T @ Xc / n
  rng = np.random.default_rng(0)
  W = 0.1 * rng.normal(size=(d, k))
  psi = np.diag(S).copy()
  # tu código: paso E (G, B), paso M (W y psi) y criterio de parada con la log-verosimilitud
  return W, psi
Shift+Enter to run
QuizA Heywood case
You fit factor analysis and EM ends with uniqueness ψj≈10−8\psi_j \approx 10^{-8} for one variable. Which statements are correct?

More than one answer may be correct.

QuizPCA scores and posterior means
Let W=Uk(Λk−σ2I)1/2\mat{W} = \mat{U}_k(\mat{\Lambda}_k - \sigma^2\mat{I})^{1/2} be maximum-likelihood PPCA. Which statements about posterior mean E[z∣x]\E[\vb{z} \given \vb{x}] and PCA score s=Uk⊤(x−μ)\vb{s} = \mat{U}_k\T(\vb{x} - \vb{\mu}) are correct?

More than one answer may be correct.

QuizPCA, PPCA or factor analysis?
In which scenarios is the stated choice reasonable?

More than one answer may be correct.

Summary

Key idea
A linear Gaussian latent-variable model, x=Wz+μ+ε\vb{x} = \mat{W}\vb{z} + \vb{\mu} + \vb{\varepsilon}, turns dimensionality reduction into estimating “low rank plus noise” covariance WW⊤+Ψ\mat{W}\mat{W}\T + \mat{\Psi}. With isotropic noise, its maximum likelihood is PCA; with diagonal noise, factor analysis. The model supplies what PCA lacked (likelihood, missing-data handling, noise model), at the cost of identifying W\mat{W} only up to rotation.
  • Marginal N(μ,WW⊤+Ψ)\Normal(\vb{\mu}, \mat{W}\mat{W}\T + \mat{\Psi}) and posterior N(GW⊤Ψ−1(x−μ),G)\Normal(\mat{G}\mat{W}\T\mat{\Psi}\inv(\vb{x} - \vb{\mu}), \mat{G}) with G=(I+W⊤Ψ−1W)−1\mat{G} = (\mat{I} + \mat{W}\T\mat{\Psi}\inv\mat{W})\inv. Woodbury and the determinant lemma evaluate likelihood in O(dk2)\bigO(dk^2).
  • PPCA (Tipping and Bishop): WML=Uk(Λk−σ2I)1/2R\mat{W}_{\text{ML}} = \mat{U}_k(\mat{\Lambda}_k - \sigma^2\mat{I})^{1/2}\mat{R} and σML2\sigma^2_{\text{ML}} equals mean discarded eigenvalue. The subspace is PCA’s. Posterior mean shrinks each component by 1−σ2/λj1 - \sigma^2/\lambda_j and only as σ2→0\sigma^2 \to 0 becomes orthogonal projection.
  • EM for PPCA costs O(ndk)\bigO(ndk) per iteration without forming covariance, and with missing data (MCAR or MAR) uses only observed entries in each row, jointly estimating subspace and missing values. It does not prevent overfitting.
  • Factor analysis: variable-specific uniqueness ψj\psi_j, scale equivariant; EM alternates B,G\mat{B}, \mat{G} with W\mat{W} and Ψ=diag⁡(S−WBS)\mat{\Psi} = \diag(\mat{S} - \mat{W}\mat{B}\mat{S}). A noisy variable pulls PCA but not FA. A ψj\psi_j falling to 0 is a Heywood case.
  • Likelihood is invariant under W→WR\mat{W} \to \mat{W}\mat{R}: factors have no unique meaning until rotation is fixed (varimax is a readability criterion; ICA a statistical one). Parameters d(k+1)−k(k−1)/2d(k+1) - k(k-1)/2 and Ledermann bound gl=12[(d−k)2−(d+k)]\mathrm{gl} = \frac12[(d-k)^2 - (d+k)].
  • Choose factor count with BIC or validation, not fitted likelihood. CCA is SVD of whitened views, and its probabilistic version is FA with shared latents and full-covariance noise per view.