R customized constraints optim function

佐手、 提交于 2019-12-02 12:27:36

Just to follow-up on my comment. We can use two tricks:

  1. Replace all occurrences of sigma2 in your likelihood with (sigma1 + sigma2) to ensure that sigma2 now represents the amount that is added to sigma1
  2. Use exp on sigma2 to ensure that it is non-negative.

The likelihood becomes

mlenew<-function(par){
  sigma1<-par[1]
  sigma2<-par[2]
  diagonal=2*sigma1^2+(sigma1 + exp(sigma2))^2
  nondiag<--sigma1^2*delta
  Lambda_i<-(diag(diagonal,N)+-nondiag)/diagonal
  sig<-as.matrix(diagonal*Lambda_i)
  #lokli
  loglik<--as.numeric(mvnfast::dmvn(matrix(y, byrow=T, ncol=N),mu, sig, log=T))
  loglik
}

If I run you code I get

> fit<-optim(par,mle,hessian=T,
+        method="L-BFGS-B",lower=c(0.01,0.01),
+        upper=c(30,30))
> fit$par
[1]  1.738656 12.672040

With the new code I get

> fit<-optim(par,mlenew,hessian=T,
+        method="L-BFGS-B",lower=c(0.01,0.01),
+        upper=c(30,30))
> fit$par
[1] 1.737843 2.391921

and then you need to "back-transform": The actual value of the old version of sigma2 using the new code is

> exp(2.391921) + 1.737843
[1] 12.67232

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!