'NameError: name 'tree' is not defined

Hey I'm new to Python and I am trying to follow along with a tutorial but I get this error:

NameError: name 'tree' is not defined.

The objective is obviously for the program to determine whether the fruit is an apple or orange based on the input of features. I'm using Python 3.6 with the spyder editor on Win 10. I'm sure it's something simple, thanks for any help!

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

# features = [[140, "smooth"], [130, "smooth"], [150, "bumpy"], [170, "bumpy"]]
# labels = ["apple", "apple", "orange", "orange"]
features = [[140, 1], [130, 1], [150, 0], [170, 0]]
labels = [0, 0, 1, 1]
# We build a "Decision Tree" yes/no -> yes/no
# clf means classifier
clf = tree.DecisionTreeClassifier()
# Think of "fit" as "find patters in data"
clf = clf.fit(features, labels)
print (clf.predict([[160, 0]]))


Solution 1:[1]

Add this to the top of your code:

from sklearn import tree

This is assuming that you are studying machine learning.

Solution 2:[2]

I tried this from sklearn import tree it does not work on my system.

Then I tried this from sklearn.tree import DecisionTreeClassifier and worked.

This is after installing sklearn of course.

Solution 3:[3]

One needs to import lib before using. So, to use DecisionTreeClassifier, either use below code to import & run.

from sklearn import tree.
...
dtree = tree.DecisionTreeClassifier()

Another way is to import the class itself & use it directly. E.g.

from sklearn.tree import DecisionTreeClassifier
...
dtree = DecisionTreeClassifier()

Solution 4:[4]

from sklearn.tree import _tree

...this is the one you need

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BoobyTrap
Solution 2
Solution 3 Jérôme Richard
Solution 4 Nick Krsnich