Project

Challenge week 4.1 - Genetic Algorithm

Challenge on Genetic Algorithm

Aim: To write a program in Matlab to optimise and find the global maxima of a stalagmite function.

Objectives:

1) To write a code to optimise and find the global maxima of a stalagmite function.

2) Understanding genetic algorithm.

3) Plotting graphs for three different cases and for the optimum value of function.

What is Genetic Algorithm?

Before getting started with the code, let’s get an understanding of the subject first. So, Genetic Algorithm (GA) is a search-based optimization technique based on the principles of Genetics and Natural Selection. It is frequently used to find optimal or near-optimal solutions to difficult problems which otherwise would take a lifetime to solve. It is frequently used to solve optimization problems, in research, and in machine learning.

Introduction to Optimization

Optimization is the process of making something better. In any process, we have a set of inputs and a set of outputs as shown in the following figure.

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 is a stalagmite?

Stalactite and stalagmite are elongated forms of various minerals deposited from solution by slowly dripping water. A stalactite hangs like an icicle from the ceiling or sides of a cavern. A stalagmite appears like an inverted stalactite, rising from the floor of a cavern.

Stalagmite function

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.

GA – Motivation

Genetic Algorithms have the ability to deliver a “good enough” solution “fast-enough”. This makes genetic algorithms attractive for use in solving optimisation problems.

The reasons why GAs are needed are as follows –

Solving Difficult Problems

In computer science, there is a large set of problems, which are NP-Hard. What this essentially means is that, even the most powerful computing systems take a very long time (even years!) to solve that problem. In such a scenario, GAs prove to be an efficient tool to provide usable near-optimal solutions in a short amount of time.

Failure of Gradient Based Methods

Traditional calculus based methods work by starting at a random point and by moving in the direction of the gradient, until we reach the top of the hill. This technique is efficient and works very well for single-peaked objective functions like the cost function in linear regression. However, in most real-world situations, we have a very complex problem called as landscapes, which are made of many peaks and many valleys, which causes such methods to fail, as they suffer from an inherent tendency of being stuck at the local optima as shown in the following figure.

Getting a Good Solution Fast

Some difficult problems like the Travelling Salesperson Problem (TSP) have real-world applications like path finding and VLSI Design. Now imagine that you are using your GPS Navigation system, and it takes a few minutes (or even a few hours) to compute the “optimal” path from the source to destination. Delay in such real world applications is not acceptable and therefore a “good-enough” solution, which is delivered “fast” is what is required.

Basic Terminology

Before beginning a discussion on Genetic Algorithms, it is essential to be familiar with some basic terminology, which will be used throughout this tutorial.

  • Population − It is a subset of all the possible (encoded) solutions to the given problem. The population for a GA is analogous to the population for human beings except that instead of human beings, we have Candidate Solutions representing human beings.
  • Chromosomes − A chromosome is one such solution to the given problem.
  • Gene − A gene is one element position of a chromosome.
  • Allele − It is the value a gene takes for a particular chromosome.

  • Genotype − Genotype is the population in the computation space. In the computation space, the solutions are represented in a way which can be easily understood and manipulated using a computing system.
  • Phenotype − Phenotype is the population in the actual real world solution space in which solutions are represented in a way they are represented in real world situations.
  • Decoding and Encoding − For simple problems, the phenotype and genotype spaces are the same. However, in most of the cases, the phenotype and genotype spaces are different. Decoding is a process of transforming a solution from the genotype to the phenotype space, while encoding is a process of transforming from the phenotype to genotype space. Decoding should be fast as it is carried out repeatedly in a GA during the fitness value calculation.

For example, consider the 0/1 Knapsack Problem. The Phenotype space consists of solutions, which just contain the item numbers of the items to be picked.

However, in the genotype space it can be represented as a binary string of length n (where n is the number of items). A 0 at position x represents that xth item is picked while a 1 represents the reverse. This is a case where genotype and phenotype spaces are different.

  • Fitness Function − A fitness function simply defined is a function which takes the solution as input and produces the suitability of the solution as the output. In some cases, the fitness function and the objective function may be the same, while in others it might be different based on the problem.
  • Genetic Operators − These alter the genetic composition of the offspring. These include crossover, mutation, selection, etc.

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. 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.

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 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.

Syntax for GA

x = ga(fun,nvars)

x = ga(fun,nvars,A,b)

x = ga(fun,nvars,A,b,Aeq,beq)

x = ga(fun,nvars,A,b,Aeq,beq,lb,ub)

x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon)

x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options)

x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,intcon)

x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,intcon,options)

x = ga(problem)

[x,fval] = ga(___)

[x,fval,exitflag,output] = ga(___)

[x,fval,exitflag,output,population,scores] = ga(___)

where, fun = function to be optimised(stalagmite function in our case)

nvars – no of input variables

A&b – linear inequality constraints

Aeq&beq – linear equality constraints

lb – lower bounds

up – upper bounds

nonlcon – non-linear constraints

options – optimisation options

Understanding the code

So herein, we have to optimize a stalagmite function. For it, we firstly create a function named stalagmite_func wherein we define the function given by the equation stated above. In it, we have negated the value of the function. This is done because our ga solver is a solver meant to find the minima of any given function. If incase we don’t negate our function, our ga solver will return the minima of our given function, which isn’t our aim. Hence, on negating the function we flip our function by 180° and find the minima which actually is our maxima with a negative sign. To overcome this we again negate our function while plotting, which negates the negative maxima (-*-=+) and gives us our required maxima. So, moving on to our main code. In it we firstly define our search space as x and y arrays. Then we convert these variables into 2D arrays using meshing. Further, we make sure our function is as required by inputting these variables on calling the stalagmite_func. Then we plot it in a 3D graph with the surf function.

Moving ahead with our three different cases. First one is to check the statistical behavior with unbounded input variables. Here we check for the optimal values of our function given out by our ga solver. There are many values obtained as outputs with a very wayward and unclear graph. To get rid of this, we then solve our ga in between upper and lower bounds of the input variables. This forms our case 2. Since we aren’t providing any linear equalities or inequalities we place ‘[]’ in their place. Still we aren’t there yet (our optimal value), hence we head on to yet another trick in the book to get our value. We use optimoptions to optimize our options and get the optimum value. Herein, we increase the population size of the cycle to 300 from 50 that is the default value assumed by ga unless mentioned. Again, as there are no nonlinear or integer constraints for our problem we place ‘[]’ in their place. Hence, we obtain the optimum value of our given function.

The Code

% Stalagmite function

function [f] = stalagmite_func(input)
f1x = (sin((5.1*pi*input(1))+0.5)).^6;
f1y = (sin((5.1*pi*input(2))+0.5)).^6;
a1 = (input(1)-0.0667).^2/0.64;
a2 = (input(2)-0.0667).^2/0.64;
f2x = exp(-4*log(2).*a1);
f2y = exp(-4*log(2).*a2);
f = -(f1x.*f2x.*f1y.*f2y);
end

%Using genetic algorithm to find maxima

%Input variables for search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);

%Converting to 2D arrays
[X,Y] = meshgrid(x,y);

%Checking validity of function
for i = 1:length(X)
    for j = 1:length(Y)
        input_vector(1)= X(i,j);
        input_vector(2)= Y(i,j);
        f1(i,j) = stalagmite_func(input_vector);
    end
end
%Plotting
figure(1)
surf(X,Y,-f1)
xlabel('x values')
ylabel('y values')
zlabel('Function maximum')
title('Stalagmite')
shading interp

%%
%Case1-Statistical behaviour with unbounded input variables
num_cases=50; %Number of iterations 
tic
for i=1:num_cases
    [input,fopt(i)]=ga(@stalagmite_func,2);
    xopt(i)=input(1);
    yopt(i)=input(2);
end
study_time_Case1 = toc %Taking stock of time taken
%Plotting
figure(2)
subplot(2,1,1)
hold on
surfc(X,Y,-f1)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r') %For 3D plotting
xlabel('x values')
ylabel('y values')
zlabel('Function maximum')
title('Unbounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('Iteration')
ylabel('Function maximum')

%%
%Case2- Statistical behaviour with bounded input variables
tic
for i=1:num_cases
    [input,fopt(i)]=ga(@stalagmite_func,2,[],[],[],[],[0;0],[0.6;0.6]);
    xopt(i)=input(1);
    yopt(i)=input(2);
end
study_time_Case2 = toc
figure(3)
subplot(2,1,1)
hold on
surfc(X,Y,-f1)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
xlabel('x values')
ylabel('y values')
zlabel('Function maximum')
title('Bounded inputs')
subplot(2,1,2)
plot(-fopt)
xlabel('Iteration')
ylabel('Function maximum')

%%
%Case3 - Statistical behaviour with bounded input variables and higher populationsize
options=optimoptions('ga');
options=optimoptions(options,'Populationsize',300); %Taking a population size of 300 
tic
for i=1:num_cases
    [input,fopt(i)]=ga(@stalagmite_func,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
    xopt(i)=input(1);
    yopt(i)=input(2);
end
study_time_Case3 = toc
figure(4)
subplot(2,1,1)
hold on
surfc(X,Y,-f1)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
xlabel('x values')
ylabel('y values')
zlabel('Function maximum')
title('Bounded inputs with higher populationsize')
subplot(2,1,2)
plot(-fopt)
xlabel('Iteration')
ylabel('Function maximum')

Outputs

References

https://www.tutorialspoint.com/genetic_algorithms/genetic_algorithms_introduction.htm

https://skill-lync.com/knowledgebase/genetic-algorithm-explained

https://in.mathworks.com/help/gads/ga.html

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.

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.