In order to learn more about Factor Analysis, I've tried to implement a common model in R by hand, using MLE.
So I simulated data ( data ~ beta_1 + beta_2*x) . I employed PCA for generating starting values for X, and a normal distribution sample for betas. After defining a log likelihood, I started to run the iterations.
However, it takes so long to converge (although it does after one hour). I'm unsure if it is related to some adjustment I overlooked.
Anyway, my question is: is there some way of optimizing these iterations and estimating factor loadings in less time? If so, what are my mistakes here?
# Generating data
nbetas <- 100
nxs <- 36
betas <- matrix(rnorm(2*nbetas), ncol=2)
xs <- rnorm(nxs)
results <- matrix(0, nrow=nxs, ncol=nbetas)
for (i in 1:nxs)
for (j in 1:nbetas)
results[i,j] <- betas[j,1] + betas[j,2]*xs[i]
# A simple PCA recovers the xs
plot(cmdscale(dist(results))[,1], xs)
# Log Likelihood function
norm.loglike <- function(betas_h,xs_h,values) {
print(class(betas_h))
soma <- 0
for (i in 1:nxs)
for (j in 1:nbetas)
soma <- soma + dnorm(values[i,j], mean=(betas_h[j] + betas_h[j+nbetas]*xs_h[i]))
# It seems that optim doesn't take on matrix, so I'm dealing with a vector
print(-soma)
return(-soma)
}
xs_new <- cmdscale(dist(results))[,1] # starting values for x
# First estimation
betas_new <- optim(matrix(rnorm(nbetas*2), ncol=2), norm.loglike, method="L-BFGS-B",xs_h=xs_new, values=results)$par
# Iterations
for (i in 1:30) {
print(i)
xs_new <- optim(xs_new, norm.loglike, "L-BFGS-B",betas=betas_new, values=results)$par
betas_new <- optim(betas_new, norm.loglike, method="L-BFGS-B",xs=xs_new, values=results)$par
}
# Plotting graphs to check them
plot(xs,xs_new)
plot(betas[,1], betas_new[,1])
plot(betas[,2], betas_new[,2])