Skip to content

PCA on sparse, noncentered data #12794

Closed

Description

@pavlin-policar

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.

Activity

  1. rth commented on Dec 15, 2018

    @rth
    Member

    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.

  2. pavlin-policar commented on Dec 16, 2018

    @pavlin-policar
    Author

    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:

    >>> x = datasets.load_boston().data
    >>> x.mean(axis=0)  # Not centered!
    array([  3.61352356,  11.36363636,  11.13677866,   0.06916996,
             0.55469506,   6.28463439,  68.57490119,   3.79504269,
             9.54940711, 408.23715415,  18.4555336 , 356.67403162,
            12.65306324])
    
    >>> sksvd = decomposition.TruncatedSVD(n_components=6)
    >>> sksvd.fit(x)
    >>> sksvd.singular_values_
    array([12585.18158999,  3445.97405949,   645.75710949,   402.05046109,
             158.96461248,   121.50293599])
    
    >>> skpca = decomposition.PCA(n_components=6)
    >>> skpca.fit(x)
    >>> skpca.singular_values_
    array([3949.60823205, 1776.63071036,  642.86374839,  366.98207453,
            158.634553  ,  118.64982369])

    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.

  3. jnothman commented on Dec 18, 2018

    @jnothman
    Member
  4. glemaitre commented on Dec 19, 2018

    @glemaitre
    Member

    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?

  5. pavlin-policar commented on Dec 19, 2018

    @pavlin-policar
    Author

    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.

  6. glemaitre commented on Dec 19, 2018

    @glemaitre
    Member
  7. amueller commented on Dec 19, 2018

    @amueller
    Member

    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.

  8. pavlin-policar commented on Dec 19, 2018

    @pavlin-policar
    Author

    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.

  9. glemaitre commented on Dec 19, 2018

    @glemaitre
    Member

    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.

  10. pavlin-policar commented on Dec 20, 2018

    @pavlin-policar
    Author

    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.

  11. lesshaste commented on Dec 20, 2018

    @lesshaste

    For the variance I guess you can just use the formula:

    E[X^2] - (E[X])^2

  12. jeremiedbb commented on Dec 20, 2018

    @jeremiedbb
    Member

    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

  13. glemaitre commented on Dec 20, 2018

    @glemaitre
    Member

    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 ;)

  14. adrinjalali commented on Dec 20, 2018

    @adrinjalali
    Member

    @pavlin-policar would you be keen on opening a PR with the changes?

  15. pavlin-policar commented on Dec 20, 2018

    @pavlin-policar
    Author

    Yeah, sure. I'll give it a shot.

    @jeremiedbb Thank's that's going to make things easier.

  16. 41 remaining items

  17. andportnoy commented on Dec 17, 2022

    @andportnoy
    Contributor

    Relative tolerance study

    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

    passrate-tolerance-study-2022-12-10_12-08-40

    Elementwise mismatch rate by solver

    For the tests that failed, the fraction of the elements that didn't pass the comparison.

    Plot

    mismatch-tolerance-study-2022-12-10_12-15-17

  18. andportnoy commented on Dec 17, 2022

    @andportnoy
    Contributor

    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.

  19. lobpcg commented on Dec 17, 2022

    @lobpcg
    Contributor

    @andportnoy your tests results look plausible, except for the full solver which should be expected to be 100% accurate.

  20. andportnoy commented on Dec 17, 2022

    @andportnoy
    Contributor

    @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.

    What do you think?

  21. lobpcg commented on Dec 17, 2022

    @lobpcg
    Contributor

    You should probably use the full float64 solver as the baseline, after figuring our why it's not 100% accurate.

  22. andportnoy commented on Feb 24, 2023

    @andportnoy
    Contributor

    Getting back to this. Short term goals:

    1. figure out why the full solver fails most test cases,
    2. rerun the tests using the full solver outputs as reference.
  23. andportnoy commented on Feb 24, 2023

    @andportnoy
    Contributor

    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).

  24. andportnoy commented on Feb 28, 2023

    @andportnoy
    Contributor

    Plots for #12794 (comment) redone actually using the density parameter properly. Note the passrate is much better for higher densities.

    Overall passrate

    pca-sparse-passrate-600f2f141-20230228-141530

    Mismatch rate of failed tests

    pca-sparse-mismatch-600f2f141-20230228-141004

    The plots can be reproduced by running

    bash pca-sparse-debug/scripts/passrate-main.sh
    bash pca-sparse-debug/scripts/mismatch-main.sh

    on the branch (commit 600f2f1).

  25. andportnoy commented on Feb 28, 2023

    @andportnoy
    Contributor

    Plots for #12794 (comment) redone.

    Pass rate by solver

    pca-sparse-passrate-tolerance-600f2f141-20230228-142509

    Elementwise mismatch rate by solver

    pca-sparse-mismatch-tolerance-600f2f141-20230228-143349

  26. andportnoy commented on Feb 28, 2023

    @andportnoy
    Contributor

    Now need to get back to figuring out why the full solver has failures.

  27. andportnoy commented on Apr 22, 2023

    @andportnoy
    Contributor

    Full solver debug

    Summary

                              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:

    1. 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
      if issparse(X):
          self.mean_ = X.sum(axis=0) / X.shape[0]
      else:
          self.mean_ = np.mean(X, axis=0)
      the failure rate goes down to 386/4000 (9.65%).
    2. 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%).
    3. 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.

  28. lobpcg commented on Apr 24, 2023

    @lobpcg
    Contributor

    @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.

  29. andportnoy commented on May 24, 2023

    @andportnoy
    Contributor

    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?

  30. glemaitre commented on May 17, 2024

    @glemaitre
    Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions