Solving the Traveling Salesman Problem (TSP) Using a Genetic Algorithm in Python
Introduction
The Traveling Salesman Problem (TSP) is a classic optimization problem where the goal is to find the shortest possible route that visits a set of cities exactly once and returns to the origin city. TSP is NP-hard, meaning that as the number of cities increases, the problem becomes computationally intensive to solve exactly.
Genetic Algorithms (GAs) are a type of evolutionary algorithm inspired by natural selection, which are particularly useful for optimization problems like TSP. GAs work by evolving a population of candidate solutions over generations, using operators such as selection, crossover, and mutation to explore the solution space.
Why Use a Genetic Algorithm for TSP?
- Heuristic Nature: GAs are effective for finding good-enough solutions in a reasonable time frame, especially for large instances where exact algorithms are impractical.
- Flexibility: They can handle various constraints and complexities inherent in real-world TSP variants.
- Parallelism: The population-based approach allows for parallel exploration of multiple solutions.
Implementation Overview
We'll implement a Genetic Algorithm to solve a small instance of TSP. The implementation includes:
- Representation: Each individual in the population represents a possible tour (sequence of cities).
- Fitness Function: The fitness of an individual is inversely related to the total distance of the tour.
- Selection: We use tournament selection to choose parents for reproduction.
- Crossover: Order Crossover (OX) is used to combine two parents into offspring.
- Mutation: Swap mutation is applied to introduce variability.
- Evolution: The population evolves over multiple generations, improving the overall fitness.
Python Implementation
Below is a self-contained Python script that implements a Genetic Algorithm to solve the TSP. The script includes comments for clarity and uses standard Python libraries.
import random
import math
import matplotlib.pyplot as plt
# Define the City class
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, city):
return math.hypot(self.x - city.x, self.y - city.y)
# Define the Individual (Tour)
class Individual:
def __init__(self, city_list):
self.city_list = city_list
self.fitness = 0.0
self.distance = 0.0
def calculate_fitness(self):
self.distance = 0.0
for i in range(len(self.city_list)):
from_city = self.city_list[i]
to_city = self.city_list[(i + 1) % len(self.city_list)]
self.distance += from_city.distance_to(to_city)
self.fitness = 1 / self.distance if self.distance > 0 else float('inf')
# Genetic Algorithm for TSP
class GeneticAlgorithm:
def __init__(self, cities, population_size=100, elite_size=20, mutation_rate=0.01, generations=500):
self.cities = cities
self.population_size = population_size
self.elite_size = elite_size
self.mutation_rate = mutation_rate
self.generations = generations
self.population = []
def initial_population(self):
self.population = []
for _ in range(self.population_size):
shuffled_cities = random.sample(self.cities, len(self.cities))
individual = Individual(shuffled_cities)
individual.calculate_fitness()
self.population.append(individual)
def rank_population(self):
self.population.sort(key=lambda x: x.fitness, reverse=True)
def selection(self):
selection_results = []
df = [ind.fitness for ind in self.population]
cumulative_sum = sum(df)
probabilities = [f / cumulative_sum for f in df]
cumulative_prob = []
total = 0
for p in probabilities:
total += p
cumulative_prob.append(total)
for _ in range(self.elite_size):
selection_results.append(self.population[_])
for _ in range(self.population_size - self.elite_size):
pick = random.random()
for i, individual in enumerate(self.population):
if pick <= cumulative_prob[i]:
selection_results.append(individual)
break
return selection_results
def crossover(self, parent1, parent2):
child_p1 = []
child_p2 = []
gene_a = int(random.random() * len(parent1.city_list))
gene_b = int(random.random() * len(parent1.city_list))
start_gene = min(gene_a, gene_b)
end_gene = max(gene_a, gene_b)
for i in range(start_gene, end_gene):
child_p1.append(parent1.city_list[i])
child_p2 = [city for city in parent2.city_list if city not in child_p1]
child = Individual(child_p1 + child_p2)
return child
def mutate(self, individual):
for swapped in range(len(individual.city_list)):
if random.random() < self.mutation_rate:
swap_with = int(random.random() * len(individual.city_list))
city1 = individual.city_list[swapped]
city2 = individual.city_list[swap_with]
individual.city_list[swapped] = city2
individual.city_list[swap_with] = city1
individual.calculate_fitness()
def next_generation(self, selection_results):
children = []
self.rank_population()
# Elitism
for i in range(self.elite_size):
children.append(self.population[i])
# Crossover
for i in range(self.elite_size, self.population_size):
parent1 = random.choice(selection_results[:self.population_size//2])
parent2 = random.choice(selection_results[:self.population_size//2])
child = self.crossover(parent1, parent2)
children.append(child)
# Mutation
for individual in children[self.elite_size:]:
self.mutate(individual)
# Calculate fitness
for individual in children:
individual.calculate_fitness()
self.population = children
def run(self):
self.initial_population()
for i in range(self.generations):
self.rank_population()
print(f'Generation {i+1} | Best distance: {self.population[0].distance:.2f}')
selection_results = self.selection()
self.next_generation(selection_results)
best_individual = self.population[0]
return best_individual
# Utility function to create random cities
def create_random_cities(num_cities, width=100, height=100):
cities = []
for _ in range(num_cities):
x = random.randint(0, width)
y = random.randint(0, height)
cities.append(City(x, y))
return cities
# Plot the best route
def plot_route(individual):
plt.figure(figsize=(10, 6))
x = [city.x for city in individual.city_list] + [individual.city_list[0].x]
y = [city.y for city in individual.city_list] + [individual.city_list[0].y]
plt.plot(x, y, 'o-', color='blue')
plt.title(f'Best Route | Total Distance: {individual.distance:.2f}')
plt.xlabel('X Coordinate')
plt.ylabel('Y Coordinate')
plt.show()
# Main execution
if __name__ == "__main__":
# Create a list of cities
num_cities = 20
cities = create_random_cities(num_cities)
# Initialize Genetic Algorithm
ga = GeneticAlgorithm(cities=cities, population_size=100, elite_size=20, mutation_rate=0.01, generations=500)
# Run the algorithm
best_route = ga.run()
# Print the best distance
print(f'Final Best Distance: {best_route.distance:.2f}')
# Plot the best route
plot_route(best_route)
How to Run the Code
-
Prerequisites:
- Python 3.x installed on your machine.
matplotlib library for plotting. You can install it using:
pip install matplotlib
-
Execution:
-
Output:
- The script will print the best distance found in each generation.
- After completing all generations, it will display the final best distance and plot the corresponding route.
Notes and Further Improvements
- Parameters Tuning: The performance of the Genetic Algorithm heavily depends on parameters like population size, elite size, mutation rate, and the number of generations. Experimenting with these can lead to better solutions.
- Crossover and Mutation Operators: Different crossover and mutation strategies can be implemented to potentially yield better results.
- Scalability: For larger instances of TSP, more sophisticated techniques and optimizations may be necessary to handle the increased complexity.
- Visualization Enhancements: Additional visualization features can be added to observe the evolution of the population over generations.
Conclusion
Genetic Algorithms provide a powerful heuristic for solving complex optimization problems like the Traveling Salesman Problem. This implementation showcases the fundamental components of a GA and demonstrates how evolutionary principles can be leveraged to find near-optimal solutions in a computationally efficient manner.