This repository contains a Python implementation of a Genetic Algorithm (GA) class and an example application solving the Traveling Salesman Problem (TSP).
Class_GA.py: Contains theGeneticAlgorithmclass, a flexible implementation of a genetic algorithm.TS_example.py: Demonstrates how to use theGeneticAlgorithmclass to solve a Traveling Salesman Problem.
- Python 3.6 or higher
- No additional libraries required
-
Clone this repository:
git clone https://github.com/yourusername/ga-tsp-solver.git cd ga-tsp-solver -
Run the TSP example:
python TS_example.py
This will execute the genetic algorithm to find an optimal solution for the TSP defined in the script.
To use the GeneticAlgorithm class for your own problems:
-
Import the class:
from Class_GA import GeneticAlgorithm
-
Define your fitness function. It should take a chromosome (list of integers) as input and return a fitness score (float).
-
Initialize the GA:
ga = GeneticAlgorithm( population_size=100, chromosome_length=your_chromosome_length, fitness_func=your_fitness_function, mutation_rate=0.02, crossover_rate=0.8, elitism=0.1 )
-
Evolve the population:
best_solution = ga.evolve(generations=500)
-
Interpret the result based on your problem domain.
- Modify the
mutation_rate,crossover_rate, andelitismparameters to fine-tune the algorithm's performance. - Adjust the
population_sizeand number ofgenerationsbased on your problem's complexity and computational resources. - For problems other than permutation-based ones like TSP, you may need to modify the
generate_chromosome,crossover, andmutatemethods in theGeneticAlgorithmclass.
Contributions to improve the algorithm or add new features are welcome. Please feel free to submit pull requests or open issues for any bugs or enhancements.
This project is open-source and available under the MIT License.