Challenge

Week 5 - Genetic Algorithm

AIM :

To Write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.

THEORY:

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

STALAGMITE FUNCTION :

  • A stalagmite is an upward-growing mound of mineral deposits that have precipitated from water dripping onto the floor of a cave.
  • Most stalagmites have rounded or flattened tips.
  • A stalagmite function generally refers to the function with which we are generating values over a stalagmite kind of surface for finding out the local and global maxima and minima of that particular given function.
  • For this in Matlab we are using a method called 'Optimization'.
  • It is a programming which does a selection of the best element with regard to some criterion from some set of population.
  • Optimization is done by systematically choosing input values ​​from within an allowed set and computing the results of the function.
  • In matlab to perform optimization we use 'Genetic Algorithm 'method which is a inbuild function in matlab to find the global maxima of that given stalagmite function.

WHAT ARE GENITIC ALGORITHM??..

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

PROCESS OF NATURAL SELECTION:

The process of natural selection starts with the selection of fittest individuals from a population. They produce offspring which inherit the characteristics of the parents and will be added to the next generation. If parents have better fitness, their offspring will be better than parents and have a better chance at surviving. This process keeps on iterating and at the end, a generation with the fittest individuals will be found. This notion can be applied for a search problem. We consider a set of solutions for a problem and select the set of best ones out of them. Five phases are considered in a genetic algorithm.

1. Initial population

2. Fitness function

3. Selection

4. Crossover

5. Mutation

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 function

  • 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 OF GA :

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

fun - objective function.

nvars - number of variables (specified as positive integer)

A,b - Linear inequality constraints (A -real matrix;b -real vector)

Aeq,beq - linear equality constraints

lb - lower bounds

ub - upper bounds

nonlcon - Non linear constraints

options - optimization option.

GENITIC ALOGORITHM IN GENERAL : Segregation of bunch of points to get the maximun number of outputs(with higher fitness value)

MAIN SCRIPT:

close all
clear all
clc

% Defining input space fo x and y
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 50



% 2.USING THE COMMAND meshgrid() CREATING 2D COORDINATE MATRIXES FOR X AND Y
[xx,yy] = meshgrid(x,y);


%3.USING NESTED FOR LOOP STRUCTURE TO ACESS X AND Y COORDINATES FOR EACH
%AXES
% i AND j ARE THE NUMBER OF ITTERATION
% Evaluating the stalagmite function
for i = 1:length(x)
     for j = 1:length(y)
          inputs(1) = xx(i,j);
         inputs(2) = yy(i,j);
         inputs = [inputs(1),inputs(2)];
         f(i,j)= stalagmite(inputs);
         
     end 
end

%% case 1: performing the unbounded GA study
tic
for i = 1:num_cases
    [inputs,fopt(i)] = ga(@stalagmite,2)
    xopt(i) = inputs(1)
    yopt(i) = inputs(2)
end
study_time1 = toc
% plotting the graph
figure(1)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'Marker','o','MarkerFaceColor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('itteration')
ylabel('function maximum')

%% performing the bounded GA study 
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
% ploting the graph
figure(2)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'Marker','o','MarkerFaceColor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('itteration')
ylabel('function maximum')

%% performing bounded GA study using population size
options = optimoptions('ga')
options = optimoptions(options,'PopulationSize',270)
tic
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)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'Marker','o','MarkerFaceColor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('itteration')
ylabel('function maximum')

FUNCTION SCRIPT:

function f = stalagmite(inputs)
x = inputs(1);
y = inputs(2);

f1x = (sin((5.1*pi*x)+0.5))^6;
f1y = (sin((5.1*pi*y)+0.5))^6;
f2x = exp(-4*log(2)*((x-0.0667)^2/0.64));
f2y = exp(-4*log(2)*((y-0.0667)^2/0.64));

f = -(f1x*f1y*f2x*f2y);

end

PROGRAME EXPLANATION AND OUTPUTS:

close all
clear all
clc
% Defining input space fo x and y
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 50
  • First we initialise the values of x and y taking 150 values between the interval 0 and 0.6
  • We consider no of iterations num_spaces=50.
% 2.USING THE COMMAND meshgrid() CREATING 2D COORDINATE MATRIXES FOR X AND Y
[xx,yy] = meshgrid(x,y);
%3.USING NESTED FOR LOOP STRUCTURE TO ACESS X AND Y COORDINATES FOR EACH
%AXES
% i AND j ARE THE NUMBER OF ITTERATION
% Evaluating the stalagmite function
for i = 1:length(x)
for j = 1:length(y)
inputs(1) = xx(i,j);
inputs(2) = yy(i,j);
inputs = [inputs(1),inputs(2)];
f(i,j)= stalagmite(inputs);
end
end
  • 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.
function f = stalagmite(inputs)
x = inputs(1);
y = inputs(2);
f1x = (sin((5.1*pi*x)+0.5))^6;
f1y = (sin((5.1*pi*y)+0.5))^6;
f2x = exp(-4*log(2)*((x-0.0667)^2/0.64));
f2y = exp(-4*log(2)*((y-0.0667)^2/0.64));
f = -(f1x*f1y*f2x*f2y);
end
  • Now let us make our first study-we take no of iterations = num_spaces and we use the genetic algorithm function to caluclate the maxima of the function.
  • we store the outputs into results which contain maximas and fopt which contain the value at which the maxima is obtained.
  • Here the ga is initiated with random population.
tic
for i = 1:num_cases
[inputs,fopt(i)] = ga(@stalagmite,2)
xopt(i) = inputs(1)
yopt(i) = inputs(2)
end
study_time1 = toc
% plotting the graph
figure(1)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'Marker','o','MarkerFaceColor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('itteration')
ylabel('function maximum')
  • 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 functio 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 timeIf the study is executed the output is displayed as-

  • Here we can see the optimal values went outside the values of x and y resulting in falling away from stagalmite surface.
  • So we failed to reach the global maxima in this case.
  • The study time = 3.3890s

Let us specify the lower and upper bounds of x and y in this case,the ga is initiated with random population only.

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
% ploting the graph
figure(2)
subplot(2,1,1)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'Marker','o','MarkerFaceColor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('itteration')
ylabel('function maximum')
  • 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 functio 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.
  • If the study is executed the output is displayed as

  • Though the optimum values are within the limits it could not give us the exact maxima values.
  • The study time = 4.4112s which is more than above study.

NOW let us make our third study with initial population and bounded values

In this case let us increase our initial population which is default as 50 to 270.

%% performing bounded GA study using population size
options = optimoptions('ga')
options = optimoptions(options,'PopulationSize',270)
tic
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)
surf(x,y,-f)
shading interp
hold on
plot3(xopt,yopt,-fopt,'Marker','o','MarkerFaceColor','r')
subplot(2,1,2)
plot(-fopt)
xlabel('itteration')
ylabel('function maximum')
  • Here in this case to set a initial population we need to use command called optimumoptions and get our value of 'populationsize' to 270.
  • 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 functio 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.
  • If the study is executed the output is displayed as

  • Though the time of execution is more i this case we are sucessful to find out the correct maxima for the stalagmite function.
  • So by increasing the initrial population size of the ga we can increase the accuracy of the algorithm.
  • The study time = 9.8194s which is more than above two studies.
ERROS:
In line 22 &23 instead of 'xx and yy" i typed only 'x and y',after changing the error was solved
references:
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.