Search code examples
pythonscikit-learnpca

TypeError: PCA() got an unexpected keyword argument 'n_components'


Hi I was trying to implement the PCA(), but I'm getting an error, '

TypeError: PCA() got an unexpected keyword argument 'n_components'.

from sklearn.decomposition import PCA
#Principal component analysis
def PCA(X,Y):
    pca = PCA(n_components=2)
    X = pca.fit_transform(X)

    plot_2d_space(X, Y, 'Imbalanced dataset (2 PCA components)')

Can someone please tell me a possible reason for this


Solution

  • First you are importing from sklearn.decomposition import PCA and then you're using same name for your function def PCA

    So next time you'll call the function, it will call your function not from the scikit-learn function.

    So basically pca = PCA(n_components=2) expects the arguments X and Y where you're passing n_components.

    Solution:

    Change the name of your function and it should work:

    def PCA_2(X,Y):
        pca = PCA(n_components=2)
        X = pca.fit_transform(X)
    
        plot_2d_space(X, Y, 'Imbalanced dataset (2 PCA components)')