Understanding Logistic Regression using Customer Churn
We will create a model for a telecommunications company using Logistic Regrssion to predict when its customers will leave for a competitor, so that they can take some action to retain the customers.
A telecommunications company is concerned about the number of customers leaving their landline business for cable competitors. They need to understand who is leaving. Imahine that you are an analyst at this company and you have to find out who is leaving and why. In this blog post, we will create a model for the telecommunications company using Logistic Regrssion to predict when its customers will leave for a competitor, so that they can take some action to retain the customers.
While Linear Regression is suited for estimating continuous values, 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 som e sort of guidance on what would be the most probable class for that data point. For this, we use Logistic Regression.
Logistic Regression is a variation of Linar 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. Logistic Regression fits a special s-shaped curve by taking the linear regression and transforming the numeric estimate into a probability.
The dataset we'll be using contains information about 200 customers. It includes information about:
- Customers who left within the last month - the column is called Churn.
- 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.
- Customer account information - how long they have been a customer, contract, payment method, paperless billing, monthly charges, and total charges.
- Demographic information about customers - geneder, age, range, and if they have partners and dependents.
Typically, it is less expensive to keep customers than to acquire new ones, so the focus of this analysis is to predict the customers who will stay with the company.
import pandas as pd
import numpy as np
import pylab as pl
import scipy.optimize as opt
import matplotlib.pyplot as plt
%matplotlib inline
df = pd.read_csv('ChurnData.csv')
df.head()
df.shape
df = df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip', 'callcard', 'wireless', 'churn']]
df['churn'] = df['churn'].astype('int')
df.head()
df.shape
Define X and y for the dataset.
X = np.asarray(df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip']])
X[0:5]
y = np.asarray(df['churn'])
y[0:5]
Normalize the dataset.
from sklearn import preprocessing
X = preprocessing.StandardScaler().fit(X).transform(X)
X[0:5]
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)
print('Train set: ', X_train.shape, y_train.shape)
print('Test set: ', X_test.shape, y_test.shape)
Modeling
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. This version of Logisitic Regression supports Regularization. Regularization is a technique used to solve the overfitting problem in machine learning models. C parameter indicates inverse of regularization strength, which must be a positive float. Smaller values specify stronger regularization.
Now let's fit our model with the train set.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train, y_train)
LR
yhat = LR.predict(X_test)
yhat
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 the second column is the probability of class 0, P(Y=0|X).
yhat_prob = LR.predict_proba(X_test)
yhat_prob
from sklearn.metrics import jaccard_similarity_score
jaccard_similarity_score(y_test, yhat)
from sklearn.metrics import classification_report, confusion_matrix
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
print(confusion_matrix(y_test, yhat, labels=[1,0]))
cnf_matrix = confusion_matrix(y_test, yhat, labels=[1,0])
np.set_printoptions(precision=2)
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['churn=1','churn=0'],normalize= False, title='Confusion matrix')
The first row is for customers whose actual churn value in the test set is 1. As you can calculate, out of 40 customers, the churn value of 15 of them is 1.A nd out of these 15, the classifier correctly predicted 6 of them as 1, and 9 of them as 0. It means that for 6 customers, the actual churn value was 1 in the test set, and the classifier correctly predicted those as 1. However, the actual label of 9 customers was 1, and the classifier predicted these as 0, which is not very good. We can consider it as the error of the model for the first row.
Let's look at the second row. There were 25 customers for whom the churn value was 0. 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 is shows the model's ability to correctly predict or separate the classes.We can interpret these numbers as the count of true positives, false positives, true negatives, and false negatives.
print(classification_report(y_test, yhat))
Based on the count of each section, we can calcualte precision and recall of each label.
- Precision is a measure of the accuracy provided that a class label has been predicted. It is defined by: Precision = TP/(TP+FP)
- Recall is the true positive rate. It is defined as: Recall = TP / (TP+FN)
So we can calculate Precision and Recall for each class.
F1 score is the harmonic average of the precision and recall, where an F1 score reaches its best value at 1 (prefect precision and recall) and worst at 0. It's a good way to show that a classifier has a good value for both recall and precision.
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.
from sklearn.metrics import log_loss
log_loss(y_test, yhat_prob)