# Predicting Customer Propensity using Classification Algorithms¶

In this notebook, we will show you how to predict customer propensity to buy the product based on his/her interactions on the website. Using that propensity, if a certain threshold are reached we will then decide whether to assign an agent to offer a chat to the customer. We will also be using different classification algorithms to show how each algorithms are coded.

Because we will only be using sample data for exercise purposes, the data set that we'll be using here are very small (500 rows of data). Thus, we might not get a real accurate predictions out of it.

## Call to Action¶

• Analyse real-time customer's actions on website
• Predict the propensity score
• Offer chat once propensity score exceeds threshold

We will load the data file then checkout the summary statistics and columns for that file.

In [1]:
import pandas as pd
import numpy as np
import os
from sklearn.model_selection  import train_test_split, cross_val_score
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
import sklearn.metrics

# After loading the data, we look at the data types to make sure that the data has been loaded correctly.
customer_data.dtypes

Out[1]:
SESSION_ID         int64
IMAGES             int64
REVIEWS            int64
FAQ                int64
SPECS              int64
SHIPPING           int64
BOUGHT_TOGETHER    int64
COMPARE_SIMILAR    int64
VIEW_SIMILAR       int64
WARRANTY           int64
dtype: object

The data contains information about the various links on the website that are clicked by the user during his browsing. This is past data that will be used to build the model.

• Session ID : A unique identifier for the web browsing session
• Other columns : a boolean indicator to show whether the prospect visited that particular page or did the activity mentioned.
In [2]:
# View the top records to understand how the data looks like.

Out[2]:
0 1001 0 0 1 0 1 0 0 0 1 0 0
1 1002 0 1 1 0 0 0 0 0 0 1 0
2 1003 1 0 1 1 1 0 0 0 1 0 0
3 1004 1 0 0 0 1 1 1 0 0 0 0
4 1005 1 1 1 0 1 0 1 0 0 0 0
In [3]:
#Do summary statistics analysis of the data to make sure the data is not skewed in any way.
customer_data.describe()

Out[3]:
count 500.000000 500.000000 500.0000 500.000000 500.0000 500.000000 500.000000 500.000000 500.000000 500.000000 500.000000 500.000000
mean 1250.500000 0.510000 0.5200 0.440000 0.4800 0.528000 0.500000 0.580000 0.468000 0.532000 0.550000 0.370000
std 144.481833 0.500401 0.5001 0.496884 0.5001 0.499715 0.500501 0.494053 0.499475 0.499475 0.497992 0.483288
min 1001.000000 0.000000 0.0000 0.000000 0.0000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
25% 1125.750000 0.000000 0.0000 0.000000 0.0000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
50% 1250.500000 1.000000 1.0000 0.000000 0.0000 1.000000 0.500000 1.000000 0.000000 1.000000 1.000000 0.000000
75% 1375.250000 1.000000 1.0000 1.000000 1.0000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000
max 1500.000000 1.000000 1.0000 1.000000 1.0000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000

### Perform Correlation Analysis¶

In [4]:
customer_data.corr()['BUY']

Out[4]:
SESSION_ID         0.026677
IMAGES             0.046819
REVIEWS            0.404628
FAQ               -0.095136
SPECS              0.009950
SHIPPING          -0.022239
BOUGHT_TOGETHER   -0.103562
COMPARE_SIMILAR    0.190522
VIEW_SIMILAR      -0.096137
WARRANTY           0.179156
Name: BUY, dtype: float64

Looking at the correlations above we can see that features like REVIEWS, BOUGHT_TOGETHER, COMPARE_SIMILAR, WARRANTY and SPONSORED_LINKS have medium correlation to the target variable. We will reduce our feature set to only those features that have some good correlation.

In [5]:
#Drop columns with low correlation


## Training and Testing Split¶

We now split the model into training and testing data in the ratio of 70:30

In [6]:
pred_train, pred_test, tar_train, tar_test  =   train_test_split(predictors, targets, test_size=.3)

print( "Predictor_Training :", pred_train.shape," | ", "Predictor_Testing :", pred_test.shape )

Predictor_Training : (350, 5)  |  Predictor_Testing : (150, 5)


## Build Model and Check Accuracy¶

Using Naïve Bayes Classifier

Definition: Naïve Bayes algorithm based on Bayes’ theorem with the assumption of independence between every pair of features. Naive Bayes classifiers work well in many real-world situations such as document classification and spam filtering.

Advantages: This algorithm requires a small amount of training data to estimate the necessary parameters. Naive Bayes classifiers are extremely fast compared to more sophisticated methods.

In [7]:
nb = GaussianNB()
nb.fit(pred_train, tar_train)

nb_predictions = nb.predict(pred_test)

#Analyze accuracy of nb predictions
sklearn.metrics.confusion_matrix(tar_test, nb_predictions)

Out[7]:
array([[76, 20],
[24, 30]], dtype=int64)
In [8]:
sklearn.metrics.accuracy_score(tar_test, nb_predictions)

Out[8]:
0.7066666666666667
In [9]:
print(sklearn.metrics.classification_report(tar_test, nb_predictions))

              precision    recall  f1-score   support

0       0.76      0.79      0.78        96
1       0.60      0.56      0.58        54

micro avg       0.71      0.71      0.71       150
macro avg       0.68      0.67      0.68       150
weighted avg       0.70      0.71      0.70       150


Using Logistic Regression Classifier

Definition: Logistic regression is a machine learning algorithm for classification. In this algorithm, the probabilities describing the possible outcomes of a single trial are modelled using a logistic function.

Advantages: Logistic regression is designed for this purpose (classification), and is most useful for understanding the influence of several independent variables on a single outcome variable.

Disadvantages: Works only when the predicted variable is binary, assumes all predictors are independent of each other, and assumes data is free of missing values.

In [10]:
lr = LogisticRegression(solver='liblinear')
lr.fit(pred_train, tar_train)

lr_predictions = lr.predict(pred_test)

#Analyze accuracy of predictions
sklearn.metrics.confusion_matrix(tar_test, lr_predictions)

Out[10]:
array([[77, 19],
[28, 26]], dtype=int64)
In [11]:
sklearn.metrics.accuracy_score(tar_test, lr_predictions)

Out[11]:
0.6866666666666666
In [12]:
print(sklearn.metrics.classification_report(tar_test, lr_predictions))

              precision    recall  f1-score   support

0       0.73      0.80      0.77        96
1       0.58      0.48      0.53        54

micro avg       0.69      0.69      0.69       150
macro avg       0.66      0.64      0.65       150
weighted avg       0.68      0.69      0.68       150



Definition: Stochastic gradient descent is a simple and very efficient approach to fit linear models. It is particularly useful when the number of samples is very large. It supports different loss functions and penalties for classification.

Advantages: Efficiency and ease of implementation.

Disadvantages: Requires a number of hyper-parameters and it is sensitive to feature scaling.

In [13]:
sgd = SGDClassifier(max_iter=1000, shuffle=True, tol=1e-3, random_state=101)
sgd.fit(pred_train, tar_train)

sgd_predictions = sgd.predict(pred_test)

#Analyze accuracy of sgd predictions
sklearn.metrics.confusion_matrix(tar_test, sgd_predictions)

Out[13]:
array([[84, 12],
[35, 19]], dtype=int64)
In [14]:
sklearn.metrics.accuracy_score(tar_test, sgd_predictions)

Out[14]:
0.6866666666666666
In [15]:
print(sklearn.metrics.classification_report(tar_test, sgd_predictions))

              precision    recall  f1-score   support

0       0.71      0.88      0.78        96
1       0.61      0.35      0.45        54

micro avg       0.69      0.69      0.69       150
macro avg       0.66      0.61      0.61       150
weighted avg       0.67      0.69      0.66       150


Using K-Nearest Neighbors Classifier

Definition: Neighbours based classification is a type of lazy learning as it does not attempt to construct a general internal model, but simply stores instances of the training data. Classification is computed from a simple majority vote of the k nearest neighbours of each point.

Advantages: This algorithm is simple to implement, robust to noisy training data, and effective if training data is large.

Disadvantages: Need to determine the value of K and the computation cost is high as it needs to computer the distance of each instance to all the training samples.

In [16]:
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(pred_train, tar_train)

knn_predictions = knn.predict(pred_test)

#Analyze accuracy of knn predictions
sklearn.metrics.confusion_matrix(tar_test, knn_predictions)

Out[16]:
array([[75, 21],
[20, 34]], dtype=int64)
In [17]:
sklearn.metrics.accuracy_score(tar_test, knn_predictions)

Out[17]:
0.7266666666666667
In [18]:
print(sklearn.metrics.classification_report(tar_test, knn_predictions))

              precision    recall  f1-score   support

0       0.79      0.78      0.79        96
1       0.62      0.63      0.62        54

micro avg       0.73      0.73      0.73       150
macro avg       0.70      0.71      0.70       150
weighted avg       0.73      0.73      0.73       150


Using Decision Tree Classifier

Definition: Given a data of attributes together with its classes, a decision tree produces a sequence of rules that can be used to classify the data.

Advantages: Decision Tree is simple to understand and visualise, requires little data preparation, and can handle both numerical and categorical data.

Disadvantages: Decision tree can create complex trees that do not generalise well, and decision trees can be unstable because small variations in the data might result in a completely different tree being generated.

In [19]:
dtree = DecisionTreeClassifier(max_depth=10, min_samples_leaf=15, random_state=101)
dtree.fit(pred_train, tar_train)

dtree_predictions = dtree.predict(pred_test)

#Analyze accuracy of dtree predictions
sklearn.metrics.confusion_matrix(tar_test,dtree_predictions)

Out[19]:
array([[83, 13],
[29, 25]], dtype=int64)
In [20]:
sklearn.metrics.accuracy_score(tar_test, dtree_predictions)

Out[20]:
0.72
In [21]:
print(sklearn.metrics.classification_report(tar_test, dtree_predictions))

              precision    recall  f1-score   support

0       0.74      0.86      0.80        96
1       0.66      0.46      0.54        54

micro avg       0.72      0.72      0.72       150
macro avg       0.70      0.66      0.67       150
weighted avg       0.71      0.72      0.71       150


Using Random Forest Classifier

Definition: Random forest classifier is a meta-estimator that fits a number of decision trees on various sub-samples of datasets and uses average to improve the predictive accuracy of the model and controls over-fitting. The sub-sample size is always the same as the original input sample size but the samples are drawn with replacement.

Advantages: Reduction in over-fitting and random forest classifier is more accurate than decision trees in most cases.

Disadvantages: Slow real time prediction, difficult to implement, and complex algorithm.

In [22]:
rf = RandomForestClassifier(n_estimators=100, oob_score=True, n_jobs=-1,
random_state=101, max_features=None, min_samples_leaf=30)
rf.fit(pred_train, tar_train)

rf_predictions = rf.predict(pred_test)

#Analyze accuracy of rf predictions
sklearn.metrics.confusion_matrix(tar_test, rf_predictions)

Out[22]:
array([[74, 22],
[23, 31]], dtype=int64)
In [23]:
sklearn.metrics.accuracy_score(tar_test, rf_predictions)

Out[23]:
0.7
In [24]:
print(sklearn.metrics.classification_report(tar_test, rf_predictions))

              precision    recall  f1-score   support

0       0.76      0.77      0.77        96
1       0.58      0.57      0.58        54

micro avg       0.70      0.70      0.70       150
macro avg       0.67      0.67      0.67       150
weighted avg       0.70      0.70      0.70       150


Using Support Vector Machine Classifier

Definition: Support vector machine is a representation of the training data as points in space separated into categories by a clear gap that is as wide as possible. New examples are then mapped into that same space and predicted to belong to a category based on which side of the gap they fall.

Advantages: Effective in high dimensional spaces and uses a subset of training points in the decision function so it is also memory efficient.

Disadvantages: The algorithm does not directly provide probability estimates, these are calculated using an expensive five-fold cross-validation.

In [25]:
svm = SVC(C=1, kernel='linear', gamma='auto')
svm.fit(pred_train, tar_train)
svm_predictions = svm.predict(pred_test)

#Analyze accuracy of svm predictions
sklearn.metrics.confusion_matrix(tar_test, svm_predictions)

Out[25]:
array([[83, 13],
[30, 24]], dtype=int64)
In [26]:
#sklearn.metrics.accuracy_score(tar_test, svm_predictions)
scores = cross_val_score(svm, predictors, targets, cv=5)
scores.mean()

Out[26]:
0.722
In [27]:
print(sklearn.metrics.classification_report(tar_test, svm_predictions))

              precision    recall  f1-score   support

0       0.73      0.86      0.79        96
1       0.65      0.44      0.53        54

micro avg       0.71      0.71      0.71       150
macro avg       0.69      0.65      0.66       150
weighted avg       0.70      0.71      0.70       150



## Using probability as propensity score¶

Instead of doing a Yes/No prediction, we want to predict the probability of somebody who wants to buy, and we can do that by using a method called predict_proba.

Let's say we use NB model:

In [28]:
pred_prob=nb.predict_proba(pred_test)
pred_prob[0,1]

Out[28]:
0.10621579226568478

The probability above can be read as 11% chance that the customer will buy the product.

## Real time predictions¶

From the models we examine, let's say the best model to use for our real time prediction is the Naive Bayes.

So when the customer starts visiting the pages one by one, we collect that list and then use it to compute the probability. We do that for every new click that comes in.

So let us start. The prospect just came to your website. There are no significant clicks. Let us compute the probability. The array of values passed has the values for REVIEWS, BOUGHT_TOGETHER, COMPARE_SIMILAR, WARRANTY and SPONSORED_LINKS. So the array is all zeros to begin with

In [29]:
browsing_data = np.array([0,0,0,0,0]).reshape(1, -1)
print("New visitor: propensity :", nb.predict_proba(browsing_data)[:,1] )

New visitor: propensity : [0.04544815]


So the initial probability is 5%. Now, suppose the customer does a comparison of similar products. The array changes to include a 1 for that function. The new probability will be

In [30]:
browsing_data = np.array([0,0,1,0,0]).reshape(1, -1)
print("After checking similar products: propensity :", nb.predict_proba(browsing_data)[:,1] )

After checking similar products: propensity : [0.1082966]


It goes up. Next, he checks out reviews.

In [31]:
browsing_data = np.array([1,0,1,0,0]).reshape(1, -1)
print("After checking reviews: propensity :", nb.predict_proba(browsing_data)[:,1] )

After checking reviews: propensity : [0.5612052]


It shoots up to 50+%. You can have a threshold for when you want to offer chat. You can keep checking this probability against that threshold to see if you want to popup a chat window.

This example shows you how you can use predictive analytics in real time to decide whether a customer has high propensity to convert and offer him a chat with a sales rep/agent.

## References:¶

Next Topic: How to recommend products to customer based on items affinity?