Genetic algorithm applied to TSP

Genetic Algorithms (GAs) are a type of evolutionary algorithm inspired by natural selection, used to find approximate solutions to optimization and search problems. They start with a population of randomly generated candidate solutions, each represented by a chromosome. Individuals are selected based on their fitness, which measures how good a solution is. Selected individuals undergo crossover (recombination) to produce offspring, followed by mutation to introduce random changes, maintaining genetic diversity. The new generation replaces the old, and this process repeats until a stopping criterion, such as a maximum number of generations or convergence, is met.

The Traveling Salesman Problem (TSP) is a classic optimization challenge where the goal is to find the shortest possible route visiting a set of cities exactly once and returning to the origin city. It is an NP-hard problem with various exact and heuristic algorithms for its solution. Exact algorithms like brute force and dynamic programming are computationally intensive, while heuristics like nearest neighbor and minimum spanning tree (MST) based algorithms provide approximate solutions. Genetic algorithms are particularly effective for TSP due to their capability to search large and complex spaces. They represent tours as chromosomes, apply selection, crossover, and mutation to evolve better solutions over generations, thus finding efficient routes in complex TSP scenarios.

The results of TSP problem solved by genetic algorithm:

rich text editor imagerich text editor image

matlab code is as follows:

% Copyright (c) 2023, https://matlabcode.dev, All rights reserved.

% This code is provided for educational purposes and is open for sharing and modification.

% Please ensure proper attribution when using or distributing this code.

clc; clear all; close all;

% Parameter settings

numCities = 20; % Number of cities

numGenerations = 5000; % Number of generations

populationSize = 50; % Population size

mutationRate = 0.1; % Mutation rate

crossoverRate = 0.9; % Crossover rate

% Generate initial city coordinates

cities = generateCities(numCities);

% Generate initial population

population = generatePopulation(populationSize, numCities);

% Genetic algorithm iteration

bestvalue_fig = [];

for generation = 1:numGenerations

generation

% Calculate fitness

fitness = calculateFitness(population, cities);

% Find the best route

[~, bestIndex] = max(fitness);

bestRoute = population(bestIndex, :);

% Selection

selectedPopulation = selection(population, fitness);

% Crossover

crossedPopulation = crossover(selectedPopulation, crossoverRate);

% Mutation

mutatedPopulation = mutation(crossedPopulation, mutationRate);

% Update population

population = [selectedPopulation; mutatedPopulation];

population(end, 🙂 = bestRoute;

bestvalue_fig = [bestvalue_fig 1 / max(fitness)];

end

% Plot the best route

plotRoute(cities, bestRoute);

Leave a Comment