# 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 cosimport mathdef objectiveFunction(X):    value = 20 + ( X*X + X*X ) - 10 * ( math.cos(2*math.pi * X) + math.cos(2*math.pi * X) )    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 gadomains=np.array([[-5.12,5.12]]*2)model=ga(function=objectiveFunction,dimension=2,variable_type='real',variable_boundaries=domains)model.run()`

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.