Repository navigation
Conversation
|
Thank you for opening your first pull request to scikit-learn! 🎉 To help get your contribution reviewed, please make sure that:
|
| @@ -10,7 +10,7 @@ | |||
| from sklearn.base import clone | |||
There was a problem hiding this comment.
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.
| assert _infer_dimension(spectrum, n_samples) == expected | ||
|
|
||
|
|
||
| def test_infer_dimension_tied_eigenvalues_is_not_an_error(): |
There was a problem hiding this comment.
this is a behavior change!! previously would be a math domain error
cakedev0
left a comment
There was a problem hiding this comment.
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.
| """ | ||
| xp, _ = get_namespace(spectrum) | ||
| # Reject +inf or nan | ||
| if ll < xp.inf and ll > best_ll: |
There was a problem hiding this comment.
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)
1The 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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Good catch. I need to think about the numerics a bit, bear with me :)
There was a problem hiding this comment.
Ok yep I think float64 makes sense. Have changed.
| _assess_dimension(spectrum, rank, n_samples) | ||
|
|
||
|
|
||
| def test_small_eigenvalues_mle(): |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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
|
Thanks @cakedev0 ! Have updated - let me know if you have any other questions. |
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]>
Before,
_infer_dimensionwas 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)withX.shape = (3000, 3000)used to take an hour just to infer the dimension, now it takes less than a second.laplace_pca.m
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:
n-1in place ofn1)Also Minka materialized a full O(d^2)
invediffmatrix; I wanted to keep memory usage atO(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,
pais 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 doubleforloop in the original implementation: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}$$
The set of pairs under consideration is
And the trick is to split on whether$j$ is inside the retained block:
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):
and its running total
The inner sum$R(i)$ runs to $d$ regardless of $k$ , so $D$ is a plain prefix sum:
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$ $\hat\lambda_j = \lambda_j$ , so the contribution is
and
Grouping by the larger index$j$ makes this a prefix sum too:
On$\mathcal{C}_k$ (that is, $j > k$ ): every such $j$ has
$\hat\lambda_j = v_k$ , so the summand $\log(v_k^{-1} - \lambda_i^{-1})$ does$j$ . Writing
not depend on
the inner sum is that one value repeated$d-k$ times:
Putting it together:
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:
Had claude turn that into a nice table after running on my m3 mac:
Now the cost is pretty much only the SVD. Extrapolating, previously
_infer_dimensionwould 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:
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_spectratest case.Any other comments?