Reconstruction error alone cannot choose the number of principal components L. Implement two diagnostics. Rows of the arrays are observations.
reconstruction_curves(X_train, X_test, L_values): fit PCA on X_train only (sample mean and MLE covariance with divisor N, eigenvectors by decreasing eigenvalue). For each L in L_values (each 0≤L≤D), reconstruct every row as x^=μ+ULUL⊤(x−μ) and compute the mean over rows of ∥x−x^∥2. Return (train_err, test_err), two lists aligned with L_values.
profile_loglik(eigvals): the profile likelihood for eigenvalues sorted in decreasing order, λ1≥⋯≥λLmax. For each L=1,…,Lmax−1 split them into k≤L and k>L, let μ1(L) and μ2(L) be the two group means and
σ2(L)=Lmax∑k≤L(λk−μ1)2+∑k>L(λk−μ2)2
the pooled variance, and score ℓ(L)=∑k≤LlogN(λk∣μ1,σ2)+∑k>LlogN(λk∣μ2,σ2). Return (ll, L_star): the list of ℓ(L) for L=1..Lmax−1 and the L with the largest value (smallest L on ties).