Challenge

Week 5 - Genetic Algorithm

Code For GA MATLAB.

% Genetic Algorithm to Optimize Stalagmite Function

populationSize = 100; % Adjust population size as needed

numGenerations = 100; % Adjust number of generations as needed

mutationRate = 0.01; % Adjust mutation rate as needed

% Initialize population

population = rand(populationSize, 2) * 10 - 5; % Random initialization within [-5, 5]

for generation = 1:numGenerations

% Evaluate fitness

fitness = -(population(:,1).^2 + population(:,2).^2) .* exp(-(population(:,1).^2 + population(:,2).^2));

% Selection: Roulette Wheel Selection

cumulativeFitness = cumsum(fitness);

totalFitness = sum(fitness);

selectionProbabilities = cumulativeFitness / totalFitness;

% Initialize selected population

selectedPopulation = zeros(populationSize, 2);

% Select individuals

for i = 1:populationSize

% Select a random number between 0 and 1

r = rand();

% Find the index of the first cumulative probability greater than the random number

index = find(cumulativeFitness >= r * totalFitness, 1);

% Assign the selected individual to the selected population

index = find(cumulativeFitness >= round(r * totalFitness), 1);

end

% Crossover: Single Point Crossover

crossoverPoints = randi([1, 2], populationSize / 2, 1);

offspring = zeros(populationSize, 2);

for i = 1:2:populationSize

parent1 = selectedPopulation(i, :);

parent2 = selectedPopulation(i+1, :);

offspring(i, :) = [parent1(1:crossoverPoints(ceil(i/2))), parent2(crossoverPoints(ceil(i/2))+1:end)];

offspring(i+1, :) = [parent2(1:crossoverPoints(ceil(i/2))), parent1(crossoverPoints(ceil(i/2))+1:end)];

end

% Mutation

mutateIndices = rand(populationSize, 2) < mutationRate;

offspring(mutateIndices) = rand(sum(mutateIndices(:)), 1) * 10 - 5;

% Replace population with offspring

population = offspring;

end

% Find best solution

bestFitness = -(population(:,1).^2 + population(:,2).^2) .* exp(-(population(:,1).^2 + population(:,2).^2));

[bestFitness, bestIndex] = max(bestFitness);

bestSolution = population(bestIndex, :);

fprintf('Best Solution: (%f, %f)\n', bestSolution(1), bestSolution(2));

fprintf('Fitness: %f\n', bestFitness);

  • Step-wise explanation of your code.
  • Mention the errors while programming.
  • Steps taken to overcome those errors.
  • Screenshots showing errors thrown in command window.

Part 2.

Certainly! Let's start with an explanation of genetic algorithms (GAs):

Explanation of Genetic Algorithms (GAs):

Genetic algorithms are a type of optimization algorithm inspired by the process of natural selection and evolution in biology. The main idea behind genetic algorithms is to mimic the process of natural selection to solve optimization problems. They work by simulating the evolution of potential solutions to a problem over successive generations.

Here's how genetic algorithms work:

Initialization: The process begins with a population of potential solutions, usually generated randomly or using some heuristic method.

Evaluation: Each solution in the population is evaluated and assigned a fitness score based on how well it solves the problem. The fitness score represents how close the solution is to the optimal solution.

Selection: Solutions with higher fitness scores are more likely to be selected for reproduction. This mimics the concept of "survival of the fittest" in natural selection. There are various selection methods, such as roulette wheel selection, tournament selection, or elitism.

Reproduction (Crossover): Selected solutions (parents) are combined to create new solutions (offspring) through crossover or recombination. This involves exchanging information between two parent solutions to produce one or more offspring solutions. Common crossover techniques include single-point crossover, multi-point crossover, and uniform crossover.

Mutation: To maintain genetic diversity in the population and prevent premature convergence, random changes are introduced to some solutions in the population. This step is called mutation. Mutation can occur with a low probability and typically involves small changes to a solution.

Replacement: The offspring and potentially mutated solutions replace some of the existing solutions in the population, ensuring that the population size remains constant.

Termination: The process continues for a fixed number of generations or until a termination criterion is met, such as finding a solution with satisfactory fitness or reaching a maximum number of generations.

By iteratively applying these steps, genetic algorithms explore the solution space and converge towards optimal or near-optimal solutions for the given problem.

Explanation of ga Syntax in MATLAB:

In MATLAB, the Genetic Algorithm Toolbox provides a function called ga to implement genetic algorithms. Here's an explanation of its syntax:

[x, fval] = ga(@fitnessfun, nvars)

@fitnessfun: This is a function handle that represents the fitness function to be optimized. It takes a vector of decision variables as input and returns a scalar value representing the fitness of the solution.

nvars: This specifies the number of decision variables in the optimization problem.

Additional optional parameters can be provided to customize the behavior of the genetic algorithm, such as:

lb and ub: Lower and upper bounds for the decision variables, respectively.

options: A structure containing options for the genetic algorithm, such as population size, crossover and mutation parameters, and termination criteria.

The ga function searches for the optimal solution by evolving a population of potential solutions using the genetic algorithm framework. After the algorithm completes, it returns the best solution found (x) and its corresponding fitness value (fval).

In summary, the ga function in MATLAB provides a convenient way to apply genetic algorithms to optimization problems by specifying the fitness function and other relevant parameters. It automates the process of population initialization, evolution, and termination, making it easier to find optimal or near-optimal solutions to various optimization problems.

% Define arrays containing data for each study (F_max_study1, F_max_study2, F_max_study3)

% Plot graph for Study 1

figure;

plot(1:numel(F_max_study1), F_max_study1, 'LineWidth', 2);

title('Study 1: F Maximum vs. Number of Iterations');

xlabel('Number of Iterations');

ylabel('F Maximum');

grid on;

% Plot graph for Study 2

figure;

plot(1:numel(F_max_study2), F_max_study2, 'LineWidth', 2);

title('Study 2: F Maximum vs. Number of Iterations');

xlabel('Number of Iterations');

ylabel('F Maximum');

grid on;

% Plot graph for Study 3

figure;

plot(1:numel(F_max_study3), F_max_study3, 'LineWidth', 2);

title('Study 3: F Maximum vs. Number of Iterations');

xlabel('Number of Iterations');

ylabel('F Maximum');

grid on;

% Define arrays containing data for each study (F_max_study1, F_max_study2, F_max_study3)

Steps Taken to Overcome this Error

Using round for Indexing:

Ensure that rounding errors are minimal and do not significantly affect the selection process.

Verify that rounding does not lead to incorrect index selection, especially near boundaries.

Using ceil for Indexing:

Check for out-of-bounds indices after rounding up to ensure they fall within the valid range.

Handle boundary conditions appropriately to prevent accessing invalid indices.

Explicit Conversion to Integer for Indexing:

Double-check that truncating the index using floor does not lead to incorrect selection.

Ensure that the resulting index falls within the valid range and handles boundary conditions properly.

Using max to Ensure Index is within Bounds:

Validate that limiting the index using max does not hide underlying issues with the selection process.

Debug the selection process to ensure proper indexing and handle out-of-bounds cases explicitly.

Checking for Empty Index:

While checking for an empty index is useful, ensure that it covers all possible scenarios, including boundary conditions and precision issues.

Implement robust error handling to address any unexpected conditions that may arise during the selection process.

By following these steps and carefully addressing each potential error scenario, you can ensure the reliability and correctness of the code, especially in critical components like the selection step of a genetic algorithm.

Code for plotting the graph

% Define parameters for all three studies

populationSize = 100;

numGenerations = 100;

mutationRate = 0.01;

% Initialize arrays to store maximum fitness values for each study

maxFitness_study1 = zeros(1, numGenerations);

maxFitness_study2 = zeros(1, numGenerations);

maxFitness_study3 = zeros(1, numGenerations);

% Perform all three studies and store maximum fitness values

for i = 1:numGenerations

% Run study 1

% (Replace the following block with your code for study 1)

% maxFitness_study1(i) = ...

% Run study 2

% (Replace the following block with your code for study 2)

% maxFitness_study2(i) = ...

% Run study 3

% (Replace the following block with your code for study 3)

% maxFitness_study3(i) = ...

end

% Plot graphs for all three studies

iterations = 1:numGenerations;

figure;

plot(iterations, maxFitness_study1, 'b-', 'LineWidth', 2);

hold on;

plot(iterations, maxFitness_study2, 'r--', 'LineWidth', 2);

plot(iterations, maxFitness_study3, 'g-.', 'LineWidth', 2);

% Add title and labels

title('Maximum Fitness vs. Number of Iterations');

xlabel('Number of Iterations');

ylabel('Maximum Fitness');

% Add legend

legend('Study 1', 'Study 2', 'Study 3');

% Show plot

grid on;

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.