Factor analysis models x=Wz+μ+ϵ with z∼N(0,IL) and ϵ∼N(0,Ψ), Ψ diagonal, so x∼N(μ,WW⊤+Ψ). Fit it with EM. Rows of X (shape (N, D)) are observations; psi is the length-D vector of diagonal entries of Ψ.
fa_em_step(X, W, mu, psi): one EM iteration, returning (W_new, mu_new, psi_new).
- E step: Σ=(IL+W⊤Ψ−1W)−1 and mi=ΣW⊤Ψ−1(xi−μ).
- M step: estimate W~=(W,μ) jointly using bi=(mi,1) and Ci=E[z~z~⊤]=[Σ+mimi⊤mi⊤mi1]: W~=(∑ixibi⊤)(∑iCi)−1, then Ψ=N1diag(∑i(xi−W~bi)xi⊤).
fa_loglik(X, W, mu, psi): the total log-likelihood ∑ilogN(xi∣μ,WW⊤+Ψ) as a Python float.
fa_em(X, L, n_iter, seed): initialise with rng = np.random.default_rng(seed), W = rng.normal(size=(D, L)), mu the sample mean and psi the per-column variance (X.var(axis=0)); run n_iter steps. Return (W, mu, psi, logliks) where logliks lists the log-likelihood after each step.