ImportError: cannot import name 'tree' for sklearn

11,583

Solution 1

The solution is to rename your "sklearn.py" under the "Machine Learning" folder to any other name but not "sklearn.py".

Why? That's the mechanism of Python modules searching sequence. Try prepend these lines to your "sklearn.py":

import sys
print(sys.path)

You'll find the first element of the output list is always an empty string, which means the current directory has the highest priority on modules searching. Runs from sklearn import tree at "C:\Machine Learning" folder will import the local same name "sklearn.py" as "sklearn" module, instead of importing the machine learning module globally.

Solution 2

I had the same issue. Using sublime text 3 as editor and build. Very simple to solve in my case.

My working file was also named 'sklearn.py' so when I was attempting to "import sklearn" it was importing its own file found in the current working directory - without error. But when I attempted to 'from sklearn import tree' it failed.

Just changing the name of my working file program to something else solved the problem.

Thanks.

Share:
11,583
AlphaBetaGamma96
Author by

AlphaBetaGamma96

Updated on June 17, 2022

Comments

  • AlphaBetaGamma96
    AlphaBetaGamma96 almost 2 years

    I've recently installed Scipy, Numpy and Scikit-learn by using pip, but when I run the program below

    from sklearn import tree
    
    features = [[140, 1], [130, 1], [150, 1], [170, 1]] #input
    labels = [0, 0, 1, 1] #output
    
    clf = tree.DecisionTreeClassifier()  
    clf = clf.fit(features, labels) #fit = find patterns in data
    
    print (clf.predict([[160, 0]]))
    

    The shell prints this error

    Traceback (most recent call last):
      File "C:/Machine Learning/sklearn.py", line 1, in <module>
        from sklearn import tree
      File "C:/Machine Learning\sklearn.py", line 1, in <module>
        from sklearn import tree
    ImportError: cannot import name 'tree'
    

    Does anyone know how to solve this? I've tried uninstalling and reinstalling it, but I get the same error. Many thanks in advance!

  • AlphaBetaGamma96
    AlphaBetaGamma96 almost 8 years
    I've changed the name and saved it in another directory the one with all the site-packages. But I get the same error. I'm new to using sklearn and I've only starting learning python about a month ago
  • Philip Tzou
    Philip Tzou almost 8 years
    OK. Can you check if there's any *.pyc file (py2) or __pycache__ folder (py3) inside your workspace and delete them all? Also can you write a new .py file, try import sklearn then print(sklearn) and post the result here?