[R] How to get the same result for GA optimization?
Daniel Lobo
d@n|e|obo9976 @end|ng |rom gm@||@com
Wed May 7 16:36:02 CEST 2025
I am using *Genetic Algorithm* to maximize some function which use data.
I use GA package in R for this (
https://cran.r-project.org/web/packages/GA/index.html)
Below is my code
library(GA)
set.seed(1)
Dat = data.frame(rnorm(1000), matrix(rnorm(1000 * 30), nc = 30))
Fitness_Fn = function(x) {
return(cor(Dat[, 1], as.matrix(Dat[, -1]) %*% matrix(x, nc = 1))[1,1])
}
ga(type = 'real-valued', fitness = Fitness_Fn, seed = 1, lower =
rep(0, 30), upper = rep(1, 30), elitism = 10, popSize = 200, maxiter =
1, pcrossover = 0.9, pmutation = 0.9, run = 1)
However now I alter the columns of my data and rerun the GA
Dat = Dat[, c(1, 1 + sample(1:30, 30, replace = F))]
Fitness_Fn = function(x) {
return(cor(Dat[, 1], as.matrix(Dat[, -1]) %*% matrix(x, nc = 1))[1,1])
}
ga(type = 'real-valued', fitness = Fitness_Fn, seed = 1, lower =
rep(0, 30), upper = rep(1, 30), elitism = 10, popSize = 200, maxiter =
1, pcrossover = 0.9, pmutation = 0.9, run = 1)
Surprisingly, I get different result from above 2 implementations.
In first case, I get
GA | iter = 1 | Mean = 0.01534124 | Best = 0.04351926
In second case,
GA | iter = 1 | Mean = 0.01705027 | Best = 0.04454167
I have fixed the random number generation using seed = 1 in the ga() function,
So I am expecting I would get exactly same result.
Could you please help identify the issue here? I want to get exactly same
result irrespective of the order of the columns of dat for above function.
Thanks for your time.
[[alternative HTML version deleted]]
More information about the R-help
mailing list