Smart Discounts with Logistic Regression | Machine Learning from Scratch (Part I) | by Venelin Valkov | Towards Data Science

TL;DR in this part you will build a Logistic Regression model using Python from scratch. In the process, you will learn about the Gradient descent algorithm and use it to train your model.
Smart Discounts with Logistic RegressionPredicting House Prices with Linear RegressionBuilding a Decision Tree from Scratch in PythonColor palette extraction with K-means clusteringMovie review sentiment analysis with Naive BayesMusic artist Recommender System using Stochastic Gradient DescentFashion product image classification using Neural NetworksBuild a taxi driving agent in a post-apocalyptic world using Reinforcement Learning
Smart Discounts with Logistic Regression
Predicting House Prices with Linear Regression
Building a Decision Tree from Scratch in Python
Color palette extraction with K-means clustering
Movie review sentiment analysis with Naive Bayes
Music artist Recommender System using Stochastic Gradient Descent
Fashion product image classification using Neural Networks
Build a taxi driving agent in a post-apocalyptic world using Reinforcement Learning
Let’s say you’re developing your online clothing store. Some of your customers are already paying full price. Some don’t. You want to create a promotional campaign and offer discount codes to some customers in the hopes that this might increase your sales. But you don’t want to send discounts to customers which are likely to pay full price. How should you pick the customers that will receive discounts?
Complete source code notebook (Google Colaboratory):
colab.research.google.com
You collected some data from your database(s), analytics packages, etc. Here’s what you might’ve come up with:
Let’s load the data into a Pandas data frame:
And have a look at it:
Note — the presented data is a simplification of a real dataset you might have. If your data is really simple, you might try simpler methods.
Logistic regression is used for classification problems when the dependant/target variable is binary. That is, its values are true or false. Logistic regression is one of the most popular and widely used algorithms in practice (see this).
Some problems that can be solved with Logistic regression include:
- Email — deciding if it is spam or not- Online transactions — fraudulent or not- Tumor classification — malignant or benign- Customer upgrade — will the customer buy the premium upgrade or not
We want to predict the outcome of a variable y, such that:
and set 0: negative class (e.g. email is not spam) or 1: positive class (e.g. email is spam).
Linear regression is another very popular model. It works under the assumption that the observed phenomena (your data) are explainable by a straight line.
The response variable y of the Linear regression is not restricted within the [0, 1] interval. That makes it pretty hard to take binary decisions based on its output. Thus, not suitable for our needs.
Given our problem, we want a model that uses 1 variable (predictor) (x_1 -amount_spent) to predict whether or not we should send a discount to the customer.
where the coefficients w_i are parameters of the model. Let the coefficient vector W be:
Then we can represent h_w(x) in a more compact form:
That is the Linear Regression model.
We want to build a model that outputs values that are between 0 and 1, so we want to come up with a hypothesis that satisfies:
For Logistic Regression we want to modify this and introduce another function g:
We’re going to define g as:
where
g is also known as the sigmoid function or the logistic function. After substitution, we end up with:
for our hypothesis.
Intuitively, we’re going to use the sigmoid function “over the” Linear regression model to bound it within [0;+1].
Recall that the sigmoid function is defined as:
Let’s translate it to a Python function:
A graphical representation of the sigmoid function:
It looks familiar, right? Notice how fast it converges to -1 or +1.
Let’s examine some approaches to find good parameters for our model. But what does good mean in this context?
We have a model that we can use to make decisions, but we still have to find the parameters W. To do that, we need an objective measurement of how good a given set of parameters are. For that purpose, we will use a loss (cost) function:
Which is also known as the Log loss or Cross-entropy loss function
We can compress the above function into one:
where
Let’s implement it in Python:
Let’s think of 3 numbers that represent the coefficients w0, w1, w2.
loss: 25.0 predicted: 0.999999999986112 actual: 0.0
Unfortunately, I am pretty lazy, and this approach seems like a bit too much work for me. Let’s go to the next one:
Alright, these days computers are pretty fast, 6+ core laptops are everywhere. Smartphones can be pretty performant, too! Let’s use that power for goodTM and try to find those pesky parameters by just trying out a lot of numbers:
0.0 0.0 0.0 6.661338147750941e-16 9.359180097590508e-141.3887890837434982e-11 2.0611535832696244e-09 3.059022736706331e-07 4.539889921682063e-05 0.006715348489118056 0.6931471805599397 5.006715348489103 10.000045398900186 15.000000305680194 19.999999966169824 24.99999582410784 30.001020555434774 34.945041100449046 inf inf
Amazing, the first parameter value we tried got us a loss of 0. Is it your lucky day or this will always be the case, though? The answer is left as an exercise for the reader :)
Gradient descent algorithms (yes, there are a lot of them) provide us with a way to find a minimum of some function f. They work by iteratively going in the direction of the descent as defined by the gradient.
In Machine Learning, we use gradient descent algorithms to find “good” parameters for our models (Logistic Regression, Linear Regression, Neural Networks, etc...).
How does it work? Starting somewhere, we take our first step downhill in the direction specified by the negative gradient. Next, we recalculate the negative gradient and take another step in the direction it specifies. This process continues until we get to a point where we can no longer move downhill — a local minimum.
Ok, but how can we find that gradient thing? We have to find the derivate of our cost function since our example is rather simple.
The first derivative of the sigmoid function is given by the following equation:
Complete derivation can be found here.
Recall that the cost function was given by the following equation:
Given
We obtain the first derivative of the cost function:
Now that we have the derivate, we can go back to our updating rule and use it there:
The parameter a is known as learning rate. High learning rate can converge quickly, but risks overshooting the lowest point. Low learning rate allows for confident moves in the direction of the negative gradient. However, it time-consuming so it will take us a lot of time to get to converge.
The algorithm we’re going to use works as follows:
Repeat until convergence {  1. Calculate gradient average  2. Multiply by learning rate  3. Subtract from weights}
Let’s do this in Python:
About that until convergence part. You might notice that we kinda brute-force our way around it. That is, we will run the algorithm for a preset amount of iterations. Another interesting point is the initialization of our weights W — initially set at zero.
Let’s put our implementation to the test, literally. But first, we need a function that helps us predict y given some data X (predict whether or not we should send a discount to a customer based on its spending):
Now for our simple test:
Note that we use reshape to add a dummy dimension to X. Further, after our call to predict, we round the results. Recall that the sigmoid function spits out (kinda like a dragon with an upset stomach) numbers in the [0; 1] range. We’re just going to round the result in order to obtain our 0 or 1 (yes or no) answers.
run_tests()
Here is the result of running our test case:
F
Well, that’s not good, after all that hustling we’re nowhere near achieving our goal of finding good parameters for our model. But, what went wrong?
Welcome to your first model debugging session! Let’s start by finding whether our algorithm improves over time. We can use our loss metric for that:
run_tests()
We pretty much copy & pasted our training code except that we’re printing the training loss every 10,000 iterations. Let’s have a look:
loss: 0.6931471805599453 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056loss: 0.41899283818630056F........
Suspiciously enough, we found a possible cause for our problem on the first try! Our loss doesn’t get low enough, in other words, our algorithm gets stuck at some point that is not a good enough minimum for us. How can we fix this? Perhaps, try out different learning rate or initializing our parameter with a different value?
First, a smaller learning rate a :
run_tests()
With a=0.001 we obtain this:
loss: 0.42351356323845546 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056 	loss: 0.41899283818630056F.......
Not so successful, are we? How about adding one more parameter for our model to find/learn?
run_tests()
And for the results:
........---------------------------------------------------------Ran 8 tests in 0.686s  OK
What we did here? We added a new element to our parameter vector W and set it’s initial value to 1. Seems like this turn things into our favor!
Knowing all of the details of the inner workings of the Gradient descent is good, but when solving problems in the wild, we might be hard pressed for time. In those situations, a simple & easy to use interface for fitting a Logistic Regression model might save us a lot of time. So, let’s build one!
But first, let’s write some tests:
run_tests()
We just packed all previously written functions into a tiny class. One huge advantage of this approach is the fact that we hide the complexity of the Gradient descent algorithm and the use of the parameters W.
Now that you’re done with the “hard” part let’s use the model to predict whether or not we should send discount codes.
Let’s recall our initial data:
Now let’s try our model on data obtained from 2 new customers:
Customer 1 - $10Customer 2 - $250
y_test
Recall that 1 means send code and 0 means do not send:
array([1., 0.])
Looks reasonable enough. Care to try out more cases?
You can find complete source code and run the code in your browser here:
colab.research.google.com
Well done! You have a complete (albeit simple) LogisticRegressor implementation that you can play with. Go on, have some fun with it!
Coming up next, you will implement a Linear regression model from scratch :)
Smart Discounts with Logistic RegressionPredicting House Prices with Linear RegressionBuilding a Decision Tree from Scratch in PythonColor palette extraction with K-means clusteringMovie review sentiment analysis with Naive BayesMusic artist Recommender System using Stochastic Gradient DescentFashion product image classification using Neural NetworksBuild a taxi driving agent in a post-apocalyptic world using Reinforcement Learning
Smart Discounts with Logistic Regression
Predicting House Prices with Linear Regression
Building a Decision Tree from Scratch in Python
Color palette extraction with K-means clustering
Movie review sentiment analysis with Naive Bayes
Music artist Recommender System using Stochastic Gradient Descent
Fashion product image classification using Neural Networks
Build a taxi driving agent in a post-apocalyptic world using Reinforcement Learning
Like what you read? Do you want to learn even more about Machine Learning?