From f318fb954fa39e7ccad33861f368196f13aeb821 Mon Sep 17 00:00:00 2001 From: 202310715009 DWI PUTRI SETIAWAN <202310715009@mhs.ubharajaya.ac.id> Date: Wed, 19 Nov 2025 13:20:23 +0700 Subject: [PATCH] Upload files to "Classification" --- ...ri Setiawan-Clas-Decision-Trees-drug.ipynb | 771 ++++++++++++++++++ ...wan-Clas-K-Nearest-neighbors-CustCat.ipynb | 1 + 2 files changed, 772 insertions(+) create mode 100644 Classification/Dwi Putri Setiawan-Clas-Decision-Trees-drug.ipynb create mode 100644 Classification/Dwi Putri Setiawan-Clas-K-Nearest-neighbors-CustCat.ipynb diff --git a/Classification/Dwi Putri Setiawan-Clas-Decision-Trees-drug.ipynb b/Classification/Dwi Putri Setiawan-Clas-Decision-Trees-drug.ipynb new file mode 100644 index 0000000..9c11cbd --- /dev/null +++ b/Classification/Dwi Putri Setiawan-Clas-Decision-Trees-drug.ipynb @@ -0,0 +1,771 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

\n", + " \n", + " \"Skills\n", + " \n", + "

\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": [ + "

Table of contents

\n", + "\n", + "
\n", + "
    \n", + "
  1. About the dataset
  2. \n", + "
  3. Downloading the Data
  4. \n", + "
  5. Pre-processing
  6. \n", + "
  7. Setting up the Decision Tree
  8. \n", + "
  9. Modeling
  10. \n", + "
  11. Prediction
  12. \n", + "
  13. Evaluation
  14. \n", + "
  15. Visualization
  16. \n", + "
\n", + "
\n", + "
\n", + "
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Import the Following Libraries:\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "if you uisng you own version comment out\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "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": {}, + "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": [ + "
\n", + "

About the 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", + "
\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", + "
\n", + "
\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", + "
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "

Downloading the Data

\n", + " To download the data, we will use pandas library to read itdirectly into a dataframe from IBM Object Storage.\n", + "
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
AgeSexBPCholesterolNa_to_KDrug
023FHIGHHIGH25.355drugY
147MLOWHIGH13.093drugC
247MLOWHIGH10.114drugC
328FNORMALHIGH7.798drugX
461FLOWHIGH18.043drugY
\n", + "
" + ], + "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": {}, + "source": [ + "
\n", + "

Practice

\n", + " What is the size of data? \n", + "
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(200, 6)" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_data.shape" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
Click here for the solution\n", + "\n", + "```python\n", + "my_data.shape\n", + "\n", + "```\n", + "\n", + "
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "

Pre-processing

\n", + "
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using my_data as the Drug.csv data read by pandas, declare the following variables:
\n", + "\n", + "\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": {}, + "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": {}, + "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": {}, + "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": [ + "
\n", + "\n", + "
\n", + "

Setting up the Decision Tree

\n", + " We will be using train/test split on our decision tree. Let's import train_test_split from sklearn.cross_validation.\n", + "
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now train_test_split will return 4 different parameters. We will name them:
\n", + "X_trainset, X_testset, y_trainset, y_testset

\n", + "The train_test_split will need the parameters:
\n", + "X, y, test_size=0.3, and random_state=3.

\n", + "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.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "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": [ + "

Practice

\n", + "Print the shape of X_trainset and y_trainset. Ensure that the dimensions match.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Shape of X training set (140, 5) & Size of Y training set (140,)\n" + ] + } + ], + "source": [ + "print('Shape of X training set {}'.format(X_trainset.shape),'&',' Size of Y training set {}'.format(y_trainset.shape))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
Click here for the solution\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", + "
\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": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Shape of X test set (60, 5) & Size of y test set (60,)\n" + ] + } + ], + "source": [ + "print('Shape of X test set {}'.format(X_testset.shape),'&','Size of y test set {}'.format(y_testset.shape))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
Click here for the solution\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", + "
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "
\n", + "

Modeling

\n", + " We will first create an instance of the DecisionTreeClassifier called drugTree.
\n", + " Inside of the classifier, specify criterion=\"entropy\" so we can see the information gain of each node.\n", + "
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "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 X_trainset and training response vector y_trainset \n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "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": [ + "
\n", + "\n", + "
\n", + "

Prediction

\n", + " Let's make some predictions on the testing dataset and store it into a variable called predTree.\n", + "
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "predTree = drugTree.predict(X_testset)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can print out predTree and y_testset if you want to visually compare the predictions to the actual values.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "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": [ + "
\n", + "\n", + "
\n", + "

Evaluation

\n", + " Next, let's import metrics from sklearn and check the accuracy of our model.\n", + "
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "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": [ + "
\n", + "\n", + "
\n", + "

Visualization

\n", + "\n", + "Let's visualize the tree\n", + "\n", + "
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "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\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": {}, + "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", + "Joseph Santarcangelo\n", + "\n", + "Richard Ye\n", + "\n", + "##

© IBM Corporation 2020. All rights reserved.

\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 +} diff --git a/Classification/Dwi Putri Setiawan-Clas-K-Nearest-neighbors-CustCat.ipynb b/Classification/Dwi Putri Setiawan-Clas-K-Nearest-neighbors-CustCat.ipynb new file mode 100644 index 0000000..c2370bc --- /dev/null +++ b/Classification/Dwi Putri Setiawan-Clas-K-Nearest-neighbors-CustCat.ipynb @@ -0,0 +1 @@ +{"cells":[{"cell_type":"markdown","id":"50dd3ab8-d3c7-414e-8a04-de256458110f","metadata":{},"outputs":[],"source":["

\n"," \n"," \"Skills\n"," \n","

\n","\n","# K-Nearest Neighbors\n","\n","Estimated time needed: **25** minutes\n","\n","## Objectives\n","\n","After completing this lab you will be able to:\n","\n","* Use K Nearest neighbors to classify data\n"]},{"cell_type":"markdown","id":"8cc8579e-5bea-43f2-a4b6-091a67e0d4f8","metadata":{},"outputs":[],"source":["In this Lab you will load a customer dataset, fit the data, and use K-Nearest Neighbors to predict a data point. But what is **K-Nearest Neighbors**?\n"]},{"cell_type":"markdown","id":"6e1fbd4b-04d1-4553-b980-e310c4b94956","metadata":{},"outputs":[],"source":["**K-Nearest Neighbors** is a supervised learning algorithm. Where the data is 'trained' with data points corresponding to their classification. To predict the class of a given data point, it takes into account the classes of the 'K' nearest data points and chooses the class in which the majority of the 'K' nearest data points belong to as the predicted class.\n"]},{"cell_type":"markdown","id":"67ecd5e6-ddf8-4194-a29b-554adc05887d","metadata":{},"outputs":[],"source":["### Here's an visualization of the K-Nearest Neighbors algorithm.\n","\n","\n"]},{"cell_type":"markdown","id":"671e055a-2597-4418-b072-5d301c417f71","metadata":{},"outputs":[],"source":["In this case, we have data points of Class A and B. We want to predict what the star (test data point) is. If we consider a k value of 3 (3 nearest data points), we will obtain a prediction of Class B. Yet if we consider a k value of 6, we will obtain a prediction of Class A.\n"]},{"cell_type":"markdown","id":"16ca7ce0-b90d-433d-8267-16889daab00c","metadata":{},"outputs":[],"source":["In this sense, it is important to consider the value of k. Hopefully from this diagram, you should get a sense of what the K-Nearest Neighbors algorithm is. It considers the 'K' Nearest Neighbors (data points) when it predicts the classification of the test point.\n"]},{"cell_type":"markdown","id":"13e2fc62-a7dc-4055-b733-47566e10d07a","metadata":{},"outputs":[],"source":["

Table of contents

\n","\n","
\n","
    \n","
  1. About the dataset
  2. \n","
  3. Data Visualization and Analysis
  4. \n","
  5. Classification
  6. \n","
\n","
\n","
\n","
\n"]},{"cell_type":"code","id":"6a35418d-65b5-47c8-aeb6-98b4eaea40c2","metadata":{},"outputs":[],"source":["!pip install scikit-learn==0.23.1"]},{"cell_type":"markdown","id":"70821d8d-1897-4787-9204-3a3b5677b655","metadata":{},"outputs":[],"source":["Let's load required libraries\n"]},{"cell_type":"code","id":"5a5e101e-84be-4eff-b36e-93614207e901","metadata":{},"outputs":[],"source":["import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\n%matplotlib inline"]},{"cell_type":"markdown","id":"48151937-c957-46f3-a673-feb7aec7e433","metadata":{},"outputs":[],"source":["
\n","

About the dataset

\n","
\n"]},{"cell_type":"markdown","id":"76b88915-054d-4846-91ec-cec8770330a8","metadata":{},"outputs":[],"source":["Imagine a telecommunications provider has segmented its customer base by service usage patterns, categorizing the customers into four groups. If demographic data can be used to predict group membership, the company can customize offers for individual prospective customers. It is a classification problem. That is, given the dataset, with predefined labels, we need to build a model to be used to predict class of a new or unknown case.\n","\n","The example focuses on using demographic data, such as region, age, and marital, to predict usage patterns.\n","\n","The target field, called **custcat**, has four possible values that correspond to the four customer groups, as follows:\n","1- Basic Service\n","2- E-Service\n","3- Plus Service\n","4- Total Service\n","\n","Our objective is to build a classifier, to predict the class of unknown cases. We will use a specific type of classification called K nearest neighbour.\n"]},{"cell_type":"markdown","id":"99e40fa9-2705-48f9-919c-d51d3afdac37","metadata":{},"outputs":[],"source":["### Load Data \n"]},{"cell_type":"markdown","id":"f29b0faa-a744-4321-baa1-a78b5ccc6e35","metadata":{},"outputs":[],"source":["Let's read the data using pandas library and print the first five rows.\n"]},{"cell_type":"code","id":"26617481-6a16-4386-b3ae-8891a61c266f","metadata":{},"outputs":[],"source":["df = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/teleCust1000t.csv')\ndf.head()"]},{"cell_type":"markdown","id":"49bb317b-18a3-4452-b4d8-98991b0cafb4","metadata":{},"outputs":[],"source":["
\n","

Data Visualization and Analysis

\n","
\n"]},{"cell_type":"markdown","id":"a35c0e08-c6c8-4aea-9077-c64e0912d510","metadata":{},"outputs":[],"source":["#### Let’s see how many of each class is in our data set\n"]},{"cell_type":"code","id":"35663d40-5703-42dd-bc0b-a1dd77033cfe","metadata":{},"outputs":[],"source":["df['custcat'].value_counts()"]},{"cell_type":"markdown","id":"b6759022-a615-459d-ac02-69f118958582","metadata":{},"outputs":[],"source":["#### 281 Plus Service, 266 Basic-service, 236 Total Service, and 217 E-Service customers\n"]},{"cell_type":"markdown","id":"0d7876be-b6b5-4fe4-a1a6-6ee4897ec921","metadata":{},"outputs":[],"source":["You can easily explore your data using visualization techniques:\n"]},{"cell_type":"code","id":"b07f3c50-d4eb-4aa9-8f5a-1e3b89420d6c","metadata":{},"outputs":[],"source":["df.hist(column='income', bins=50)"]},{"cell_type":"markdown","id":"de791018-974b-4be9-a82a-849db96ae681","metadata":{},"outputs":[],"source":["### Feature set\n"]},{"cell_type":"markdown","id":"ed045716-eb24-41c1-a468-d30827e3ee44","metadata":{},"outputs":[],"source":["Let's define feature sets, X:\n"]},{"cell_type":"code","id":"c5f2c3e9-e45b-4432-a8c3-e8674389ab1b","metadata":{},"outputs":[],"source":["df.columns"]},{"cell_type":"markdown","id":"95ca5f4f-4209-4026-b8f8-5020ef3163aa","metadata":{},"outputs":[],"source":["To use scikit-learn library, we have to convert the Pandas data frame to a Numpy array:\n"]},{"cell_type":"code","id":"1769f574-c9f5-4dd2-8146-350fdb9185a6","metadata":{},"outputs":[],"source":["X = df[['region', 'tenure','age', 'marital', 'address', 'income', 'ed', 'employ','retire', 'gender', 'reside']] .values #.astype(float)\nX[0:5]\n"]},{"cell_type":"markdown","id":"f4376d1a-e8f1-4cdf-a7d7-f3d218565172","metadata":{},"outputs":[],"source":["What are our labels?\n"]},{"cell_type":"code","id":"07da778e-e7f1-4233-8af6-59a1bbeac5f5","metadata":{},"outputs":[],"source":["y = df['custcat'].values\ny[0:5]"]},{"cell_type":"markdown","id":"7e868c7f-fd5f-44f5-a131-13a64cff631c","metadata":{},"outputs":[],"source":["## Normalize Data\n"]},{"cell_type":"markdown","id":"167e0e90-8eb1-4b40-a42e-8a2bbce198a6","metadata":{},"outputs":[],"source":["Data Standardization gives the data zero mean and unit variance, it is good practice, especially for algorithms such as KNN which is based on the distance of data points:\n"]},{"cell_type":"code","id":"d30b71b9-b3ce-4e4f-a375-420bad62d8c6","metadata":{},"outputs":[],"source":["X = preprocessing.StandardScaler().fit(X).transform(X.astype(float))\nX[0:5]"]},{"cell_type":"markdown","id":"29a38e12-bd26-48db-9511-97c10ef1a139","metadata":{},"outputs":[],"source":["### Train Test Split\n","\n","Out of Sample Accuracy is the percentage of correct predictions that the model makes on data that the model has NOT been trained on. Doing a train and test on the same dataset will most likely have low out-of-sample accuracy, due to the likelihood of our model overfitting.\n","\n","It is important that our models have a high, out-of-sample accuracy, because the purpose of any model, of course, is to make correct predictions on unknown data. So how can we improve out-of-sample accuracy? One way is to use an evaluation approach called Train/Test Split.\n","Train/Test Split involves splitting the dataset into training and testing sets respectively, which are mutually exclusive. After which, you train with the training set and test with the testing set.\n","\n","This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset is not part of the dataset that has been used to train the model. It is more realistic for the real world problems.\n"]},{"cell_type":"code","id":"a7db8ebb-7510-4a96-a432-8f05c8ac3274","metadata":{},"outputs":[],"source":["from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4)\nprint ('Train set:', X_train.shape, y_train.shape)\nprint ('Test set:', X_test.shape, y_test.shape)"]},{"cell_type":"markdown","id":"4172870e-bd3b-4932-92d5-b59b0572f663","metadata":{},"outputs":[],"source":["
\n","

Classification

\n","
\n"]},{"cell_type":"markdown","id":"fbd3a77c-f5c1-4cf2-a92f-93d98630d9f3","metadata":{},"outputs":[],"source":["

K nearest neighbor (KNN)

\n"]},{"cell_type":"markdown","id":"9cc73162-016b-4770-a2c9-88b67f9e26ab","metadata":{},"outputs":[],"source":["#### Import library\n"]},{"cell_type":"markdown","id":"4c091b12-5381-43cc-b542-9f0f464353e6","metadata":{},"outputs":[],"source":["Classifier implementing the k-nearest neighbors vote.\n"]},{"cell_type":"code","id":"696597af-ffc6-4127-a136-b56525a4070b","metadata":{},"outputs":[],"source":["from sklearn.neighbors import KNeighborsClassifier"]},{"cell_type":"markdown","id":"f86038f7-0ab8-47c1-b405-8df721f1221a","metadata":{},"outputs":[],"source":["### Training\n","\n","Let's start the algorithm with k=4 for now:\n"]},{"cell_type":"code","id":"b187df34-8a26-475f-8d0b-ec924c8d3a3f","metadata":{},"outputs":[],"source":["k = 4\n#Train Model and Predict \nneigh = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)\nneigh"]},{"cell_type":"markdown","id":"5cb1e821-a40f-4042-904f-dd5c3ad777e3","metadata":{},"outputs":[],"source":["### Predicting\n","\n","We can use the model to make predictions on the test set:\n"]},{"cell_type":"code","id":"ddef6f3b-4da6-4dab-866a-e00d472d3ec1","metadata":{},"outputs":[],"source":["yhat = neigh.predict(X_test)\nyhat[0:5]"]},{"cell_type":"markdown","id":"d2aa31be-7fcb-4934-8dc8-12350f676958","metadata":{},"outputs":[],"source":["### Accuracy evaluation\n","\n","In multilabel classification, **accuracy classification score** is a function that computes subset accuracy. This function is equal to the jaccard_score function. Essentially, it calculates how closely the actual labels and predicted labels are matched in the test set.\n"]},{"cell_type":"code","id":"bfec7d70-a928-41fb-bb23-8a62f58a604f","metadata":{},"outputs":[],"source":["from sklearn import metrics\nprint(\"Train set Accuracy: \", metrics.accuracy_score(y_train, neigh.predict(X_train)))\nprint(\"Test set Accuracy: \", metrics.accuracy_score(y_test, yhat))"]},{"cell_type":"markdown","id":"7d3aa1f9-4a47-41ad-9cfc-4fdf9a95b9e3","metadata":{},"outputs":[],"source":["## Practice\n","\n","Can you build the model again, but this time with k=6?\n"]},{"cell_type":"code","id":"45eee4c1-4d3c-4097-8193-21068ea62ddf","metadata":{},"outputs":[],"source":["# write your code here\n\n\n"]},{"cell_type":"markdown","id":"b03b71fd-13d3-4902-86b6-ebbcb3b402e0","metadata":{},"outputs":[],"source":["
Click here for the solution\n","\n","```python\n","k = 6\n","neigh6 = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)\n","yhat6 = neigh6.predict(X_test)\n","print(\"Train set Accuracy: \", metrics.accuracy_score(y_train, neigh6.predict(X_train)))\n","print(\"Test set Accuracy: \", metrics.accuracy_score(y_test, yhat6))\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","id":"7549d064-c217-4adc-9ead-51f9051261ec","metadata":{},"outputs":[],"source":["#### What about other K?\n","\n","K in KNN, is the number of nearest neighbors to examine. It is supposed to be specified by the user. So, how can we choose right value for K?\n","The general solution is to reserve a part of your data for testing the accuracy of the model. Then choose k =1, use the training part for modeling, and calculate the accuracy of prediction using all samples in your test set. Repeat this process, increasing the k, and see which k is the best for your model.\n","\n","We can calculate the accuracy of KNN for different values of k.\n"]},{"cell_type":"code","id":"33dd2f9c-7be9-47d7-82ee-93a1810d8fcc","metadata":{},"outputs":[],"source":["Ks = 10\nmean_acc = np.zeros((Ks-1))\nstd_acc = np.zeros((Ks-1))\n\nfor n in range(1,Ks):\n \n #Train Model and Predict \n neigh = KNeighborsClassifier(n_neighbors = n).fit(X_train,y_train)\n yhat=neigh.predict(X_test)\n mean_acc[n-1] = metrics.accuracy_score(y_test, yhat)\n\n \n std_acc[n-1]=np.std(yhat==y_test)/np.sqrt(yhat.shape[0])\n\nmean_acc"]},{"cell_type":"markdown","id":"f38e16d3-afa7-4ef0-8593-4b3df3e6be36","metadata":{},"outputs":[],"source":["#### Plot the model accuracy for a different number of neighbors.\n"]},{"cell_type":"code","id":"1ca445e2-c1e4-433a-a567-0bd1b8656d8c","metadata":{},"outputs":[],"source":["plt.plot(range(1,Ks),mean_acc,'g')\nplt.fill_between(range(1,Ks),mean_acc - 1 * std_acc,mean_acc + 1 * std_acc, alpha=0.10)\nplt.fill_between(range(1,Ks),mean_acc - 3 * std_acc,mean_acc + 3 * std_acc, alpha=0.10,color=\"green\")\nplt.legend(('Accuracy ', '+/- 1xstd','+/- 3xstd'))\nplt.ylabel('Accuracy ')\nplt.xlabel('Number of Neighbors (K)')\nplt.tight_layout()\nplt.show()"]},{"cell_type":"code","id":"cdb104ab-6f4c-4edb-a114-c85e160f1b0c","metadata":{},"outputs":[],"source":["print( \"The best accuracy was with\", mean_acc.max(), \"with k=\", mean_acc.argmax()+1) "]},{"cell_type":"markdown","id":"e4f7fdf0-d809-405a-802f-11953f0b6fa0","metadata":{},"outputs":[],"source":["### Thank you for completing this lab!\n","\n","## Author\n","\n","Saeed Aghabozorgi\n","\n","### Other Contributors\n","\n","Joseph Santarcangelo\n","\n","##

© IBM Corporation 2020. All rights reserved.

\n","\n","\n","\n"]}],"metadata":{"kernelspec":{"display_name":"Python","language":"python","name":"conda-env-python-py"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"prev_pub_hash":"5363c84665c2ea4c62cd198411b6c0935cac4acc844e6f1b323a6313f712f535"},"nbformat":4,"nbformat_minor":4} \ No newline at end of file