luca-scr / GA

An R package for optimization using genetic algorithms
http://luca-scr.github.io/GA/
91 stars 29 forks source link

Optimizing Functions with Factor and Numerical Inputs #57

Open swaheera opened 2 years ago

swaheera commented 2 years ago

I am trying to optimize a function that can accept "numerical" and "factor" inputs. For the optimization, I am using the "GA" library. Here are the references I am using:

Suppose I have a function that looks like this:

my_function <- function(r1, r2) {

  #define function here, e.g:

#this "select" can be done using "dplyr" or SQL
 part1 <- SELECT * FROM my_data WHERE (col_1 IN r1) AND (col_2 > r2) 

 part2<- mean(part1$col_3)

}

In this example:

Problem: Currently, I am trying to optimize "my_function" using the "ga" function in R:

library(GA)
GA <- ga(type = "real-valued", 
         fitness = function(x)  my_function(x[1], x[2]),
         lower = c(c("a", "b", "c", "d"), 1), upper = c(c("a", "b", "c", "d"), 100), 
         popSize = 50, maxiter = 1000, run = 100)

But I am not sure how to set this up correctly. I am not sure how to correctly define "my_function", and I am not sure how to correctly define "GA".

Can someone please show me how to do this?

Thanks