Reputation: 766
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!
Upvotes: 4
Views: 16109
Reputation: 163
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.
Upvotes: 1
Reputation: 6438
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.
Upvotes: 2