Skip to content

SparsePCA incorrectly scales results in .transform() #9394

Closed

Description

@AndreusUltimus

Description

When using SparsePCA, the transform() method incorrectly scales the results based on the number of rows in the data matrix passed.

Proposed Fix

I am regrettably unable to do a pull request from where I sit. The issue is with this chunk of code, as of writing this at line number 179 in sparse_pca.py:

        U = ridge_regression(self.components_.T, X.T, ridge_alpha,
                             solver='cholesky')
        s = np.sqrt((U ** 2).sum(axis=0))
        s[s == 0] = 1
        U /= s
        return U

I honestly do not understand the details of the chosen implementation of SparsePCA. Depending on the objectives of the class, making use of the features as significant for unseen examples requires one of two modifications. Either (a) learn the scale factor s from the training data (i.e., make it an instance attribute like .scale_factor_), or (b) use .mean(axis=0) instead of .sum(axis=0) to remove the number-of-examples dependency.

Steps/Code to Reproduce

from sklearn.decomposition import SparsePCA
import numpy as np


def get_data( count, seed ):
    np.random.seed(seed)
    col1 = np.random.random(count)
    col2 = np.random.random(count)

    data = np.hstack([ a[:,np.newaxis] for a in [
        col1 + .01*np.random.random(count),
        -col1 + .01*np.random.random(count),
        2*col1 + col2 + .01*np.random.random(count),
        col2 + .01*np.random.random(count),
        ]])
    return data


train = get_data(1000,1)
spca = SparsePCA(max_iter=20)
results_train = spca.fit_transform( train )

test = get_data(10,1)
results_test = spca.transform( test )

print( "Training statistics:" )
print( "  mean: %12.3f" % results_train.mean() )
print( "   max: %12.3f" % results_train.max() )
print( "   min: %12.3f" % results_train.min() )
print( "Testing statistics:" )
print( "  mean: %12.3f" % results_test.mean() )
print( "   max: %12.3f" % results_test.max() )
print( "   min: %12.3f" % results_test.min() )

Output:

Training statistics:
  mean:       -0.009
   max:        0.067
   min:       -0.080
Testing statistics:
  mean:       -0.107
   max:        0.260
   min:       -0.607

Expected Results

The test results min/max values are on the same scale as the training results.

Actual Results

The test results min/max values are much larger than the training results, because fewer examples were used. It is trivial to repeat this process with various sizes of training and testing data to see the relationship.

Activity

  1. rth commented on Sep 2, 2017

    @rth
    Member

    Actual Results

    The test results min/max values are much larger than the training results, because fewer examples were used.

    @Andrewww Thanks for opening this issue. I can confirm your results (they are also true for the MiniBatchSparsePCA), and that in unit tests sklearn/decomposition/tests/test_sparse_pca.py the transform value does not seem to be validated as far as I could see.

    How do you propose to make sure that your solution is correct? For instance, is there a case where SparsePCA should produce the same results as PCA (e.g. by setting alpha=0)? Otherwise is it possible to either validate the results with the example in the original paper (section 5.5) or with those produced by some other implementation? cc @vene

  2. AndreusUltimus commented on Sep 14, 2017

    @AndreusUltimus
    Author

    @rth Honestly, I had not dug into the math to determine what the correct solution would be; I merely discovered the dependency on number of examples, knew that was wrong, and proposed a solution that at least eliminates that dependency.

    I suspect the examples in the original paper is the best approach (you mention section 5.5, but I only see 5.1 through 5.3, which really are three separate examples that would make good unit tests).

    Again, I did not dig through the math, but if I assume that SPCA is what I think it is (PCA estimated with an L1 penalty altering the original loss function), then alpha=0 should recover the PCA solution and again that yields good unit tests.

    I feel like a terrible contributor, but all I can really do from where I sit is comment on bugs and provide typed ideas of solutions in comments. Artifact of my job.

  3. rth commented on Sep 14, 2017

    @rth
    Member

    I feel like a terrible contributor, but all I can really do from where I sit is comment on bugs and provide typed ideas of solutions in comments. Artifact of my job.

    Well, all your previous bug reports were accurate and provided a fix: that is very helpful. Thank you )

    Someone would just need to investigate this issue in more detail...

  4. added this to the 0.20 milestone on Sep 15, 2017
  5. lesteve commented on Sep 15, 2017

    @lesteve
    Member

    This seems like a bug indeed although I don't know much about SparsePCA. I quickly looked at it and the PCA does not give the same results as the SparsePCA with alpha=0 and ridge_alpha=0 (whether they should or not I am not sure). One thing I noticed is that spca.components_ are not normalized (in contrary to pca.components_) and their norms seems to depend on the size of the data as well so maybe there was some logic behind the transform scaling ...

  6. summer-bebop commented on Jul 16, 2018

    @summer-bebop
    Contributor

    I discussed with @GaelVaroquaux and I'll try to take care of it.
    The summary of our discussion :
    I have to verify that the spca and pca components are the same modulo a rotation and a normalization which is our hyporthesis. From there : change the behaviour of SparsePCA and define a deprecation path. We suggest to add a scale_components parameter to SparsePCA with default value = False which would leave things untouched. If this parameter is set to True then we compute the norm of the components during training and normalize with it this should mitigate the scaling problem. If everything works out we deprecate the default scale_components=False.
    Hopefully I'll manage to do that during the sprint.

  7. vene commented on Jul 16, 2018

    @vene
    Member

    Indeed the result with no regularization will only match PCA up to rotation & scaling because they are constrained differently (our SPCA does not have orthonormal constraints). I suspect they should have equal reconstruction MSE, right?

    According to this discussion I agree the current transform is indeed wrong. As far as I understand the proposed fix is about .fit, not .transform-- when you say "leave things untouched" you mean other than fixing the .transform bug? If not, with scale_components=True will transform be normalized twice?

    (Disclaimer: I'm missing a lot of context and forgot everything about the code)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions