Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JoseRFJuniorLLMs/d36a9829a10bbe9b9801091a78af634f to your computer and use it in GitHub Desktop.
Save JoseRFJuniorLLMs/d36a9829a10bbe9b9801091a78af634f 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",
"<h1><center>Decision Trees</center></h1>"
]
},
{
"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 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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1>Table of contents</h1>\n",
"\n",
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
" <ol>\n",
" <li><a href=\"#about_dataset\">About the dataset</a></li>\n",
" <li><a href=\"#downloading_data\">Downloading the Data</a></li>\n",
" <li><a href=\"#pre-processing\">Pre-processing</a></li>\n",
" <li><a href=\"#setting_up_tree\">Setting up the Decision Tree</a></li>\n",
" <li><a href=\"#modeling\">Modeling</a></li>\n",
" <li><a href=\"#prediction\">Prediction</a></li>\n",
" <li><a href=\"#evaluation\">Evaluation</a></li>\n",
" <li><a href=\"#visualization\">Visualization</a></li>\n",
" </ol>\n",
"</div>\n",
"<br>\n",
"<hr>"
]
},
{
"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,
"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": [
"<div id=\"about_dataset\">\n",
" <h2>About the dataset</h2>\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",
" <br>\n",
" <br>\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",
" <br>\n",
" <br>\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",
"</div>\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"<div id=\"downloading_data\"> \n",
" <h2>Downloading the Data</h2>\n",
" To download the data, we will use !wget to download it from IBM Object Storage.\n",
"</div>"
]
},
{
"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,
"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": [
"<div id=\"practice\"> \n",
" <h3>Practice</h3> \n",
" What is the size of data? \n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"# write your code here\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div href=\"pre-processing\">\n",
" <h2>Pre-processing</h2>\n",
"</div>"
]
},
{
"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",
"\n",
"<ul>\n",
" <li> <b> X </b> as the <b> Feature Matrix </b> (data of my_data) </li>\n",
" <li> <b> y </b> as the <b> response vector (target) </b> </li>\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 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()__\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,
"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": [
"<hr>\n",
"\n",
"<div id=\"setting_up_tree\">\n",
" <h2>Setting up the Decision Tree</h2>\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>.\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": 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,
"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": [
"<h3>Practice</h3>\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,
"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,
"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": [
"<hr>\n",
"\n",
"<div id=\"modeling\">\n",
" <h2>Modeling</h2>\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.\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": 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,
"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": [
"<hr>\n",
"\n",
"<div id=\"prediction\">\n",
" <h2>Prediction</h2>\n",
" Let's make some <b>predictions</b> on the testing dataset and store it into a variable called <b>predTree</b>.\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": 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,
"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": [
"<hr>\n",
"\n",
"<div id=\"evaluation\">\n",
" <h2>Evaluation</h2>\n",
" Next, let's import <b>metrics</b> from sklearn and check the accuracy of our model.\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": 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,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"# your code here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"\n",
"<div id=\"visualization\">\n",
" <h2>Visualization</h2>\n",
" Lets visualize the tree\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Notice: You might need to uncomment and install the pydotplus and graphviz libraries if you have not installed these before\n",
"# !conda install -c conda-forge pydotplus -y\n",
"# !conda install -c conda-forge python-graphviz -y"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": 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,
"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": [
"<h2>Want to learn more?</h2>\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: <a href=\"http://cocl.us/ML0101EN-SPSSModeler\">SPSS Modeler</a>\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 <a href=\"https://cocl.us/ML0101EN_DSX\">Watson Studio</a>\n",
"\n",
"<h3>Thanks for completing this lesson!</h3>\n",
"\n",
"<h4>Author: <a href=\"https://ca.linkedin.com/in/saeedaghabozorgi\">Saeed Aghabozorgi</a></h4>\n",
"<p><a href=\"https://ca.linkedin.com/in/saeedaghabozorgi\">Saeed Aghabozorgi</a>, PhD is a Data Scientist in IBM with a track record of developing enterprise level applications that substantially increases clients’ ability to turn data into actionable knowledge. He is a researcher in data mining field and expert in developing advanced analytic methods like machine learning and statistical modelling on large datasets.</p>\n",
"\n",
"<hr>\n",
"\n",
"<p>Copyright &copy; 2018 <a href=\"https://cocl.us/DX0108EN_CC\">Cognitive Class</a>. This notebook and its source code are released under the terms of the <a href=\"https://bigdatauniversity.com/mit-license/\">MIT License</a>.</p>"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"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.6"
},
"widgets": {
"state": {},
"version": "1.1.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment