我非常感谢您对以下代码的优化提供帮助。对于我需要运行的迭代次数,目前要花很长时间。
基本上,我正在寻找用于估计感兴趣变量的最佳模型参数集。我正在模拟一组模型参数和目标变量,使用它们(在一个循环中)对目标信号进行建模,然后将每个模型化信号与观察到的信号进行比较,并在其中将它们最小化的过程中选择一个我们试图预测的(模拟)值。然后,使用RMSE函数选择与观察值相比,哪一组模型参数提供最小的误差。
非常感谢
#Empty variable
est_hold <- NULL
# Model Parameters (simulated and/or estimated via NLS earlier)
beta <- seq(0.001,0.2,0.01)
sig.g <- seq(0.028, 0.038,length.out = 20)
sig.v <- seq(0.6, 0.8,length.out = 20)
params <- data.frame(rbind(beta,sig.g,sig.v))
# Simulated variable of interest (Dependant variable)
sim_var <- seq(1,100,0.1)
# Observed signal (Independant variable)
obs_sig <- seq(0.0001,0.8,length.out = 100000)
# Observed variable of interest (Dependant variable)
obs_var2 <- seq(1,100,length.out = 100000)
min.func <- function(x) {sim_var[which.min(x)]}
system.time({
for(c in 1:ncol(params)){
# Modelled signal (Independant)
model_var <- params[2,c]*exp(-params[1,c]*sim_var)+params[3,c]*(1-exp(-params[1,c]*sim_var))
# Calculate difference between each modelled value (using simulated params) and each observed value
diff <- t(apply(as.data.frame(model_var),1,"-",obs_sig))
diff <- abs(diff)
# Apply function, to select a simulated dependant value where differences are minimised
est <- apply(diff,2,min.func)
rm(diff)
est_hold <- cbind(est_hold,unlist(est))
}})
# RMSE function, to calculate RMSE between observed dependant variable and the modelled dependant variable (using simulated params)
rmse.fun = function(x){sqrt(sum((obs_var2-x)^2)/length(obs_var2))}
# Apply the RMSE function to the matrix of modelled values
# (where each column represents modelled values using each of the simulated params)
sim_rmse <- apply(est_hold,2,rmse.fun)
# Find the position of the lowest RMSE
ind <- which.min(sim_rmse)
#Use this position to subset the parameters (...and continue with script/modelling)
final_params <- params[ind]