# sklearn.decomposition.PCA explained_variance_ratio_ attribute does not exist

When trying to identify the variance explained by the first two columns of my dataset using the explained_variance_ratio_ attribute of sklearn.decomposition.PCA I recieve the following error:

AttributeError: 'PCA' object has no attribute 'explained_variance_ratio_'


My code (condensed):

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

df = df.dropna()
df_transform = StandardScaler().fit_transform(df)
pca = PCA(n_components=2).fit_transform(df_transform)
var_exp = pca.explained_variance_ratio_


When the last line is executed, I get the error:

AttributeError: 'PCA' object has no attribute 'explained_variance_ratio_'


I am using sklearn version 0.20.0

Edit

After examining the attributes of sklearn.decomposition.PCA, I see that the attribute does indeed not exist (as shown in image).

This is untested, but I believe the error is occurring because you're calling explained variance on the fit_transform object, as opposed to simply just the results of fit.

Try:

df = pd.read_csv('Input.csv')
df = df.dropna()
df_transform = StandardScaler().fit_transform(df)
pca = PCA(n_components=2).fit(df_transform)
new_df = pca.transform(df_transform)
var_exp = pca.explained_variance_ratio_

• This version worked for me. – D Adams Apr 29 at 23:48

The problem is you do not need to pass through your parameters through the PCA algorithm again (essentially what it looks like you are doing is the PCA twice). Just add the .explained_variance_ratio_ to the end of the variable that you assigned the PCA to

For example try:

pca = PCA(n_components=2).fit_transform(df_transform)


Setting instead your var_exp = to:

var_exp = pca.explained_variance_ratio_

• Sadly, this does not solve the problem. Examining the attributes of pca using pdb.set_trace(), I see the attribute explained_variance_ratio_ does not exist... Any idea how/why this is? – Lobke Oct 20 '18 at 14:24
• @Lobke Sorry if my answer was not helpful. When I reproduced your code with a different data set and made the changes above it corrected the error. Do you have a snapshot of the csv file that you are using so that maybe I can try to get a more accurate sense of your problem? – Ethan Oct 21 '18 at 19:22
• And just to clarify - you indeed tried adjusting your code to (in your case) to say var_exp = PCs.var_explained_ratio_ – Ethan Oct 21 '18 at 19:24
• Yep, as the edit above shows, the issue is not in the implementation of the method, but in sklearn.decomposition.PCA itself. I tried reinstalling everything in a virtual environment to try and solve the issue, but to no avail... Any ideas? – Lobke Oct 22 '18 at 15:21
• Do you have a snapshot of the data set that you are using, so I can try to reproduce your error? – Ethan Oct 22 '18 at 18:56