Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Created on Skills Network Labs
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"button": false,
"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 align=\"center\"><font size=\"5\"> Logistic Regression with Python</font></h1>\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": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"<a id=\"ref1\"></a>\n",
"\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, useful 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 and transforming the numeric estimate into a probability with the following function, which is called 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?cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-ML0101EN-Coursera-20231514&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-ML0101EN-Coursera-20231514&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-ML0101EN-Coursera-20231514&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-ML0101EN-Coursera-20231514&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ), 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\n",
"src=\"https://ibm.box.com/shared/static/kgv9alcghmjcv97op4d6onkyxevk23b1.png\" width=\"400\" align=\"center\">\n",
"\n",
"The objective of **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",
"\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": "markdown",
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Lets first import required libraries:\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"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": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"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",
"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",
"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": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"### Load the Telco Churn data\n",
"\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": 2,
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--2020-10-17 22:39:48-- https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-Coursera/labs/Data_files/ChurnData.csv\n",
"Resolving cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)... 67.228.254.196\n",
"Connecting to cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)|67.228.254.196|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 35943 (35K) [text/csv]\n",
"Saving to: ‘ChurnData.csv’\n",
"\n",
"ChurnData.csv 100%[===================>] 35.10K --.-KB/s in 0.02s \n",
"\n",
"2020-10-17 22:39:48 (1.79 MB/s) - ‘ChurnData.csv’ saved [35943/35943]\n",
"\n"
]
}
],
"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-Coursera/labs/Data_files/ChurnData.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)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"### Load Data From CSV File\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"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>tenure</th>\n",
" <th>age</th>\n",
" <th>address</th>\n",
" <th>income</th>\n",
" <th>ed</th>\n",
" <th>employ</th>\n",
" <th>equip</th>\n",
" <th>callcard</th>\n",
" <th>wireless</th>\n",
" <th>longmon</th>\n",
" <th>...</th>\n",
" <th>pager</th>\n",
" <th>internet</th>\n",
" <th>callwait</th>\n",
" <th>confer</th>\n",
" <th>ebill</th>\n",
" <th>loglong</th>\n",
" <th>logtoll</th>\n",
" <th>lninc</th>\n",
" <th>custcat</th>\n",
" <th>churn</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>11.0</td>\n",
" <td>33.0</td>\n",
" <td>7.0</td>\n",
" <td>136.0</td>\n",
" <td>5.0</td>\n",
" <td>5.0</td>\n",
" <td>0.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>4.40</td>\n",
" <td>...</td>\n",
" <td>1.0</td>\n",
" <td>0.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>0.0</td>\n",
" <td>1.482</td>\n",
" <td>3.033</td>\n",
" <td>4.913</td>\n",
" <td>4.0</td>\n",
" <td>1.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>33.0</td>\n",
" <td>33.0</td>\n",
" <td>12.0</td>\n",
" <td>33.0</td>\n",
" <td>2.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>9.45</td>\n",
" <td>...</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>2.246</td>\n",
" <td>3.240</td>\n",
" <td>3.497</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>23.0</td>\n",
" <td>30.0</td>\n",
" <td>9.0</td>\n",
" <td>30.0</td>\n",
" <td>1.0</td>\n",
" <td>2.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>6.30</td>\n",
" <td>...</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>1.0</td>\n",
" <td>0.0</td>\n",
" <td>1.841</td>\n",
" <td>3.240</td>\n",
" <td>3.401</td>\n",
" <td>3.0</td>\n",
" <td>0.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>38.0</td>\n",
" <td>35.0</td>\n",
" <td>5.0</td>\n",
" <td>76.0</td>\n",
" <td>2.0</td>\n",
" <td>10.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>6.05</td>\n",
" <td>...</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>1.800</td>\n",
" <td>3.807</td>\n",
" <td>4.331</td>\n",
" <td>4.0</td>\n",
" <td>0.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>7.0</td>\n",
" <td>35.0</td>\n",
" <td>14.0</td>\n",
" <td>80.0</td>\n",
" <td>2.0</td>\n",
" <td>15.0</td>\n",
" <td>0.0</td>\n",
" <td>1.0</td>\n",
" <td>0.0</td>\n",
" <td>7.10</td>\n",
" <td>...</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>0.0</td>\n",
" <td>1.960</td>\n",
" <td>3.091</td>\n",
" <td>4.382</td>\n",
" <td>3.0</td>\n",
" <td>0.0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>5 rows × 28 columns</p>\n",
"</div>"
],
"text/plain": [
" tenure age address income ed employ equip callcard wireless \\\n",
"0 11.0 33.0 7.0 136.0 5.0 5.0 0.0 1.0 1.0 \n",
"1 33.0 33.0 12.0 33.0 2.0 0.0 0.0 0.0 0.0 \n",
"2 23.0 30.0 9.0 30.0 1.0 2.0 0.0 0.0 0.0 \n",
"3 38.0 35.0 5.0 76.0 2.0 10.0 1.0 1.0 1.0 \n",
"4 7.0 35.0 14.0 80.0 2.0 15.0 0.0 1.0 0.0 \n",
"\n",
" longmon ... pager internet callwait confer ebill loglong logtoll \\\n",
"0 4.40 ... 1.0 0.0 1.0 1.0 0.0 1.482 3.033 \n",
"1 9.45 ... 0.0 0.0 0.0 0.0 0.0 2.246 3.240 \n",
"2 6.30 ... 0.0 0.0 0.0 1.0 0.0 1.841 3.240 \n",
"3 6.05 ... 1.0 1.0 1.0 1.0 1.0 1.800 3.807 \n",
"4 7.10 ... 0.0 0.0 1.0 1.0 0.0 1.960 3.091 \n",
"\n",
" lninc custcat churn \n",
"0 4.913 4.0 1.0 \n",
"1 3.497 1.0 1.0 \n",
"2 3.401 3.0 0.0 \n",
"3 4.331 4.0 0.0 \n",
"4 4.382 3.0 0.0 \n",
"\n",
"[5 rows x 28 columns]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"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": [
"Lets select some features for the modeling. Also we change the target data type to be integer, as it is a requirement by the skitlearn algorithm:\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"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>tenure</th>\n",
" <th>age</th>\n",
" <th>address</th>\n",
" <th>income</th>\n",
" <th>ed</th>\n",
" <th>employ</th>\n",
" <th>equip</th>\n",
" <th>callcard</th>\n",
" <th>wireless</th>\n",
" <th>churn</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>11.0</td>\n",
" <td>33.0</td>\n",
" <td>7.0</td>\n",
" <td>136.0</td>\n",
" <td>5.0</td>\n",
" <td>5.0</td>\n",
" <td>0.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>33.0</td>\n",
" <td>33.0</td>\n",
" <td>12.0</td>\n",
" <td>33.0</td>\n",
" <td>2.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>23.0</td>\n",
" <td>30.0</td>\n",
" <td>9.0</td>\n",
" <td>30.0</td>\n",
" <td>1.0</td>\n",
" <td>2.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0.0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>38.0</td>\n",
" <td>35.0</td>\n",
" <td>5.0</td>\n",
" <td>76.0</td>\n",
" <td>2.0</td>\n",
" <td>10.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>1.0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>7.0</td>\n",
" <td>35.0</td>\n",
" <td>14.0</td>\n",
" <td>80.0</td>\n",
" <td>2.0</td>\n",
" <td>15.0</td>\n",
" <td>0.0</td>\n",
" <td>1.0</td>\n",
" <td>0.0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" tenure age address income ed employ equip callcard wireless \\\n",
"0 11.0 33.0 7.0 136.0 5.0 5.0 0.0 1.0 1.0 \n",
"1 33.0 33.0 12.0 33.0 2.0 0.0 0.0 0.0 0.0 \n",
"2 23.0 30.0 9.0 30.0 1.0 2.0 0.0 0.0 0.0 \n",
"3 38.0 35.0 5.0 76.0 2.0 10.0 1.0 1.0 1.0 \n",
"4 7.0 35.0 14.0 80.0 2.0 15.0 0.0 1.0 0.0 \n",
"\n",
" churn \n",
"0 1 \n",
"1 1 \n",
"2 0 \n",
"3 0 \n",
"4 0 "
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"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": {
"button": true,
"new_sheet": true,
"run_control": {
"read_only": false
}
},
"source": [
"## Practice\n",
"\n",
"How many rows and columns are in this dataset in total? What are the name of columns?\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"(200, 10)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# write your code here\n",
"churn_df.shape\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lets define X, and y for our dataset:\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 11., 33., 7., 136., 5., 5., 0.],\n",
" [ 33., 33., 12., 33., 2., 0., 0.],\n",
" [ 23., 30., 9., 30., 1., 2., 0.],\n",
" [ 38., 35., 5., 76., 2., 10., 1.],\n",
" [ 7., 35., 14., 80., 2., 15., 0.]])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X = np.asarray(churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip']])\n",
"X[0:5]"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 1, 0, 0, 0])"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"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": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[-1.13518441, -0.62595491, -0.4588971 , 0.4751423 , 1.6961288 ,\n",
" -0.58477841, -0.85972695],\n",
" [-0.11604313, -0.62595491, 0.03454064, -0.32886061, -0.6433592 ,\n",
" -1.14437497, -0.85972695],\n",
" [-0.57928917, -0.85594447, -0.261522 , -0.35227817, -1.42318853,\n",
" -0.92053635, -0.85972695],\n",
" [ 0.11557989, -0.47262854, -0.65627219, 0.00679109, -0.6433592 ,\n",
" -0.02518185, 1.16316 ],\n",
" [-1.32048283, -0.47262854, 0.23191574, 0.03801451, -0.6433592 ,\n",
" 0.53441472, -0.85972695]])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"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": [
"Okay, we split our dataset into train and test set:\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Train set: (160, 7) (160,)\n",
"Test set: (40, 7) (40,)\n"
]
}
],
"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": [
"Lets build our model using **LogisticRegression** from 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 internet.\n",
"\n",
"The version of Logistic Regression in Scikit-learn, support regularization. Regularization is a technique used to solve the overfitting problem in machine learning models.\n",
"**C** parameter indicates **inverse of regularization strength** which must be a positive float. Smaller values specify stronger regularization. \n",
"Now lets fit our model with train set:\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"LogisticRegression(C=0.01, class_weight=None, dual=False, fit_intercept=True,\n",
" intercept_scaling=1, max_iter=100, multi_class='warn',\n",
" n_jobs=None, penalty='l2', random_state=None, solver='liblinear',\n",
" tol=0.0001, verbose=0, warm_start=False)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"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": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0])"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"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 1, P(Y=1|X), and second column is probability of class 0, P(Y=0|X):\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0.54132919, 0.45867081],\n",
" [0.60593357, 0.39406643],\n",
" [0.56277713, 0.43722287],\n",
" [0.63432489, 0.36567511],\n",
" [0.56431839, 0.43568161],\n",
" [0.55386646, 0.44613354],\n",
" [0.52237207, 0.47762793],\n",
" [0.60514349, 0.39485651],\n",
" [0.41069572, 0.58930428],\n",
" [0.6333873 , 0.3666127 ],\n",
" [0.58068791, 0.41931209],\n",
" [0.62768628, 0.37231372],\n",
" [0.47559883, 0.52440117],\n",
" [0.4267593 , 0.5732407 ],\n",
" [0.66172417, 0.33827583],\n",
" [0.55092315, 0.44907685],\n",
" [0.51749946, 0.48250054],\n",
" [0.485743 , 0.514257 ],\n",
" [0.49011451, 0.50988549],\n",
" [0.52423349, 0.47576651],\n",
" [0.61619519, 0.38380481],\n",
" [0.52696302, 0.47303698],\n",
" [0.63957168, 0.36042832],\n",
" [0.52205164, 0.47794836],\n",
" [0.50572852, 0.49427148],\n",
" [0.70706202, 0.29293798],\n",
" [0.55266286, 0.44733714],\n",
" [0.52271594, 0.47728406],\n",
" [0.51638863, 0.48361137],\n",
" [0.71331391, 0.28668609],\n",
" [0.67862111, 0.32137889],\n",
" [0.50896403, 0.49103597],\n",
" [0.42348082, 0.57651918],\n",
" [0.71495838, 0.28504162],\n",
" [0.59711064, 0.40288936],\n",
" [0.63808839, 0.36191161],\n",
" [0.39957895, 0.60042105],\n",
" [0.52127638, 0.47872362],\n",
" [0.65975464, 0.34024536],\n",
" [0.5114172 , 0.4885828 ]])"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"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",
"\n",
"Lets try jaccard index for accuracy evaluation. we can define jaccard as the size of the intersection divided by the size of the union of two label sets. 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": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.75"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from sklearn.metrics import jaccard_similarity_score\n",
"jaccard_similarity_score(y_test, yhat)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### confusion matrix\n",
"\n",
"Another way of looking at accuracy of classifier is to look at **confusion matrix**.\n"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 6 9]\n",
" [ 1 24]]\n"
]
}
],
"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": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Confusion matrix, without normalization\n",
"[[ 6 9]\n",
" [ 1 24]]\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAU4AAAEmCAYAAAAN9HleAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8vihELAAAACXBIWXMAAAsTAAALEwEAmpwYAAAeoElEQVR4nO3de7wd49338c93J0ScG5FIQoQWaWjFoUVKhPRpKa1qqaJoy42qarVOrT5CtfetrVYPlEa5KUKoQxFFHw2aOiYRhziXOCQhJyEIkvg9f8ysWra911qTrL3WzF7ft9e8suawrvntTPbPNdd1zTWKCMzMrHZtzQ7AzKxonDjNzDJy4jQzy8iJ08wsIydOM7OMnDjNzDJy4rS6kdRb0g2SXpV01QqUc6CkW+sZW7NI2knSE82Ow+pLHsfZeiQdAHwfGAosAqYBP4uISStY7kHAd4AREbF0RePMO0kBbBIRTzc7Fmss1zhbjKTvA78B/hvoDwwG/gDsVYfiNwSebIWkWQtJPZsdg3WRiPDSIguwFvA6sG+FY3qRJNZZ6fIboFe6bxTwIvADYA4wG/hGuu804B1gSXqOQ4FTgUvLyh4CBNAzXf868AxJrfdZ4MCy7ZPKvjcCuB94Nf1zRNm+24HTgX+l5dwK9O3kZyvFf0JZ/F8EPgc8CSwAflR2/CeBu4GF6bFnAyun++5Mf5Y30p93v7LyTwReAi4pbUu/8+H0HFun6wOBecCoZv/b8JJtcY2ztewArAJcW+GYk4HtgeHAliTJ48dl+9cjScCDSJLjOZI+FBFjSGqx4yNi9Yi4oFIgklYDfgfsHhFrkCTHaR0c1weYkB67DvBrYIKkdcoOOwD4BtAPWBk4rsKp1yP5OxgEnAKcD3wN2AbYCThF0sbpscuAY4G+JH93o4GjACJiZHrMlunPO76s/D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kJggg==\n",
"text/plain": [
"<Figure size 432x288 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"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": [
"Look at first row. The first row is for customers whose actual churn value in test set is 1.\n",
"As you can calculate, out of 40 customers, the churn value of 15 of them is 1. \n",
"And out of these 15, the classifier correctly predicted 6 of them as 1, and 9 of them as 0. \n",
"\n",
"It means, for 6 customers, the actual churn value were 1 in test set, and classifier also correctly predicted those as 1. However, while the actual label of 9 customers were 1, the classifier predicted those as 0, which is not very good. We can consider it as 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",
"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 confusion matrix is that shows the model’s ability to correctly predict or separate the classes. In specific case of 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": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" precision recall f1-score support\n",
"\n",
" 0 0.73 0.96 0.83 25\n",
" 1 0.86 0.40 0.55 15\n",
"\n",
" micro avg 0.75 0.75 0.75 40\n",
" macro avg 0.79 0.68 0.69 40\n",
"weighted avg 0.78 0.75 0.72 40\n",
"\n"
]
}
],
"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",
"- **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 true positive rate. It is defined as: Recall =  TP / (TP + FN)\n",
"\n",
"So, we can calculate 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",
"And 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",
"\n",
"Now, lets 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": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.6017092478101185"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"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": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.6865653549233828"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# write your code here\n",
"LR1 = LogisticRegression(C=0.0001, solver='newton-cg').fit(X_train,y_train)\n",
"yhat1 = LR1.predict(X_test)\n",
"yhat_prob1 = LR1.predict_proba(X_test)\n",
"log_loss(y_test, yhat_prob1)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click **here** for the solution.\n",
"\n",
"<!-- Your answer is below:\n",
" \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"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n",
"| ----------------- | ------- | ---------- | --------------------- |\n",
"| 2020-08-04 | 0 | Nayef | Upload file to Gitlab |\n",
"| | | | |\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<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>\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.6.11"
},
"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
You can’t perform that action at this time.