#Neural network
h = function(x)
{
  exp(x)/(1+exp(x))
}
dh = function(x)
{
  exp(x)/(1+exp(x))^2
}
g = function(x)
{
  x
}

#Simulate data
if(!exists("d.nn"))
{
set.seed(43253)
n = 10000
p = 12
X = matrix(rnorm(n*p),ncol=p)
X = scale(X)
X = cbind(1,X) #Has the effect of including the intercept into the alpha vector
n = nrow(X)
p = ncol(X)
M = 5  #Size of sub-sample
beta = runif(M)
alpha = matrix(runif(M*p),ncol=p)
zz = X%*%t(alpha)
z = h(zz)
TT = z%*%matrix(beta,ncol=1)
eta = g(TT)
y = g(TT)+rnorm(n)
show(beta)
show(sum((y-eta)^2))    #RSS for true set of parameters
d.nn = data.frame(y=y,x=X)
}

#Linear regression, something to compare to
fit = lm(y~.-1,data=d.nn)
show(sum((d.nn$y-fit$fitted)^2))    #RSS based on a linear model

y=d.nn$y
X=as.matrix(d.nn[,-1])



lambda = 0
#mvec = c(1,3,5,10,20,30,40,50,100,150,200)  #Subsample-size
mvec = rep(1,11)
deltavec= seq(0.5,1,length=11)
#deltavec = rep(0.5,11)
Q.rep = matrix(NA,nrow=11,ncol=10)
for(v in 1:11)
for(rep in 1:10)
{
  m = mvec[v]
  delta = deltavec[v]
alpha = matrix(runif(M*p),ncol=p)
zz = X%*%t(alpha)
z = h(zz)

#Finding initial values for beta based on linear regression
fit = lm(y~.-1,data=data.frame(y=y,z=z))
beta = fit$coef
#beta = (runif(M))
Qvec = NULL
itvec = NULL
for(it in 0:10000)
{
  #Subsampling
  ind = sample(1:n,m,replace=FALSE)
  X.sub = X[ind,,drop=FALSE]
  y.sub = y[ind]
  #Forwards
  zz = X.sub%*%t(alpha)
  z = h(zz)
  TT = z%*%matrix(beta,ncol=1)
  eta = g(TT)
  res = as.vector(y.sub-eta)
  
  #Backwards
  df.beta = z
  dQ.beta = rep(0,M)
  for(m in 1:M)
   dQ.beta[m] = -2*sum(res*df.beta[,m])+2*lambda*beta[m]
  dQ.alpha = matrix(nrow=M,ncol=p)
  for(m in 1:M)
  for(j in 1:p)
  {
    df.alpha = beta[m]*dh(zz[,m])*X.sub[,j]
    dQ.alpha[m,j] = -2*sum(res*df.alpha)
  }
  dQ.alpha = dQ.alpha + 2*lambda*alpha
  #Learning rate
  gamma = 1/(m*(1+it)^delta)
  beta = beta-gamma*dQ.beta
  alpha = alpha-gamma*dQ.alpha
  
  if(it%%1000==0)   #Compute full objective function
  {
    #Forwards
    zz = X%*%t(alpha)
    z = h(zz)
    TT = z%*%matrix(beta,ncol=1)
    eta = g(TT)
    res = as.vector(y-eta)
    Q = sum(res^2)+lambda*sum(alpha^2)+lambda*sum(beta^2)
    Qvec = c(Qvec,Q)
    itvec = c(itvec,it)
    show(c(it,Q,beta))
  }
}
Q.rep[v,rep] = Q
}

matplot(matrix(rep(deltavec,10),ncol=10),Q.rep,xlab=expression(~delta),ylab="Q",
        ylim=c(9925,11000),pch=1,col=1)
#matplot(matrix(rep(mvec,10),ncol=10),Q.rep,xlab="m",ylab="Q",pch=1,col=1)
#Plot value of Q as function of iteration
#pdf("../doc/Stoc_grad_NN_Q.pdf",height=5,width=15)
plot(itvec,Qvec,type="l",xlab="Iteration",ylab="Q")
plot(itvec[-1],Qvec[-1],type="l",xlab="Iteration",ylab="Q")
dev.off()
