Skip to content

KernelPCA: fit_transform and transform methods are inconsistent in case of zero eigenvalues #12141

Closed

Description

@smarie

In current implementation of KernelPCA, when there are zero eigenvalues that are not removed (remove_zero_eig=False), then fit_transform and fit + transform methods lead to inconsistent results.

  • when fit_transform is run, there is an optimization code that does not recompute the gram matrix. Therefore the transformed X is X_transformed = self.alphas_ * np.sqrt(self.lambdas_) here
  • when transform is run, of course it cannot use the same shortcut and therefore the gram matrix is recomputed and a dot product is performed here. Because the eigenvectors self.alphas_ are not saved in a scaled version (I do not know why), they are scaled just here, by dividing by the square root of the eigenvalues np.sqrt(self.lambdas_). When eigenvalues are zero, this leads to infinite values in the eigenvectors which after the dot product may result in infinite values or nan values.

To fix this issue, I guess that we should not scale the eigenvectors when the eigenvalue is zero.

There are two ways to do this:

  • either do this in the transform method for example by
def transform(self, X):
        """Transform X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)
        """
        check_is_fitted(self, 'X_fit_')

        # Compute centered gram matrix between X and training data X_fit_
        K = self._centerer.transform(self._get_kernel(X, self.X_fit_))

        # scale eigenvectors
        scaled_alphas = self.alphas_ / np.sqrt(self.lambdas_)

        # properly take null-space into account for the dot product
        scaled_alphas[:, self.lambdas_ == 0] = 0

        # Project by doing a scalar product between K and the scaled eigenvects
        return np.dot(K, scaled_alphas)
  • or we could scale the self.alphas_ directly when they are created (at the end of _fit). In which case we would need to adapt fit_transform and transform.

Activity

  1. smarie commented on Sep 24, 2018

    @smarie
    ContributorAuthor

    (previous comment edited for clarity)

    Actually doing the second option may be dangerous only in one case: if self.alphas_ is directly referenced by some application (or stored in a persistent kPCA model from another version and read back in the newest version). Do we prefer maintaining legacy compatibility for internal attributes, or improving readability and (slightly) performance ?

    In the PR I will therefore go for the "legacy compliant" option (the first one).

  2. added a commit that references this issue on Sep 24, 2018
    27b4de5
  3. NicolasHug commented on Oct 3, 2018

    @NicolasHug
    Member

    Could you please add a minimal code example illustrating the issue?

  4. smarie commented on Oct 8, 2018

    @smarie
    ContributorAuthor

    Sure :

    (EDIT: this example is now ok)

    import numpy as np
    from numpy.testing import assert_array_almost_equal
    from sklearn.decomposition import KernelPCA
    
    data = [[1, 1],
            [0, 0]]
    
    X_fit = np.array(data)
    
    k = KernelPCA(2, eigen_solver="dense")
    A = k.fit(X_fit).transform(X_fit)
    B = k.fit_transform(X_fit)
    
    assert_array_almost_equal(np.abs(A), np.abs(B))

    Yields:

    AssertionError: Arrays are not almost equal to 6 decimals
    x and y nan location mismatch:
     x: array([[0.707107,       nan],
           [ 0.707107,       nan]])
     y: array([[0.707107, 0.      ],
           [ 0.707107, 0.      ]])

    I will add the corresponding unit test.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions