CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
DanielBarnes18

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: DanielBarnes18/IBM-Data-Science-Professional-Certificate
Path: blob/main/09. Machine Learning with Python/03. Classification/02. Decision Trees.ipynb
Views: 4598
Kernel: Python 3 (ipykernel)
cognitiveclass.ai logo

Decision Trees

Objectives

After completing this lab you will be able to:

  • Develop a classification model using Decision Tree Algorithm

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

Import the Following Libraries:

  • numpy (as np)
  • pandas
  • DecisionTreeClassifier from sklearn.tree
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 features of this dataset are Age, Sex, Blood Pressure, and the Cholesterol of the patients, and the target is the drug that each patient responded to.

It is a sample of multiclass 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 an unknown patient, or to prescribe a drug to a new patient.

Now, read the data using pandas dataframe:

my_data = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/drug200.csv', delimiter=",") my_data[0:5]

Practice

What is the size of data?
# write your code here my_data.shape
(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.

X = my_data[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']].values X[0:5]
array([[23, 'F', 'HIGH', 'HIGH', 25.355], [47, 'M', 'LOW', 'HIGH', 13.093], [47, 'M', 'LOW', 'HIGH', 10.114], [28, 'F', 'NORMAL', 'HIGH', 7.798], [61, 'F', 'LOW', 'HIGH', 18.043]], dtype=object)

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

from sklearn import preprocessing le_sex = preprocessing.LabelEncoder() le_sex.fit(['F','M']) X[:,1] = le_sex.transform(X[:,1]) le_BP = preprocessing.LabelEncoder() le_BP.fit([ 'LOW', 'NORMAL', 'HIGH']) X[:,2] = le_BP.transform(X[:,2]) le_Chol = preprocessing.LabelEncoder() le_Chol.fit([ 'NORMAL', 'HIGH']) X[:,3] = le_Chol.transform(X[:,3]) X[0:5]
array([[23, 0, 0, 0, 25.355], [47, 1, 1, 0, 13.093], [47, 1, 1, 0, 10.114], [28, 0, 2, 0, 7.798], [61, 0, 1, 0, 18.043]], dtype=object)

Now we can fill the target variable.

y = my_data["Drug"] y[0:5]
0 drugY 1 drugC 2 drugC 3 drugX 4 drugY Name: Drug, dtype: object

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.
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.

X_trainset, X_testset, y_trainset, y_testset = train_test_split(X, y, test_size=0.3, random_state=3)

Practice

Print the shape of X_trainset and y_trainset. Ensure that the dimensions match.
print('Shape of X training set {}'.format(X_trainset.shape),'&',' Size of Y training set {}'.format(y_trainset.shape))
Shape of X training set (140, 5) & Size of Y training set (140,)

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

print('Shape of X training set {}'.format(X_testset.shape),'&',' Size of Y training set {}'.format(y_testset.shape))
Shape of X training set (60, 5) & Size of Y training set (60,)

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.
drugTree = DecisionTreeClassifier(criterion="entropy", max_depth = 4) drugTree # it shows the default parameters
DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='entropy', max_depth=4, 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='deprecated', random_state=None, splitter='best')

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

drugTree.fit(X_trainset,y_trainset)
DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='entropy', max_depth=4, 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='deprecated', random_state=None, splitter='best')

Prediction

Let's make some predictions on the testing dataset and store it into a variable called predTree.
predTree = drugTree.predict(X_testset)

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

print (predTree [0:5]) print (y_testset [0:5])
['drugY' 'drugX' 'drugX' 'drugX' 'drugX'] 40 drugY 51 drugX 139 drugX 197 drugX 170 drugX Name: Drug, dtype: object

Evaluation

Next, let's import metrics from sklearn and check the accuracy of our model.
from sklearn import metrics import matplotlib.pyplot as plt print("DecisionTrees's Accuracy: ", metrics.accuracy_score(y_testset, predTree))
DecisionTrees's Accuracy: 0.9833333333333333

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 matches with the true set of labels, then the subset accuracy is 1.0; otherwise it is 0.0.


Visualization

Let's visualize the tree

# Notice: You might need to uncomment and install the pydotplus and graphviz libraries if you have not installed these before !conda install -c conda-forge pydotplus -y !conda install -c conda-forge python-graphviz -y
Collecting package metadata (current_repodata.json): ...working... done Solving environment: ...working... done # All requested packages already installed. Collecting package metadata (current_repodata.json): ...working... done Solving environment: ...working... done # All requested packages already installed.
#conda install python-graphviz #!python -m pip install graphviz #!python -m pip install pydotplus
from io import StringIO import pydotplus import graphviz import matplotlib.image as mpimg from sklearn import tree %matplotlib inline
dot_data = StringIO() filename = "drugtree.png" featureNames = my_data.columns[0:5] out=tree.export_graphviz(drugTree,feature_names=featureNames, out_file=dot_data, class_names= np.unique(y_trainset), filled=True, special_characters=True,rotate=False) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(filename) img = mpimg.imread(filename) plt.figure(figsize=(100, 200)) plt.imshow(img,interpolation='nearest')
<matplotlib.image.AxesImage at 0x25c13b66408>
Image in a Jupyter notebook