I am trying to learn how to use Genetic algorithm (GA) in r. So, here is my code:
library(genalg)
evalf <- function(x) {
soln <- dnorm(x, mean = 16, sd = 4)
return(soln)
}
iter = 100
GAmodel <- rbga.bin(size = 5, popSize = 200, iters = iter, mutationChance = 0.002, elitism = F, evalFunc = evalf)
return with the warning,
There were 50 or more warnings (use warnings() to see the first 50)
as follows:
1: In evalVals[object] = evalFunc(population[object, ]) :
number of items to replace is not a multiple of replacement length
Further, I think GA does not return the correct answer since I got as follows:
cat(summary.rbga(GAmodel))
return,
GA Settings
Type = binary chromosome
Population size = 200
Number of Generations = 100
Elitism = FALSE
Mutation Chance = 0.002
Search Domain
Var 1 = [,]
Var 0 = [,]
GA Results
Best Solution : 0 0 1 0 1
If I convert the Best Solution using binary2decimal(c(0,0,1,0,1))
, I got 5
. However the correct answer should be 16
.
Could you please give me suggestions on how to solve this problem using GA ?
Thank you
To solve this problem using GA you need to change evalf to:
evalf <- function(x) 1/dnorm(binary2decimal(x), mean = 16, sd = 4)
It seems that fitness function should return smaller value for data that is closer to solution. Also fitness function should return the value - not a vector - so you need to convert chromosome by using binary2decimal.