ShuangXin
ShuangXin

Reputation: 21

"missing value where TRUE/FALSE needed" error in GA package

When running a genetic algorithm using the GA package, I am receiving a "missing value where TRUE/FALSE needed" error. In my code below, like is a function for fitness and X is a numeric vector of length 6.

library(GA)
y<-c(46,38,49,55)
W<-matrix(c(0,1,0,0,1,0,0,0,0,0,0,1,0,0,1,0),ncol=4)
ei<-eigen(W)$values
data<- matrix(c(14691,14150,14607,15140,5337,5386,5207,5178),ncol=2)
         like=function(x)
            {
              co<-c(x[2],x[3])  
              e<-x[4]*W%*%y-data%*%co-x[1]
              L<-30*log(2)-15*log(2*pi)+log(prod(1-x[4]*Re(ei)))-15*log(x[5])+sum(log(pnorm(-x[6]*e/sqrt(x[5]))))
              -0.5/x[5]*t(e)%*%e
              return(L)
            }
    GA <- ga(type = "real-valued", 
             fitness =  like,
             min=c(-100,0,-50,-10,0.001,0),
             max=c(100,100,0,10,100,10),
             popSize = 100, maxiter = 200,
             optim = TRUE)

The result and error are as below:

GA | iter = 1 
Mean =      -Inf | Best = -2.870387 
Error in if (fmin > (sfactor * fave - fmax)/(sfactor - 1)) { : 
  missing value where TRUE/FALSE needed

Upvotes: 2

Views: 1398

Answers (1)

josliber
josliber

Reputation: 44330

This is a cryptic error, but a good hint of the problem is in the iteration 1 summary information:

Mean = -Inf | Best = -2.870387

The average objective value from your function is negative infinity, meaning some iterate is returning objective value negative infinity. A bit of debugging code identifies sample data that gives this issue:

x <- c(-3.2, 5.7, -26.9, -6.1, 37, 9)
like(x)
# [1] -Inf

Since you are maximizing, you could just cap the returned function value at a sensible lower bound, for instance by replacing return(L) with return(pmax(L, -1e6)). Then you get sensible results:

GA | iter = 200

Mean = 102.2197 | Best = 106.0328 | Final local search = 106.0328

Upvotes: 1

Related Questions