You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I suppose this is more of a feature request than anything else. There are several implementations of PCA that can compute the decomposition on noncentered, sparse data, while the implementation here does not support sparse matrices at all.
A matlab implementation can be found here and a Python implementation here. So far, I've been using the Python implementation, but it's missing some things and will eventually be deprecated (facebookarchive/fbpca#9).
I haven't looked at the code or math too much, but as far as I'm aware, it's just a matter of adding a term to randomized_range_finder to account for centering.
Is this something that you guys are aware of, and is anyone working on this? This would an awesome feature to have.
Did you see the TruncatedSVD estimator? In the current implementation, it should be equivalent to PCA on centered data, except that it does not necessarily center the data and also supports sparse input.
Yes, I am aware of TruncatedSVD, but that's different. It's true that SVD on centered data is PCA, but SVD on noncentered data is not equivalent to PCA.
It's easy to see the difference with a simple example:
Now, I'm dealing with huge sparse matrices. If I densify them, they would not fit into memory, so centering the matrix is not an option (we lose all sparsity with centering).
Yes, I could perform incremental PCA, loading chunks of the matrix into memory at a time, but that's really slow. Yes, I could perform SVD on these matrices, which is fine, but not the same as PCA. Now, like I said in my first comment, this can be done i.e. we can compute PCA on noncentered data directly, without ever having to directly perform centering. This is what I'm missing. I hope I've it's clear enough this time. PCA is possible and is very fast on sparse matrices, and I feel it really should be included in scikit-learn.
Yes, I am aware of TruncatedSVD, but that's different. It's true that SVD on centered data is PCA, but SVD on noncentered data is not equivalent to PCA.
I am confused. It seems that you want PCA with non centered data which is as you mentioned, different from PCA. So it seems that you want the truncated SVD, isn't it?
Perhaps I've been unclear. I'll try to be more clear this time :)
What we know
We know that SVD is not PCA. It is different. But, we usually compute PCA by taking a matrix X, centering it, then applying SVD. This is equivalent to taking X, centering it, computing its covariance matrix C, then computing the eigenvalues and eigenvectors of C.
So this is nothing new. We typically compute PCA via the SVD. And when X is centered, SVD is the same as PCA. Otherwise they are different.
The problem
Sometimes we can't center our matrix. If we have a huge sparse matrix, centering it will eliminate the sparseness and make the matrix dense. This is often impossible if X is really, really big. It can't fit into memory. So we can't do PCA. There are incremental ways to do this (I believe incremental PCA is used for this), but this requires a lot of disk reads, so it's slow.
We can still do SVD, but since X is not centered, this is not the same as PCA. PCA is often nicer because it's easier to interpret things. It's pretty hard to interpret an SVD (or I just might not be aware of it).
The solution
In the implementations I referenced (I don't know which paper the formulation comes from - I haven't gone through the maths), they implement randomized SVD and randomized PCA. But, PCA is computed with a randomized method that never needs to center X. To emphasise this, it is possible to compute actual PCA without ever having to center the original, potentially huge X matrix.
To achieve this, we take the already implemented randomized SVD algorithm, and add a couple of negative terms, which account for centering. The changes to the algorithm are very minor.
The randomized SVD implemented here is great and could be extended with just a couple of terms, and we could have it compute both the SVD and PCA. Setting a single flag e.g. apply_centering to randomized_svd could switch between the two.
Conclusion
I hope I've made this very clear this time. I also hope it's clear that having this in scikit-learn would be very beneficial. Again, this is a more efficient way to compute PCA on sparse matrices, one that doesn't require us to make them dense. PCA is already implemented in scikit-learn, so adding an implementation that supports sparse data seems like the natural next step. This is not the same as SVD. PCA is nicer than SVD because it has a clearer interpretation.
I could work on this if needed, but I am not at all familliar with the codebase, and have fairly limited time.
Reacted by Shay Palachy-Affek, Roberto Ulloa and Otmane EL ALOI
Yeah I think it's clear and I think we probably want it but we need to research the math and check speed tradeoffs and complexity of adding the method etc.
Actually, I've just briefly looked at the implementations and it seems to be astonishingly simple.
Randomized methods use power iteration to increase the spectral gap, which is just a fancy way of saying multiplication by the original matrix X multiple times. SVD already does this in the current implementation.
Since PCA is just SVD(X - means), and SVD is computed with power iteration, now the power iteration looks like this: (X - means) * Q where Q is the basis. And if we use the distributive property of the dot product we can instead do (X * means) - (means * Q), meaning X never has to be centered.
I don't think I've explained this properly (clearly I need to work on my explanations), but it's just a clever application of the distributive property of the dot product.
So, I've played around with this a little bit and I think these are all the changes needed int the randomized SVD solver.
The only real change is that whenever we apply a non-centered matrix A to any other matrix, we distribute the mean subtraction like so: (A - m) X = AX - mX, avoiding the need to ever center A.
diff --git a/sklearn/utils/extmath.py b/sklearn/utils/extmath.py
index 19df5b161..0ab75721e 100644
--- a/sklearn/utils/extmath.py+++ b/sklearn/utils/extmath.py@@ -147,6 +147,7 @@ def safe_sparse_dot(a, b, dense_output=False):
def randomized_range_finder(A, size, n_iter,
power_iteration_normalizer='auto',
+ subtract_mean=False,
random_state=None):
"""Computes an orthonormal matrix whose range approximates the range of A.
@@ -211,28 +212,39 @@ def randomized_range_finder(A, size, n_iter,
else:
power_iteration_normalizer = 'LU'
+ if subtract_mean:+ c = np.mean(A, axis=0).reshape((1, -1))+ applyA = lambda X: safe_sparse_dot(A, X) - safe_sparse_dot(c, X)+ applyAT = lambda X: safe_sparse_dot(A.T, X) - \+ safe_sparse_dot(c.T, Q.sum(axis=0).reshape((1, -1)))+ else:+ applyA = lambda X: safe_sparse_dot(A, X)+ applyAT = lambda X: safe_sparse_dot(A.T, X)++ Q = applyA(Q)+
# Perform power iterations with Q to further 'imprint' the top
# singular vectors of A in Q
for i in range(n_iter):
if power_iteration_normalizer == 'none':
- Q = safe_sparse_dot(A, Q)- Q = safe_sparse_dot(A.T, Q)+ Q = applyAT(Q)+ Q = applyA(Q)
elif power_iteration_normalizer == 'LU':
- Q, _ = linalg.lu(safe_sparse_dot(A, Q), permute_l=True)- Q, _ = linalg.lu(safe_sparse_dot(A.T, Q), permute_l=True)+ Q, _ = linalg.lu(applyAT(Q), permute_l=True)+ Q, _ = linalg.lu(applyA(Q), permute_l=True)
elif power_iteration_normalizer == 'QR':
- Q, _ = linalg.qr(safe_sparse_dot(A, Q), mode='economic')- Q, _ = linalg.qr(safe_sparse_dot(A.T, Q), mode='economic')+ Q, _ = linalg.qr(applyAT(Q), mode='economic')+ Q, _ = linalg.qr(applyA(Q), mode='economic')
# Sample the range of A using by linear projection of Q
# Extract an orthonormal basis
- Q, _ = linalg.qr(safe_sparse_dot(A, Q), mode='economic')+ Q, _ = linalg.qr(Q, mode='economic')
return Q
def randomized_svd(M, n_components, n_oversamples=10, n_iter='auto',
power_iteration_normalizer='auto', transpose='auto',
- flip_sign=True, random_state=0):+ flip_sign=True, subtract_mean=False, random_state=0):
"""Computes a truncated randomized SVD
Parameters
@@ -333,11 +345,20 @@ def randomized_svd(M, n_components, n_oversamples=10, n_iter='auto',
# this implementation is a bit faster with smaller shape[1]
M = M.T
- Q = randomized_range_finder(M, n_random, n_iter,- power_iteration_normalizer, random_state)+ Q = randomized_range_finder(+ M,+ size=n_random,+ n_iter=n_iter,+ power_iteration_normalizer=power_iteration_normalizer,+ subtract_mean=subtract_mean,+ random_state=random_state,+ )
# project M to the (k + p) dimensional space using the basis vectors
B = safe_sparse_dot(Q.T, M)
+ if subtract_mean:+ c = np.mean(M, axis=0).reshape((1, -1))+ B -= np.dot(c.T, Q.sum(axis=0).reshape((1, -1)))
# compute the SVD on the thin matrix: (k + p) wide
Uhat, s, V = linalg.svd(B, full_matrices=False)
I've run all the tests for TruncatedSVD, and they pass. In the PCA learner, there's one problematic line:
total_var=np.var(X, ddof=1, axis=0)
which fails on sparse matrices. I'd expect something like sparse variance to be already implemented, but I'm not familliar with the codebase and don't know where to look. If not, it should be relatively straightforward to implement this as well.
I'd expect something like sparse variance to be already implemented, but I'm not familliar with the codebase and don't know where to look. If not, it should be relatively straightforward to implement this as well.
in sklearn you have mean_variance_axis in utils/sparsefuncs_fast.py, so that sould not be an issue
I looked into the paper and they actually only speak of the SVD which explain why our implementation does not remove the mean.
Then, your proposal looks good to me. Since that we already have solver='auto' in PCA, we could default to always 'randomized' for sparse matrices with little changes within the code.
@pavlin-policar thanks a lot for the clarifications and the patience ;)
I varied the relative tolerance used in elementwise comparisons of the components vectors (corresponding to $V^T$ in $A = U\Sigma V^T$) coming from PCA on sparse data with implicit centering to those coming from dense PCA on the same data. The range that I tested is $\{10^0, 10^{-1}, ..., 10^{-7}\}$ (8 positions total), where $10^{-7}$ is the default value. The absolute tolerance was set to 0 (default) and the final comparison in np.assert_allclose is to rtol*desired + atol (see NumPy docs).
Below I'm showing plots of the resulting test pass rates and elementwise mismatch rates (of the failed tests) for each solver.
Rate values are shown up to 2 significant digits. 0 and 1 are true 0 and 1.
Tentative conclusion
For my personal practical purposes, LOBPCG passes the correctness test on this small data set (300x400). Don't know if those tolerances/error rates are acceptable in scikit-learn.
ARPACK seems to always have a small number of elements that are significantly far away from the desired value, that could also be acceptable. Not sure yet how to debug.
Randomized is performing very badly, even when tolerance is relaxed. I'll try to compare intermediate outputs to see where the divergence comes from.
The full solver is not interesting for practical purposes.
Pass rate by solver
Fraction of the tests that passed for each solver, broken down by relative tolerance level.
Plot
Elementwise mismatch rate by solver
For the tests that failed, the fraction of the elements that didn't pass the comparison.
I'm still trying to get a large number of tests to run across all environments on CI, I'll post an analysis of that later. It will likely only include the default tolerance level since the full range timed out.
@lobpcg Agreed, it's a little suspicious. I'll try to root cause.
In each case I'm essentially comparing the SVD of the densified centered data to the SVD of the implicitly centered sparse data, using the same solver. Maybe I should instead use the outputs of a single, highest precision accuracy, dense solver as the only reference. Or carry out the SVD using an arbitrary precision library and convert the results to nearest float64 values.
I discovered that I wasn't using the density parameter (1-sparsity) at all, so it defaulted to 0.01 everywhere (instead of the [0.01, 0.05, 0.1, 0.3] range that I expected). So the results in #12794 (comment) and #12794 (comment) are incorrect (correct only for 0.01 density).
19.03% failure rate
| use same averaging algorithm
V
9.65% failure rate
| allow atol=1e-12
V
2.5% failure rate
increase dimensions | | increase dimensions
from 400x300 to 400x3000 | | from 400x300 to 4000x300
V V
10% failure rate 0% failure rate
(all tests pass)
Details
As is, 761/4000 (19.03%) full solver tests fail. These tests compare the following two outputs:
A. densify the sparse matrix first, pass the result to the solver
B. pass the sparse matrix to the solver as is.
I've found some issues that are increasing the failure rate:
In both cases A and B the following is run on the input:
self.mean_=np.mean(X, axis=0)
X-=self.mean_
When X is a sparse matrix, however, np.mean dispatches to a different algorithm than when X is dense. This results in different mean values being computed and contributes to the mismatches.
After the code is replaced with
atol (absolute tolerance) was set to 0, causing mismatches when the expected element value is 0 and the observed value is not exactly equal to 0, however small. Allowing atol=1e-12 brings the failure rate down to 100/4000 (2.5%).
The size and shape of the problem plays a significant role. Increasing the number of rows tenfold (400x300 -> 4000x300) at this point results in all tests passing. Increasing the number of columns tenfold (400x300 -> 400x3000), however, brings the failure rate up to 400/4000 (10%).
I don't know what role the distribution of our (randomly generated) inputs plays with respect to test outcomes.
@andportnoy it appears that it might help your debugging if you run the extreme cases - examples with 1 or 2 rows or columns, where the svd part becomes trivial/exact so you would mostly check the operation of the mean.
Your randomly generated input I guess is expected to always have an approximately constant (e.g., zero) mean, depending on a distribution. To change this, you may want to add random shifts to randomly generated columns/rows.
One issue with the distribution here is that the entries are i.i.d., so the covariance matrix has a constant repeated on the diagonal and off diagonal entries all zeros… Would this be an "ill-conditioned" input to SVD, especially if the matrix is underdetermined?
Activity
rth commentedon Dec 15, 2018
Did you see the TruncatedSVD estimator? In the current implementation, it should be equivalent to PCA on centered data, except that it does not necessarily center the data and also supports sparse input.
pavlin-policar commentedon Dec 16, 2018
Yes, I am aware of TruncatedSVD, but that's different. It's true that SVD on centered data is PCA, but SVD on noncentered data is not equivalent to PCA.
It's easy to see the difference with a simple example:
Now, I'm dealing with huge sparse matrices. If I densify them, they would not fit into memory, so centering the matrix is not an option (we lose all sparsity with centering).
Yes, I could perform incremental PCA, loading chunks of the matrix into memory at a time, but that's really slow. Yes, I could perform SVD on these matrices, which is fine, but not the same as PCA. Now, like I said in my first comment, this can be done i.e. we can compute PCA on noncentered data directly, without ever having to directly perform centering. This is what I'm missing. I hope I've it's clear enough this time. PCA is possible and is very fast on sparse matrices, and I feel it really should be included in scikit-learn.
jnothman commentedon Dec 18, 2018
glemaitre commentedon Dec 19, 2018
I am confused. It seems that you want PCA with non centered data which is as you mentioned, different from PCA. So it seems that you want the truncated SVD, isn't it?
pavlin-policar commentedon Dec 19, 2018
Perhaps I've been unclear. I'll try to be more clear this time :)
What we know
We know that SVD is not PCA. It is different. But, we usually compute PCA by taking a matrix X, centering it, then applying SVD. This is equivalent to taking X, centering it, computing its covariance matrix C, then computing the eigenvalues and eigenvectors of C.
So this is nothing new. We typically compute PCA via the SVD. And when X is centered, SVD is the same as PCA. Otherwise they are different.
The problem
Sometimes we can't center our matrix. If we have a huge sparse matrix, centering it will eliminate the sparseness and make the matrix dense. This is often impossible if X is really, really big. It can't fit into memory. So we can't do PCA. There are incremental ways to do this (I believe incremental PCA is used for this), but this requires a lot of disk reads, so it's slow.
We can still do SVD, but since X is not centered, this is not the same as PCA. PCA is often nicer because it's easier to interpret things. It's pretty hard to interpret an SVD (or I just might not be aware of it).
The solution
In the implementations I referenced (I don't know which paper the formulation comes from - I haven't gone through the maths), they implement randomized SVD and randomized PCA. But, PCA is computed with a randomized method that never needs to center X. To emphasise this, it is possible to compute actual PCA without ever having to center the original, potentially huge X matrix.
To achieve this, we take the already implemented randomized SVD algorithm, and add a couple of negative terms, which account for centering. The changes to the algorithm are very minor.
The randomized SVD implemented here is great and could be extended with just a couple of terms, and we could have it compute both the SVD and PCA. Setting a single flag e.g.
apply_centeringtorandomized_svdcould switch between the two.Conclusion
I hope I've made this very clear this time. I also hope it's clear that having this in scikit-learn would be very beneficial. Again, this is a more efficient way to compute PCA on sparse matrices, one that doesn't require us to make them dense. PCA is already implemented in scikit-learn, so adding an implementation that supports sparse data seems like the natural next step. This is not the same as SVD. PCA is nicer than SVD because it has a clearer interpretation.
I could work on this if needed, but I am not at all familliar with the codebase, and have fairly limited time.
glemaitre commentedon Dec 19, 2018
amueller commentedon Dec 19, 2018
Yeah I think it's clear and I think we probably want it but we need to research the math and check speed tradeoffs and complexity of adding the method etc.
pavlin-policar commentedon Dec 19, 2018
Actually, I've just briefly looked at the implementations and it seems to be astonishingly simple.
Randomized methods use power iteration to increase the spectral gap, which is just a fancy way of saying multiplication by the original matrix X multiple times. SVD already does this in the current implementation.
Since PCA is just SVD(X - means), and SVD is computed with power iteration, now the power iteration looks like this: (X - means) * Q where Q is the basis. And if we use the distributive property of the dot product we can instead do (X * means) - (means * Q), meaning X never has to be centered.
I don't think I've explained this properly (clearly I need to work on my explanations), but it's just a clever application of the distributive property of the dot product.
glemaitre commentedon Dec 19, 2018
If I am not wrong (I never really read the code before) it looks like the solver
randomized_svd:Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions, Halko, et al., 2009 https://arxiv.org/abs/0909.4061
which is the one used by default in the
TruncatedSVD.pavlin-policar commentedon Dec 20, 2018
So, I've played around with this a little bit and I think these are all the changes needed int the randomized SVD solver.
The only real change is that whenever we apply a non-centered matrix A to any other matrix, we distribute the mean subtraction like so: (A - m) X = AX - mX, avoiding the need to ever center A.
I've run all the tests for TruncatedSVD, and they pass. In the PCA learner, there's one problematic line:
which fails on sparse matrices. I'd expect something like sparse variance to be already implemented, but I'm not familliar with the codebase and don't know where to look. If not, it should be relatively straightforward to implement this as well.
lesshaste commentedon Dec 20, 2018
For the variance I guess you can just use the formula:
E[X^2] - (E[X])^2
jeremiedbb commentedon Dec 20, 2018
in sklearn you have
mean_variance_axisinutils/sparsefuncs_fast.py, so that sould not be an issueglemaitre commentedon Dec 20, 2018
I looked into the paper and they actually only speak of the SVD which explain why our implementation does not remove the mean.
Then, your proposal looks good to me. Since that we already have
solver='auto'inPCA, we could default to always'randomized'for sparse matrices with little changes within the code.@pavlin-policar thanks a lot for the clarifications and the patience ;)
adrinjalali commentedon Dec 20, 2018
@pavlin-policar would you be keen on opening a PR with the changes?
pavlin-policar commentedon Dec 20, 2018
Yeah, sure. I'll give it a shot.
@jeremiedbb Thank's that's going to make things easier.
41 remaining items
andportnoy commentedon Dec 17, 2022
Relative tolerance study
I varied the relative tolerance used in elementwise comparisons of the$V^T$ in $A = U\Sigma V^T$ ) coming from PCA on sparse data with implicit centering to those coming from dense PCA on the same data. The range that I tested is $\{10^0, 10^{-1}, ..., 10^{-7}\}$ (8 positions total), where $10^{-7}$ is the default value. The absolute tolerance was set to 0 (default) and the final comparison in
componentsvectors (corresponding tonp.assert_allcloseis tortol*desired + atol(see NumPy docs).Below I'm showing plots of the resulting test pass rates and elementwise mismatch rates (of the failed tests) for each solver.
Rate values are shown up to 2 significant digits.
0and1are true0and1.Tentative conclusion
For my personal practical purposes, LOBPCG passes the correctness test on this small data set (300x400). Don't know if those tolerances/error rates are acceptable in scikit-learn.
ARPACK seems to always have a small number of elements that are significantly far away from the desired value, that could also be acceptable. Not sure yet how to debug.
Randomized is performing very badly, even when tolerance is relaxed. I'll try to compare intermediate outputs to see where the divergence comes from.
The full solver is not interesting for practical purposes.
Pass rate by solver
Fraction of the tests that passed for each solver, broken down by relative tolerance level.
Plot
Elementwise mismatch rate by solver
For the tests that failed, the fraction of the elements that didn't pass the comparison.
Plot
andportnoy commentedon Dec 17, 2022
I'm still trying to get a large number of tests to run across all environments on CI, I'll post an analysis of that later. It will likely only include the default tolerance level since the full range timed out.
lobpcg commentedon Dec 17, 2022
@andportnoy your tests results look plausible, except for the full solver which should be expected to be 100% accurate.
andportnoy commentedon Dec 17, 2022
@lobpcg Agreed, it's a little suspicious. I'll try to root cause.
In each case I'm essentially comparing the SVD of the densified centered data to the SVD of the implicitly centered sparse data, using the same solver. Maybe I should instead use the outputs of a single, highest
precisionaccuracy, dense solver as the only reference. Or carry out the SVD using an arbitrary precision library and convert the results to nearest float64 values.What do you think?
lobpcg commentedon Dec 17, 2022
You should probably use the full float64 solver as the baseline, after figuring our why it's not 100% accurate.
andportnoy commentedon Feb 24, 2023
Getting back to this. Short term goals:
andportnoy commentedon Feb 24, 2023
I discovered that I wasn't using the density parameter (
1-sparsity) at all, so it defaulted to 0.01 everywhere (instead of the[0.01, 0.05, 0.1, 0.3]range that I expected). So the results in #12794 (comment) and #12794 (comment) are incorrect (correct only for 0.01 density).andportnoy commentedon Feb 28, 2023
Plots for #12794 (comment) redone actually using the density parameter properly. Note the passrate is much better for higher densities.
Overall passrate
Mismatch rate of failed tests
The plots can be reproduced by running
on the branch (commit 600f2f1).
andportnoy commentedon Feb 28, 2023
Plots for #12794 (comment) redone.
Pass rate by solver
Elementwise mismatch rate by solver
andportnoy commentedon Feb 28, 2023
Now need to get back to figuring out why the full solver has failures.
andportnoy commentedon Apr 22, 2023
Full solver debug
Summary
Details
As is, 761/4000 (19.03%) full solver tests fail. These tests compare the following two outputs:
A. densify the sparse matrix first, pass the result to the solver
B. pass the sparse matrix to the solver as is.
I've found some issues that are increasing the failure rate:
np.meandispatches to a different algorithm than when X is dense. This results in different mean values being computed and contributes to the mismatches.After the code is replaced with
atol(absolute tolerance) was set to 0, causing mismatches when the expected element value is 0 and the observed value is not exactly equal to 0, however small. Allowingatol=1e-12brings the failure rate down to 100/4000 (2.5%).400x300 -> 4000x300) at this point results in all tests passing. Increasing the number of columns tenfold (400x300 -> 400x3000), however, brings the failure rate up to 400/4000 (10%).I don't know what role the distribution of our (randomly generated) inputs plays with respect to test outcomes.
lobpcg commentedon Apr 24, 2023
@andportnoy it appears that it might help your debugging if you run the extreme cases - examples with 1 or 2 rows or columns, where the svd part becomes trivial/exact so you would mostly check the operation of the mean.
Your randomly generated input I guess is expected to always have an approximately constant (e.g., zero) mean, depending on a distribution. To change this, you may want to add random shifts to randomly generated columns/rows.
andportnoy commentedon May 24, 2023
One issue with the distribution here is that the entries are i.i.d., so the covariance matrix has a constant repeated on the diagonal and off diagonal entries all zeros… Would this be an "ill-conditioned" input to SVD, especially if the matrix is underdetermined?
glemaitre commentedon May 17, 2024
Nowadays, we have the
arpacksolver that uses the linear operator that allows to process sparse data with PCA: https://scikit-learn.org/dev/auto_examples/release_highlights/plot_release_highlights_1_4_0.html#improved-memory-and-runtime-efficiency-for-pca-on-sparse-data