Decision trees are a supervised, probabilistic, machine learning classifier that are often used as decision support tools. Like any other classifier, they are capable of predicting the label of a sample, and the way they do this is by examining the probabilistic outcomes of your samples' features.
Decision trees are one of the oldest and most used machine learning algorithms, perhaps even pre-dating machine learning. They're very popular and have been around for decades. Following through with sequential cause-and-effect decisions comes very naturally.
Decision trees are a good tool to use when you want backing evidence to support a decision.
We train the UCI's wheat-seeds dataset with decision trees and see the decision boundary plots produced by it.
You can find the dataset in the above link or in this Github dataset folder.
You can refer to the related "Decision Trees" article for more details about the method.
In [1]:
import pandas as pd
In [2]:
#
# Load up the wheat dataset into dataframe 'df'
#
df = pd.read_csv("../datasets/wheat.data", index_col='id')
In [3]:
df.head()
Out[3]:
What we want to do is to predict the wheat type based on the wheat seed characteristics.
To simplify the boundary plot, we consider only two of the characteristics.
In [4]:
# we keep groove and perimeter, plus of course the target: wheat type
wheatSimpler = df.drop(columns = ['compactness', 'width', 'length', 'area', 'asymmetry'])
In [5]:
wheatSimpler.info()
In [6]:
# An easy way to show which rows have nans in them
print (wheatSimpler[pd.isnull(wheatSimpler).any(axis=1)])
In [7]:
#
# Only a few rows. Go ahead and drop any row with a nan
#
wheatSimpler.dropna(axis=0, inplace=True)
#
# INFO: In the future, you might try setting the nan values to the
# mean value of that column, groove; the mean should only be calculated for
# the specific class rather than across all classes, in this case for canadian type
In [8]:
#
# Copy the labels out of the dataframe into variable 'labels' , then remove
# them from the dataframe. Encode the labels:
# canadian:0, kama:1, and rosa:2
#
labels = wheatSimpler.wheat_type.copy() # copy “y” values out
wheatSimpler.drop(['wheat_type'], axis=1, inplace=True) # drop output column
labels = labels.map({'canadian':0, 'kama':1, 'rosa':2}) # encoding
In [9]:
from sklearn.model_selection import train_test_split
In [10]:
X_train, X_test, y_train, y_test = train_test_split(wheatSimpler, labels, test_size=0.3,
random_state=7)
In [11]:
#
# We use the SkLearn module tree
#
from sklearn import tree
In [12]:
#
# note that I force the tree depth to a maximum of two (for simplification)
#
model = tree.DecisionTreeClassifier(max_depth=2, random_state=2)
model.fit(X_train, y_train)
Out[12]:
Let's plot the tree using the sklearn.tree internal feature, which gives an idea of how the features are considered in the model
In [13]:
tree.plot_tree(model, feature_names=X_train.columns, filled=True)
Out[13]:
As you can see the tree consists of a series of splitting rules, starting at the top of the tree with a question (answer is Yes on the left and No on the right) and goes on with "branches"to finally ends in "leaves" or "terminal nodes" after several splits (in this case two, since I have limited it above using max_depth).
Decision trees are simple and very easy to interpret, you just need to look at the questions.
The first question is: "has this seed a groove less or equal than 5.576?"
This question in fact splits the predictor space in two.
Let's plot the decision boundaries to see how they work.
In [14]:
import matplotlib as mpl
import matplotlib.pyplot as plt
In [15]:
import numpy as np
In [16]:
x,y = np.meshgrid(wheatSimpler.perimeter, wheatSimpler.groove)
In [17]:
Z = model.predict(np.c_[x.ravel(), y.ravel()])
Z = Z.reshape(x.shape)
In [18]:
fig, ax = plt.subplots()
ax.scatter(wheatSimpler.perimeter, wheatSimpler.groove, c = labels)
ax.hlines(y=5.6, xmin=12, xmax=17.5, linestyle='-', label="1st question")
ax.vlines(x=13.5, ymin=3.5, ymax=5.6, linestyle='--', label="2nd question")
ax.vlines(x=14, ymin=5.6, ymax=6.9, linestyle=':', label="3rd question")
ax.legend(loc='best')
fig.suptitle("Predictor space")
ax.set_xlabel("Seed Perimeter")
ax.set_ylabel("Seed Groove");
You can see that the predictor space has been segmented in a number of simple regions, four to be precise and a wheat type is predicted according to its position in one of the regions.
Use decision trees to peruse The Mushroom Data Set, drawn from the Audubon Society Field Guide to North American Mushrooms (1981). The data set details mushrooms described in terms of many physical characteristics, such as cap size and stalk length, along with a classification of poisonous or edible.
You can find the dataset in the above UCI link or in the Dataset folder here in github.
As a standard disclaimer, if you eat a random mushroom you find, you are doing so at your own risk.
In [20]:
#
# Load up the mushroom dataset into dataframe 'X'
# Header information is on the dataset's website at the UCI ML Repo
#
colNames=['label', 'cap-shape','cap-surface','cap-color','bruises','odor',
'gill-attachment','gill-spacing','gill-size','gill-color','stalk-shape',
'stalk-root','stalk-surface-above-ring','stalk-surface-below-ring',
'stalk-color-above-ring','stalk-color-below-ring','veil-type',
'veil-color','ring-number','ring-type','spore-print-color','population',
'habitat']
X = pd.read_csv("../datasets/agaricus-lepiota.data", header=None, na_values='?',
names=colNames)
In [21]:
X.head()
Out[21]:
In [22]:
X.describe()
Out[22]:
In [23]:
#
# drop any row with a nan
#
X.dropna(axis=0, inplace=True)
print (X.shape)
In [24]:
#
# : Copy the labels out of the dset into variable 'y' then Remove
# them from X.
y = X[X.columns[0]].copy()
X.drop(X.columns[0], axis=1,inplace=True)
In [25]:
#
# Encode labels poisonous / edible
y = y.map({'p':0, 'e':1})
# Encode the rest
#
X = pd.get_dummies(X)
In [26]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=7)
In [27]:
#
# Create a DT classifier. No need to set any parameters, let;s get the ful depth
#
model = tree.DecisionTreeClassifier()
In [28]:
#
# train the classifier on the training data / labels:
#
model.fit(X_train, y_train)
Out[28]:
In [29]:
tree.plot_tree(model, feature_names=X_train.columns, filled=True)
Out[29]:
RESULT: top two features you should consider when deciding if a mushroom is eadible or not: Odor and Gill Size.
In [30]:
# score the classifier on the testing data / labels:
# Returns the mean accuracy on the given test data and labels.
score = model.score(X_test, y_test)
print ("High-Dimensionality Score: ", round((score*100), 3))