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.

- 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
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
```

Out[1]:

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
- Buy : Whether the prospect ended up buying the product
- 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.
customer_data.head()
```

Out[2]:

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]:

In [4]:

```
customer_data.corr()['BUY']
```

Out[4]:

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
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

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 )
```

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.

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]:

In [8]:

```
sklearn.metrics.accuracy_score(tar_test, nb_predictions)
```

Out[8]:

In [9]:

```
print(sklearn.metrics.classification_report(tar_test, nb_predictions))
```

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]:

In [11]:

```
sklearn.metrics.accuracy_score(tar_test, lr_predictions)
```

Out[11]:

In [12]:

```
print(sklearn.metrics.classification_report(tar_test, lr_predictions))
```

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]:

In [14]:

```
sklearn.metrics.accuracy_score(tar_test, sgd_predictions)
```

Out[14]:

In [15]:

```
print(sklearn.metrics.classification_report(tar_test, sgd_predictions))
```

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]:

In [17]:

```
sklearn.metrics.accuracy_score(tar_test, knn_predictions)
```

Out[17]:

In [18]:

```
print(sklearn.metrics.classification_report(tar_test, knn_predictions))
```

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]:

In [20]:

```
sklearn.metrics.accuracy_score(tar_test, dtree_predictions)
```

Out[20]:

In [21]:

```
print(sklearn.metrics.classification_report(tar_test, dtree_predictions))
```

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]:

In [23]:

```
sklearn.metrics.accuracy_score(tar_test, rf_predictions)
```

Out[23]:

In [24]:

```
print(sklearn.metrics.classification_report(tar_test, rf_predictions))
```

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]:

In [26]:

```
#sklearn.metrics.accuracy_score(tar_test, svm_predictions)
scores = cross_val_score(svm, predictors, targets, cv=5)
scores.mean()
```

Out[26]:

In [27]:

```
print(sklearn.metrics.classification_report(tar_test, svm_predictions))
```

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]:

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

In [29]:

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

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] )
```

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] )
```

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.

- Ponnambalam, K. (2017, July 3). Predictive customer analytics. Retrieved from https://www.linkedin.com/learning/predictive-customer-analytics
- Garg, R. (2018, January 19). 7 types of classification algorithms. Retrieved May 5, 2019 from https://www.analyticsindiamag.com/7-types-classification-algorithms/
- Scikit Learn. (2018). API reference. Retrieved May 4, 2019 from https://scikit-learn.org/stable/modules/classes.html

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