Plot the cumulative explained variance of our PCA

Viewed 1867

Im currently making an assignment for school an i'm a little stuck.

The assignment goes as following:

Plot the cumulative explained variances using ax.plot and look for the number of components at which we can account for >90% of our variance; assign this to n_components.

To achieve this, i've been provided the following code:

import numpy as np


cum_exp_variance = np.cumsum(exp_variance)

print(cum_exp_variance)
fig, ax = plt.subplots()
ax.plot(cum_exp_variance)
ax.axhline(y=0.9, linestyle='--')
n_components = PCA(n_components= 0.9)

pca = PCA(n_components, random_state=10)
pca.fit(scaled_train_features)
pca_projection = pca.transform(scaled_train_features)

But i keep getting an error when i try to assign the variance to the n_components variable. The error is the following:

    TypeError                                 Traceback (most recent call last)
<ipython-input-42-a902c6ee649b> in <module>()
     15 # Perform PCA with the chosen number of components and project data onto components
     16 pca = PCA(n_components, random_state=10)
---> 17 pca.fit(scaled_train_features)
     18 pca_projection = pca.transform(scaled_train_features)

/usr/local/lib/python3.5/dist-packages/sklearn/decomposition/pca.py in fit(self, X, y)
    327             Returns the instance itself.
    328         """
--> 329         self._fit(X)
    330         return self
    331 

/usr/local/lib/python3.5/dist-packages/sklearn/decomposition/pca.py in _fit(self, X)
    382             if max(X.shape) <= 500:
    383                 svd_solver = 'full'
--> 384             elif n_components >= 1 and n_components < .8 * min(X.shape):
    385                 svd_solver = 'randomized'
    386             # This is also the case of n_components in (0,1)

TypeError: unorderable types: PCA() >= int()

My guess is that it is a very simple mistake, but i can't seem to figure it out.

All help is greatly appreciated

1 Answers

(I'm assuming that you are using PCA from scikit-learn).

The problem is with the following line of your code:

n_components = PCA(n_components= 0.9)

Now n_components hold an object of type PCA, but that's not what you want! According to the documentation, n_components should be an integer, float, string, or None. I think you want to do:

n_components = 0.9
Related