#Stochastic gradient on logistic regression
#
#Simulate data
set.seed(2323)
n = 100000
x = rnorm(n)
theta = c(0.1,2)
p = exp(theta[1]+theta[2]*x)/(1+exp(theta[1]+theta[2]*x))
y = rbinom(n,1,prob=p)

loglik = function(b,x,y)
{
  eta = b[1]+b[2]*x
  p = exp(eta)/(1+exp(eta))
  l = sum(y*eta-log(1+exp(eta)))
  l
}

#Obtain true optimum by glm
b.opt = glm(y~x,family=binomial)$coef
show(b.opt)

N.it1 = 200       #Number of iterations
N.it2 = 100000     #Number of iterations
N.it3 = 100000    #Number of iterations
N.it4 = 100000    #Number of iteratio

#Gradient decent
start_time <- Sys.time()
b = c(0,1)         #Initial value
#Loop
bseq = b
alpha = 1
l = loglik(b,x,y)
for(it in 1:N.it1)
{
  #alpha = 10/it
  alpha  = 0.5
  p.cur = exp(b[1]+b[2]*x)/(1+exp(b[1]+b[2]*x))
  g = colMeans(cbind(y-p.cur,(y-p.cur)*x))
  b = b + alpha*g  #Note we are doing maximization
  l = loglik(b,x,y)
#  show(c(l,b))
  bseq = rbind(bseq,b)
}
end_time <- Sys.time()
t1 = as.numeric(end_time-start_time)
show(end_time - start_time)

## SGD k=1   alpha=10/it
start_time <- Sys.time()
b = c(0,1)         #Initial value
k = 1             #Number of samples for estimating gradient
#Loop
bseq2 = b
for(it in 1:N.it2)
{
  i = sample(1:n,k)
  alpha = 10/it
  p.i = exp(b[1]+b[2]*x[i])/(1+exp(b[1]+b[2]*x[i]))
  g = colMeans(cbind(y[i]-p.i,(y[i]-p.i)*x[i]))
  b = b + alpha*g
  bseq2 = rbind(bseq2,b)
}
end_time <- Sys.time()
t2 = as.numeric(end_time-start_time)
show(end_time - start_time)


# SGD k=10 alpha =10/it
start_time <- Sys.time()
b = c(0,1)         #Initial value
k = 10             #Number of samples for estimating gradient
#Loop
bseq3 = b
for(it in 1:N.it3)
{
  i = sample(1:n,k)
  alpha = 10/it
  p.i = exp(b[1]+b[2]*x[i])/(1+exp(b[1]+b[2]*x[i]))
  g = colMeans(cbind(y[i]-p.i,(y[i]-p.i)*x[i]))
  b = b + alpha*g
  bseq3 = rbind(bseq3,b)
}
end_time <- Sys.time()
t3 = as.numeric(end_time-start_time)
show(end_time - start_time)
lines(c(0:N.it3)*t3/N.it3,bseq3[,2],col=4)

## constant minibatch
# SGD k=10 alpha =10/it

start_time <- Sys.time()
b = c(0,1)         #Initial value
k = 10             #Number of samples for estimating gradient
#Loop
bseq4 = b
for(it in 1:N.it4)
{
  i = sample(1:n,k)
  #alpha = 10/it
  alpha=0.1
  p.i = exp(b[1]+b[2]*x[i])/(1+exp(b[1]+b[2]*x[i]))
  g = colMeans(cbind(y[i]-p.i,(y[i]-p.i)*x[i]))
  b = b + alpha*g
  bseq4 = rbind(bseq4,b)
}
end_time <- Sys.time()
t4 = as.numeric(end_time-start_time)
show(end_time - start_time)

plot(c(0:N.it1)*t1/N.it1,bseq[,2],ylim=c(1,3),col=2,xlab="Seconds",
        ylab=expression(~beta[2]),type="l");abline(h=b.opt[2],col=1);
lines(c(0:N.it2)*t2/N.it2,bseq2[,2],col=3)
lines(c(0:N.it3)*t3/N.it3,bseq3[,2],col=4)
lines(c(0:N.it4)*t4/N.it4,bseq4[,2],col=5)
legend("bottomright",c("Opt","GD alpha=0.5","SGD,k=1, alpha=1/it ","SGD,k=10, alpha=1/it","SGD,k=10 aplha=0.1"),lty=1,col=1:5)

