Week 4 - Genetic Algorithm
AIM:
- To write a code in MATLAB to optimise the stalagmite function and find the global maxima of the function.
THEORY:
In CS and op research, a genetic algorithm (GA) is a metaheuristic inspired by the process of natural selection that belongs to the larger class of evolutionary algorithms (EA). Genetic algos are commonly used to generate high-quality solutions to optimization and search problems by relying on biologically inspired operators such as mutation, crossover and selection.
CODING:
MAIN CODE:
clear all
close all
clc
% definin our search space
x = linspace(0,0.6,150);
y = linspace(0,0.6,150);
num_cases = 50;
% creating a 2D mesh
[xx yy] = meshgrid(x,y);
% eval tha stalgamite func
for i = 1:length(xx)
for j = 1:length(yy)
input_vector(1) = xx(i,j);
input_vector(2) = xx(i,j);
f(i,j) = stalagamite(input_vector);
end
end
% stat behaviuor
surfc(xx,yy,-f)
xlabel('X')
ylabel('Y')
shading interp
plot3(x0pt1,yopt1,'marker','o','markersize',5,'markerfacecolor','r');
title('unbound inputs')
subplot(2,1,2)
plot(-fopt1)
xlabel('iteration')
ylabel('function_minimum')
% Behaviour
tic
for i = 1:num_cases
[inputs,fopt2(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
xopt2(i) = inputs(1);
yopt2(i) = inputs(2);
end
study_time2 = toc;
figure(2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
xlabel('X')
ylabel('Y')
shading interp
plot3(xopt2,yopt2,-fopt2,'marker','o','markersize',5,'markerfacecolor','r')
subplot(2,1,2)
plot(-fopt2)
xlabel('iteration')
ylabel('function_minimum')
% inc popilation
options = gaoptimset(@ga);
options = gaoptimset(options,'populationsize',300);
tic
for i = 1:num_cases
[inputs,fopt3(i)] = ga(@stalagmite,2,[],[],[],[],[0;0],[1;1]);
xopt3(i) = inputs(1);
yopt3(i) = inputs(2);
end
study_time2 = toc;
figure(2)
subplot(2,1,1)
hold on
surfc(xx,yy,-f)
xlabel('X')
ylabel('Y')
shading interp
plot3(xopt2,yopt2,-fopt2,'marker','o','markersize',5,'markerfacecolor','r')
subplot(2,1,2)
plot(-fopt3)
xlabel('iteration')
ylabel('function_minimum')
FUNCTION:
% stalagamite function
x= input_vector(1);
y= input_vector(2);
f1_x = (sin(5.1*pi*x +0.5)).^6;
f1_y = (sin(5.1*pi*y +0.5)).^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 = -(f1_x*f2_x*f1_y*f2_y);
end
RESULT:
EXPLANATION:
- Creating a Stalgamite function as shown in the code.
- Maximization of stalagamite function using gen. algo.
- Creating a 2D array using mesh grid command.
- Assigning values of input(1) and input(2) using 2 for loops.
- Plotting the values.