Genetic Algorithms with gaoptim package

[This article was first published on Random Miner, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Two days ago i just submitted my first R package: gaoptim. For my surprise, the next day it was already living on CRAN.

In this post i want to show you how to use gaoptim to perform a simple function maximization. This same task could be accomplished with the function optim() from the stats package, but this should serve as a simple introduction to Genetic Algorithms, which are particularly good when you have a huge search space.

The R code below defines a ‘wild’ function, with global maximum at about -15.81515. Then we setup a GAReal object and call the evolve() function, passing the number of generations to evolve as argument. Finally, we plot the results.

Some planned features for the next package version are:

  • feature selection
  • binary encoding
Enjoy it!

# global minimum at about -15.81515
wild.FUN = function (x)
10*sin(0.3*x)*sin(1.3*x^2) + 0.00001*x^4 + 0.2*x+80
# GAReal performs maximization, so transform the target function
target.FUN = function(x)
-wild.FUN(x)
require(gaoptim)
# The target function can return negative values, so use a uniform selection
# See ?GAReal details section
ga = GAReal(target.FUN, lb = -50, ub = 50, selection = 'uniform')
ga$evolve(200)
# plot the original function and results
op <- par(no.readonly = TRUE)
par(mfrow = c(2, 1))
plot(wild.FUN, -50, 50, n=1000, main = "GAReal() minimising 'wild function'")
xmin = ga$bestIndividual()
ymin = wild.FUN(xmin)
abline(h = ymin, v = xmin, lty = 'dashed', col = 'tomato')
plot(ga)
par(op)

To leave a comment for the author, please follow the link and comment on their blog: Random Miner.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)