0%

Decision Tree Classifier

In this lab exercise, you will learn a popular machine learning algorithm, Decision Tree. You will use this classification algorithm to build a model from historical data of patients, and their response to different medications. Then you use the trained decision tree to predict the class of a unknown patient, or to find a proper drug for a new patient.

Import the Following Libraries:

  • numpy (as np)
  • pandas
  • DecisionTreeClassifier from sklearn.tree
In [134]:
import numpy as np 
import pandas as pd
from sklearn.tree import DecisionTreeClassifier

About the dataset

Imagine that you are a medical researcher compiling data for a study. You have collected data about a set of patients, all of whom suffered from the same illness. During their course of treatment, each patient responded to one of 5 medications, Drug A, Drug B, Drug c, Drug x and y.

Part of your job is to build a model to find out which drug might be appropriate for a future patient with the same illness. The feature sets of this dataset are Age, Sex, Blood Pressure, and Cholesterol of patients, and the target is the drug that each patient responded to.

It is a sample of binary classifier, and you can use the training part of the dataset to build a decision tree, and then use it to predict the class of a unknown patient, or to prescribe it to a new patient.

Downloading the Data

To download the data, we will use !wget to download it from IBM Object Storage.
In [135]:
!wget -O drug200.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/drug200.csv
--2020-05-09 03:29:07--  https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/drug200.csv
Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.196
Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)|67.228.254.196|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 6027 (5.9K) [text/csv]
Saving to: ‘drug200.csv’

drug200.csv         100%[===================>]   5.89K  --.-KB/s    in 0s      

2020-05-09 03:29:07 (22.5 MB/s) - ‘drug200.csv’ saved [6027/6027]

now, read data using pandas dataframe:

In [136]:
my_data = pd.read_csv("drug200.csv", delimiter=",")
my_data[0:5]
Out[136]:
Age Sex BP Cholesterol Na_to_K Drug
0 23 F HIGH HIGH 25.355 drugY
1 47 M LOW HIGH 13.093 drugC
2 47 M LOW HIGH 10.114 drugC
3 28 F NORMAL HIGH 7.798 drugX
4 61 F LOW HIGH 18.043 drugY

Size of Data

In [137]:
# write your code here
print('Size', my_data.size)
my_data.shape
Size 1200
Out[137]:
(200, 6)

Pre-processing

Using my_data as the Drug.csv data read by pandas, declare the following variables:

  • X as the Feature Matrix (data of my_data)
  • y as the response vector (target)

Remove the column containing the target name since it doesn't contain numeric values.

In [138]:
X = my_data[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']]
X[0:5]
Out[138]:
Age Sex BP Cholesterol Na_to_K
0 23 F HIGH HIGH 25.355
1 47 M LOW HIGH 13.093
2 47 M LOW HIGH 10.114
3 28 F NORMAL HIGH 7.798
4 61 F LOW HIGH 18.043

As you may figure out, some features in this dataset are categorical such as Sex or BP. Unfortunately, Sklearn Decision Trees do not handle categorical variables. But still we can convert these features to numerical values. pandas.get_dummies() Convert categorical variable into dummy/indicator variables.

In [139]:
from sklearn.preprocessing import LabelEncoder
le_sex = LabelEncoder()
X.iloc[:, 1:2] = le_sex.fit_transform(X.iloc[:,1:2])

le_BP = LabelEncoder()
X.iloc[:, 2:3] = le_BP.fit_transform(X.iloc[:, 2:3])

le_chol = LabelEncoder()
X.iloc[:, 3:4] = le_chol.fit_transform(X.iloc[:, 3:4])

print(X.head(5))
   Age  Sex  BP  Cholesterol  Na_to_K
0   23    0   0            0   25.355
1   47    1   1            0   13.093
2   47    1   1            0   10.114
3   28    0   2            0    7.798
4   61    0   1            0   18.043
/home/jupyterlab/conda/envs/python/lib/python3.6/site-packages/sklearn/preprocessing/label.py:235: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
/home/jupyterlab/conda/envs/python/lib/python3.6/site-packages/pandas/core/indexing.py:966: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self.obj[item] = s

Now we can fill the target variable.

In [142]:
y = my_data.iloc[:, 5:6]
y.tail(5)
y = np.reshape(y,(-1,1))

y = pd.DataFrame(y)


y_val = LabelEncoder()
y = y_val.fit_transform(y)

y = np.reshape(y,(-1,1))

Setting up the Decision Tree

We will be using train/test split on our decision tree. Let's import train_test_split from sklearn.cross_validation.
In [143]:
from sklearn.model_selection import train_test_split

Now train_test_split will return 4 different parameters. We will name them:
X_trainset, X_testset, y_trainset, y_testset

The train_test_split will need the parameters:
X, y, test_size=0.3, and random_state=3.

The X and y are the arrays required before the split, the test_size represents the ratio of the testing dataset, and the random_state ensures that we obtain the same splits.

In [144]:
x_train , x_test, y_train , y_test = train_test_split(X, y, train_size = 0.7, test_size = 0.3 , random_state = 3)

The shape of X_trainset and y_trainset. Ensure that the dimensions match

In [145]:
# your code

print(x_train.shape,'\n', y_train.shape , '\n')

#making the y df in same 2D instead of 1D

print(y_train.ndim)
print(type(y_train))


print(type(y_train))


y_train = np.array([[y_train]])
(140, 5) 
 (140, 1) 

2
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>

Print the shape of X_testset and y_testset. Ensure that the dimensions match


Modeling

We will first create an instance of the DecisionTreeClassifier called drugTree.
Inside of the classifier, specify criterion="entropy" so we can see the information gain of each node.
In [162]:
# your code
print(x_test.shape,'\n', y_test.shape , '\n')
(60, 5) 
 (60, 1) 

In [149]:
drugTree = DecisionTreeClassifier(criterion = 'entropy', max_depth = 9)
drugTree # it shows the default parameters
Out[149]:
DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=9,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='best')

Next, we will fit the data with the training feature matrix X_trainset and training response vector y_trainset

In [154]:
drugTree.fit(X,y)
Out[154]:
DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=9,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='best')

Prediction

Let's make some predictions on the testing dataset and store it into a variable called predTree.
In [156]:
y_pred = drugTree.predict(x_test)

You can print out predTree and y_testset if you want to visually compare the prediction to the actual values.

In [167]:
print("Predictions : ",y_pred[0:5])
print("Actual Values :",y_test[0:5].T)
Predictions :  [4 3 3 3 3]
Actual Values : [[4 3 3 3 3]]

Evaluation

Next, let's import metrics from sklearn and check the accuracy of our model.
In [160]:
from sklearn import metrics
import matplotlib.pyplot as plt
print("DecisionTrees's Accuracy: ", metrics.accuracy_score(y_test, y_pred))
DecisionTrees's Accuracy:  1.0

Accuracy classification score computes subset accuracy: the set of labels predicted for a sample must exactly match the corresponding set of labels in y_true.

In multilabel classification, the function returns the subset accuracy. If the entire set of predicted labels for a sample strictly match with the true set of labels, then the subset accuracy is 1.0; otherwise it is 0.0.