Why does my genetic algorithm return negative fitness values?

时间:2019-04-16 22:48:04

标签: r genetic-algorithm fitness

I'm trying to minimize the function and then graph it, but I'm getting negative fitness values and I don't know how or why. I'm using the GA package which basically handles the algorithm for me as long as I send it a fitness function. (documentation can be found here. https://cran.r-project.org/web/packages/GA/vignettes/GA.html)

# Objective function for I-beam cross section area
cross <- function(x1, x2, x3, x4) {
  2 * x2 * x4 + x3 * (x1 - 2 * x4) # Not possible to be negative
}

Parameters to the genetic algorithm.

crossGA <- ga(
  type = "real-valued",
  fitness = function(x)
    -cross(x[1], x[2], x[3], x[4]),
  lower = c(10, 10, 0.9, 0.9), # Not possible to be negative
  upper = c(80, 50, 5, 5), # Not possible to be negative
  popSize = 50,
  maxiter = 100,
  run = 100,
  pcrossover = 0.75,
  pmutation = .001
)

Output.

GA | iter = 1 | Mean = -295.2791 | Best = -104.4886
GA | iter = 2 | Mean = -231.7914 | Best = -104.4886
GA | iter = 3 | Mean = -205.53407 | Best =  -82.49887
GA | iter = 4 | Mean = -199.11156 | Best =  -82.49887
GA | iter = 5 | Mean = -164.27739 | Best =  -82.49887
GA | iter = 6 | Mean = -138.23192 | Best =  -82.49887
GA | iter = 7 | Mean = -117.80066 | Best =  -72.36154
GA | iter = 8 | Mean = -107.05787 | Best =  -72.36154
GA | iter = 9 | Mean = -93.94951 | Best = -72.36154
GA | iter = 10 | Mean = -86.25630 | Best = -72.36154

1 个答案:

答案 0 :(得分:0)

You defined your fitness function to be -cross(...), which negates the value and thus makes it negative. In other words, it looks like it was a typo in your code.