简体   繁体   中英

ImportError: cannot import name 'tree' for sklearn

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM