优化两个函数的运行时

时间:2015-06-24 18:16:10

标签: r performance runtime

我还是这个R的新手,我写了两个功能需要很长时间才能运行。我试图尽可能地优化,但是没有能够节省很多时间。

我想要做的是创建一个函数来估计两个参数,以便最小化函数kvasum。我怀疑我的问题是在buttom的循环中。我有很多观察,并希望用不同的参数运行它。

# Generate Data
x <- runif(1000)
vpk <- data.frame(x);
names(vpk) <-'V1'
n <- 20000000

# This function takes the mean squared errors of the vpk vector and the convergence rate 
#The function therefore returns a value
#The NA's have been omitted here

kvasum = function(par){
  q <- (log(vpk$V1) / log(1 / n) - (-1+(par[1]+1/par[2])) )
  q <- q[!is.na(q)]
  ((10 - 0) / 1000) * sum(q^2)
}


#The function optim has been used to find alpha and beta such that kvasum is minimized. 
#To be sure it is a global minumum, different starting parameters has been tried using a for loop. 
#The starting values, the value of the function and the parameter estimates has been saved in a vector r 
r <- matrix(ncol = 5, nrow = 10000000)
t = 1
for(a in seq(from = 0.01, to = 5,by = 0.01)){
  for(b in seq(from = 0.01, to = 1.99, by = 0.01)){
    h <- optim(par = c(a, b), kvasum, method = 'L-BFGS-B', lower = c(0.0000001, 0.0000001), upper=c(5, 1.999999))
    t <- 1+t
    r[t,] <- c(a, b, h$value, h$par)
  }
}

0 个答案:

没有答案