Skip to content

Perf: algorithmic improvement to PCA(n_components="mle") - #34619

Open
jberg5 wants to merge 4 commits into
scikit-learn:mainfrom
jberg5:fast-laplace
Open

jberg5 wants to merge 4 commits into
scikit-learn:mainfrom
jberg5:fast-laplace

Conversation

@jberg5

@jberg5 jberg5 commented Jul 31, 2026 •

Copy link
Copy Markdown

Before, _infer_dimension was O(d^3), where d = min(samples, features) = n_features (we need more samples than features by construction). This PR adapts Minka's O(d^2) implementation of his laplace approximation, which he originally implemented in matlab. sklearn.PCA(n_components="mle").fit(X) with X.shape = (3000, 3000) used to take an hour just to infer the dimension, now it takes less than a second.

laplace_pca.m
function [k,p] = laplace_pca(data, e, d, n, alpha, beta)
% LAPLACE_PCA   Estimate latent dimensionality by Laplace approximation.
%
% k = LAPLACE_PCA([],e,d,n) returns an estimate of the latent dimensionality
% of a dataset with eigenvalues e, original dimensionality d, and size n.
% LAPLACE_PCA(data) computes (e,d,n) from the matrix data 
% (data points are rows)
% [k,p] = LAPLACE_PCA(...) also returns the log-probability of each 
% dimensionality, starting at 1.  k is the argmax of p.

% Written by Tom Minka

if ~isempty(data)
  [n,d] = size(data);
  m = mean(data);
  data0 = data - repmat(m, n, 1);
  e = svd(data0,0).^2/n;
end
if nargin < 5
  alpha = 0;
  beta = 0;
end
e = e(:);
% break off the eigenvalues which are identically zero
i = find(e < eps);
e(i) = [];

% logediff(i) = sum_{j>i} log(e(i) - e(j))
logediff = zeros(1,length(e));
for i = 1:(length(e)-1)
  j = (i+1):length(e);
  logediff(i) = sum(log(e(i) - e(j))) + (d-length(e))*log(e(i));
end
cumsum_logediff = cumsum(logediff);

n1 = n-1+alpha;
ehat = (e + beta/n)*n/n1;
inve = 1./ehat;
% invediff(i,j) = log(inve(i) - inve(j))  (if i > j)
%               = 0                       (if i <= j)
invediff = repmat(inve,1,length(e)) - repmat(inve',length(e),1);
invediff(invediff <= 0) = 1;
invediff = log(invediff);
% cumsum_invediff(i,j) = sum_{t=(j+1):i} log(inve(t) - inve(j))
cumsum_invediff = cumsum(invediff,1);
% row_invediff(i) = sum_{j=1:(i-1)} sum_{t=(j+1):i} log(inve(t) - inve(j))
row_invediff = row_sum(cumsum_invediff);
% row_invediff(k) = sum_{i=1:(k-1)} sum_{j=(i+1):k} log(inve(j) - inve(i))

loge = log(ehat);
cumsum_loge = cumsum(loge);

cumsum_e = cumsum(ehat);

dn = length(e);
kmax = length(e)-1;
%dn = d;
%kmax = min([kmax 15]);
ks = 1:kmax;
% the normalizing constant for the prior (from James)
% sum(z(1:k)) is -log(p(U))
z = log(2) + (d-ks+1)/2*log(pi) - gammaln((d-ks+1)/2);
cumsum_z = cumsum(z);
for i = 1:length(ks)
  k = ks(i);
  %e1 = e(1:k);
  %e2 = e((k+1):length(e));
  %v = sum(e2)/(d-k);
  %v = (cumsum_e(end) - cumsum_e(k))/(length(cumsum_e)-k);
  v = (cumsum_e(end) - cumsum_e(k))/(d-k);
  p(i) = -n1/2*cumsum_loge(k) + (-n1*(d-k)/2)*log(v);
  p(i) = p(i) - cumsum_z(k) - k/2*log(n1);
  % compute h = logdet(A_Z)
  h = row_invediff(k) + cumsum_logediff(k);
  % lambda_hat(i)=1/v for i>k
  h = h + (d-k)*sum(log(1/v - inve(1:k)));
  m = d*k-k*(k+1)/2;
  h = h + m*log(n);
  p(i) = p(i) + (m+k)/2*log(2*pi) - h/2;
  % missing terms added August 21 2008
  p(i) = p(i) + 1.5*k*log(2);
  p(i) = p(i) - 0.5*log(d-k);
  if alpha > 0
    ck = alpha*(d-k)/2*log(beta*(d-k)/2) - gammaln(alpha*(d-k)/2) + ...
	k*(alpha/2*log(beta/2) - gammaln(alpha/2));
    p(i) = p(i) - n1*d/2 - 0.5*log(n1) + ck;
  end
end
[pmax,i] = max(p);
k = ks(i);
  
v0 = cumsum_e(end)/length(cumsum_e);
p0 = -n1*d/2*log(v0) - 0.5*log(d);
%p0 = -n1*d/2*log(v0)
%p0 = -alpha*d/2*log(beta/alpha);
%p0 = -alpha*d/2*log(beta*d/2) + alpha*d/2*log(alpha*d/2);
if alpha > 0
  % must inline ck and put at end
  p0 = p0 - n1*d/2 - 0.5*log(n1) + alpha*d/2*log(beta*d/2) - gammaln(alpha*d/2);
end
if p0 >= pmax
  k = 0;
end
p = [p0 p];

%p(3)
%figure(1)
%plot(p)

My goal here was to port the algorithmic improvement without making any changes that would affect the selected rank. To that end, I left out a few things that we should possibly add in at some point in the future:

  • the "missing terms added August 21 2008" (not in the original paper)
  • n-1 in place of n
  • returning rank 0 when there is no discernible signal (we always return at least 1)
  • considering up to the number of eigenvalues above the floor minus one, which is one fewer than we do

Also Minka materialized a full O(d^2) invediff matrix; I wanted to keep memory usage at O(d), so didn't do that. Not much practical impact on runtime anyway.

Math

Expand me to see how the math works!

The math equivalence was not intuitive to me at first, but really just rests on decomposing sums and recognizing which parts actually depend on which dimensions. Writing it up here to reinforce my own understanding and help any future readers as well.

Anyway, pa is the runtime culprit in the original formulation. Note the double product (or double sum in log space), which is what was written as a literal double for loop in the original implementation:

$$|A_Z| = \prod_{i=1}^{k} \prod_{j=i+1}^{d} N \left( \hat\lambda_j^{-1} - \hat\lambda_i^{-1} \right) \left( \lambda_i - \lambda_j \right)$$

$$\mathrm{pa}(k) = \log|A_Z| = \sum_{i=1}^{k}\sum_{j=i+1}^{d} \left[ \log(\lambda_i - \lambda_j) + \log\left(\hat\lambda_j^{-1} - \hat\lambda_i^{-1}\right) + \log N \right]$$

For a candidate rank $k \in [1, d-1]$ the PPCA maximum-likelihood estimates of the eigenvalues are

$$\hat\lambda_i^{(k)} = \begin{cases} \lambda_i & i \le k \text{ (signal)} \ v_k & i > k \text{ (noise)} \end{cases}$$

$$v_k = \frac{1}{d-k}\sum_{j=k+1}^{d}\lambda_j$$

The set of pairs under consideration is

$$\mathcal{P}_k = \lbrace (i,j) : 1 \le i \le k, \ i &lt; j \le d \rbrace$$

And the trick is to split on whether $j$ is inside the retained block:

$$\mathcal{S}_k = \lbrace (i,j) \in \mathcal{P}_k : j \le k \rbrace$$ (signal-signal pairs)

$$\mathcal{C}_k = \lbrace (i,j) \in \mathcal{P}_k : j &gt; k \rbrace$$ (signal-noise pairs)

The former is an upper triangle with k choose 2 pairs; the latter is a rectangle; the total number of pairs is given by
$$|\mathcal{P}_k| = \frac{k(k-1)}{2} + k(d-k) = dk - \frac{k(k+1)}{2} = m_k$$

and we can use $$m_k$$ for the $$log N$$ term to avoid a loop there entirely. Back to the interesting stuff, let's consider the eigenvalue-gap factor (which only sees the raw eigenvalues and does not depend on the noise estimate or k in any way):

$$R(i) = \sum_{j=i+1}^{d} \log(\lambda_i - \lambda_j)$$

and its running total

$$D(k) = \sum_{i=1}^{k} R(i)$$

The inner sum $R(i)$ runs to $d$ regardless of $k$, so $D$ is a plain prefix sum:

$$D(k) = D(k-1) + R(k), \qquad D(0) = 0$$

The second factor does depend on the partition, because $\hat\lambda_j$ differs
between the two regions.

On $\mathcal{S}_k$ (that is, $j \le k$): here $\hat\lambda_i = \lambda_i$
and $\hat\lambda_j = \lambda_j$, so the contribution is

$$P(k) = \sum_{1 \le i &lt; j \le k} \log\left(\frac{1}{\lambda_j} - \frac{1}{\lambda_i}\right)$$

Grouping by the larger index $j$ makes this a prefix sum too:

$$P(k) = P(k-1) + \sum_{i=1}^{k-1}\log\left(\frac{1}{\lambda_k} - \frac{1}{\lambda_i}\right), \qquad P(0) = P(1) = 0$$

On $\mathcal{C}_k$ (that is, $j &gt; k$): every such $j$ has
$\hat\lambda_j = v_k$, so the summand $\log(v_k^{-1} - \lambda_i^{-1})$ does
not depend on $j$
. Writing

$$Q(k) = \sum_{i=1}^{k}\log\left(\frac{1}{v_k} - \frac{1}{\lambda_i}\right)$$

the inner sum is that one value repeated $d-k$ times:

$$\sum_{(i,j) \in \mathcal{C}_k} \log\left(\hat\lambda_j^{-1} - \hat\lambda_i^{-1}\right) = (d-k) Q(k)$$

$Q(k)$ is the one piece that cannot be accumulated, because $v_k$ moves with
$k$. It is recomputed each rank at $O(k)$.

Putting it together:

$$\mathrm{pa}(k) = D(k) + P(k) + (d-k) Q(k) + m_k \log N$$

No more double loops! Each component is at most O(k).

Reference Issues/PRs

Previously I had just vectorized the implementation without changing the algorithm: #33602

This version is much faster!

PERFORMANCE

Running this benchmark script on my branch versus main:

import time
import numpy as np
from sklearn.decomposition import PCA

rng = np.random.default_rng(0)

# Warm up
PCA(n_components="mle", svd_solver="full").fit(rng.standard_normal((32, 16)))

for n_features in [64, 128, 256, 512, 1024]:
    n_samples = 2 * n_features
    signal = rng.standard_normal((n_samples, 10)) @ rng.standard_normal((10, n_features))
    X = signal + rng.standard_normal((n_samples, n_features))

    pca = PCA(n_components="mle", svd_solver="full")
    start = time.perf_counter()
    pca.fit(X)
    elapsed = time.perf_counter() - start

    print(
        f"n_features={n_features:5d}  n_samples={n_samples:5d}  "
        f"n_components_={pca.n_components_:4d}  {elapsed:9.3f}s"
    )

Had claude turn that into a nice table after running on my m3 mac:

┌────────────┬───────────┬─────────────┬─────────┐
│ n_features │   main    │ this branch │ speedup │
├────────────┼───────────┼─────────────┼─────────┤
│         64 │   0.038 s │     0.002 s │     20x │
├────────────┼───────────┼─────────────┼─────────┤
│        128 │   0.305 s │     0.005 s │     61x │
├────────────┼───────────┼─────────────┼─────────┤
│        256 │   2.376 s │     0.020 s │    119x │
├────────────┼───────────┼─────────────┼─────────┤
│        512 │  19.057 s │     0.084 s │    227x │
├────────────┼───────────┼─────────────┼─────────┤
│       1024 │ 152.786 s │     0.420 s │    364x │
└────────────┴───────────┴─────────────┴─────────┘

Now the cost is pretty much only the SVD. Extrapolating, previously _infer_dimension would have taken more than a day on my hardware to crunch n_features=10000; now it takes less than a second.

What does this implement/fix? Explain your changes.

Fixes #34618

First time contributor introduction

Hi! I'm just some guy. I write a lot of Python professionally and make open source contributions in my spare time.

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

All of the above, although I can vouch for every line of code in this. Opus 5 is outstanding at exactly this task: given a reference implementation in another language, translate it to Python. In particular, I used it for fuzz testing, and some of the more "interesting" spectra have been preserved in the new test_infer_dimension_sensitive_spectra test case.

Any other comments?

@github-actions

Copy link
Copy Markdown

Thank you for opening your first pull request to scikit-learn! 🎉

To help get your contribution reviewed, please make sure that:

  • You have filled out the pull request template.
  • The pull request addresses an existing issue that is ready for
    contribution (e.g. not tagged as "Needs Triage", "Needs Decision", ...).
    If you are proposing a new feature, please open an issue to discuss it first.
  • There are no other open pull requests already targeting the same issue.
  • You have followed the pull request checklist.
    In particular, linting and tests should pass.

@@ -10,7 +10,7 @@
from sklearn.base import clone

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests reworked slightly because I got rid of assess_dimension since the whole idea here is to use cumulative sums and it would have been messy to pass those quantities into and out of the function. Also felt like keeping track of every likelihood when we only need the maximum was wasteful, so removed tests that examine the likelihoods of the entire spectrum. Added more that shook out of fuzz testing.

Comment thread sklearn/decomposition/tests/test_pca.py Outdated
assert _infer_dimension(spectrum, n_samples) == expected


def test_infer_dimension_tied_eigenvalues_is_not_an_error():

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a behavior change!! previously would be a math domain error

@cakedev0 cakedev0 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR, the added complexity is fairly reasonable for what it does.

AI found a few nits, I haven't had the time to review it myself yet.

Comment thread sklearn/decomposition/_pca.py Outdated
"""
xp, _ = get_namespace(spectrum)
# Reject +inf or nan
if ll < xp.inf and ll > best_ll:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With exact ties, every rank whose pa contains a tied pair gets ll = +inf and is skipped. Since log_diff_sum is cumulative, a tie among the leading eigenvalues skips every rank and we silently fall back to 1:

>>> _infer_dimension(np.array([10., 10., 10., .01, .009, .008, .007]), 50)
1

The 3 equal strong components are clearly signal here. It's not a regression (main raises ValueError: math domain error), but I don't think returning 1 is better than an error. It can happen with real data: the spectrum of np.tile(np.eye(6), (5, 1)) (5 equal eigenvalues) crashes on main and gives 1 here.

I'd keep this PR a pure speed-up: return the best finite rank when there is one (so [10, 1, 1, 1] gives 1, which is nice), and raise a ValueError with a clear message when no rank has a finite likelihood. Then test_infer_dimension_tied_eigenvalues_is_not_an_error would check that error instead of the fallback. What to do with ties can be discussed in a separate issue. WDYT?

@jberg5 jberg5 Oct 31, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, yeah fair, I didn't really know what to do with ties. I think I'll go back to main's behavior where ties raise an exception, except this time I'll make the exception more user friendly. Maybe future work can decide whether there is a better strategy. Returning first finite rank when there is one is maybe a valid approach, but [20, 19, 19, 19, 1] would give 1, which doesn't feel right (my example extremely contrived tho). Anyway, yes let's keep pure speedup here and be consistent with main for now.

# inv_pair_sum(k) = sum_{i<j<k} log(1/l(j) - 1/l(i))
# pu_terms(k) = sum_{i<=k} gammaln((d-i+1)/2) - (d-i+1)/2 log(pi), so that
# -k log(2) + pu_terms(k) = log p(U)
log_diff_sum = 0.0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For float32 input, these accumulators become float32 0-d arrays after the first += (NEP 50), while main added up pa as Python floats (float64):

>>> s = np.array([3., 2., 1.], dtype=np.float32)
>>> x = 0.0; x += np.sum(np.log(s[0] - s[1:])); x.dtype
dtype('float32')

So the selected rank can differ from main for float32 data: 1 of 300 random float32 spectra (d < 120) gave 71 instead of 72 (the float64 log-likelihood gap between both ranks is ~0.005). I'd accumulate in float64, e.g. by converting spectrum with _max_precision_float_dtype(xp, device) at the start.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I need to think about the numerics a bit, bear with me :)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok yep I think float64 makes sense. Have changed.

_assess_dimension(spectrum, rank, n_samples)


def test_small_eigenvalues_mle():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These rewritten tests only assert that the result is 1, which is also the fallback value of best_rank. A regression making every log-likelihood non-finite would still pass. I'd add a test comparing to the O(d^3) formula on a few spectra (could be a small reference implementation of _assess_dimension kept in the test file).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point, I wouldn't want to keep the previous implementation around just for testing, but I added a little bit of coverage that should help for this case

@jberg5

jberg5 commented Nov 2, 2026

Copy link
Copy Markdown
Author

Thanks @cakedev0 ! Have updated - let me know if you have any other questions.

cakedev0 added a commit to cakedev0/my-scikit-learn-backlog that referenced this pull request Nov 2, 2026
done: Blog: [blog#231](scikit-learn/blog#231) (match Substack's font size), merged
todo: move [blog#228](scikit-learn/blog#228) from Waiting to Now: address lorentzenchr's review and answer jjerphan on the OpenBLAS threading layers
todo: move [sklearn#35181](scikit-learn/scikit-learn#35181) from Now to Waiting, adam2392's and antoinebaker's questions answered
add: Maintenance: follow up on [sklearn#35254](scikit-learn/scikit-learn#35254): settle option B with dherrera1911 and betatim (LDA solvers disagree with custom priors)
add: Maintenance: follow up on [sklearn#35209](scikit-learn/scikit-learn#35209): newton-cg LogisticRegressionCV test fails on the macOS x86_64 wheels
add: Maintenance: re-review [sklearn#34619](scikit-learn/scikit-learn#34619) (faster PCA mle; jberg5 addressed my comments)
add: Benchmarks: review [benchmarks#142](probabl-ai/scikit-learn-benchmarks#142) (cuML config) with the results of the AWS L4 run
add: Upstream: upstream to OpenBLAS or close [cakedev0/OpenBLAS#3](cakedev0/OpenBLAS#3) and [cakedev0/OpenBLAS#4](cakedev0/OpenBLAS#4)
todo: since dates on [sklearn#35062](scikit-learn/scikit-learn#35062) and [sklearn#35053](scikit-learn/scikit-learn#35053), and virchan's question on the latter
todo: lorentzenchr's note on [sklearn#35029](scikit-learn/scikit-learn#35029) in the fork#38 line

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Perf: PCA(n_components="mle") uses O(d^3) version of Minka's algorithm when O(d^2) exists

2 participants