Package: pygad
PyGAD:  Genetic Algorithm in PythonPyGADis an open-source easy-to-use Python 3 library for building the genetic algorithm and optimizing machine learning algorithms. It supports Keras and PyTorch. PyGAD supports optimizing both single-objective and multi-objective problems.Check documentation of thePyGAD.PyGADsupports different types of crossover, mutation, and parent selection.PyGADallows different types of problems to be optimized using the genetic algorithm by customizing the fitness function.The library is under active development and more features are added regularly. If you want a feature to be supported, please check theContact Ussection to send a request.DonationCredit/Debit Card:https://donate.stripe.com/eVa5kO866elKgM0144Open Collective:opencollective.com/pygadPayPal: Use either this link:paypal.me/ahmedfgador the e-mail addressahmed.f.gad@gmail.comInterac e-Transfer: Use e-mail addressahmed.f.gad@gmail.comInstallationTo installPyGAD, simply use pip to download and install the library fromPyPI(Python Package Index). The library is at PyPI at this pagehttps://pypi.org/project/pygad.Install PyGAD with the following command:pipinstallpygadTo get started with PyGAD, please read the documentation atRead The Docshttps://pygad.readthedocs.io.PyGAD Source CodeThe source code of the PyGAD' modules is found in the following GitHub projects:pygad: (https://github.com/ahmedfgad/GeneticAlgorithmPython)pygad.nn:https://github.com/ahmedfgad/NumPyANNpygad.gann:https://github.com/ahmedfgad/NeuralGeneticpygad.cnn:https://github.com/ahmedfgad/NumPyCNNpygad.gacnn:https://github.com/ahmedfgad/CNNGeneticpygad.kerasga:https://github.com/ahmedfgad/KerasGApygad.torchga:https://github.com/ahmedfgad/TorchGAThe documentation of PyGAD is available atRead The Docshttps://pygad.readthedocs.io.PyGAD DocumentationThe documentation of the PyGAD library is available atRead The Docsat this link:https://pygad.readthedocs.io. It discusses the modules supported by PyGAD, all its classes, methods, attribute, and functions. For each module, a number of examples are given.If there is an issue using PyGAD, feel free to post at issue in thisGitHub repositoryhttps://github.com/ahmedfgad/GeneticAlgorithmPythonor by sending an e-mail toahmed.f.gad@gmail.com.If you built a project that uses PyGAD, then please drop an e-mail toahmed.f.gad@gmail.comwith the following information so that your project is included in the documentation.Project titleBrief descriptionPreferably, a link that directs the readers to your projectPlease check theContact Ussection for more contact details.Life Cycle of PyGADThe next figure lists the different stages in the lifecycle of an instance of thepygad.GAclass. Note that PyGAD stops when either all generations are completed or when the function passed to theon_generationparameter returns the stringstop.The next code implements all the callback functions to trace the execution of the genetic algorithm. Each callback function prints its name.importpygadimportnumpyfunction_inputs=[4,-2,3.5,5,-11,-4.7]desired_output=44deffitness_func(ga_instance,solution,solution_idx):output=numpy.sum(solution*function_inputs)fitness=1.0/(numpy.abs(output-desired_output)+0.000001)returnfitnessfitness_function=fitness_funcdefon_start(ga_instance):print("on_start()")defon_fitness(ga_instance,population_fitness):print("on_fitness()")defon_parents(ga_instance,selected_parents):print("on_parents()")defon_crossover(ga_instance,offspring_crossover):print("on_crossover()")defon_mutation(ga_instance,offspring_mutation):print("on_mutation()")defon_generation(ga_instance):print("on_generation()")defon_stop(ga_instance,last_population_fitness):print("on_stop()")ga_instance=pygad.GA(num_generations=3,num_parents_mating=5,fitness_func=fitness_function,sol_per_pop=10,num_genes=len(function_inputs),on_start=on_start,on_fitness=on_fitness,on_parents=on_parents,on_crossover=on_crossover,on_mutation=on_mutation,on_generation=on_generation,on_stop=on_stop)ga_instance.run()Based on the used 3 generations as assigned to thenum_generationsargument, here is the output.on_start()

on_fitness()
on_parents()
on_crossover()
on_mutation()
on_generation()

on_fitness()
on_parents()
on_crossover()
on_mutation()
on_generation()

on_fitness()
on_parents()
on_crossover()
on_mutation()
on_generation()

on_stop()ExampleCheck thePyGAD's documentationfor information about the implementation of this example. It solves a single-objective problem.importpygadimportnumpy"""Given the following function:y = f(w1:w6) = w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + 6wx6where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7) and y=44What are the best values for the 6 weights (w1 to w6)? We are going to use the genetic algorithm to optimize this function."""function_inputs=[4,-2,3.5,5,-11,-4.7]# Function inputs.desired_output=44# Function output.deffitness_func(ga_instance,solution,solution_idx):# Calculating the fitness value of each solution in the current population.# The fitness function calulates the sum of products between each input and its corresponding weight.output=numpy.sum(solution*function_inputs)fitness=1.0/numpy.abs(output-desired_output)returnfitnessfitness_function=fitness_funcnum_generations=100# Number of generations.num_parents_mating=7# Number of solutions to be selected as parents in the mating pool.# To prepare the initial population, there are 2 ways:# 1) Prepare it yourself and pass it to the initial_population parameter. This way is useful when the user wants to start the genetic algorithm with a custom initial population.# 2) Assign valid integer values to the sol_per_pop and num_genes parameters. If the initial_population parameter exists, then the sol_per_pop and num_genes parameters are useless.sol_per_pop=50# Number of solutions in the population.num_genes=len(function_inputs)last_fitness=0defcallback_generation(ga_instance):globallast_fitnessprint(f"Generation ={ga_instance.generations_completed}")print(f"Fitness    ={ga_instance.best_solution()[1]}")print(f"Change     ={ga_instance.best_solution()[1]-last_fitness}")last_fitness=ga_instance.best_solution()[1]# Creating an instance of the GA class inside the ga module. Some parameters are initialized within the constructor.ga_instance=pygad.GA(num_generations=num_generations,num_parents_mating=num_parents_mating,fitness_func=fitness_function,sol_per_pop=sol_per_pop,num_genes=num_genes,on_generation=callback_generation)# Running the GA to optimize the parameters of the function.ga_instance.run()# After the generations complete, some plots are showed that summarize the how the outputs/fitenss values evolve over generations.ga_instance.plot_fitness()# Returning the details of the best solution.solution,solution_fitness,solution_idx=ga_instance.best_solution()print(f"Parameters of the best solution :{solution}")print(f"Fitness value of the best solution ={solution_fitness}")print(f"Index of the best solution :{solution_idx}")prediction=numpy.sum(numpy.array(function_inputs)*solution)print(f"Predicted output based on the best solution :{prediction}")ifga_instance.best_solution_generation!=-1:print(f"Best fitness value reached after{ga_instance.best_solution_generation}generations.")# Saving the GA instance.filename='genetic'# The filename to which the instance is saved. The name is without extension.ga_instance.save(filename=filename)# Loading the saved GA instance.loaded_ga_instance=pygad.load(filename=filename)loaded_ga_instance.plot_fitness()For More InformationThere are different resources that can be used to get started with the genetic algorithm and building it in Python.Tutorial: Implementing Genetic Algorithm in PythonTo start with coding the genetic algorithm, you can check the tutorial titledGenetic Algorithm Implementation in Pythonavailable at these links:LinkedInTowards Data ScienceKDnuggetsThis tutorialis prepared based on a previous version of the project but it still a good resource to start with coding the genetic algorithm.Tutorial: Introduction to Genetic AlgorithmGet started with the genetic algorithm by reading the tutorial titledIntroduction to Optimization with Genetic Algorithmwhich is available at these links:LinkedInTowards Data ScienceKDnuggetsTutorial: Build Neural Networks in PythonRead about building neural networks in Python through the tutorial titledArtificial Neural Network Implementation using NumPy and Classification of the Fruits360 Image Datasetavailable at these links:LinkedInTowards Data ScienceKDnuggetsTutorial: Optimize Neural Networks with Genetic AlgorithmRead about training neural networks using the genetic algorithm through the tutorial titledArtificial Neural Networks Optimization using Genetic Algorithm with Pythonavailable at these links:LinkedInTowards Data ScienceKDnuggetsTutorial: Building CNN in PythonTo start with coding the genetic algorithm, you can check the tutorial titledBuilding Convolutional Neural Network using NumPy from Scratchavailable at these links:LinkedInTowards Data ScienceKDnuggetsChinese TranslationThis tutorial) is prepared based on a previous version of the project but it still a good resource to start with coding CNNs.Tutorial: Derivation of CNN from FCNNGet started with the genetic algorithm by reading the tutorial titledDerivation of Convolutional Neural Network from Fully Connected Network Step-By-Stepwhich is available at these links:LinkedInTowards Data ScienceKDnuggetsBook: Practical Computer Vision Applications Using Deep Learning with CNNsYou can also check my book cited asAhmed Fawzy Gad 'Practical Computer Vision Applications Using Deep Learning with CNNs'. Dec. 2018, Apress, 978-1-4842-4167-7which discusses neural networks, convolutional neural networks, deep learning, genetic algorithm, and more.Find the book at these links:AmazonSpringerApressO'ReillyGoogle BooksCiting PyGAD - Bibtex Formatted CitationIf you used PyGAD, please consider adding a citation to the following paper about PyGAD:@article{gad2023pygad,
  title={Pygad: An intuitive genetic algorithm python library},
  author={Gad, Ahmed Fawzy},
  journal={Multimedia Tools and Applications},
  pages={1--14},
  year={2023},
  publisher={Springer}
}Contact UsE-mail:ahmed.f.gad@gmail.comLinkedInPaperspaceKDnuggetsTowardsDataScienceGitHub