[R] How to get the same result for GA optimization?
Michael Dewey
||@t@ @end|ng |rom dewey@myzen@co@uk
Wed May 7 18:02:44 CEST 2025
Dear Daniel
As far as I can see you have re-generated the data before calling ga()
so the data is not just a permutation of the first set.
Michael
On 07/05/2025 15:36, Daniel Lobo wrote:
> 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]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Michael Dewey
More information about the R-help
mailing list