Optimizing a function with Genetic Algorithm in Python

Function Optimization means how to find the maximum and/or minimum of the function in a given domain. The aim is to find the optimal value viz. maximum or minimum value of a function.

To explain the process in Python we take an example of the Rastrigin function. Let us understand what this function means first.

Today we are focusing on the Rastrigin function. In two dimensions the Rastrigin function is given as follows:

The objective function in Python can be written as follows:

from numpy.ma.core import cos
import math

def objectiveFunction(X):
value = 20 + ( X[0]*X[0] + X[1]*X[1] ) - 10 * ( math.cos(2*math.pi * X[0]) + math.cos(2*math.pi * X[1]) )
return -1 * value

-1 is multiplied in objective function here as, by doing this a maxima problem turns to a minima problem. This means that this setting of GA is to find minima and the Rastringin function finds maxima, so multiplying by -1 converts maxima to minima, and gives solution but the optimal value shall be negative of the actual value.

Now, lets come to the question: “How genetic algorithm can be used to find optimal value of any function, right here Rastrigin function”

Genetic algorithm takes an objective function. The objective function we have taken is the Rastrigin function in two dimensions for explanation. We import Genetic algorithm library in python called geneticalgorithm. Next step is to define the domain of all variables. We have taken two dimensions and hence two domains for each of the two domains are required to be provided programatically.

Next, make a Genetic Algorithm model where in we defined the objective function and variable type to be real-valued as we search over continuous values, provide domains, and finally run the model.

More specifications can be provided for GA as well, we shall discuss them later.

from geneticalgorithm import geneticalgorithm as ga




Run the code and here in less than 2 minutes we get the results.

The optimal value is 80 [as -1 was multiplied to solve the problem with GA so now we remove it] and optima occurs at [ 4.52296907 -4.52302981].

This provides optimal values of a function using Genetic Algorithms.

Published by Nidhika

Hi, Apart from profession, I have inherent interest in writing especially about Global Issues of Concern, fiction blogs, poems, stories, doing painting, cooking, photography, music to mention a few! And most important on this website you can find my suggestions to latest problems, views and ideas, my poems, stories, novels, some comments, proposals, blogs, personal experiences and occasionally very short glimpses of my research work as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: