2
$\begingroup$

I am learning python and trying myself out at mashine learning. I am reproducing a super simple example - based on the infamous iris dataset. Here it goes:

from sklearn import datasets
iris = datasets.load_iris()

X = iris.data
y = iris.target

from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .5)

from sklearn import tree
nordan_tree = tree.DecisionTreeClassifier()

nordan_tree.fit(X_train, y_train)

from sklearn.metrics import accuracy_score 

I get the following error message:

Traceback (most recent call last):
  File "tree3.py", line 17, in <module>
    print(accuracy_score(y_test, predictions))
NameError: name 'predictions' is not defined

I don't get it. As far as I understand, predictions is the vector containing all the predictions produced with DecisionTreeClassifier? What am I doing wrong?

$\endgroup$

2 Answers 2

2
$\begingroup$

You have not defined the variable predictions anywhere. You will need to get them from your classifier somehow. You have fit your nordan_tree on your training data, now you can use the fitted nordan_tree to generate the predictions, for example like this:

predictions = nordan_tree.predict(X_test)

Then your line of:

print(accuracy_score(y_test, predictions))

should work.

$\endgroup$
4
  • $\begingroup$ Thanks alot! That answers my questions perfectly. I thought - somehow - that sklearn's tree-clf stores the predictions in predictions by default. $\endgroup$
    – Rachel
    Aug 19, 2016 at 12:35
  • 1
    $\begingroup$ It has never seen your test set yet so it wouldn't know what to predict on, and packages generally do not put anything in global variables but return their values via the functions calls (in this case the predict function of your classifier object) $\endgroup$ Aug 19, 2016 at 12:37
  • $\begingroup$ I am a frequent stata user and python is totally new to me. Your answer helps me a great deal. Thank you! Now I only need to understand how to print the decision tree... slowly...but steady. $\endgroup$
    – Rachel
    Aug 19, 2016 at 12:48
  • 1
    $\begingroup$ The sklearn package has terrific documentation and a lot of examples, make sure to look at those! $\endgroup$ Aug 19, 2016 at 12:49
2
$\begingroup$

Use the below instructions as it was worked for me

from sklearn.metrics import accuracy_score

predictions = nordan_tree.predict(X_test)

print(accuracy_score(y_test, predictions))
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.