R optim vector最大化用户定义的函数

时间:2017-11-08 16:31:52

标签: r optimization

我有以下数据框,我想找到optimised_vector的全局最大值

set.seed(1)
xxx<-data.frame(C1 = c("obs1","obs2","obs3","obs4","obs5","obs6"),
                X1 = round(runif(6, 1, 6),digits=1),
                X2 = round(runif(6, 1, 6),digits=1),
                X3 = round(runif(6, 1, 6),digits=1),
                X4 = round(runif(6, 1, 6),digits=1),
                X5 = round(runif(6, 1, 6),digits=1)
)

yyy<-data.frame(C1 = c("obs1","obs2","obs3","obs4","obs5","obs6"),
                YY = c(1,2,3,4,5,6)
)

#optimised_vector<-c(1,1,1,1,1,1)
optimised_vector<-c("coef1","coef2","coef3","coef4","coef5","coef6")

所以我构建了这些函数来试图找到我的虚拟数据之间的最大相关性。但是我希望能够为optimised_vector的每个元素强加一些约束,比如非负性和最大值0.75

inner_function <- function(xxx,optimised_vector) {

   scoring <- rowSums(xxx[,2:6] * optimised_vector)
   return (scoring)
}

maximiser <- function(optimised_vector) {   
   1-cor(
      yyy$YY, 
      inner_function(xxx,optimised_vector),
      method="kendall", use="pairwise")
   }

然后我运行优化以获得结果......

optim(par = c(1,1,1,1,1,1),
      fn  = maximiser)

这是否正确,是否甚至找到全局收敛点以及如何施加约束?

1 个答案:

答案 0 :(得分:0)

使用方法L-BFGS-B

可以使用bounderies
optim(par     = c(1,1,1,1,1,1),
      fn      = maximiser,     
      method  = "L-BFGS-B", 
      lower   = rep(0, 4), 
      upper   = rep(0.75, 4))