Challenge

Week 4.1 - Genetic Algorithm

AIM : A code in MATLAB to optimise the stalagmite function and find the global maxima of the function.

Theory : Genetic algorithm is one of the optimisation processes. It is a search based optimisation technique based on the principles of genetics and natural selection. It is frequently used to find optimal or near optimal solutions which would take a lifetime to solve. It is frequently used to solve optimisation problems, in research and in machine learning.

Optimisation : Optimisation is a decision making process, it helps to find the better results. Under a set of prioritized criteria or constraints, it is a procedure which is executed iteratively by comparing various solutions till an optimum or a satisfactory solution is found.

Optimization refers to finding the values of inputs in such a way that we get the “best” output values. The definition of “best” varies from problem to problem, but in mathematical terms, it refers to maximizing or minimizing one or more objective functions, by varying the input parameters.

The set of all possible solutions or values which the inputs can take make up the search space. In this search space, lies a point or a set of points which gives the optimal solution. The aim of optimization is to find that point or set of points in the search space.

What are Genetic Algorithms?

Nature has always been a great source of inspiration to all mankind. Genetic Algorithms (GAs) are search based algorithms based on the concepts of natural selection and genetics. GAs are a subset of a much larger branch of computation known as Evolutionary Computation.

GAs were developed by John Holland and his students and colleagues at the University of Michigan, most notably David E. Goldberg and has since been tried on various optimization problems with a high degree of success.

In GAs, we have a pool or a population of possible solutions to the given problem. These solutions then undergo recombination and mutation (like in natural genetics), producing new children, and the process is repeated over various generations. Each individual (or candidate solution) is assigned a fitness value (based on its objective function value) and the fitter individuals are given a higher chance to mate and yield more “fitter” individuals. This is in line with the Darwinian Theory of “Survival of the Fittest”.

In this way we keep “evolving” better individuals or solutions over generations, till we reach a stopping criterion.

Genetic Algorithms are sufficiently randomized in nature, but they perform much better than random local search (in which we just try various random solutions, keeping track of the best so far), as they exploit historical information as well.

Advantages of GAs

GAs have various advantages which have made them immensely popular. These include −

  • Does not require any derivative information (which may not be available for many real-world problems).
  • Is faster and more efficient as compared to the traditional methods.
  • Has very good parallel capabilities.
  • Optimizes both continuous and discrete functions and also multi-objective problems.
  • Provides a list of “good” solutions and not just a single solution.
  • Always gets an answer to the problem, which gets better over the time.
  • Useful when the search space is very large and there are a large number of parameters involved.

Limitations of GAs

Like any technique, GAs also suffer from a few limitations. These include −

  • GAs are not suited for all problems, especially problems which are simple and for which derivative information is available.
  • Fitness value is calculated repeatedly which might be computationally expensive for some problems.
  • Being stochastic, there are no guarantees on the optimality or the quality of the solution.
  • If not implemented properly, the GA may not converge to the optimal solution.

Basic Structure

The basic structure of a GA is as follows −We start with an initial population (which may be generated at random or seeded by other heuristics), select parents from this population for mating. Apply crossover and mutation operators on the parents to generate new off-springs. And finally these off-springs replace the existing individuals in the population and the process repeats. In this way genetic algorithms actually try to mimic the human evolution to some extent.

1.Initial population -The process begins with a set of individuals which is called a Population. Each individual is a solution to the problem you want to solve. An individual is characterized by a set of parameters (variables) known as Genes. Genes are joined into a string to form a Chromosome (solution). In a genetic algorithm, the set of genes of an individual is represented using a string, in terms of an alphabet. Usually, binary values ​​are used (string of 1s and Os). We say that we encode the genes in a chromosome.

2.Fitness fuction-

Fitness Function (also known as the Evaluation Function) evaluates how close a given solution is to the optimum solution of the desired problem. It determines how fit a solution is.

  • why we use fitness functions :

In genetic algorithms, each solution is generally represented as a string of binary numbers, known as a chromosome. We have to test these solutions and come up with the best set of solutions to solve a given problem. Each solution, therefore, needs to be awarded a fitness score, to indicate how close it came to meeting the overall specification of the desired solution. This score is generated by applying the fitness function to the test, or results obtained from the tested solution.

3.Selection-

The selectionj is based on the fitness score.The idea of ​​selection phase is to select the fittest individuals and let them pass their genes to the next generation. Two pairs of individuals (parents) are selected based on their fitness scores. Individuals with high fitness have more chance to be selected for reproduction.

4.Crossover-

Crossover is the most significant phase in a genetic algorithm. For each pair of parents to be mated, a crossover point is chosen at random from within the genes. Offspring are created by exchanging the genes of parents among themselves until the crossover point is reached.

5. Mutation-

In certain new offspring formed, some of their genes can be subjected to a mutation with a low random probability. This implies that some of the bits in the bit string can be flipped. Mutation occurs to maintain diversity within the population and prevent premature convergence . termination The algorithm terminates if the population has converged (does not produce offspring which are significantly different from the previous generation).

Then it is said that the genetic algorithm has provided a set of solutions to our problem. The population has a fixed size. As new generations are formed, individuals with least fitness die, providing space for new offspring. The sequence of phases is repeated to produce individuals in each new generation which are better than the previous generation. Ga as function of matlab

Syntax for genetic algorithm-

we can give the inputs by any one of the following ways-

Description of input variables-

These are the various input syntaxes that can be given-

x = ga(fun,nvars) finds a local unconstrained minimum, x, to the objective function, fun. nvars is the dimension (number of design variables) of fun.

Passing Extra Parameters (Optimization Toolbox) explains how to pass extra parameters to the objective function and nonlinear constraint functions, if necessary.

x = ga(fun,nvars,A,b) finds a local minimum x to fun, subject to the linear inequalities A*x ≤ b. ga evaluates the matrix product A*x as if x is transposed (A*x').

x = ga(fun,nvars,A,b,Aeq,beq) finds a local minimum x to fun, subject to the linear equalities Aeq*x = beq and A*x ≤ b. (Set A=[] and b=[] if no linear inequalities exist.) ga evaluates the matrix product Aeq*x as if x is transposed (Aeq*x').

x = ga(fun,nvars,A,b,Aeq,beq,lb,ub) defines a set of lower and upper bounds on the design variables, x, so that a solution is found in the range lb ≤ x ≤ ub. (Set Aeq=[] and beq=[] if no linear equalities exist.)

x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon) subjects the minimization to the constraints defined in nonlcon. The function nonlcon accepts x and returns vectors C and Ceq, representing the nonlinear inequalities and equalities respectively. ga minimizes the fun such that C(x) ≤ 0 and Ceq(x) = 0. (Set lb=[] and ub=[] if no bounds exist.)

x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options) minimizes with the default optimization parameters replaced by values in options. (Set nonlcon=[] if no nonlinear constraints exist.) Create options using optimoptions.

x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon) or x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options) requires that the variables listed in IntCon take integer values.

When there are integer constraints, ga does not accept linear or nonlinear equality constraints, only inequality constraints.

x = ga(problem) finds the minimum for problem, where problem is a structure.

Governing Equations :

The above equations are used in the stalagmite function to plot the graph in the main functions.

Mian body of code :

function A = stagalmite(input_vector)
x=input_vector(1);
y=input_vector(2);
f1=(sin(5.1*pi*x+0.5)).^6;
f2=exp((-4*log(2)*((x-0.0667).^2))/0.64);
f3=(sin(5.1*pi*y+0.5)).^6;
f4=exp((-4*log(2))*((y-0.0667).^2)/0.64);
A =-(f1*f2*f3*f4);
end

Determining the equations to find maximum of the stalagmite.

code for stalagmite:

close all 
clear all
clc

% defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);

% creating a 2Dimensional mesh
[xx yy] = meshgrid(x,y);
%evaluating the stalagmite function
for i = 1:length(xx)
    for j = 1:length(yy)
        input_vector(1) = xx(i,j);
        input_vector(2) = yy(i,j);
        f(i,j) = stalagmite(input_vector);
    end
end
surf(xx,yy,-f)
shading interp
[x,fval] = ga(@stalagmite,2)

Explination : First we initialise the values of x and y taking 150 values between the interval 0 and 0.6.

Since we need to plot a 3D surface plot we take the 2d array of x and y using meshgrid command and store them in input_vector array ,so that it can be used as an argument to call the function stalagmite

we create another fuction file for the stalagmite function. here we take the ouput as -f since ga only minimises a given function.so if -f is considered it automatically gives us the maxima. on execuitng the code we will get the stalagmite plot.

code to find global maxima of the stalagmite :

close all 
clear all
clc

% defining our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 50

% creating a 2Dimensional mesh
[xx yy] = meshgrid(x,y);

%evaluating the stalagmite function
for i = 1:length(xx)
    for j = 1:length(yy)
        input_vector(1) = xx(i,j);
        input_vector(2) = yy(i,j);
        f(i,j) = stalagmite(input_vector);
    end
end
% study 1- statistical behaviour
for i = 1:num_cases
    [inputs,fopt(i)] = ga(@stalagmite,2)
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end
study_time1=tic
figure(1)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('unbounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations')
ylabel('function miximum')

%study 2 - statistical behaviour-with upper & lower bounds.
tic

for i = 1:num_cases
    [inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6])
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end
study_time2 = toc
figure(2)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('Bounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations')
ylabel('function miximum')

%study 3 - increased GA iterations
tic
options = optimoptions('ga');
options = optimoptions(options,'populationsize',300);

for i = 1:num_cases
    [inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options)
    xopt(i) = inputs(1);
    yopt(i) = inputs(2);
end
study_time3 = toc
figure(3)
subplot(2,1,1)
hold on
surfc(x,y,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('Bounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('iterations')
ylabel('function miximum')

Explination :

For unbounded inputs : now we store the results into xopt, yopt.now we need to plot the surface of x,y,-f to get the 3D plot.We use the plot3 command to make a plot of xopt,yopt and -fopt to plot the optimum maximas.Also let us plot the fopt function so that we can visualise the optimum values at each iteration.

To get the time taken to complete cycle we used the tic toc commands to record the time.

After execuitng the code we can see the optimal values went outside the values of x and y resulting in falling away from stalagmite surface. So we cannot find the exact global maxima in this case, the plot was shown in the screenshot1.

For bounded inputs : let us specify the lower and upper bounds of x and y in this case,the ga is initiated with random population only.now we store the results into xopt, yopt.now we need to plot the surface of x,y,-f to get the 3D plot.We use the plot3 command to make a plot of xopt,yopt and -fopt to plot the optimum maximas.Also let us plot the fopt function so that we can visualise the optimum values at each iteration.

To get the time taken to complete cycle we used the tic toc commands to record the time.

After execuitng the code we can see the optimal values were within the limits of stalagmite surface. but we are not able to finding the exact global maxima in this case also, the plot was shown in the screenshot2.

For bounded inputs with increased GA iterations(increased initial population) :

Here in this case to set a initial population we need to use command called optimumoptions and get our value of 'populationsize' to 300.now we store the results into xopt, yopt.now we need to plot the surface of x,y,-f to get the 3D plot.We use the plot3 command to make a plot of xopt,yopt and -fopt to plot the optimum maximas.Also let us plot the fopt function so that we can visualise the optimum values at each iteration.

To get the time taken to complete cycle we used the tic toc commands to record the time.

time taken to ececute the code is 11.9326s

After execuitng the code we get the global maxima of stalagmite surface. the plot was shown in the screenshot3.

though the time of execution is more in this case we were sucessful to find out the correct maxima for the stalagmite function.So by increasing the initial population size of the ga we can increase the accuracy of the algorithm.

Error in code :

After executing the code I got a message “Optimization terminated: average change in the fitness value less than options.FunctionTolerance.” as shown in screenshot

Steps taken to overcome error :

Removing semicolon(;) at the end of the following lines from the code gives me the output.

[inputs,fopt(i)] = ga(@stalagmite,2);
[inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6]);

[inputs,fopt(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.