Upload files to "MODUL 3_CLASSIFICATION"

This commit is contained in:
202310715145 SUMIH 2025-11-20 10:49:53 +07:00
parent 594c9f8abe
commit b524dd4e74
4 changed files with 5311 additions and 0 deletions

View File

@ -0,0 +1,813 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<p style=\"text-align:center\">\n",
" <a href=\"https://skills.network/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkML0101ENSkillsNetwork20718538-2022-01-01\" target=\"_blank\">\n",
" <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/assets/logos/SN_web_lightmode.png\" width=\"200\" alt=\"Skills Network Logo\">\n",
" </a>\n",
"</p>\n",
"\n",
"# Decision Trees\n",
"\n",
"Estimated time needed: **15** minutes\n",
"\n",
"## Objectives\n",
"\n",
"After completing this lab you will be able to:\n",
"\n",
"* Develop a classification model using Decision Tree Algorithm\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n"
]
},
{
"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=\"https://#about_dataset\">About the dataset</a></li>\n",
" <li><a href=\"https://#downloading_data\">Downloading the Data</a></li>\n",
" <li><a href=\"https://#pre-processing\">Pre-processing</a></li>\n",
" <li><a href=\"https://#setting_up_tree\">Setting up the Decision Tree</a></li>\n",
" <li><a href=\"https://#modeling\">Modeling</a></li>\n",
" <li><a href=\"https://#prediction\">Prediction</a></li>\n",
" <li><a href=\"https://#evaluation\">Evaluation</a></li>\n",
" <li><a href=\"https://#visualization\">Visualization</a></li>\n",
" </ol>\n",
"</div>\n",
"<br>\n",
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Import the Following Libraries:\n",
"\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>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"if you uisng you own version comment out\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Surpress warnings:\n",
"def warn(*args, **kwargs):\n",
" pass\n",
"import warnings\n",
"warnings.warn = warn"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import sys\n",
"import numpy as np \n",
"import pandas as pd\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"import sklearn.tree as tree"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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 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.\n",
" <br>\n",
" <br>\n",
" It is a sample of multiclass 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 an unknown patient, or to prescribe a drug to a new patient.\n",
"</div>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div id=\"downloading_data\"> \n",
" <h2>Downloading the Data</h2>\n",
" To download the data, we will use pandas library to read itdirectly into a dataframe from IBM Object Storage.\n",
"</div>\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Age</th>\n",
" <th>Sex</th>\n",
" <th>BP</th>\n",
" <th>Cholesterol</th>\n",
" <th>Na_to_K</th>\n",
" <th>Drug</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>23</td>\n",
" <td>F</td>\n",
" <td>HIGH</td>\n",
" <td>HIGH</td>\n",
" <td>25.355</td>\n",
" <td>drugY</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>47</td>\n",
" <td>M</td>\n",
" <td>LOW</td>\n",
" <td>HIGH</td>\n",
" <td>13.093</td>\n",
" <td>drugC</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>47</td>\n",
" <td>M</td>\n",
" <td>LOW</td>\n",
" <td>HIGH</td>\n",
" <td>10.114</td>\n",
" <td>drugC</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>28</td>\n",
" <td>F</td>\n",
" <td>NORMAL</td>\n",
" <td>HIGH</td>\n",
" <td>7.798</td>\n",
" <td>drugX</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>61</td>\n",
" <td>F</td>\n",
" <td>LOW</td>\n",
" <td>HIGH</td>\n",
" <td>18.043</td>\n",
" <td>drugY</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Age Sex BP Cholesterol Na_to_K Drug\n",
"0 23 F HIGH HIGH 25.355 drugY\n",
"1 47 M LOW HIGH 13.093 drugC\n",
"2 47 M LOW HIGH 10.114 drugC\n",
"3 28 F NORMAL HIGH 7.798 drugX\n",
"4 61 F LOW HIGH 18.043 drugY"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"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=\",\")\n",
"my_data.head()"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"<div id=\"practice\"> \n",
" <h3>Practice</h3> \n",
" What is the size of data? \n",
"</div>\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"(200, 6)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# write your code here\n",
"my_data.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"my_data.shape\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div href=\"pre-processing\">\n",
" <h2>Pre-processing</h2>\n",
"</div>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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 </b> (target) </li>\n",
"</ul>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Remove the column containing the target name since it doesn't contain numeric values.\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"array([[23, 'F', 'HIGH', 'HIGH', 25.355],\n",
" [47, 'M', 'LOW', 'HIGH', 13.093],\n",
" [47, 'M', 'LOW', 'HIGH', 10.114],\n",
" [28, 'F', 'NORMAL', 'HIGH', 7.798],\n",
" [61, 'F', 'LOW', 'HIGH', 18.043]], dtype=object)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = my_data[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']].values\n",
"X[0:5]\n"
]
},
{
"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 does not handle categorical variables. We can still convert these features to numerical values using the **LabelEncoder() method**\n",
"to convert the categorical variable into dummy/indicator variables.\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"array([[23, 0, 0, 0, 25.355],\n",
" [47, 1, 1, 0, 13.093],\n",
" [47, 1, 1, 0, 10.114],\n",
" [28, 0, 2, 0, 7.798],\n",
" [61, 0, 1, 0, 18.043]], dtype=object)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"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.\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"0 drugY\n",
"1 drugC\n",
"2 drugC\n",
"3 drugX\n",
"4 drugY\n",
"Name: Drug, dtype: object"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = my_data[\"Drug\"]\n",
"y[0:5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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>\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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.\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"tags": []
},
"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": {},
"source": [
"<h3>Practice</h3>\n",
"Print the shape of X_trainset and y_trainset. Ensure that the dimensions match.\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Shape of X training set (140, 5) & Size of Y training set (140,)\n"
]
}
],
"source": [
"# your code\n",
"print('Shape of X training set {}'.format(X_trainset.shape),'&', 'Size of Y training set {}'.format(y_trainset.shape))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"print('Shape of X training set {}'.format(X_trainset.shape),'&',' Size of Y training set {}'.format(y_trainset.shape))\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Print the shape of X_testset and y_testset. Ensure that the dimensions match.\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Shape of X testing set (60, 5) & Size of Y testing set (60,)\n"
]
}
],
"source": [
"# your code\n",
"\n",
"print('Shape of X testing set {}'.format(X_testset.shape),'&', 'Size of Y testing set {}'.format(y_testset.shape))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"print('Shape of X test set {}'.format(X_testset.shape),'&','Size of y test set {}'.format(y_testset.shape))\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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>\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"DecisionTreeClassifier(criterion='entropy', max_depth=4)"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"drugTree = DecisionTreeClassifier(criterion=\"entropy\", max_depth = 4)\n",
"drugTree # it shows the default parameters"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we will fit the data with the training feature matrix <b> X_trainset </b> and training response vector <b> y_trainset </b>\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"DecisionTreeClassifier(criterion='entropy', max_depth=4)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"drugTree.fit(X_trainset,y_trainset)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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>\n"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"predTree = drugTree.predict(X_testset)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can print out <b>predTree</b> and <b>y_testset</b> if you want to visually compare the predictions to the actual values.\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['drugY' 'drugX' 'drugX' 'drugX' 'drugX']\n",
"40 drugY\n",
"51 drugX\n",
"139 drugX\n",
"197 drugX\n",
"170 drugX\n",
"Name: Drug, dtype: object\n"
]
}
],
"source": [
"print (predTree [0:5])\n",
"print (y_testset [0:5])\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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>\n"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"DecisionTrees's Accuracy: 0.9833333333333333\n"
]
}
],
"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": {},
"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 matches with the true set of labels, then the subset accuracy is 1.0; otherwise it is 0.0.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"\n",
"<div id=\"visualization\">\n",
" <h2>Visualization</h2>\n",
"\n",
"Let's visualize the tree\n",
"\n",
"</div>\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"tags": []
},
"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\n",
"\n",
"#After executing the code below, a file named 'tree.png' would be generated which contains the decision tree image."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from sklearn.tree import export_graphviz\n",
"export_graphviz(drugTree, out_file='tree.dot', filled=True, feature_names=['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K'])\n",
"!dot -Tpng tree.dot -o tree.png\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Thank you for completing this lab!\n",
"\n",
"## Author\n",
"\n",
"Saeed Aghabozorgi\n",
"\n",
"### Other Contributors\n",
"\n",
"<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkML0101ENSkillsNetwork20718538-2022-01-01\" target=\"_blank\">Joseph Santarcangelo</a>\n",
"\n",
"<a href=\"https://www.linkedin.com/in/richard-ye/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkML0101ENSkillsNetwork20718538-2022-01-01\" target=\"_blank\">Richard Ye</a>\n",
"\n",
"## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n",
" \n",
"<!--\n",
"## Change Log\n",
"\n",
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n",
"| ----------------- | ------- | ---------- | ------------------------------------------------ |\n",
"| 2022-05-24 | 2.3 | Richard Ye | Fixed ability to work in JupyterLite and locally |\n",
"| 2020-11-20 | 2.2 | Lakshmi | Changed import statement of StringIO |\n",
"| 2020-11-03 | 2.1 | Lakshmi | Changed URL of the csv |\n",
"| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n",
"| | | | |\n",
"| | | | |\n",
"--!>\n",
"\n"
]
}
],
"metadata": {
"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.7.12"
},
"prev_pub_hash": "1228bf81fd1be0f6e7dda62256f4ffcb19b064217fc51f2e012abde9b84c2b0d"
},
"nbformat": 4,
"nbformat_minor": 4
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long