Week 4.1 - Genetic Algorithm
A genetic algorithm is a search heuristic that is inspired by Charles Darwin’s theory of natural evolution. This algorithm reflects the process of natural selection where the fittest individuals are selected for reproduction in order to produce offspring of the next generation.
Notion 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.
- Initial population
- Fitness function
- Selection
- Crossover
- Mutation
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 0s). We say that we encode the genes in a chromosome.
Fitness Function
The fitness function determines how fit an individual is (the ability of an individual to compete with other individuals). It gives a fitness score to each individual. The probability that an individual will be selected for reproduction is based on its fitness score.
Selection
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.
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.
For example, consider the crossover point to be 3 as shown below.
Offspring are created by exchanging the genes of parents among themselves until the crossover point is reached.
The new offspring are added to the population.
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.
General syntaxof ga in matlab:
clear all
close all
clc
%Describing Search Space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
%Creating 2-D array
[xx,yy]=meshgrid(x,y);
num_cases = 50;
f=get_stalagmite(xx,yy);
tic
%Study 1: Statisticalbehavior of ga
for i = 1:num_cases
[inputs, fopt(i)] = ga(@stalagmite, 2);
xopt(i) = inputs(1);
yopt(i) = inputs(2);
end
study_time1=toc;
figure(1)
subplot(2,1,1)
hold on
surfc(xx,yy,-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 Maximum')
tic
%Study 2: Statistical behaviorof ga with boundary coditions
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(xx,yy,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('Bounded Inputs')
subplot(2,1,2)
plot(fopt)
xlabel('Numbr of interactions')
ylabel('Function Maximum')
%Study 3: Statistical behavior b icrasing number of ga iterations
options=optimoptions('ga');
options=optimoptions(options,'populationsize',170);
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)
hold on
surfc(xx,yy,-f)
shading interp
plot3(xopt,yopt,-fopt,'marker','o','markersize',5,'markerfacecolor','r')
title('Bounded inputs')
subplot(2,1,2)
plot(fopt)
xlabel('Number of iteration')
ylabel('Fuction maximum')
Line 1-3: Clears the workspace, Closes all open matlab figure windows and clears command window
Line 6 & 7: Establishes search space for the ga function
Line 10: Converts the two 1-D arrays, x & y, into 2-D arrays
Line 12: Assigns the variable 'num_cases' a value of '50'
Line 13: Calls the 'get_stalagmite' function and stores the output in 'f'
Line 15: Starts stopwatch timer for first study
Line 17: Initiates for loop for values between 1 and 'num_cases'
Line 18: Finds the local unconstrained minimum of the function 'stalagmite' with 2 variables as input a gives the x and y coordites pertaining to that minimum as output with the value of the function at that point
Line 19 & 20: Stores the values of inputs 1 and 2 in xopt(i) and yopt(i) respectively
Line 21: Ends for loop
Line 22: Stops the stop watch and stores the value in 'study_time1'
Line 23: Initiates Figure 1
Line 24: Creates a subplot of a figure containing 2 rows and 1 column and the last variable in the subplot command means it is the 1st subplot
Line 25: Retains current plot
Line 26: Plots a surface plot of xx, yy and -f (negative to invert hte function back to positive axis)
Line 27: Sets color shading properties
Line 28: Creates a 3-D plot of xopt, yopt and -fopt
Line 29: Gives title to the current figure
Line 30: Creates 2nd plot of the subplot
Line 31: Creates a 2-D plot of 'fopt' against number of iterations
Line 32 & 33: Creates x and y axis labels
Line 35: Starts stopwatch timer for second study
Line 37: Initiates for loop for values between 1 and 'num_cases'
Line 38: Finds the local unconstrained minimum of the function 'stalagmite' with 2 variables as input and upper and lower boundary conditions and gives the x and y coordinates pertaining to that minimum as output with the value of the function at that point
Line 39 & 40: Stores the values of inputs 1 and 2 in xopt(i) and yopt(i) respectively
Line 41: Ends for loop
Line 43: Stops the stop watch and stores the value in 'studu_time2'
Line 44: Initiates Figure 2
Line 45: Creates a subplot of a figure containing 2 rows and 1 column and the last variable in the subplot command means it is the 1st subplot
Line 46: Retains current plot
Line 47: Plots a surface plot of xx, yy and -f
Line 48: Sets color shading properties
Line 49: Creates a 3-D plot of xopt, yopt and -fopt
Line 50: Gives title to the current figure
Line 51: Creates 2nd plot of the subplot
Line 52: Creates a 2-D plot of 'fopt' against number of iterations
Line 53 & 54: Creates x and y axis labels
Line 57: Returns a set of optimum options for the ga solver
Line 58: Returns a copy of options with the named parameters altered with the specified values.
Line 60: Starts stopwatch timer for third study
Line 61: Initiates for loop for values between 1 and 'num_cases'
Line 62: Finds the local unconstrained minimum of the function 'stalagmite' with 2 variables as input,within the specified boundary conditions and minimizes the default optimization parameters as specified within 'options' and gives the x and y coordinates pertaining to that minimum as output with the value of the function at that point
Line 63 & 64: Stores the values of inputs 1 and 2 in xopt(i) and yopt(i) respectively
Line 65: Ends for loop
Line 67: Stops the stop watch and stores the value in 'studu_time3'
Line 69: Initiates Figure 3
Line 70: Creates a subplot of a figure containing 2 rows and 1 column and the last variable in the subplot command means it is the 1st subplot
Line 71: Retains current plot
Line 72: Plots a surface plot of xx, yy and -f
Line 73: Sets color shading properties
Line 74: Creates a 3-D plot of xopt, yopt and -fopt
Line 75: Gives title to the current figure
Line 76: Creates 2nd plot of the subplot
Line 77: Creates a 2-D plot of 'fopt' against number of iterations
Line 78 & 79: Creates x and y axis labels
GET_STALAGMITE FUNCTION:
function[f]=get_stalagmite(xx,yy)
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
end
Line 1: Creates function with the name 'get_stalagmite' which accepts 2 variables as inputs
Line 3: Initiates for loop for values between 1 and the length of the array 'xx'
Line 4: Initiates for loop for values between 1 and the length of the array 'yy'
Line 5: Assigns the value of xx(i,j) to input_vector(1)
Line 6: Assigns the value of yy(i,j) to input_vector(2)
Line 7: Callsthe function 'stalagmite' and stores its values in f(i,j)
Line 8: Ends j for loop
Line 9: Ends i for loop
Line 10: Ends function
STALAGMITE FUNCTION:
function [f] = stalagmite(inputs)
x = inputs(1);
y = inputs(2);
f1_x = [sin(5.1*pi*x)].^6;
f1_y = [sin(5.1*pi*y)].^6;
f2_x = exp(-4*log(2)*((x-0.0667).^2)/0.64);
f2_y = exp(-4*log(2)*((y-0.0667).^2)/0.64);
f = -1*f1_x*f2_x*f1_y*f2_y;
end
The above function creates the 'stalagmite' function for which the optimization is to be conducted. The negative sign is included so that the function is described in the negative axis as ga finds the minimum value of the function