Challenge

Week 4.1 - Genetic Algorithm

AIM-

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

Objective:

  • To write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
  • To Plot graphs for all 3 studies (Unbounded, Bounded & Optimization).

Theory:

A 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 solve complex problems which otherwise would take a lifetime to solve. It is commonly used to solve optimisation problems, in research, and in machine learning.

Genetic Algorithm:

Genetic Algorithms (GAs) are search based algorithms based on the concepts of natural selection and genetics. GAs is a subset of a much larger branch of computation known as Evolutionary Computation.

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

Stalagmite function

1. 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 particularly given function.

2. For this in Matlab we are using a method called Optimization. It is programming which does a selection of the best element with regard to some criterion from some set of populations.

3. Optimization is done by systematically choosing input values from within an allowed set and computing the results of the function.

4. In MatLab to perform optimisation we use 'The genetic Algorithm method which is an inbuild function in MatLab to find this al the global maxima of that given stalagmite function.

Notion of Natural Selection

The process of natural selection starts with the selection of the fittest individuals from a population. They produce offspring which inherit the characteristics of the parents and will be added to the next generation of parents have better fitness, their offspring will be better than parents and bove a better chance at surviving This process keeps on iterating and at the end, a generation with the fastest individuals will be found. This notion can be applied to 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 -

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 (a string of Is and Os). We say that we encode the genes in a chromosome.

2. Fitness function

The 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 to 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 selection is based on the fitness score. The idea of the selection phase is to select the fittest individuals and let the pass their genes to the next generation. Two pairs of individuals (parents) are selected based on their fitness score 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 Dast fitness die, providing space for new offspring. The sequence of phases is repeated to produce individuals in each new generation who are better than the previous generation Ga as a function of Matlab.

Governing Equation:

Stalagmite Function 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

As per the Governing Equation, we framed the code in Matlab. But in last A variable as used value in "-".

Reason:

This Stalagmite Function gives the output of the Local Maxima by default. For our project, we need to find the global maxima. so to make Global Maxima as final out of this function we are using A =-(f1*f2*f3*f4);

so that we can see in the graph that we can see the Global Maxima value on the negative side.

Final Program:

close all
clear all
clc

x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_spaces = 50;

% forming 2d array
[xx,yy] = meshgrid(x,y);

for i = 1:length(x)
    for j = 1: length(y)
        input_vector(1) = xx(i,j);
        input_vector(2) = yy(i,j);
        f(i,j) = stagalmite(input_vector);
    end
end

% study 1_ unbounded
tic
for i = 1:num_spaces
    [results,fopt(i)] = ga(@stagalmite,2);
    xopt(i) = results(1);
    yopt(i) = results(2);
end

study_time1 = toc

figure(1)
subplot(2,1,1)
surf(x,y,f)
shading interp
hold on
plot3(xopt,yopt,fopt,'marker','O','MarkerSize',5,'MarkerFaceColor','r')
xlabel('X axis')
ylabel('Y axis')
title('Unbounded Input')
subplot(2,1,2)
plot(fopt)
xlabel('Interaction')
ylabel('Function Minimum')

% Study 2- Bounded
tic
for i = 1:num_spaces
    [results,fopt(i)] = ga(@stagalmite,2,[],[],[],[],[0;0],[0.6;0.6]);
    xopt(i) = results(1);
    yopt(i) = results(2);
end
study_time2 = toc

figure(2)
subplot(2,1,1)
surf(x,y,f)
shading interp
hold on
plot3(xopt,yopt,fopt,'marker','O','MarkerSize',5,'MarkerFaceColor','r')
xlabel('X axis')
ylabel('Y axis')
title('Bounded Input')
subplot(2,1,2)
plot(fopt)
xlabel('Interaction')
ylabel('Function Minimum')

% Study 3 increased initial population
tic
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',300);
for p = 1: num_spaces
    [results,fopt(p)] = ga(@stagalmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
    xopt(p) = results(1);
    yopt(p) = results(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','MarkerSize',5,'MarkerFaceColor','r')
xlabel('X axis')
ylabel('Y axis')
title('increased initial population Input')
subplot(2,1,2)
plot(fopt)
xlabel('Interaction')
ylabel('Function Minimum')

Program Explanation:

close all
clear all
clc
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_spaces = 50;
First we give input values for X & Y taking 150 values for a regular interval between 0 to 0.6.
No of interactions = 50
% forming 2d array
[xx,yy] = meshgrid(x,y);
for i = 1:length(x)
for j = 1: length(y)
input_vector(1) = xx(i,j);
input_vector(2) = yy(i,j);
f(i,j) = stagalmite(input_vector);
end
end

we need to plot a 3D surface plot we take the 2d array of x and y using the mesh grid command and store them in an input vector array so that it can be used as an argument to call the function stalagmite we create another function file for the stalagmite function, here we take the output as -f since ga only minimises a given function. so it-t is considered it automatically gives us the maxima.

1st Study about the unbounded

% study 1_ unbounded
tic
for i = 1:num_spaces
[results,fopt(i)] = ga(@stagalmite,2);
xopt(i) = results(1);
yopt(i) = results(2);
end
study_time1 = toc

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

for i = 1: 50 is to fix the range for running the Genetic algorithm.

X=ga(fun,nvars) find the local unconstrained minimum x, to the objective function (fun), and nvars is the

dimension (no. of design variable) of the function.

Now drawback of ga () command is, it always calculates the value for x where the function is minimum

thus gives us the global minima. But we need to calculate global maxima in our code, So to achieve that we are minimizing the fitting function with a(minus) symbol, because Maximizing f(xy) is the same as minimizing-1(xy).

That is the reason we have put-(minus) symbol in the equation of "" in the function code.

Study time1 will be calculated.
figure(1)
subplot(2,1,1)
surf(x,y,f)
shading interp
hold on
plot3(xopt,yopt,fopt,'marker','O','MarkerSize',5,'MarkerFaceColor','r')
xlabel('X axis')
ylabel('Y axis')
title('Unbounded Input')
subplot(2,1,2)
plot(fopt)
xlabel('Interaction')
ylabel('Function Minimum')
We store the results into xopt, yopt. now we need to plot the surface of x,y, and f to get the 3D plot. We use the plot3 command to make a plot of xopt,yopt and fopt to plot the optimum maximal. Also, let us plot the fopt function so that we can visualise the optimum values at each iteration.
The study executes the output displayed as.

Here we can see the optimal values went outside the values of x and y resulting in falling away from the stalagmite surface. So we failed to reach the global maxima in this case. This is because the value of x & Y is not bounded in the ga command in the next command, we going to bound the limits.

Then we will get different values every time you run the program.

2nd Study about the Bounded values

% Study 2- Bounded
tic
for i = 1:num_spaces
[results,fopt(i)] = ga(@stagalmite,2,[],[],[],[],[0;0],[0.6;0.6]);
xopt(i) = results(1);
yopt(i) = results(2);
end
study_time2 = toc

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

for i = 1: 50 is to fix the range for running the Genetic algorithm.

X=ga(fun,nvars,A,b,Aeq,beq,lb,ub) define a set of lower and upper bounds on the design variablexso solution is found between the range (Set A= [] and b= [] if no linear inequalities exist) (Set Aeq-1] and beqit no linear equalities exist)

Study time2 will be calculated.
figure(2)
subplot(2,1,1)
surf(x,y,f)
shading interp
hold on
plot3(xopt,yopt,fopt,'marker','O','MarkerSize',5,'MarkerFaceColor','r')
xlabel('X axis')
ylabel('Y axis')
title('Bounded Input')
subplot(2,1,2)
plot(fopt)
xlabel('Interaction')
ylabel('Function Minimum')
now we store the results into xopt, yopt now we need to plot the surface of x,y, and f to get the 3D plot. We use the plot3 command to make a plot of xopt,yopt and fopt to plot the optimum maximal. Also, let us plot the fopt function so that we can visualise the optimum values at each iteration.
The study executes the output displayed as.
In the above figure, we can observe that now the graph is much better to clear the previous one and now -ga() predicts that the global maxima are somewhere between the three points that are in first plot 7. When we look at the second plot, we can observe that our second value is between 0.6 to 1 8. But here we still didn't get the optimized value le results are yet not clear. To overcome this problem, further, we are using the modified "ga ()" command.
3rd Static behaviour of Bounded Input with Increased Population:
tic
options = optimoptions('ga');
options = optimoptions(options,'PopulationSize',300);
for p = 1: num_spaces
[results,fopt(p)] = ga(@stagalmite,2,[],[],[],[],[0;0],[0.6;0.6],[],[],options);
xopt(p) = results(1);
yopt(p) = results(2);
end
study_time3 = toc
To get the time taken to complete the cycle we used the tic toc commands to record the time.
Options- optimoptions (SolverName)returns a set of default options for the SolverName solver

Options-optimoptions (SolverName ,Name Value) return options with name parameters altered with the specified values

X = ga(fun,nvars,A,b,Aeq,beqib,ub,nonicon,options)minimizes with the default optimization porter replaced by values in option
Thus by doing this we have changed the "population size" to 300. Then, in the 'ga() function we have used the following syntax to give this change as one of the inputs.
Here in the above syntax, we have elder all the inputs as that of the previous code additionally we can also give nonlinear constraints and "options" le. (change of default values as inputs in 'ga () function.
Since here we don't have any nonlinear constraints, we have entered in its place and we have entered the "options as inputs to bell the "ga ()" that there is the change in default values.
Study time3 will be calculated.
figure(3)
subplot(2,1,1)
surf(x,y,f)
shading interp
hold on
plot3(xopt,yopt,fopt,'marker','O','MarkerSize',5,'MarkerFaceColor','r')
xlabel('X axis')
ylabel('Y axis')
title('increased initial population Input')
subplot(2,1,2)
plot(fopt)
xlabel('Interaction')
ylabel('Function Minimum')
Now we store the results into xopt, yopt now we need to plot the surface of x,y, and f to get the 3D plot. We use the plot3 command to make a plot of xopt,yopt and fopt to plot the optimum maximal. Also, let us plot the fopt function so that we can visualise the optimum values at each iteration.
subplot(2,1,1) it creates the graph output as per this command.
sub plot (2 rows, 1 column, plot the values in 1 row)
subplot(2,1,2)
subplot (2 rows 1 column created, plot the values in 2 row)
here in 2 graph, we plotting fopt values which we get from ''ga()"
Then we are naming for the title & axis of the graph
The study executes the output displayed as.

From the above fig, we can observe that by increasing the population size we have got a single optimized value in the graph. If we increase the population size further, the value will be more accurate 12 in the 2 plots we can observe that the maximum value for many iterations is near 0.9999985 and only in 3 Iteration "ga () predicts that the value of T is less than of other iteration values, So the maximum value is somewhere near to this value 14. This problem can be further rectified by increasing the population size and our graph will be much more clear.

Output:
1st Study about the unbounded
2nd Study about the Bounded values
3rd Static behaviour of Bounded Input with Increased Population:
Workspace Output:
Conclusion:

The idea behind the above studies is to observe how the 'ga ()' commands work with different inputs and how to obtain the same value for a function even if "ga" is run several times. Thus Global Maxima is found for the stalagmite function. A Genetic Algorithm is one of the most used methods for obtaining optimized value.

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.