Predict Ads Click – Practice Data Analysis and Logistic Regression Prediction

Machine Learning Project for Predict Ads Click based on the available attributes

Problem Statement or Business Problem

In this project we will be working with a data set, indicating whether or not a particular internet user clicked on an Advertisement. We will try to create a model that will predict whether or not they will click on an ad based off the features of that user.

Attribute Information or Dataset Details:

  1. ‘Daily Time Spent on Site’: consumer time on site in minutes
  2. ‘Age’: cutomer age in years
  3. ‘Area Income’: Avg. Income of geographical area of consumer
  4. ‘Daily Internet Usage’: Avg. minutes a day consumer is on the internet
  5. ‘Ad Topic Line’: Headline of the advertisement
  6. ‘City’: City of consumer
  7. ‘Male’: Whether or not consumer was male
  8. ‘Country’: Country of consumer
  9. ‘Timestamp’: Time at which consumer clicked on Ad or closed window
  10. ‘Clicked on Ad’: 0 or 1 indicated clicking on Ad

Technology Used

  1. Apache Spark
  2. Spark SQL
  3. Apache Spark MLLib
  4. Scala
  5. DataFrame-based API
  6. Databricks Notebook

Introduction

Welcome to this project on predict Ads Click in Apache Spark Machine Learning using Databricks platform community edition server which allows you to execute your spark code, free of cost on their server just by registering through email id.

In this project, we explore Apache Spark and Machine Learning on the Databricks platform.

I am a firm believer that the best way to learn is by doing. That’s why I haven’t included any purely theoretical lectures in this tutorial: you will learn everything on the way and be able to put it into practice straight away. Seeing the way each feature works will help you learn Apache Spark machine learning thoroughly by heart.

We’re going to look at how to set up a Spark Cluster and get started with that. And we’ll look at how we can then use that Spark Cluster to take data coming into that Spark Cluster, a process that data using a Machine Learning model, and generate some sort of output in the form of a prediction. That’s pretty much what we’re going to learn about the predictive model.

In this project, we will be performing predict Ads Click using a Logistic Regression algorithm.

We will learn:

  1. Preparing the Data for Processing.
  2. Basics flow of data in Apache Spark, loading data, and working with data, this course shows you how Apache Spark is perfect for a Machine Learning job.
  3. Learn the basics of Databricks notebook by enrolling in Free Community Edition Server
  4. Define the Machine Learning Pipeline
  5. Train a Machine Learning Model
  6. Testing a Machine Learning Model
  7. Evaluating a Machine Learning Model (i.e. Examine the Predicted and Actual Values)

The goal is to provide you with practical tools that will be beneficial for you in the future. While doing that, you’ll develop a model with a real use opportunity.

I am really excited you are here, I hope you are going to follow all the way to the end of the Project. It is fairly straight forward fairly easy to follow through the article we will show you step by step each line of code & we will explain what it does and why we are doing it.

Free Account creation in Databricks

Creating a Spark Cluster

Basics about Databricks notebook

Loading Data into Databricks Environment

Load Data in Dataframe

%scala

val csv = spark.read.option("inferSchema","true").option("header", "true").csv("/FileStore/tables/advertising-1.csv")

csv.show()

Output:

+--------------------+---+----------+------------------+--------------------+-----------------+----+--------------------+-------------------+-----------+
|DailyTimeSpentonSite|Age|AreaIncome|DailyInternetUsage|         AdTopicLine|             City|Male|             Country|          Timestamp|ClickedonAd|
+--------------------+---+----------+------------------+--------------------+-----------------+----+--------------------+-------------------+-----------+
|               68.95| 35|   61833.9|            256.09|Cloned 5thgenerat...|      Wrightburgh|   0|             Tunisia|2016-03-27 00:53:11|          0|
|               80.23| 31|  68441.85|            193.77|Monitored nationa...|        West Jodi|   1|               Nauru|2016-04-04 01:39:02|          0|
|               69.47| 26|  59785.94|             236.5|Organic bottom-li...|         Davidton|   0|          San Marino|2016-03-13 20:35:42|          0|
|               74.15| 29|  54806.18|            245.89|Triple-buffered r...|   West Terrifurt|   1|               Italy|2016-01-10 02:31:19|          0|
|               68.37| 35|  73889.99|            225.58|Robust logistical...|     South Manuel|   0|             Iceland|2016-06-03 03:36:18|          0|
|               59.99| 23|  59761.56|            226.74|Sharable client-d...|        Jamieberg|   1|              Norway|2016-05-19 14:30:17|          0|
|               88.91| 33|  53852.85|            208.36|Enhanced dedicate...|      Brandonstad|   0|             Myanmar|2016-01-28 20:59:32|          0|
|                66.0| 48|  24593.33|            131.76|Reactive local ch...| Port Jefferybury|   1|           Australia|2016-03-07 01:40:15|          1|
|               74.53| 30|   68862.0|            221.51|Configurable cohe...|       West Colin|   1|             Grenada|2016-04-18 09:33:42|          0|
|               69.88| 20|  55642.32|            183.82|Mandatory homogen...|       Ramirezton|   1|               Ghana|2016-07-11 01:42:51|          0|
|               47.64| 49|  45632.51|            122.02|Centralized neutr...|  West Brandonton|   0|               Qatar|2016-03-16 20:19:01|          1|
|               83.07| 37|  62491.01|            230.87|Team-oriented gri...|East Theresashire|   1|             Burundi|2016-05-08 08:10:10|          0|
|               69.57| 48|  51636.92|            113.12|Centralized conte...|   West Katiefurt|   1|               Egypt|2016-06-03 01:14:41|          1|
|               79.52| 24|  51739.63|            214.23|Synergistic fresh...|       North Tara|   0|Bosnia and Herzeg...|2016-04-20 21:49:22|          0|
|               42.95| 33|   30976.0|            143.56|Grass-roots coher...|     West William|   0|            Barbados|2016-03-24 09:31:49|          1|
|               63.45| 23|  52182.23|            140.64|Persistent demand...|   New Travistown|   1|               Spain|2016-03-09 03:41:30|          1|
|               55.39| 37|  23936.86|            129.41|Customizable mult...|   West Dylanberg|   0|Palestinian Terri...|2016-01-30 19:20:41|          1|
|               82.03| 41|  71511.08|            187.53|Intuitive dynamic...|      Pruittmouth|   0|         Afghanistan|2016-05-02 07:00:58|          0|
|                54.7| 36|  31087.54|            118.39|Grass-roots solut...|      Jessicastad|   1|British Indian Oc...|2016-02-13 07:53:55|          1|
|               74.58| 40|  23821.72|            135.51|Advanced 24/7 pro...|       Millertown|   1|  Russian Federation|2016-02-27 04:43:07|          1|
+--------------------+---+----------+------------------+--------------------+-----------------+----+--------------------+-------------------+-----------+
only showing top 20 rows

Print Schema

%scala

csv.printSchema()

Output:

root
 |-- DailyTimeSpentonSite: double (nullable = true)
 |-- Age: integer (nullable = true)
 |-- AreaIncome: double (nullable = true)
 |-- DailyInternetUsage: double (nullable = true)
 |-- AdTopicLine: string (nullable = true)
 |-- City: string (nullable = true)
 |-- Male: integer (nullable = true)
 |-- Country: string (nullable = true)
 |-- Timestamp: string (nullable = true)
 |-- ClickedonAd: integer (nullable = true)

Statistics of Data

%scala

csv.select("DailyTimeSpentonSite", "Age", "AreaIncome", "DailyInternetUsage", "AdTopicLine", "City", "Male", "Country", "Timestamp", "ClickedonAd" ).describe().show()

Output:

+-------+--------------------+-----------------+------------------+------------------+--------------------+----------+-------------------+-----------+-------------------+------------------+
|summary|DailyTimeSpentonSite|              Age|        AreaIncome|DailyInternetUsage|         AdTopicLine|      City|               Male|    Country|          Timestamp|       ClickedonAd|
+-------+--------------------+-----------------+------------------+------------------+--------------------+----------+-------------------+-----------+-------------------+------------------+
|  count|                1000|             1000|              1000|              1000|                1000|      1000|               1000|       1000|               1000|              1000|
|   mean|   65.00020000000012|           36.009| 55000.00008000003|180.00010000000003|                null|      null|              0.481|       null|               null|               0.5|
| stddev|  15.853614567500212|8.785562310125924|13414.634022282358|  43.9023393019801|                null|      null|0.49988887654046543|       null|               null|0.5002501876563867|
|    min|                32.6|               19|           13996.5|            104.78|Adaptive 24hour G...| Adamsbury|                  0|Afghanistan|2016-01-01 02:52:10|                 0|
|    max|               91.43|               61|           79484.8|            269.96|Visionary recipro...|Zacharyton|                  1|   Zimbabwe|2016-07-24 00:22:16|                 1|
+-------+--------------------+-----------------+------------------+------------------+--------------------+----------+-------------------+-----------+-------------------+------------------+

Create Temporary View so we can perform Spark SQL on Data

%scala

csv.createOrReplaceTempView("AdsData");

Spark SQL

%sql

select * from AdsData;

Exploratory Data Analysis or EDA​

One Visualization to Rule Them All​

%sql

select * from AdsData

Histogram for Age​

%sql

select Age from AdsData

Scatter Plot for Age and Area Income

Scatter Plot for Age and Daily Time Spent on Site

Collecting all String Columns into an Array

%scala

var StringfeatureCol = Array("AdTopicLine", "City", "Country", "Timestamp");

StringIndexer encodes a string column of labels to a column of label indices.

Example of StringIndexer

%scala

import org.apache.spark.ml.feature.StringIndexer

val df = spark.createDataFrame(
  Seq((0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c"))
).toDF("id", "category")

df.show()

val indexer = new StringIndexer()
  .setInputCol("category")
  .setOutputCol("categoryIndex")

val indexed = indexer.fit(df).transform(df)

indexed.show()

Output:

+---+--------+
| id|category|
+---+--------+
|  0|       a|
|  1|       b|
|  2|       c|
|  3|       a|
|  4|       a|
|  5|       c|
+---+--------+

+---+--------+-------------+
| id|category|categoryIndex|
+---+--------+-------------+
|  0|       a|          0.0|
|  1|       b|          2.0|
|  2|       c|          1.0|
|  3|       a|          0.0|
|  4|       a|          0.0|
|  5|       c|          1.0|
+---+--------+-------------+

Define the Pipeline​

A predictive model often requires multiple stages of feature preparation.

A pipeline consists of a series of transformer and estimator stages that typically prepare a DataFrame for modeling and then train a predictive model.

In this case, you will create a pipeline with stages:

  1. A StringIndexer estimator that converts string values to indexes for categorical features
  2. A VectorAssembler that combines categorical features into a single vector
%scala

import org.apache.spark.ml.attribute.Attribute
import org.apache.spark.ml.feature.{IndexToString, StringIndexer}
import org.apache.spark.ml.{Pipeline, PipelineModel}

val indexers = StringfeatureCol.map { colName =>
  new StringIndexer().setInputCol(colName).setHandleInvalid("skip").setOutputCol(colName + "_indexed")
}

val pipeline = new Pipeline()
                    .setStages(indexers)      

val AdsFinalDF = pipeline.fit(csv).transform(csv)

Print Schema to view String Columns are converted in to equivalent Numerical Columns

%scala

AdsFinalDF.printSchema()

Output:

root
 |-- DailyTimeSpentonSite: double (nullable = true)
 |-- Age: integer (nullable = true)
 |-- AreaIncome: double (nullable = true)
 |-- DailyInternetUsage: double (nullable = true)
 |-- AdTopicLine: string (nullable = true)
 |-- City: string (nullable = true)
 |-- Male: integer (nullable = true)
 |-- Country: string (nullable = true)
 |-- Timestamp: string (nullable = true)
 |-- ClickedonAd: integer (nullable = true)
 |-- AdTopicLine_indexed: double (nullable = false)
 |-- City_indexed: double (nullable = false)
 |-- Country_indexed: double (nullable = false)
 |-- Timestamp_indexed: double (nullable = false)

Display Data

Split the Data

It is common practice when building machine learning models to split the source data, using some of it to train the model and reserving some to test the trained model. In this project, you will use 70% of the data for training, and reserve 30% for testing.

%scala

val splits = AdsFinalDF.randomSplit(Array(0.7, 0.3))
val train = splits(0)
val test = splits(1)
val train_rows = train.count()
val test_rows = test.count()
println("Training Rows: " + train_rows + " Testing Rows: " + test_rows)

Prepare the Training Data

To train the Classification model, you need a training data set that includes a vector of numeric features, and a label column. In this project, you will use the VectorAssembler class to transform the feature columns into a vector, and then rename the ClickedonAd column to the label.

VectorAssembler()

VectorAssembler(): is a transformer that combines a given list of columns into a single vector column. It is useful for combining raw features and features generated by different feature transformers into a single feature vector, in order to train ML models like logistic regression and decision trees.

VectorAssembler accepts the following input column types: all numeric types, boolean type, and vector type.

In each row, the values of the input columns will be concatenated into a vector in the specified order.

%scala

import org.apache.spark.ml.feature.VectorAssembler

val assembler = new VectorAssembler().setInputCols(Array("DailyTimeSpentonSite", "Age", "AreaIncome", "DailyInternetUsage", "AdTopicLine_indexed", "City_indexed", "Male", "Country_indexed", "Timestamp_indexed")).setOutputCol("features")

val training = assembler.transform(train).select($"features", $"ClickedonAd".alias("label"))

training.show(false)

Output:

+--------------------------------------------------------+-----+
|features                                                |label|
+--------------------------------------------------------+-----+
|[32.6,38.0,40159.2,190.05,154.0,855.0,0.0,182.0,205.0]  |1    |
|[32.84,40.0,41232.89,171.72,896.0,523.0,0.0,186.0,349.0]|1    |
|[32.99,45.0,49282.87,177.46,600.0,459.0,0.0,76.0,609.0] |1    |
|[33.33,45.0,53350.11,193.58,635.0,199.0,1.0,200.0,87.0] |1    |
|[33.52,43.0,42191.61,165.56,989.0,322.0,0.0,16.0,650.0] |1    |
|[34.04,34.0,40182.84,174.88,750.0,221.0,1.0,33.0,237.0] |1    |
|[34.3,41.0,53167.68,160.74,702.0,919.0,1.0,125.0,674.0] |1    |
|[34.66,32.0,48246.6,194.83,144.0,131.0,0.0,47.0,955.0]  |1    |
|[34.78,48.0,42861.42,208.21,255.0,313.0,1.0,10.0,421.0] |1    |
|[34.86,38.0,49942.66,154.75,626.0,910.0,0.0,64.0,839.0] |1    |
|[34.96,42.0,36913.51,160.49,757.0,903.0,1.0,204.0,761.0]|1    |
|[35.0,40.0,46033.73,151.25,324.0,827.0,1.0,47.0,836.0]  |1    |
|[35.25,50.0,47051.02,194.44,416.0,866.0,0.0,84.0,12.0]  |1    |
|[35.33,32.0,51510.18,200.22,575.0,68.0,0.0,99.0,780.0]  |1    |
|[35.34,45.0,46693.76,152.86,165.0,165.0,0.0,21.0,837.0] |1    |
|[35.49,47.0,36884.23,170.04,300.0,573.0,0.0,41.0,521.0] |1    |
|[35.49,48.0,43974.49,159.77,329.0,844.0,0.0,61.0,503.0] |1    |
|[35.55,39.0,51593.46,151.18,767.0,948.0,0.0,7.0,69.0]   |1    |
|[35.65,40.0,31265.75,172.58,779.0,589.0,1.0,114.0,652.0]|1    |
|[35.66,36.0,59240.24,172.57,390.0,39.0,0.0,56.0,264.0]  |1    |
+--------------------------------------------------------+-----+
only showing top 20 rows

Train a Classification Model

Next, you need to train a Classification model using the training data. To do this, create an instance of the LogisticRegression algorithm you want to use and use its fit method to train a model based on the training DataFrame. In this project, you will use a Logistic Regression Classifier algorithm – though you can use the same technique for any of the regression algorithms supported in the spark.ml API

%scala
import org.apache.spark.ml.classification.LogisticRegression

val lr = new LogisticRegression().setLabelCol("label").setFeaturesCol("features").setMaxIter(10).setRegParam(0.3)
val model = lr.fit(training)
println ("Model trained!")

Prepare the Testing Data

Now that you have a trained model, you can test it using the testing data you reserved previously. First, you need to prepare the testing data in the same way as you did the training data by transforming the feature columns into a vector. This time you’ll rename the ClickedonAd column to trueLabel.

%scala

val testing = assembler.transform(test).select($"features", $"ClickedonAd".alias("trueLabel"))
testing.show(false)

Output:

+--------------------------------------------------------+---------+
|features                                                |trueLabel|
+--------------------------------------------------------+---------+
|[32.6,45.0,48206.04,185.47,494.0,509.0,0.0,44.0,618.0]  |1        |
|[32.91,37.0,51691.55,181.02,350.0,222.0,0.0,10.0,968.0] |1        |
|[33.21,43.0,42650.32,167.07,615.0,951.0,1.0,11.0,655.0] |1        |
|[34.87,40.0,59621.02,200.23,116.0,143.0,0.0,0.0,807.0]  |1        |
|[35.11,35.0,47638.3,158.03,268.0,590.0,1.0,25.0,360.0]  |1        |
|[35.21,39.0,52340.1,154.0,9.0,549.0,1.0,144.0,431.0]    |1        |
|[35.61,46.0,51868.85,158.22,928.0,605.0,0.0,77.0,448.0] |1        |
|[35.98,45.0,43241.88,150.79,306.0,293.0,0.0,18.0,882.0] |1        |
|[35.98,47.0,55993.68,165.52,287.0,904.0,1.0,33.0,353.0] |1        |
|[36.37,40.0,47338.94,144.53,699.0,587.0,1.0,229.0,566.0]|1        |
|[36.49,52.0,42136.33,196.61,521.0,753.0,1.0,123.0,342.0]|1        |
|[36.56,29.0,42838.29,195.89,872.0,934.0,0.0,143.0,4.0]  |1        |
|[36.87,36.0,29398.61,195.91,796.0,537.0,0.0,25.0,127.0] |1        |
|[37.0,48.0,36782.38,158.22,333.0,335.0,1.0,122.0,424.0] |1        |
|[37.74,40.0,65773.49,190.95,64.0,8.0,0.0,153.0,730.0]   |1        |
|[38.46,42.0,58183.04,145.98,151.0,190.0,1.0,118.0,490.0]|1        |
|[38.52,38.0,42581.23,137.28,136.0,438.0,1.0,53.0,446.0] |1        |
|[38.63,48.0,57777.11,222.11,131.0,103.0,0.0,91.0,497.0] |1        |
|[38.65,31.0,51812.71,154.77,890.0,19.0,1.0,161.0,705.0] |1        |
|[39.36,29.0,52462.04,161.79,451.0,320.0,1.0,13.0,75.0]  |1        |
+--------------------------------------------------------+---------+
only showing top 20 rows

Test the Model

Now you’re ready to use the transform method of the model to generate some predictions. You can use this approach to predict the ClickedonAd; but in this case, you are using the test data which includes a known true label value, so you can compare the ClickedonAd

%scala

val prediction = model.transform(testing)
val predicted = prediction.select("features", "prediction", "probability", "trueLabel")
predicted.show()

Output:

+--------------------+----------+--------------------+---------+
|            features|prediction|         probability|trueLabel|
+--------------------+----------+--------------------+---------+
|[32.6,45.0,48206....|       1.0|[0.20811025881326...|        1|
|[32.91,37.0,51691...|       1.0|[0.31956141319863...|        1|
|[33.21,43.0,42650...|       1.0|[0.18307568886620...|        1|
|[34.87,40.0,59621...|       1.0|[0.41415274834976...|        1|
|[35.11,35.0,47638...|       1.0|[0.28115981773569...|        1|
|[35.21,39.0,52340...|       1.0|[0.21347568191581...|        1|
|[35.61,46.0,51868...|       1.0|[0.12907250010859...|        1|
|[35.98,45.0,43241...|       1.0|[0.16776868120973...|        1|
|[35.98,47.0,55993...|       1.0|[0.20199999995847...|        1|
|[36.37,40.0,47338...|       1.0|[0.11657537074460...|        1|
|[36.49,52.0,42136...|       1.0|[0.15971239043603...|        1|
|[36.56,29.0,42838...|       1.0|[0.31450520128951...|        1|
|[36.87,36.0,29398...|       1.0|[0.28235382047653...|        1|
|[37.0,48.0,36782....|       1.0|[0.12884550143574...|        1|
|[37.74,40.0,65773...|       1.0|[0.34479248000343...|        1|
|[38.46,42.0,58183...|       1.0|[0.20520380530337...|        1|
|[38.52,38.0,42581...|       1.0|[0.20946291415944...|        1|
|[38.63,48.0,57777...|       1.0|[0.35839240587673...|        1|
|[38.65,31.0,51812...|       1.0|[0.23955858546733...|        1|
|[39.36,29.0,52462...|       1.0|[0.39786637605094...|        1|
|[39.86,28.0,51171...|       1.0|[0.35952660017466...|        1|
|[39.94,41.0,64927...|       1.0|[0.20218646470646...|        1|
|[39.96,35.0,53898...|       1.0|[0.17460080310886...|        1|
|[40.17,26.0,47391...|       1.0|[0.32835094263083...|        1|
|[41.16,49.0,59448...|       1.0|[0.21348805216437...|        1|
|[41.28,50.0,50960...|       1.0|[0.09718229289735...|        1|
|[41.39,41.0,68962...|       1.0|[0.27950647178205...|        1|
|[41.49,53.0,31947...|       1.0|[0.13502296292156...|        1|
|[41.67,36.0,53817...|       1.0|[0.16854964990851...|        1|
|[41.84,49.0,37605...|       1.0|[0.12554085595612...|        1|
|[41.86,39.0,53041...|       1.0|[0.20764016781652...|        1|
|[42.06,34.0,43241...|       1.0|[0.21803531503911...|        1|
|[42.95,33.0,30976...|       1.0|[0.22505498087169...|        1|
|[43.16,35.0,25371...|       1.0|[0.18659800608425...|        1|
|[43.49,47.0,50335...|       1.0|[0.10843231478770...|        1|
|[43.67,31.0,25686...|       1.0|[0.30562188129436...|        1|
|[43.77,52.0,49030...|       1.0|[0.08333808436416...|        1|
|[43.83,45.0,35684...|       1.0|[0.09101458352672...|        1|
|[43.84,36.0,70592...|       1.0|[0.37924930280019...|        1|
|[44.11,41.0,43111...|       1.0|[0.15881127452131...|        1|
|[44.33,37.0,52723...|       1.0|[0.13652823946037...|        1|

Evaluating a Model (We got 93% Accuracy)

%scala

import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator


val evaluator = new MulticlassClassificationEvaluator()
  .setLabelCol("trueLabel")
  .setPredictionCol("prediction")
  .setMetricName("accuracy")
val accuracy = evaluator.evaluate(prediction)

Output:
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
evaluator: org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator = MulticlassClassificationEvaluator: uid=mcEval_ebd948da765b, metricName=accuracy, metricLabel=0.0, beta=1.0, eps=1.0E-15
accuracy: Double = 0.9377049180327869
val tp = predicted.filter("prediction == 1 AND truelabel == 1").count().toFloat
val fp = predicted.filter("prediction == 1 AND truelabel == 0").count().toFloat
val tn = predicted.filter("prediction == 0 AND truelabel == 0").count().toFloat
val fn = predicted.filter("prediction == 0 AND truelabel == 1").count().toFloat
val metrics = spark.createDataFrame(Seq(
 ("TP", tp),
 ("FP", fp),
 ("TN", tn),
 ("FN", fn),
 ("Precision", tp / (tp + fp)),
 ("Recall", tp / (tp + fn)))).toDF("metric", "value")
metrics.show()

Output:

+---------+----------+
|   metric|     value|
+---------+----------+
|       TP|     136.0|
|       FP|       4.0|
|       TN|     150.0|
|       FN|      15.0|
|Precision| 0.9714286|
|   Recall|0.90066224|
+---------+----------+

tp: Float = 136.0
fp: Float = 4.0
tn: Float = 150.0
fn: Float = 15.0
By Bhavesh