<jupyter_start><jupyter_text>Decision Trees 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 respond 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<jupyter_code>import numpy as np 
import pandas as pd
from sklearn.tree import DecisionTreeClassifier<jupyter_output><empty_output><jupyter_text>About datasetImagine 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 Data **DataSet:** [Data Set]("https://github.com/free-to-learn/Machine-Learning-DataSet/blob/master/Data/drug200.csv") now, read data using pandas dataframe:<jupyter_code>path = "https://raw.githubusercontent.com/reddyprasade/Machine-Learning-Problems-DataSets/master/Classification/drug200.csv"
my_data = pd.read_csv(path, delimiter=",")
my_data[0:5]<jupyter_output><empty_output><jupyter_text>Practice What is the size of data?<jupyter_code># write your code here
my_data.size
my_data.shape<jupyter_output><empty_output><jupyter_text>Pre-processing Using my_data as the Drug.csv data read by pandas, declare the following variables:     X as theFeature Matrix(data of my_data)y as theresponse vector (target)    Remove the column containing the target name since it doesn't contain numeric values.<jupyter_code>X = my_data[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']].values
X[0:5]
X.shape<jupyter_output><empty_output><jupyter_text>As you may figure out, some featurs in this dataset are catergorical 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.<jupyter_code>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]<jupyter_output><empty_output><jupyter_text>Now we can fill the target variable.<jupyter_code>y = my_data["Drug"]
y[0:5]<jupyter_output><empty_output><jupyter_text>--- Setting up the Decision TreeWe will be using train/test split on our decision tree. Let's import train_test_split from sklearn.cross_validation.<jupyter_code>from sklearn.model_selection import train_test_split<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>X_trainset, X_testset, y_trainset, y_testset = train_test_split(X, y, test_size=0.3, random_state=3)<jupyter_output><empty_output><jupyter_text>PracticePrint the shape of X_trainset and y_trainset. Ensure that the dimensions match<jupyter_code># your code

X_trainset.shape
y_trainset.shape<jupyter_output><empty_output><jupyter_text>Print the shape of X_testset and y_testset. Ensure that the dimensions match<jupyter_code># your code
X_testset.shape

y_testset.shape<jupyter_output><empty_output><jupyter_text>ModelingWe 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.<jupyter_code>drugTree = DecisionTreeClassifier(criterion="entropy", max_depth = 4)
drugTree # it shows the default parameters<jupyter_output><empty_output><jupyter_text>Next, we will fit the data with the training feature matrix  X_trainset  and training  response vector  y_trainset<jupyter_code>drugTree.fit(X_trainset,y_trainset)<jupyter_output><empty_output><jupyter_text>PredictionLet's make some predictions on the testing dataset and store it into a variable called predTree.<jupyter_code>predTree = drugTree.predict(X_testset)
predTree<jupyter_output><empty_output><jupyter_text>You can print out predTree and y_testset if you want to visually compare the prediction to the actual values.<jupyter_code>pd.DataFrame({"Actual_Data":y_testset,
             "New_predict":predTree})
drugTree.score(X_trainset,y_trainset)
drugTree.score(X_testset,y_testset)<jupyter_output><empty_output><jupyter_text>EvaluationNext, let's import __metrics__ from sklearn and check the accuracy of our model.<jupyter_code>from sklearn import metrics
import matplotlib.pyplot as plt
print("DecisionTrees's Accuracy: ", metrics.accuracy_score(y_testset, predTree))<jupyter_output>DecisionTrees's Accuracy:  0.9833333333333333<jupyter_text>__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.  Practice Can you calculate the accuracy score without sklearn ?<jupyter_code># your code here

Acc = ((predTree==y_testset)==True).count()
Acc
from sklearn.metrics import confusion_matrix,classification_report
Data = confusion_matrix(y_testset,predTree)
Data
import seaborn as sns
sns.heatmap(Data,annot=True)
print(classification_report(y_testset,predTree))
tree.plot_tree(drugTree)<jupyter_output><empty_output><jupyter_text>VisualizationLets visualize the tree<jupyter_code>!pip install graphviz
import os
os.environ["PATH"] += os.pathsep + 'C:/Users/reddy/AppData/Local/Programs/Python/Python36/Lib/site-packages/graphviz'
import graphviz 
dot_data = tree.export_graphviz(drugTree, out_file=None) 
graph = graphviz.Source(dot_data) 
graph.render("Tree")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07954220314735336, 'fraction_numerical': 0.007439198855507869, 'mean_word_length': 6.665570175438597, 'pattern_counts': {'":': 2, '<': 68, '<?xml version=': 0, '>': 68, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '152923', 'license': 'MIT', 'n_tokens_mistral': 2196, 'n_tokens_neox': 2118, 'n_words': 707, 'path': 'Supervised Learning/Classifications/ML0101EN7-Classification-Decision-Trees-drug-py-v1.ipynb', 'repo_name': 'free-to-learn/Machine-Learning-Concepts', 'size': '6990'}