Search code examples
pythonscikit-learnpcaspyder

Sklearn.PCA-unexpected keyword argument 'random_state'


def doPCA(data, dimensions=2):
from sklearn.decomposition import PCA
model = PCA(n_components=dimensions, svd_solver='randomized', random_state=7)
model.fit(data)
return model

File "/home/dogus/Downloads/DAT210x-master/Module5/assignment4.py", line 221, in display_pca = doPCA(T)

File "/home/dogus/Downloads/DAT210x-master/Module5/assignment4.py", line 56, in doPCA model = PCA(n_components=dimensions, svd_solver='randomized', random_state=None)

TypeError: init() got an unexpected keyword argument 'random_state'

  • I use Spyder with python2.7 in Ubuntu.
  • I installed sklearn with conda,i also installed it via 'pip install'.
  • I tried random_state=None but gave me the same error.
  • Then i ran it via terminal and it worked without any error.

Edit:

  • Scikit-learn(1.18.1),spyder,scipy,numpy,ipython updated via anaconda.
  • Then i restarted Spyder and tried to run the code but gave me the same error.
  • I ran the codes via IPython and Python consoles.

Problem caused by Spyder? How can i fix it?


Solution

  • You are probably using an old version of sklearn. The docs say that the random_state variable was added in version 0.18.0. Try updating sklearn.

    In order to make the update, look at these questions


    Based on your comment, just to make sure the problem is not the scikit-learn version, try the following

    def doPCA(data, dimensions=2): 
        from sklearn.decomposition import PCA
        import sklearn
        print sklearn.__version__
        model = PCA(n_components=dimensions, svd_solver='randomized', random_state=7)
        model.fit(data)
        return model
    

    This will only print the version of sklearn being used. As you said that you had also installed sklearn with pip, you could have conflicting versions.