Skip to content

PCA, LDA, unexpected explained_variance_ratio #9400

Open

Description

@yaohualiu
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

iris = datasets.load_iris()

X = iris.data
y = iris.target
target_names = iris.target_names

#### dimensionality reduction using PCA
pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)

#### Percentage of variance explained for each components
print('PCA: explained variance ratio (first two components): %s'
      % str(pca.explained_variance_ratio_))

#### dimensionality reduction using LDA
lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

print('LDA: explained variance ratio (first two components): %s'
      % str(lda.explained_variance_ratio_))

Expected Results

The first componet of the PCA has a larger variance ratio than that from the first componet from LDA.

Actual Results

PCA: explained variance ratio (first two components): [ 0.925 0.053]
LDA: explained variance ratio (first two components): [ 0.991 0.009]

Versions

Darwin-14.5.0-x86_64-i386-64bit
Python 3.5.3 |Anaconda custom (x86_64)| (default, Mar 6 2017, 12:15:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
NumPy 1.12.1
SciPy 0.19.1
Scikit-Learn 0.18.2

Activity

  1. amueller commented on May 22, 2018

    @amueller
    Member

    Possibly related to #9107. Thanks for the report, sorry for the slow reply.

  2. JPFrancoia commented on May 22, 2018

    @JPFrancoia
    Contributor

    Euh, I'm really not sure explained_variance_ratio should be the same for PCA and LDA.

    PCA is unsupervised, LDA is supervised. The principal components are calculated differently since LDA needs a label (y) for each point (that's why lda.fit(X, y).transform(X) and pca.fit(X).transform(X)).

    Since LDA will find different principal components, I see no reason why explained_variance_ratio should be the same in both cases.

    If I'm wrong please let me know, otherwise this issue should be closed because it's not a bug.

  3. amueller commented on May 24, 2018

    @amueller
    Member

    It shouldn't be the same, but I would have expected PCA to have more explained variance since that's what it's optimizing, while LDA has other things it optimizes. But I didn't think deeply about what the explained_variance_ratio in LDA means. My intuition was that the first principal component should explain more variance than any other direction. But maybe the denominator is different for the two ratios?

  4. ycpei commented on Dec 4, 2018

    @ycpei

    Update on 2018-12-07: I was wrong. So please ignore this comment.

    I suspect the problem has to do with the fact that each feature is normalised individually before SVD (see _solve_svd):

    X = np.sqrt(fac) * (Xc / std)
    

    This was later "rectified" with the following:

    scalings = (V[:rank] / std).T / S[:rank]
    

    where V and S are calculated using svd

    U, S, V = linalg.svd(X, full_matrices=False)
    

    I don't think this makes sense mathematically. It produces a different scalings from the following:

    X = np.sqrt(fac) * Xc
    U, S, V = linalg.svd(X, full_matrices=False)
    scalings = V[:rank].T / S[:rank]
    
  5. mateuspontesm commented on Dec 5, 2018

    @mateuspontesm

    I got the same problem on LDA, its sum of explained_variance_ratio_ was greater than 1.
    It seems related to the solver = 'eigen', as it runs ok with 'svd'. I will problably post my notebook on github later on, if it is of help I can post the link here afterwards, but for now I will leave this here:

    pctVarExp = []
    #Pipelines com os Escaladores e Redução de dimensionalidade:
    for ii, clasf in enumerate(classifs):
        pipelines[names[ii]] = Pipeline([('DimRed', LinearDiscriminantAnalysis(n_components=2, solver='eigen')), ( 'classifier', clasf)])
    #Fits e Scores
    scores = {'NN': [], 'DMC': [], 'CQG': []}
    for ii in range(500):
        X_train, X_test, y_train, y_test = train_test_split(dfX,dfY,test_size = 0.2, random_state= ii)
        for key, value in pipelines.items():
            value.fit(X_train, y_train)
            pctVarExp.append(np.sum(value.named_steps['DimRed'].explained_variance_ratio_)) # % da variância explicada pelas componentes
            scores[key].append(value.score(X_test,y_test))
    ## Tirando a média: ##
    for key in scores:
        scores[key] = np.mean(scores[key])

    When I look at pctVarExp it has values like: [1.000000001356325, 1.000000001356325, 1.000000001356325, 0.9999999914732854, 0.9999999914732854, 1.0000000191251681]

  6. YangXiaozhou commented on Mar 7, 2021

    @YangXiaozhou

    Euh, I'm really not sure explained_variance_ratio should be the same for PCA and LDA.

    PCA is unsupervised, LDA is supervised. The principal components are calculated differently since LDA needs a label (y) for each point (that's why lda.fit(X, y).transform(X) and pca.fit(X).transform(X)).

    Since LDA will find different principal components, I see no reason why explained_variance_ratio should be the same in both cases.

    If I'm wrong please let me know, otherwise this issue should be closed because it's not a bug.

    Adding on to @JPFrancoia 's comment, there is indeed no reason why the two ratios should be the same since they are computed based on different data. Therefore it might not be a bug.

    In particular, while both are ratios of descending eigenvalues against the sum of the eigenvalues, PCA computes eigenvalues from the entire data set, X, while LDA computes those from W^{-1}B, the multiplication of within-class variance and between-class variance calculated from X and y. For example, when X is fixed, PCA would produce the same eigenvectors and eigenvalues every time, thus the same ratio of variance explained. However, LDA would give different ratios (because of different projection directions found) for different sets of y even when X is the same.

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