443-970-2353
[email protected]
CV Resume
Logistic regression predicts the probability of the outcome being true. In this exercise, we will implement logistic regression and apply it to two different datasets.
The data is from the famous Machine Learning Coursera Course by Andrew Ng. The lab exercises in that course are in Octave/Matlab. I am planning to do all the programming exercises in that course with R. So far, I have done linear regression and anomaly detection.
The file ex2data1.txt contains the dataset for the first part of the exercise and ex2data2.txt is data that we will use in the second part of the exercise.
In the first part of this exercise, we will build a logistic regression model to predict whether a student gets admitted into a university. Suppose that you are the administrator of a university department and you want to determine each applicant's chance of admission based on their results on two exams. You have historical data from previous applicants that you can use as a training set for logistic regression. For each training example, you have the applicant's scores on two exams and the admissions decision.
Our task is to build a classification model that estimates an applicant's probability of admission based the scores from those two exams.
library(ggplot2)
library(data.table)
library(magrittr)
library(caret)
The first two columns contains the exam scores and the third column contains the label.
ex2data1 <- fread("ex2data1.txt",col.names=c("Exam1","Exam2","Label"))
head(ex2data1)
Before starting to implement any learning algorithm, it is always good to visualize the data if possible.
cols <- c("0" = "red","1" = "blue")
ex2data1%>%ggplot(aes(x=Exam1,y=Exam2,color=factor(Label)))+geom_point(size = 4, shape = 19,alpha=0.6)+
scale_colour_manual(values = cols,labels = c("Not admitted", "Admitted"),name="Admission Status")
Logistic Regression hypothesis is defined as:
$$h_\theta(x)=g(\theta^Tx)$$where function g is the sigmoid function, which is defined as below: $$g(z)=\frac{1}{1+e^{-z}}$$
Let's code the sigmoid function so that we can call it in the rest of our programs.
my_sigmoid=function(z){
1/(1+exp(-z))
}
For large positive values of x, the sigmoid should be close to 1, while for large negative values, the sigmoid should be close to 0. Evaluating sigmoid(0) should give exactly 0.5.
Let's check!
my_sigmoid(0)
my_sigmoid(10^10)
my_sigmoid(-10^10)
We can visualize the sigmoid function graphycally:
x=seq(-10,10, by=0.1)
y=my_sigmoid(x)
plot(x,y,type="l",col="red",xlab="",ylab="",main="Sigmoid function (Logistic curve)")
abline(v=0,lty = 2,col="gray 70")
abline(h=0.5,lty = 2,col="gray70")
The cost function in logistic regression is given by:
$$ J(\theta)=\frac{1}{m}\sum\limits_{i=1}^{m}[-y^{(i)}log(h_\theta(x^{(i)}))-(1-y^{(i)})log(1-h_\theta(x^{(i)}))] $$and the gradient of the cost is a vector of the same length as $\theta$ where the $j^{th}$ element (for j = 0, 1, ..., n) is defined as follows:
$$\frac{\partial J(\theta)}{\partial \theta_j} = \frac{1}{m}\sum\limits_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})x_j^{(i)} $$Note that while this gradient looks identical to the linear regression gradient, the formula is actually different because linear and logistic regression have different definitions of $h_\theta(x)$.
Add ones for the intercept term:
y=ex2data1$Label
X=cbind(1,ex2data1$Exam1,ex2data1$Exam2)
head(X)
Initialize fitting parameters:
initial_theta =matrix(rep(0,ncol(X)))
The function below calculates cost.
my_cost=function(theta, X, y){
cost_gradient=list()
# cost_and_gradient compute cost and gradient for logistic regression using theta
h_theta= my_sigmoid(X%*%theta)
cost= 1/nrow(X)*sum(-y*log(h_theta)-(1-y)*log(1-h_theta))
return(cost)
}
What is the cost for the initial theta parameters, which are all zeros?
round(my_cost(initial_theta, X, y),3)
The function below calculates gradient.
my_gradient=function(theta, X, y){
h_theta= my_sigmoid(X%*%theta)
## OPTION 1-- looping
# gradient=rep(0,ncol(X))
# for(j in 1:ncol(X)){
# for(i in 1:nrow(X)){
# gradient[j]=gradient[j]+1/nrow(X)*(my_sigmoid(X[i,]%*%theta)-y[i])*X[i,j]
# }
# }
# option2-more succint
gradient= 1/nrow(X)*(my_sigmoid(t(theta)%*%t(X))-t(y))%*%X
return(gradient)
}
The gradient for the initial theta parameters, which are all zeros, is shown below
round(my_gradient(initial_theta, X, y),3)
We can use gradient descent to get the optimal theta values but using optimazation libraries converges quicker. So, let's use the optim general-purpose Optimization in R to get the required theta values and the associated cost.
optimized=optim(par=initial_theta,X=X,y=y,fn=my_cost,gr=my_gradient)
names(optimized)
cat("The optimized theta values are: ")
round(optimized$par,3)
cat('The cost at the final theta values is: ')
round(optimized$value,3)
Now, let's plot the decision bounday Only 2 points are required to define a line, so let's choose two endpoints.
plot_x = c(min(ex2data1$Exam1)-2,max(ex2data1$Exam1)+2)
# Calculate the decision boundary line
plot_y = (-1/optimized$par[3])*(optimized$par[2]*plot_x+optimized$par[1])
## Calculate slope and intercept
slope =(plot_y[2]-plot_y[1])/(plot_x[2]-plot_x[1])
intercept=plot_y[2]-slope*plot_x[2]
cols <- c("0" = "red","1" = "blue")
ex2data1%>%ggplot(aes(x=Exam1,y=Exam2,color=factor(Label)))+geom_point(size = 4, shape = 19,alpha=0.6)+
scale_colour_manual(values = cols,labels = c("Not admitted", "Admitted"),name="Admission Status")+
geom_abline(intercept = intercept, slope = slope,col="purple",show.legend=TRUE)
After learning the parameters, you can use the model to predict whether a particular student will be admitted. For example, for a student with an Exam 1 score of 45 and an Exam 2 score of 85, the probability of admission is shown below.
round(my_sigmoid(c(1,45,85)%*%optimized$par),3)
Now, let's calculate the model accuracy. Let's use a threshould of 0.5.
ex2data1$fitted_result=my_sigmoid(X%*%optimized$par)
ex2data1$fitted_result_label=ifelse(ex2data1$fitted_result>=0.5,1,0)
head(ex2data1)
accuracy=sum(ex2data1$Label==ex2data1$fitted_result_label)/(nrow(ex2data1))
accuracy
In this part of the exercise, we will implement regularized logistic regression to predict whether microchips from a fabrication plant passes quality assurance (QA). During QA, each microchip goes through various tests to ensure it is functioning correctly. Suppose you are the product manager of the factory and you have the test results for some microchips on two diffeerent tests. From these two tests, you would like to determine whether the microchips should be accepted or rejected.
ex2data2 <- fread("ex2data2.txt",col.names=c("Test1","Test2","Label"))
head(ex2data2)
cols <- c("0" = "red","1" = "blue")
ex2data2%>%ggplot(aes(x=Test1,y=Test2,color=factor(Label)))+geom_point(size = 4, shape = 19,alpha=0.6)+
scale_colour_manual(values = cols,labels = c("Failed", "Passed"),name="Test Result")
The above figure shows that our dataset cannot be separated into positive and negative examples by a straight-line through the plot. Therefore, a straightforward application of logistic regression will not perform well on this dataset since logistic regression will only be able to find a linear decision boundary.
One way to fit the data better is to create more features from each data point. Let's map the features into all polynomial terms of x1 and x2 up to the sixth power.
new_data=c()
for(i in 1:6){
for(j in 0:i){
temp= (ex2data2$Test1)^i+(ex2data2$Test2)^(i-j)
new_data=cbind(new_data,temp)
}
}
colnames(new_data)=paste0("V",1:ncol(new_data))
head(new_data)
y=ex2data2$Label
X=new_data
As a result of this mapping, our vector of two features (the scores on two QA tests) has been transformed into a 28-dimensional vector. A logistic regression classier trained on this higher-dimension feature vector will have a more complex decision boundary and will appear nonlinear when drawn in our 2-dimensional plot. While the feature mapping allows us to build a more expressive classifier, it also more susceptible to overfitting. In the next parts of the exercise, we will implement regularized logistic regression to fit the data and also see for ourselves how regularization can help combat the overfitting problem.
my_cost2=function(theta, X, y,lambda){
cost_gradient=list()
# cost_and_gradient compute cost and gradient for logistic regression using theta
h_theta= my_sigmoid(X%*%theta)
cost= 1/nrow(X)*sum(-y*log(h_theta)-(1-y)*log(1-h_theta))+lambda/(2*nrow(X))*sum(theta^2)
return(cost)
}
my_gradient2=function(theta, X, y,lambda){
h_theta= my_sigmoid(X%*%theta)
## OPTION 1-- looping
gradient=rep(0,ncol(X))
for(j in 2:ncol(X)){
for(i in 1:nrow(X)){
gradient[1]=gradient[1]+1/nrow(X)*(my_sigmoid(X[i,]%*%theta)-y[i])*X[i,1]
gradient[j]=gradient[j]+1/nrow(X)*(my_sigmoid(X[i,]%*%theta)-y[i])*X[i,j]+lambda/(nrow(X))*theta[j]
}
}
# option2-more succint
# gradient= 1/nrow(X)*(my_sigmoid(t(theta)%*%t(X))-t(y))%*%X+(lambda/(nrow(X)))*c(0,theta[-1])
return(gradient)
}
Let's initialize theta:
initial_theta =matrix(rep(0,ncol(X)))
What is the cost for the initial theta?
round(my_cost2(initial_theta,X,y,lambda=10),3)
Now, since we have the cost function that we want to optimize and the gradient, we can use the optimization function optim to find the optimal theta values.
We have to try various values of lambda and select the best lambda based on cross-validation. But for now, let's just take lambda=1.
optimized=optim(par=initial_theta,X=X,y=y,lambda=1,fn=my_cost2,gr=my_gradient2,method="BFGS")
The theta values from the optimization are shown below.
matrix(as.vector(optimized$par),ncol=9)
ex2data2$fitted_result=my_sigmoid(X%*%optimized$par)
Let's use a threshould of 0.5.
ex2data2$fitted_result_label=ifelse(ex2data2$fitted_result>=0.5,1,0)
head(ex2data2,10)
Let's calculate F1 score
, which uses precision
and recall
. Precision
and rcall
in turn are calculated using true positive
, false positive
and false negative
as defined below. We will also see the model accuracy.
tp is the number of true positives: the ground truth label says it's an anomaly and our algorithm correctly classied it as an anomaly.
fp is the number of false positives: the ground truth label says it's not an anomaly, but our algorithm incorrectly classied it as an anomaly.
fn is the number of false negatives: the ground truth label says it's an anomaly, but our algorithm incorrectly classied it as not being anoma- lous.
The F1 score is computed using precision (prec) and recall (rec):
$$prec = \frac{tp}{tp+fp}$$$$rec = \frac{tp}{tp+fn}$$$$F1 = 2.\frac{prec.rec}{prec+rec}$$tp=sum((ex2data2$Label==1)&(ex2data2$fitted_result_label==1))
fp=sum((ex2data2$Label==0)&(ex2data2$fitted_result_label==1))
prec=tp/(tp+fp)
cat("The precision is:")
round(prec,3)
tp=sum((ex2data2$Label==1)&(ex2data2$fitted_result_label==1))
fn=sum((ex2data2$Label==1)&(ex2data2$fitted_result_label==0))
rec=tp/(tp+fn)
cat("The recall is:")
round(rec,3)
F1=2*(prec*rec)/(prec+rec)
cat("The F1 score is:")
round(F1,3)
accuracy=sum(ex2data2$Label==ex2data2$fitted_result_label)/nrow(ex2data2)
cat("The accuracy is: ")
round(accuracy,3)
Logistic regression is a classification machine learning technique. In this blog post, we saw how to implement logistic regression with and without regularization. In the first part, we used it to predict if a student will be admitted to a university and in the second part, we used it to predict whether microchips from a fabrication plant pass quality assurance. We used special optimization function in lieu of gradient descent to get the optimal values of the coeffients.