Praktikum_Machine_Learning/Klasifikasi.machine_learning/Aryo Saputro-202310715049-Classification Logistic Regression.ipynb

706 lines
24 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<p style=\"text-align:center\">\n",
" <a href=\"https://skills.network\" 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",
"\n",
"# Logistic Regression with Python\n",
"\n",
"\n",
"Estimated time needed: **25** minutes\n",
" \n",
"\n",
"## Objectives\n",
"\n",
"After completing this lab you will be able to:\n",
"\n",
"* Use scikit Logistic Regression to classify\n",
"* Understand confusion matrix\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this notebook, you will learn Logistic Regression, and then, you'll create a model for a telecommunication company, to predict when its customers will leave for a competitor, so that they can take some action to retain the customers.\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=\"#about_dataset\">About the dataset</a></li>\n",
" <li><a href=\"#preprocessing\">Data pre-processing and selection</a></li>\n",
" <li><a href=\"#modeling\">Modeling (Logistic Regression with Scikit-learn)</a></li>\n",
" <li><a href=\"#evaluation\">Evaluation</a></li>\n",
" <li><a href=\"#practice\">Practice</a></li>\n",
" </ol>\n",
"</div>\n",
"<br>\n",
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"ref1\"></a>\n",
"## What is the difference between Linear and Logistic Regression?\n",
"\n",
"While Linear Regression is suited for estimating continuous values (e.g. estimating house price), it is not the best tool for predicting the class of an observed data point. In order to estimate the class of a data point, we need some sort of guidance on what would be the <b>most probable class</b> for that data point. For this, we use <b>Logistic Regression</b>.\n",
"\n",
"<div class=\"alert alert-success alertsuccess\" style=\"margin-top: 20px\">\n",
"<font size = 3><strong>Recall linear regression:</strong></font>\n",
"<br>\n",
"<br>\n",
" As you know, <b>Linear regression</b> finds a function that relates a continuous dependent variable, <b>y</b>, to some predictors (independent variables $x_1$, $x_2$, etc.). For example, simple linear regression assumes a function of the form:\n",
"<br><br>\n",
"$$\n",
"y = \\theta_0 + \\theta_1 x_1 + \\theta_2 x_2 + \\cdots\n",
"$$\n",
"<br>\n",
"and finds the values of parameters $\\theta_0, \\theta_1, \\theta_2$, etc, where the term $\\theta_0$ is the \"intercept\". It can be generally shown as:\n",
"<br><br>\n",
"$$\n",
"_\\theta(𝑥) = \\theta^TX\n",
"$$\n",
"<p></p>\n",
"\n",
"</div>\n",
"\n",
"Logistic Regression is a variation of Linear Regression, used when the observed dependent variable, <b>y</b>, is categorical. It produces a formula that predicts the probability of the class label as a function of the independent variables.\n",
"\n",
"Logistic regression fits a special s-shaped curve by taking the linear regression function and transforming the numeric estimate into a probability with the following function, which is called the sigmoid function 𝜎:\n",
"\n",
"$$\n",
"_\\theta(𝑥) = \\sigma({\\theta^TX}) = \\frac {e^{(\\theta_0 + \\theta_1 x_1 + \\theta_2 x_2 +...)}}{1 + e^{(\\theta_0 + \\theta_1 x_1 + \\theta_2 x_2 +\\cdots)}}\n",
"$$\n",
"Or:\n",
"$$\n",
"ProbabilityOfaClass_1 = P(Y=1|X) = \\sigma({\\theta^TX}) = \\frac{e^{\\theta^TX}}{1+e^{\\theta^TX}} \n",
"$$\n",
"\n",
"In this equation, ${\\theta^TX}$ is the regression result (the sum of the variables weighted by the coefficients), `exp` is the exponential function and $\\sigma(\\theta^TX)$ is the sigmoid or [logistic function](http://en.wikipedia.org/wiki/Logistic_function), also called logistic curve. It is a common \"S\" shape (sigmoid curve).\n",
"\n",
"So, briefly, Logistic Regression passes the input through the logistic/sigmoid but then treats the result as a probability:\n",
"\n",
"<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/images/mod_ID_24_final.png\" width=\"400\" align=\"center\">\n",
"\n",
"\n",
"The objective of the __Logistic Regression__ algorithm, is to find the best parameters θ, for $_\\theta(𝑥)$ = $\\sigma({\\theta^TX})$, in such a way that the model best predicts the class of each case.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Customer churn with Logistic Regression\n",
"A telecommunications company is concerned about the number of customers leaving their land-line business for cable competitors. They need to understand who is leaving. Imagine that you are an analyst at this company and you have to find out who is leaving and why.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#!pip install scikit-learn==0.23.1\n",
"!pip install scikit-learn\n",
"!pip install matplotlib\n",
"!pip install pandas \n",
"!pip install numpy \n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's first import required libraries:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import pylab as pl\n",
"import numpy as np\n",
"import scipy.optimize as opt\n",
"from sklearn import preprocessing\n",
"%matplotlib inline \n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"about_dataset\">About the dataset</h2>\n",
"We will use a telecommunications dataset for predicting customer churn. This is a historical customer dataset where each row represents one customer. The data is relatively easy to understand, and you may uncover insights you can use immediately. Typically it is less expensive to keep customers than acquire new ones, so the focus of this analysis is to predict the customers who will stay with the company. \n",
"\n",
"\n",
"This data set provides information to help you predict what behavior will help you to retain customers. You can analyze all relevant customer data and develop focused customer retention programs.\n",
"\n",
"\n",
"\n",
"The dataset includes information about:\n",
"\n",
"- Customers who left within the last month the column is called Churn\n",
"- Services that each customer has signed up for phone, multiple lines, internet, online security, online backup, device protection, tech support, and streaming TV and movies\n",
"- Customer account information how long they had been a customer, contract, payment method, paperless billing, monthly charges, and total charges\n",
"- Demographic info about customers gender, age range, and if they have partners and dependents\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load the Telco Churn data \n",
"Telco Churn is a hypothetical data file that concerns a telecommunications company's efforts to reduce turnover in its customer base. Each case corresponds to a separate customer and it records various demographic and service usage information. Before you can work with the data, you must use the URL to get the ChurnData.csv.\n",
"\n",
"To download the data, we will use `!wget` to download it from IBM Object Storage.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Click here and press Shift+Enter\n",
"!wget -O ChurnData.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/ChurnData.csv"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load Data From CSV File \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"churn_df = pd.read_csv(\"ChurnData.csv\")\n",
"churn_df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"preprocessing\">Data pre-processing and selection</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's select some features for the modeling. Also, we change the target data type to be an integer, as it is a requirement by the skitlearn algorithm:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"churn_df = churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip', 'callcard', 'wireless','churn']]\n",
"churn_df['churn'] = churn_df['churn'].astype('int')\n",
"churn_df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Practice\n",
"How many rows and columns are in this dataset in total? What are the names of columns?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# write your code here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"churn_df.shape\n",
"\n",
"```\n",
"\n",
"</details>\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's define X, and y for our dataset:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X = np.asarray(churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip']])\n",
"X[0:5]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"y = np.asarray(churn_df['churn'])\n",
"y [0:5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Also, we normalize the dataset:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn import preprocessing\n",
"X = preprocessing.StandardScaler().fit(X).transform(X)\n",
"X[0:5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train/Test dataset\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We split our dataset into train and test set:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4)\n",
"print ('Train set:', X_train.shape, y_train.shape)\n",
"print ('Test set:', X_test.shape, y_test.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"modeling\">Modeling (Logistic Regression with Scikit-learn)</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's build our model using __LogisticRegression__ from the Scikit-learn package. This function implements logistic regression and can use different numerical optimizers to find parameters, including newton-cg, lbfgs, liblinear, sag, saga solvers. You can find extensive information about the pros and cons of these optimizers if you search it in the internet.\n",
"\n",
"The version of Logistic Regression in Scikit-learn, support regularization. Regularization is a technique used to solve the overfitting problem of machine learning models.\n",
"__C__ parameter indicates __inverse of regularization strength__ which must be a positive float. Smaller values specify stronger regularization. \n",
"Now let's fit our model with train set:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.metrics import confusion_matrix\n",
"LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train)\n",
"LR"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can predict using our test set:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"yhat = LR.predict(X_test)\n",
"yhat"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"__predict_proba__ returns estimates for all classes, ordered by the label of classes. So, the first column is the probability of class 0, P(Y=0|X), and second column is probability of class 1, P(Y=1|X):\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"yhat_prob = LR.predict_proba(X_test)\n",
"yhat_prob"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"evaluation\">Evaluation</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### jaccard index\n",
"Let's try the jaccard index for accuracy evaluation. we can define jaccard as the size of the intersection divided by the size of the union of the two label sets. 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",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import jaccard_score\n",
"jaccard_score(y_test, yhat,pos_label=0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### confusion matrix\n",
"Another way of looking at the accuracy of the classifier is to look at __confusion matrix__.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import classification_report, confusion_matrix\n",
"import itertools\n",
"def plot_confusion_matrix(cm, classes,\n",
" normalize=False,\n",
" title='Confusion matrix',\n",
" cmap=plt.cm.Blues):\n",
" \"\"\"\n",
" This function prints and plots the confusion matrix.\n",
" Normalization can be applied by setting `normalize=True`.\n",
" \"\"\"\n",
" if normalize:\n",
" cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n",
" print(\"Normalized confusion matrix\")\n",
" else:\n",
" print('Confusion matrix, without normalization')\n",
"\n",
" print(cm)\n",
"\n",
" plt.imshow(cm, interpolation='nearest', cmap=cmap)\n",
" plt.title(title)\n",
" plt.colorbar()\n",
" tick_marks = np.arange(len(classes))\n",
" plt.xticks(tick_marks, classes, rotation=45)\n",
" plt.yticks(tick_marks, classes)\n",
"\n",
" fmt = '.2f' if normalize else 'd'\n",
" thresh = cm.max() / 2.\n",
" for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n",
" plt.text(j, i, format(cm[i, j], fmt),\n",
" horizontalalignment=\"center\",\n",
" color=\"white\" if cm[i, j] > thresh else \"black\")\n",
"\n",
" plt.tight_layout()\n",
" plt.ylabel('True label')\n",
" plt.xlabel('Predicted label')\n",
"print(confusion_matrix(y_test, yhat, labels=[1,0]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Compute confusion matrix\n",
"cnf_matrix = confusion_matrix(y_test, yhat, labels=[1,0])\n",
"np.set_printoptions(precision=2)\n",
"\n",
"\n",
"# Plot non-normalized confusion matrix\n",
"plt.figure()\n",
"plot_confusion_matrix(cnf_matrix, classes=['churn=1','churn=0'],normalize= False, title='Confusion matrix')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's look at first row. The first row is for customers whose actual churn value in the test set is 1.\n",
"As you can calculate, out of 40 customers, the churn value of 15 of them is 1. \n",
"Out of these 15 cases, the classifier correctly predicted 6 of them as 1, and 9 of them as 0. \n",
"\n",
"This means, for 6 customers, the actual churn value was 1 in test set and classifier also correctly predicted those as 1. However, while the actual label of 9 customers was 1, the classifier predicted those as 0, which is not very good. We can consider it as the error of the model for first row.\n",
"\n",
"What about the customers with churn value 0? Lets look at the second row.\n",
"It looks like there were 25 customers whom their churn value were 0. \n",
"\n",
"\n",
"The classifier correctly predicted 24 of them as 0, and one of them wrongly as 1. So, it has done a good job in predicting the customers with churn value 0. A good thing about the confusion matrix is that it shows the models ability to correctly predict or separate the classes. In a specific case of the binary classifier, such as this example, we can interpret these numbers as the count of true positives, false positives, true negatives, and false negatives. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print (classification_report(y_test, yhat))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Based on the count of each section, we can calculate precision and recall of each label:\n",
"\n",
"\n",
"- __Precision__ is a measure of the accuracy provided that a class label has been predicted. It is defined by: precision = TP / (TP + FP)\n",
"\n",
"- __Recall__ is the true positive rate. It is defined as: Recall =  TP / (TP + FN)\n",
"\n",
" \n",
"So, we can calculate the precision and recall of each class.\n",
"\n",
"__F1 score:__\n",
"Now we are in the position to calculate the F1 scores for each label based on the precision and recall of that label. \n",
"\n",
"The F1 score is the harmonic average of the precision and recall, where an F1 score reaches its best value at 1 (perfect precision and recall) and worst at 0. It is a good way to show that a classifer has a good value for both recall and precision.\n",
"\n",
"\n",
"Finally, we can tell the average accuracy for this classifier is the average of the F1-score for both labels, which is 0.72 in our case.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### log loss\n",
"Now, let's try __log loss__ for evaluation. In logistic regression, the output can be the probability of customer churn is yes (or equals to 1). This probability is a value between 0 and 1.\n",
"Log loss( Logarithmic loss) measures the performance of a classifier where the predicted output is a probability value between 0 and 1. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import log_loss\n",
"log_loss(y_test, yhat_prob)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"practice\">Practice</h2>\n",
"Try to build Logistic Regression model again for the same dataset, but this time, use different __solver__ and __regularization__ values? What is new __logLoss__ value?\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Columns: Index(['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip',\n",
" 'callcard', 'wireless', 'longmon', 'tollmon', 'equipmon', 'cardmon',\n",
" 'wiremon', 'longten', 'tollten', 'cardten', 'voice', 'pager',\n",
" 'internet', 'callwait', 'confer', 'ebill', 'loglong', 'logtoll',\n",
" 'lninc', 'custcat', 'churn'],\n",
" dtype='object')\n",
"New LogLoss value: 0.5939226974155307\n"
]
}
],
"source": [
"# ======================================\n",
"# IMPORT LIBRARIES\n",
"# ======================================\n",
"import pandas as pd\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.metrics import log_loss\n",
"\n",
"# ======================================\n",
"# LOAD DATASET\n",
"# ======================================\n",
"df = pd.read_csv(\"ChurnData.csv\")\n",
"\n",
"# Tampilkan kolom supaya yakin\n",
"print(\"Columns:\", df.columns)\n",
"\n",
"# ======================================\n",
"# PREPROCESSING\n",
"# ======================================\n",
"df['churn'] = df['churn'].astype(int)\n",
"\n",
"X = np.asarray(df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip']])\n",
"y = np.asarray(df['churn'])\n",
"\n",
"# Train/test split\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)\n",
"\n",
"# ======================================\n",
"# LOGISTIC REGRESSION\n",
"# ======================================\n",
"model = LogisticRegression(solver='liblinear', C=0.5, max_iter=2000)\n",
"model.fit(X_train, y_train)\n",
"\n",
"yhat_prob = model.predict_proba(X_test)\n",
"new_logloss = log_loss(y_test, yhat_prob)\n",
"\n",
"print(\"New LogLoss value:\", new_logloss)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"LR2 = LogisticRegression(C=0.01, solver='sag').fit(X_train,y_train)\n",
"yhat_prob2 = LR2.predict_proba(X_test)\n",
"print (\"LogLoss: : %.2f\" % log_loss(y_test, yhat_prob2))\n",
"\n",
"```\n",
"\n",
"</details>\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Thank you for completing this lab!\n",
"\n",
"\n",
"## Author\n",
"\n",
"Saeed Aghabozorgi\n",
"\n",
"\n",
"### Other Contributors\n",
"\n",
"<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n",
"\n",
"## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n",
"\n",
"<!--\n",
"\n",
"## Change Log\n",
"\n",
"\n",
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n",
"|---|---|---|---|\n",
"| 2021-01-21 | 2.2 | Lakshmi | Updated sklearn library|\n",
"| 2020-11-03 | 2.1 | Lakshmi | Updated URL of csv |\n",
"| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n",
"| | | | |\n",
"| | | | |\n",
"\n",
"--!>\n",
"\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.12.8"
},
"prev_pub_hash": "93c3096a9aa003ffd3856deed45478e9e7e2e1d7091dd85d842ce88e28b0a595"
},
"nbformat": 4,
"nbformat_minor": 4
}