Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Michy01/3a7e0936c64f7160dc8572215d91d04a to your computer and use it in GitHub Desktop.
Save Michy01/3a7e0936c64f7160dc8572215d91d04a to your computer and use it in GitHub Desktop.
Created on Cognitive Class Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"<a href=\"https://www.bigdatauniversity.com\"><img src = \"https://ibm.box.com/shared/static/cw2c7r3o20w9zn8gkecaeyjhgw3xdgbj.png\" width = 400, align = \"center\"></a>\n",
"\n",
"# <center>Decision Trees</center>"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Import the Following Libraries:\n",
"<ul>\n",
" <li> <b>numpy (as np)</b> </li>\n",
" <li> <b>pandas</b> </li>\n",
" <li> <b>DecisionTreeClassifier</b> from <b>sklearn.tree</b> </li>\n",
"</ul>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"import numpy as np \n",
"import pandas as pd\n",
"from sklearn.tree import DecisionTreeClassifier"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"### About dataset\n",
"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. \n",
"\n",
"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. \n",
"\n",
"It is a sample of binary classifier, and you can use the training part of the dataset \n",
"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.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"### Downloading Data\n",
"To download the data, we will use !wget to download it from IBM Object Storage."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!wget -O drug200.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/drug200.csv"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"__Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"now, read data using pandas dataframe:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"my_data = pd.read_csv(\"drug200.csv\", delimiter=\",\")\n",
"my_data[0:5]"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"## Practice \n",
"What is the size of data? "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"# write your code here\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Pre-processing"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Using <b>my_data</b> as the Drug.csv data read by pandas, declare the following variables: <br>\n",
"<ul>\n",
" <li> <b> X </b> as the <b> Feature Matrix </b> (data of my_data) </li>\n",
"\n",
" \n",
" <li> <b> y </b> as the <b> response vector (target) </b> </li>\n",
"\n",
"\n",
" \n",
"</ul>"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Remove the column containing the target name since it doesn't contain numeric values."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X = my_data[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']].values\n",
"X[0:5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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()__\n",
"Convert categorical variable into dummy/indicator variables."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn import preprocessing\n",
"le_sex = preprocessing.LabelEncoder()\n",
"le_sex.fit(['F','M'])\n",
"X[:,1] = le_sex.transform(X[:,1]) \n",
"\n",
"\n",
"le_BP = preprocessing.LabelEncoder()\n",
"le_BP.fit([ 'LOW', 'NORMAL', 'HIGH'])\n",
"X[:,2] = le_BP.transform(X[:,2])\n",
"\n",
"\n",
"le_Chol = preprocessing.LabelEncoder()\n",
"le_Chol.fit([ 'NORMAL', 'HIGH'])\n",
"X[:,3] = le_Chol.transform(X[:,3]) \n",
"\n",
"X[0:5]\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can fill the target variable."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"y = my_data[\"Drug\"]\n",
"y[0:5]"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"---\n",
"## Setting up the Decision Tree\n",
"We will be using <b>train/test split</b> on our <b>decision tree</b>. Let's import <b>train_test_split</b> from <b>sklearn.cross_validation</b>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Now <b> train_test_split </b> will return 4 different parameters. We will name them:<br>\n",
"X_trainset, X_testset, y_trainset, y_testset <br> <br>\n",
"The <b> train_test_split </b> will need the parameters: <br>\n",
"X, y, test_size=0.3, and random_state=3. <br> <br>\n",
"The <b>X</b> and <b>y</b> are the arrays required before the split, the <b>test_size</b> represents the ratio of the testing dataset, and the <b>random_state</b> ensures that we obtain the same splits."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"X_trainset, X_testset, y_trainset, y_testset = train_test_split(X, y, test_size=0.3, random_state=3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"## Practice\n",
"Print the shape of X_trainset and y_trainset. Ensure that the dimensions match"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"# your code\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Print the shape of X_testset and y_testset. Ensure that the dimensions match"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"# your code\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"## Modeling\n",
"We will first create an instance of the <b>DecisionTreeClassifier</b> called <b>drugTree</b>.<br>\n",
"Inside of the classifier, specify <i> criterion=\"entropy\" </i> so we can see the information gain of each node."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"drugTree = DecisionTreeClassifier(criterion=\"entropy\", max_depth = 4)\n",
"drugTree # it shows the default parameters"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Next, we will fit the data with the training feature matrix <b> X_trainset </b> and training response vector <b> y_trainset </b>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"drugTree.fit(X_trainset,y_trainset)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"## Prediction\n",
"Let's make some <b>predictions</b> on the testing dataset and store it into a variable called <b>predTree</b>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"predTree = drugTree.predict(X_testset)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"You can print out <b>predTree</b> and <b>y_testset</b> if you want to visually compare the prediction to the actual values."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
},
"scrolled": true
},
"outputs": [],
"source": [
"print (predTree [0:5])\n",
"print (y_testset [0:5])\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"## Evaluation\n",
"Next, let's import __metrics__ from sklearn and check the accuracy of our model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"from sklearn import metrics\n",
"import matplotlib.pyplot as plt\n",
"print(\"DecisionTrees's Accuracy: \", metrics.accuracy_score(y_testset, predTree))"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"__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. \n",
"\n",
"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.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"## Practice \n",
"Can you calculate the accuracy score without sklearn ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"# your code here\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Visualization\n",
"Lets visualize the tree"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"from sklearn.externals.six import StringIO\n",
"import pydotplus\n",
"import matplotlib.image as mpimg\n",
"from sklearn import tree\n",
"%matplotlib inline "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"jupyter": {
"outputs_hidden": true
},
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"dot_data = StringIO()\n",
"filename = \"drugtree.png\"\n",
"featureNames = my_data.columns[0:5]\n",
"targetNames = my_data[\"Drug\"].unique().tolist()\n",
"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) \n",
"graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \n",
"graph.write_png(filename)\n",
"img = mpimg.imread(filename)\n",
"plt.figure(figsize=(100, 200))\n",
"plt.imshow(img,interpolation='nearest')"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"## Want to learn more?\n",
"\n",
"IBM SPSS Modeler is a comprehensive analytics platform that has many machine learning algorithms. It has been designed to bring predictive intelligence to decisions made by individuals, by groups, by systems – by your enterprise as a whole. A free trial is available through this course, available here: [SPSS Modeler](http://cocl.us/ML0101EN-SPSSModeler).\n",
"\n",
"Also, you can use Watson Studio to run these notebooks faster with bigger datasets. Watson Studio is IBM's leading cloud solution for data scientists, built by data scientists. With Jupyter notebooks, RStudio, Apache Spark and popular libraries pre-packaged in the cloud, Watson Studio enables data scientists to collaborate on their projects without having to install anything. Join the fast-growing community of Watson Studio users today with a free account at [Watson Studio](https://cocl.us/ML0101EN_DSX)\n",
"\n",
"### Thanks for completing this lesson!\n",
"\n",
"Notebook created by: <a href = \"https://ca.linkedin.com/in/saeedaghabozorgi\">Saeed Aghabozorgi</a>\n",
"\n",
"<hr>\n",
"Copyright &copy; 2018 [Cognitive Class](https://cocl.us/DX0108EN_CC). This notebook and its source code are released under the terms of the [MIT License](https://bigdatauniversity.com/mit-license/).​"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python",
"language": "python",
"name": "conda-env-python-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.7"
},
"widgets": {
"state": {},
"version": "1.1.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment