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 -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 , no noise model, and five concrete limitations follow:
- No likelihood. You cannot say how likely a new observation is, compare with 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 , 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 loses no generality: if , the model with and is the same. The assumption makes the model useful: data covariance has a rank- part plus noise.
Proof
The pair is a linear transformation of Gaussian , hence jointly Gaussian (Gaussian marginalization). By independence, , and . This proves point 1.
For conditioning, the Gaussian conditioning formula gives and : point 3. To obtain point 2 use the Woodbury identity, , and define , so :
because . Likewise, . PPCA follows with : .
∎Notice what you gain. Data covariance goes from free parameters to “low rank plus diagonal” structure. Likelihood can be evaluated without inverting a matrix: with Woodbury and the determinant lemma, , each observation costs after work shared by all. The first cell checks all formulas numerically.
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 the geometry is easy to see. Probabilistic PCA (PPCA) is the linear Gaussian model with isotropic noise, with . The plane is the batter and noise gives thickness: the data cloud is a pancake, thick in each direction perpendicular to the plane, with Gaussian distribution inside it.
For intuition let with orthonormal columns in and . Then is diagonal and the posterior of given has mean and covariance
Look at the first factor: is the coordinate of the orthogonal projection of onto the plane, expressed in units. The posterior multiplies it by : posterior mean shrinks toward the origin, more for weaker directions and noisier data, leaving residual uncertainty ignored by orthogonal projection. Only as does the posterior mean become the PCA projection and the posterior collapse to a point.
Tipping and Bishop’s closed-form solution
You have observations and seek maximum-likelihood (maximum likelihood estimator). With the sample covariance with divisor , log-likelihood after substituting (the sample mean maximizes over because and only adds cost) is
Proof
Gradient in . With , and we obtain . Since is invertible, the point is stationary if and only if .
Structure of . Write the thin SVD of rank , with and having orthonormal columns and diagonal . Then , so . Substituting into and simplifying gives : columns of are eigenvectors of with eigenvalues . This is the stated form of .
Equation for . In an eigenbasis of containing , is diagonal with for and elsewhere. Then , which vanishes exactly when is the mean discarded eigenvalue. This proves point 1.
Value at each stationary point. With and , we obtain with . This is point 3 for .
Comparison. Since at the parameter boundary (when ), a maximum is attained and is stationary; show that minimizes among admissible . (a) Exchange. Let , with , and . Then , remains admissible (its noise variance decreases), and using , and ,
(b) Add. If , add to the largest eigenvalue outside : new is the mean of the rest, at most , and log concavity (, since ) gives , with equality only if all eigenvalues outside are equal (then adding makes no difference). Neither move worsens the objective and exchange strictly improves it, so the optimum is . Admissibility holds because is the average of eigenvalues at most .
∎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 : the mean discarded variance, .
Rotation is a real freedom. is not unique: gives the same and likelihood for any orthogonal . PPCA identifies the subspace, not coordinates within it. Factor analysis returns to this thread.
Reconstruction shrinks. With (taking ) and , the previous section’s factor is , and posterior reconstruction is . Each component shrinks by : weak ones more, strong ones less. As you recover orthogonal projection, what PCA does.
The next cell checks this on the 1797 load_digits digits (8×8 pixels), with . Practical detail: sklearn.decomposition.PCA already implements this model (its score method is mean PPCA log-likelihood and noise_variance_ is ), but estimates covariance with divisor , so values differ from the maximum-likelihood estimator by factor .
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 has rank 61 and is not positive definite. The theorem required only to guarantee a maximum exists, and suffices: any with then leaves part of data variance outside its rank- subspace and . 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: or its penalized version. PCA(n_components='mle') chooses using Minka’s (2000) Bayesian approximation to this model’s evidence.
EM for PPCA: linear cost and missing data
Diagonalizing costs , prohibitive when is thousands and only components are needed. The alternative is the previous lesson’s EM algorithm applied to this model (Tipping and Bishop, 1999; Roweis, 1998), with latent (EM lower bound). For each observation, the E-step is the theorem’s posterior:
Expected complete log-likelihood is . Differentiating:
Substitution expresses the M-step in one line with : and . But the point is not to form : with centered data matrix , the E-step needs and M-step , two products costing ; the rest are matrices. One iteration costs versus 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 determined by initialization (not the eigenbasis).
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: never decreases and converges to the PCA subspace, not a particular (the result depends on random initialization because of freedom ).
Missing data
What makes EM special here is that the same structure permits missing data without changing methods. If only coordinates of row are observed, the observed vector follows , where are rows of for observed pixels. The E-step uses only those rows, and ; the M-step works pixel by pixel: is regression of on over rows observing pixel , using posterior moments; averages observed-pixel error plus . Once fitted, a missing pixel’s prediction is .
Factor analysis in the next section works similarly: each row’s posterior uses only observed variables, with mean , and the M-step proceeds variable by variable, with obtained by regression on and equal to the average over rows observing of .
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.
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.
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 rises (in the interactive, at 70% or more, compare with ). 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 continues increasing each step. With 70% missing and , 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 .
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 diagonal and different per variable:
Each row of contains loadings of variable , is its communality (variance explained by common factors), and its uniqueness (its own part). Diagonal 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 with a rank- matrix and therefore also tries to explain diagonal variances; FA only requires to explain off-diagonal entries, absorbing the rest into . Another consequence is scale equivariance: changing units of variable (multiplying by ) changes the FA maximum-likelihood solution by , (with ), and mean log-likelihood per observation changes only by the variable-change Jacobian constant (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 () and its own noise increases. Here known truth (the simulation model described in the caption) lets us measure both solutions.
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 . 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 , 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 . 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 . With and , we have and . The EM algorithm for factor analysis (Rubin and Thayer, 1982; Ghahramani and Hinton, 1996) alternates that E-step with
The update is the same regression as PPCA. The update follows by differentiating with respect to each : , and since solves its normal equations, the quadratic term in simplifies against the cross term to , the diagonal of . Each iteration works with and matrices, and likelihood never decreases.
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 : a Heywood case. Algebraically, the fit “wants” negative uniqueness variance, which is forbidden, and sticks at (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 (scikit-learn uses ), reducing , reviewing variables, or placing a prior on uniquenesses. The -selection cell below includes a minimal example where no real factor can reproduce correlations.
Rotational non-identifiability and varimax
PPCA had an arbitrary orthogonal . The same occurs in FA, becoming an interpretation problem.
The proof is one line: , so 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: retains only degrees of freedom (subtract rotations), so FA covariance structure has free parameters, compared to for full covariance. The difference
is the number of covariance constraints imposed by the model. Requiring , that is , gives the Ledermann bound (1937) on factor count; for a testable model (more restrictive than full covariance), is needed. With and there are parameters and . To fix a solution add a convention: diagonal with decreasing entries (classical maximum-likelihood convention), or zeros in predefined positions (confirmatory factor analysis).
Varimax rotation
Since any 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
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 is communality, unchanged by rotation, 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 ; rotation by angle is . With and , the number rotates by and yields and , with , and constant . Thus
the variance of the projection of point cloud onto direction . It is maximal along the cloud’s principal axis, and has period in (hence four equivalent maxima: permute factors and flip signs). With centered , . For more than two factors rotate pairs of columns until convergence, or use the previous cell’s SVD algorithm, used by FactorAnalysis(rotation='varimax').
# 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 the -factor fit, sample covariance (the saturated model) and total sample log-likelihood at covariance , statistic is compared with ; Bartlett’s correction multiplies by . Null: factors suffice. Increase until non-rejection. This is a chain of tests on the same data and depends on normality.
- BIC and AIC , with 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.
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 and cannot select it; BIC and AIC are minimized at , the true count; validation log-likelihood stops improving at ; and Bartlett’s test stops rejecting at (), clearly rejecting . For , 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 ), but exact solution requires ; EM crawls toward the boundary: after 3000 iterations keeps falling (still above our floor because EM converges very slowly near the boundary), loading approaches 1, the other two uniquenesses remain at , and likelihood remains below the saturated covariance, unattainable here.
Application: a factor model of returns
In finance, a factor model explains returns of assets using common risk factors plus asset-specific risk: , with . This is exactly this lesson’s model (with ), with two practical benefits. Estimation shrinks from covariances to parameters, and resulting covariance is invertible even with fewer dates than assets, needed for a minimum-variance portfolio (). 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 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).
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 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 and to covariance, less than noise variance of the two most volatile assets ( and ). 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 and . FA’s advantage over sample covariance is moderate with 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 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 . With two sets of variables measured on the same cases, and (for example an image and its description, or a patient’s symptoms and lab results), canonical correlation analysis (CCA) seeks directions and whose projections and are maximally correlated, then subsequent ones uncorrelated with earlier ones. With covariances :
Changing variables to and gives with and : the maximum is ‘s largest singular value and canonical correlations are all its singular values (SVD after whitening each view). The same solution is the generalized eigenvalue problem
whose eigenvalues appear in pairs : substituting and gives , whose eigenvalues are the singular values of .
Probabilistic version (Bach and Jordan, 2005). Model both views with the same latent variables: , and , with full covariance matrices (without FA’s diagonal restriction: noise within each view can correlate). This is factor analysis on joint with block-diagonal noise. According to that work its maximum-likelihood solution is and , with the first normalized canonical directions (), and spectral norms of , below one (again rotational freedom). Posterior mean is a rescaled canonical projection. The views are linked because reproduces rank- cross-covariance : what views share is exactly what common factors explain.
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 is positive definite as required. The last line is a practical warning: with below , covariances , are singular and CCA finds correlation one between independent variables, so regularize (add 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: has the same law as . 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 and Gaussian approximate posterior is PPCA; maximizing its lower bound (the same as EM’s, now with 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 , 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
Step 1 of 4. How do you obtain the joint distribution of and its covariances?
Step 1 of 4. Which parameters determine log-likelihood of a sample ?
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 with diagonal noise. Center data by their mean and use covariance with divisor . Initialize small random (with a fixed seed) and 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, psiMore than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
Summary
- Marginal and posterior with . Woodbury and the determinant lemma evaluate likelihood in .
- PPCA (Tipping and Bishop): and equals mean discarded eigenvalue. The subspace is PCA’s. Posterior mean shrinks each component by and only as becomes orthogonal projection.
- EM for PPCA costs 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 , scale equivariant; EM alternates with and . A noisy variable pulls PCA but not FA. A falling to 0 is a Heywood case.
- Likelihood is invariant under : factors have no unique meaning until rotation is fixed (varimax is a readability criterion; ICA a statistical one). Parameters and Ledermann bound .
- 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.