Here’s a step‐by‐step recipe for fitting a (linear) factor model
Model setup
We assume your (p)-dimensional observations (X_i) follow
[
X_i = B,f_i + \varepsilon_i,\quad
f_i\sim\mathcal N(0, I_k),\quad
\varepsilon_i\sim\mathcal N(0,D),
]
where
- (B) is a (p\times k) loading matrix,
- (f_i) are (k) latent factors,
- (D=\mathrm{diag}(\sigma_1^2,\dots,\sigma_p^2)) is the diagonal specific noise covariance.
Then the implied covariance is
[
\Sigma = B,B^T + D.
]
1. Choose the number of factors (k)
- Scree plot: look at eigenvalues of the sample covariance (S).
- Parallel analysis: compare to eigenvalues from random data.
- Information criteria: AIC/BIC using likelihood‐based factor analysis.
2. Initialization
A common choice is to start from PCA:
- Eigen‐decompose (S = Q,\Lambda,Q^T).
- Take the first (k) eigenvectors (Q_k) and eigenvalues (\Lambda_k).
- Initialize loadings
[
B^{(0)} = Q_k ,\Lambda_k^{1/2}.
]
- Initialize idiosyncratic variances
[
D^{(0)} = \mathrm{diag}\bigl(S - B^{(0)} (B^{(0)})^T\bigr).
]
3. Maximum‐Likelihood (EM) algorithm
Repeat until convergence:
E-step
- Compute the posterior moments of factors given data:
[
M = B^{(t)^T} \bigl(B^{(t)}B^{(t)^T} + D^{(t)}\bigr)^{-1},
\quad
\Psi = I_k - M,B^{(t)}.
]
M-step
- Update (B):
[
B^{(t+1)}
= \Bigl(\tfrac1n\sum_i X_i X_i^T M^T\Bigr)
\Bigl(\Psi + M B^{(t)}\Bigr)^{-1}.
]
- Update (D):
[
D^{(t+1)}
= \mathrm{diag}!\Bigl(,
S - B^{(t+1)} M^T S - S M B^{(t+1)^T}
+ B^{(t+1)}\bigl(\Psi + M S M^T\bigr)B^{(t+1)^T}
\Bigr).
]
Stop when the log‐likelihood or parameters change very little.
4. Simpler PCA‐based “factor” approximation
If you only want a quick “covariance cleaner” without full MLE:
- Compute the first (k) eigenpairs ((\lambda_j,,q_j)).
- Set
[
B = [,\sqrt{\lambda_1},q_1,\dots,\sqrt{\lambda_k},q_k],
\quad
D = \mathrm{diag}\Bigl(S - B B^T\Bigr).
]
- Ensure (D>0) (set any negative diagonals to a small (\varepsilon)).
5. Off-the-shelf implementations
| Language | Package/function | Notes |
|---|
| Python | sklearn.decomposition.FactorAnalysis | EM‐based, choose n_components=k |
| R | factanal(x, factors=k) | MLE via iterative method |
| MATLAB | factoran(X, k) | returns loadings and uniquenesses |
Python example
from sklearn.decomposition import FactorAnalysis
fa = FactorAnalysis(n_components=k)
fa.fit(X) # X: n × p data matrix
B_est = fa.components_.T # p × k loadings
D_est = fa.noise_variance_ # length-p vector of diag(D)
R example
fit <- factanal(data, factors=k, scores="none")
B_est <- fit$loadings[] # p × k matrix
D_est <- fit$uniquenesses # length-p vector
6. Diagnostics & validation
- Check reconstruction error: (|S - (B,B^T + D)|).
- Look at residuals (S - B,B^T - D): should be “small.”
- Cross‐validate: does your cleaned covariance improve out‐of‐sample tasks (e.g. portfolio returns)?
That’s the core workflow! Let me know if you need deeper dives on the EM updates, factor rotations, or choosing (k). 😊