Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saeedaghabozorgi/a34dde20bf94a3f0bbd7abb4c0420d95 to your computer and use it in GitHub Desktop.
Save saeedaghabozorgi/a34dde20bf94a3f0bbd7abb4c0420d95 to your computer and use it in GitHub Desktop.
Created on Cognitive Class Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"button": false,
"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>"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"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",
"\n",
"\n",
"<a id=\"ref1\"></a>\n",
"## What is different 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 **most probable class** for that data point. For this, we use **Logistic Regression**.\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, __Linear regression__ finds a function that relates a continuous dependent variable, _y_, to some predictors (independent variables _x1_, _x2_, etc.). For example, Simple linear regression assumes a function of the form:\n",
"<br><br>\n",
"$$\n",
"y = 𝜃0 + 𝜃1 * x1 + 𝜃2 * x2 +...\n",
"$$\n",
"<br>\n",
"and finds the values of parameters _θ0_, _θ1_, _𝜃2_, etc, where the term _𝜃0_ is the \"intercept\". It can be generally shown as:\n",
"<br><br>\n",
"$$\n",
"ℎ_θ(𝑥) = 𝜃^TX\n",
"$$\n",
"<p></p>\n",
"\n",
"</div>\n",
"\n",
"Logistic Regression is a variation of Linear Regression, useful when the observed dependent variable, _y_, 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",
"ℎ_θ(𝑥) = 𝜎({θ^TX}) = \\frac {e^{(θ0 + θ1 * x1 + θ2 * x2 +...)}}{1 + e^{(θ0 + θ1 * x1 + θ2 * x2 +...)}}\n",
"$$\n",
"Or:\n",
"$$\n",
"ProbabilityOfaClass_1 = P(Y=1|X) = 𝜎({θ^TX}) = \\frac{e^{θ^TX}}{1+e^{θ^TX}} \n",
"$$\n",
"\n",
"In this equation, ${θ^TX}$ is the regression result (the sum of the variables weighted by the coefficients), `exp` is the exponential function and $𝜎(θ^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\n",
"src=\"https://ibm.box.com/shared/static/kgv9alcghmjcv97op4d6onkyxevk23b1.png\" width = \"400\" align = \"center\">\n",
"\n",
"\n",
"The objective of __Logistic Regression__ algorithm, is to find the best parameters θ, for ℎ_θ(𝑥) = 𝜎({θ^TX}), in such a way that the model best predicts the class of each case."
]
},
{
"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’re an analyst at this company and you have to find out who is leaving and why."
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Lets first import required libraries:"
]
},
{
"cell_type": "code",
"execution_count": null,
"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": [
"### About dataset\n",
"We’ll use a telecommunications data for predicting customer churn. This is a historical customer data where each row represents one customer. The data is relatively easy to understand, and you may uncover insights you can use immediately. Typically it’s 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 info to help you predict behavior to retain customers. You can analyze all relevant customer data and develop focused customer retention programs.\n",
"\n",
"\n",
"\n",
"The data set 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’ve 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",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"#Click here and press Shift+Enter\n",
"!wget -O ChurnData.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/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)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"### Load Data From CSV File "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"churn_df = pd.read_csv(\"ChurnData.csv\")\n",
"churn_df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data pre-processing and selection"
]
},
{
"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:"
]
},
{
"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": {
"button": true,
"new_sheet": true,
"run_control": {
"read_only": false
}
},
"source": [
"## Practice\n",
"How many rows and columns are in this dataset in total? What are the name of columns?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"# write your code here\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lets define X, and y for our dataset:"
]
},
{
"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:"
]
},
{
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay, we split our dataset into train and test set:"
]
},
{
"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": [
"# Modeling (Logistic Regression with Scikit-learn)"
]
},
{
"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:"
]
},
{
"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:"
]
},
{
"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 1, P(Y=1|X), and second column is probability of class 0, P(Y=0|X):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"yhat_prob = LR.predict_proba(X_test)\n",
"yhat_prob"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### jaccard index\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",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import jaccard_similarity_score\n",
"jaccard_similarity_score(y_test, yhat)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### confusion matrix\n",
"Another way of looking at accuracy of classifier is to look at __confusion matrix__."
]
},
{
"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": [
"Look at first row. The firsr 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",
"\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. "
]
},
{
"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 true positive rate. It is defined as: Recall =  TP / (TP + FN)\n",
"\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 F1score 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",
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### log loss\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": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import log_loss\n",
"log_loss(y_test, yhat_prob)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Practice\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?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# write your code here\n",
"\n",
"\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",
"-->"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"## Want to learn more?\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: [SPSS Modeler](http://cocl.us/ML0101EN-SPSSModeler).\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 [Watson Studio](https://cocl.us/ML0101EN_DSX)\n",
"\n",
"### Thanks for completing this lesson!\n",
"\n",
"Notebook created by: <a href = \"https://ca.linkedin.com/in/saeedaghabozorgi\">Saeed Aghabozorgi</a>\n",
"\n",
"<hr>\n",
"Copyright &copy; 2018 [Cognitive Class](https://cocl.us/DX0108EN_CC). This notebook and its source code are released under the terms of the [MIT License](https://bigdatauniversity.com/mit-license/).​"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
},
"widgets": {
"state": {},
"version": "1.1.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment