# Help On optim function

2 messages
Open this post in threaded view
|
Report Content as Inappropriate

## Help On optim function

 This post was updated on . I have some parameters from Mclust function. The parameters are in the form   parametersDf         mu_1           mu_2          var_mc1    var_mc2          c1               c2     2   1.357283   2.962736       0.466154    0.1320129      0.5258975  0.4741025   21  8.357283   9.962736      0.466154    0.1320129      0.5258975  0.4741025   Each row in the above data frame represent the segment and each segment contain two-mixture component. (Latter on I will increase the segment and the mixture component) So for every segment with n mixture component I have to find the maxf(x) with –infinity < x < infinity f(x)=sum_i c_i N(O,mu_i,sigma_i).   Since i need to calculate the derivate f’ and set f’(x)=0 in order to have a maximum value Therefore, I thought of using Newton method In R the function I selected for my problem is optim. Code I generated the test data by set.seed(1) rv <-UnivarMixingDistribution(Norm(1,0.1),Norm(2,0.1),Norm(3,0.1),mixCoeff=c(1/3,1/3,1/3)) #cluster 1 Segment1=r(rv)(40) set.seed(1) rv <-UnivarMixingDistribution(Norm(8,0.1),Norm(9,0.1),Norm(10,0.1),mixCoeff=c(1/3,1/3,1/3)) #cluster 2 Segment2=r(rv)(40) xnorm= function(par) {   i=par['i']   x=par['meanval']   sum_prob=0   for (j in 1:l){     val=(coeff.vector[i,j]*(dnorm(x,mu.vector[i,j],sqrt(var.vector[i,j]))))     sum_prob=sum_prob+val   }   return(sum_prob) } l=3 maxvalDF=data.frame() {   parametersDf # same what i have described above   mu.vector = parametersDf[1:l]   var.vector =parametersDf[(l+1):((2*l))]   coeff.vector=parametersDf[(2*l+1):(3*l)]   #observation= append(segment1, segment2)   for(j in 1 :nrow(parametersDf))   {     val1=optim(par=c(meanval=parametersDf\$mean_mc_1[j],i=j ),                fn=xnorm,                method = "BFGS", control=list(fnscale=-1))         val2=optim(par=c(meanval=parametersDf\$mean_mc_2[j],i=j),                fn=xnorm,                method = "BFGS", control=list(fnscale=-1))     if(val1\$value >=val2\$value){       maxval1=val1\$value     }     else{       maxval1=val2\$value     }     maxvalDF=rbind(maxvalDF,data.frame(segment=j, maxval=maxval1))   }   } maxvalDF optim is giving me same value for both the segment and I dont know why? Plus does optim runs the xnorm function defined till certain iteration? Is there any other function I can use for Newtons approach I know maxNR() but i was not able to apply it to my problem Thanks in Advance for the help ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code.