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.
We will load the data file then checkout the summary statistics and columns for that file.
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
customer_data = pd.read_csv("Data/browsing.csv")
# After loading the data, we look at the data types to make sure that the data has been loaded correctly.
customer_data.dtypes
SESSION_ID int64 IMAGES int64 REVIEWS int64 FAQ int64 SPECS int64 SHIPPING int64 BOUGHT_TOGETHER int64 COMPARE_SIMILAR int64 VIEW_SIMILAR int64 WARRANTY int64 SPONSORED_LINKS int64 BUY 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.
# View the top records to understand how the data looks like.
customer_data.head()
SESSION_ID | IMAGES | REVIEWS | FAQ | SPECS | SHIPPING | BOUGHT_TOGETHER | COMPARE_SIMILAR | VIEW_SIMILAR | WARRANTY | SPONSORED_LINKS | BUY | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
#Do summary statistics analysis of the data to make sure the data is not skewed in any way.
customer_data.describe()
SESSION_ID | IMAGES | REVIEWS | FAQ | SPECS | SHIPPING | BOUGHT_TOGETHER | COMPARE_SIMILAR | VIEW_SIMILAR | WARRANTY | SPONSORED_LINKS | BUY | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
customer_data.corr()['BUY']
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 SPONSORED_LINKS 0.110328 BUY 1.000000 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.
#Drop columns with low correlation
predictors = customer_data[['REVIEWS','BOUGHT_TOGETHER','COMPARE_SIMILAR','WARRANTY','SPONSORED_LINKS']]
targets = customer_data.BUY
We now split the model into training and testing data in the ratio of 70:30
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)
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.
Disadvantages: Naive Bayes is is known to be a bad estimator.
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)
array([[76, 20], [24, 30]], dtype=int64)
sklearn.metrics.accuracy_score(tar_test, nb_predictions)
0.7066666666666667
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
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.
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)
array([[77, 19], [28, 26]], dtype=int64)
sklearn.metrics.accuracy_score(tar_test, lr_predictions)
0.6866666666666666
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.
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)
array([[84, 12], [35, 19]], dtype=int64)
sklearn.metrics.accuracy_score(tar_test, sgd_predictions)
0.6866666666666666
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
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.
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)
array([[75, 21], [20, 34]], dtype=int64)
sklearn.metrics.accuracy_score(tar_test, knn_predictions)
0.7266666666666667
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
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.
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)
array([[83, 13], [29, 25]], dtype=int64)
sklearn.metrics.accuracy_score(tar_test, dtree_predictions)
0.72
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
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.
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)
array([[74, 22], [23, 31]], dtype=int64)
sklearn.metrics.accuracy_score(tar_test, rf_predictions)
0.7
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
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.
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)
array([[83, 13], [30, 24]], dtype=int64)
#sklearn.metrics.accuracy_score(tar_test, svm_predictions)
scores = cross_val_score(svm, predictors, targets, cv=5)
scores.mean()
0.722
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
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:
pred_prob=nb.predict_proba(pred_test)
pred_prob[0,1]
0.10621579226568478
The probability above can be read as 11% chance that the customer will buy the product.
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
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
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.
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.
Next Topic: How to recommend products to customer based on items affinity?