Examples¶
Find complete Python scripts by topic, open their source on GitHub, or download examples that need no companion files. Each entry links back to its documentation guide. The same examples appear in Python example cards beside the relevant explanations in those guides.
Running the Examples¶
For examples from this documentation revision, use the matching version of PyGAD. The PyGAD 3.8.0 examples can use the published package:
python -m pip install "pygad[visualize]==3.8.0"
For development examples, including features in the Unreleased notes, clone or download the matching repository revision, then install it from the repository root:
python -m pip install -e ".[visualize]"
Run a script using its path, for example:
python examples/plots/example_plot_lifecycle.py
For a script downloaded separately, run python with the path where you saved it. It still requires a compatible installed version of PyGAD. Plotting examples need Matplotlib; PDF reports need pygad[report]. Keras and PyTorch examples need their respective frameworks. The Run this example dropdowns in the guides give additional requirements and working directories.
Examples requiring datasets link to their folders instead of offering a standalone download. Their datasets are not bundled with PyGAD or the repository. Follow the linked data setup instructions and keep the repository directory layout. The TSP notebook is listed alongside the Python scripts; it uses Google Colab and a user-supplied CSV. Adapt its Colab-specific imports and CSV path before running it locally with Jupyter.
Use documentation search or your browser’s find command to locate a topic or filename on this page.
Getting Started¶
Python script |
What it shows |
Related information |
|---|---|---|
First GA run. Optimize a linear equation, inspect the best solution, plot fitness, and save and reload the GA. |
Population and Genes¶
Python script |
What it shows |
Related information |
|---|---|---|
Initial populations. Generate values from per-gene ranges and nested spaces, or supply values and infer the dimensions. |
||
Gene spaces. Compare shared and per-gene choices, ranges, dictionaries, fixed values, and None entries. |
||
Gene constraints. Filter gene candidates with constraints that depend on other genes. |
||
Duplicate repair. Repair duplicates through a chain of replacements while respecting each gene space. |
||
Gene types and rounding. Preserve mixed numeric types, apply precision, and convert custom mutation outputs. |
||
Changing population size. Adjust the population and related runtime settings during evolution. |
Operators and Configuration¶
Python script |
What it shows |
Related information |
|---|---|---|
Custom GA operators. Implement parent selection, crossover, and mutation functions. |
||
Constructor settings and random seeds. Use callable fitness signatures, NumPy counts, and independent seeded GA instances. |
Fitness and Parallel Processing¶
Python script |
What it shows |
Related information |
|---|---|---|
Batch fitness. Return one fitness result per solution, including a shorter final batch. |
||
Parallel fitness. Evaluate population fitness with process workers and report the run time. |
||
Compare fitness execution modes. Measure complete runs for CPU, I/O, and NumPy workloads with serial, thread, process, and batch evaluation. |
||
Extra fitness arguments. Wrap a fitness function to pass additional values while preserving its PyGAD signature. |
Lifecycle and Saved Runs¶
Python script |
What it shows |
Related information |
|---|---|---|
Lifecycle callbacks. Trace fitness, parent selection, crossover, mutation, generation, and stop callbacks. |
||
Callbacks as methods. Implement fitness and lifecycle callbacks with bound methods. |
||
Callbacks as callable classes. Implement fitness and lifecycle callbacks with callable class instances. |
||
Text lifecycle summary. Print the configured GA stages and their parameters. |
||
Logging. Send progress and GA messages to a configured logger. |
||
Repeated runs and checkpoints. Continue from a saved GA and inspect the actual generation numbers in its histories. |
||
Change a loaded fitness function. Replace the fitness callable after loading, or start fresh when the objective changes. |
Multi-Objective Optimization¶
Python script |
What it shows |
Related information |
|---|---|---|
NSGA-II optimization. Optimize two objectives and inspect the resulting trade-offs. |
||
NSGA-III optimization. Configure reference points and optimize two objectives with NSGA-III. |
Plots¶
Python script |
What it shows |
Related information |
|---|---|---|
Best-fitness curve. Plot best fitness across generations on the Sphere benchmark. |
||
Fitness band. Plot per-generation minimum, mean, and maximum fitness with a shaded band. |
||
Gene histories. Show how gene values change across saved generations. |
||
Configured lifecycle. Draw detailed and compact lifecycle charts and export SVG and PNG files. |
||
New-solution rate. Count previously unseen solutions in each generation. |
||
Hypervolume history. Track the hypervolume of the non-dominated set across generations. |
||
2D Pareto front. Plot a two-objective Pareto front after NSGA-II optimization. |
||
3D Pareto front. Plot a three-objective Pareto front after NSGA-III optimization. |
||
Pareto-front evolution. Overlay the non-dominated fronts from selected generations. |
||
Pareto heatmap. Compare objective values with a solutions-by-objectives heatmap. |
||
Parallel coordinates. Compare Pareto solutions across objective axes. |
||
Pareto scatter matrix. Compare every pair of objectives in a many-objective run. |
||
Population diversity. Track mean pairwise distance between solutions across generations. |
Reports¶
Python script |
What it shows |
Related information |
|---|---|---|
PDF report. Export the run configuration, summary, best solution, and applicable plots to PDF. |
Benchmarks¶
Python script |
What it shows |
Related information |
|---|---|---|
Sphere. Optimize the Sphere single-objective benchmark. |
||
Rastrigin. Optimize the Rastrigin single-objective benchmark. |
||
Rosenbrock. Optimize the Rosenbrock single-objective benchmark. |
||
Griewank. Optimize the Griewank single-objective benchmark. |
||
Schwefel. Optimize the Schwefel single-objective benchmark. |
||
Ackley. Optimize the Ackley single-objective benchmark. |
||
Himmelblau. Optimize the Himmelblau single-objective benchmark. |
||
ZDT1. Optimize the ZDT1 problem and plot its Pareto front. |
||
ZDT2. Optimize the ZDT2 problem and plot its Pareto front. |
||
ZDT3. Optimize the ZDT3 problem and plot its Pareto front. |
||
ZDT4. Optimize the ZDT4 problem and plot its Pareto front. |
||
ZDT6. Optimize the ZDT6 problem and plot its Pareto front. |
||
DTLZ1. Optimize the DTLZ1 problem and plot its Pareto front. |
||
DTLZ2. Optimize the DTLZ2 problem and plot its Pareto front. |
||
DTLZ3. Optimize the DTLZ3 problem and plot its Pareto front. |
||
DTLZ4. Optimize the DTLZ4 problem and plot its Pareto front. |
||
Knapsack. Select items to maximize value within a weight capacity. |
||
Travelling salesman. Find a short tour using a permutation of four cities. |
||
Travelling-salesman Colab notebook. Explore a city-tour problem using a user-supplied CSV and interactive maps. Requires external data. |
Guide · Folder · Data setup |
Quality Indicators¶
Python script |
What it shows |
Related information |
|---|---|---|
Hypervolume. Measure the objective-space volume dominated by the final population. |
||
quality_indicators/example_inverted_generational_distance.py |
Inverted generational distance. Measure distance from a reference front to the approximation. |
|
Generational distance. Measure distance from the approximation to a reference front. |
||
Spacing. Measure how evenly the approximation points are spread. |
Neural Networks¶
Python script |
What it shows |
Related information |
|---|---|---|
Regression. Fit a neural network to a small numeric regression problem. |
||
XOR classification. Train a neural network on the four XOR inputs. |
||
Image classification. Classify fruit images from prepared feature vectors. Requires external data. |
Guide · Folder · Data setup |
|
Fish-weight regression. Predict fish weight from numeric measurements. Requires external data. |
Guide · Folder · Data setup |
|
Prepare image features. Extract fruit-image features and write the arrays used by the dense classifiers. Requires external data. |
Guide · Folder · Data setup |
Neural Networks with the GA¶
Python script |
What it shows |
Related information |
|---|---|---|
Regression. Fit a neural network to a small numeric regression problem. |
||
XOR classification. Train a neural network on the four XOR inputs. |
||
Image classification. Classify fruit images from prepared feature vectors. Requires external data. |
Guide · Folder · Data setup |
|
Fish-weight regression. Predict fish weight from numeric measurements. Requires external data. |
Guide · Folder · Data setup |
Convolutional Networks¶
Python script |
What it shows |
Related information |
|---|---|---|
Build a CNN. Classify fruit images using prepared image arrays. Requires external data. |
Guide · Folder · Data setup |
|
Optimize a CNN with the GA. Classify fruit images using prepared image arrays. Requires external data. |
Guide · Folder · Data setup |
Keras¶
Python script |
What it shows |
Related information |
|---|---|---|
Regression. Optimize neural-network weights with the genetic algorithm. |
||
XOR classification. Optimize neural-network weights with the genetic algorithm. |
||
Dense image classifier. Train an image classifier with the genetic algorithm. Requires external data. |
Guide · Folder · Data setup |
|
Convolutional image classifier. Train an image classifier with the genetic algorithm. Requires external data. |
Guide · Folder · Data setup |
|
Image-directory classification. Use directory-based image input for a two-class Keras CNN. Requires external data. |
Guide · Folder · Data setup |
|
Batched image-directory classification. Use directory-based image input for a two-class Keras CNN. Requires external data. |
Guide · Folder · Data setup |
PyTorch¶
Python script |
What it shows |
Related information |
|---|---|---|
Regression. Optimize neural-network weights with the genetic algorithm. |
||
XOR classification. Optimize neural-network weights with the genetic algorithm. |
||
Dense image classifier. Train an image classifier with the genetic algorithm. Requires external data. |
Guide · Folder · Data setup |
|
Convolutional image classifier. Train an image classifier with the genetic algorithm. Requires external data. |
Guide · Folder · Data setup |
Clustering¶
Python script |
What it shows |
Related information |
|---|---|---|
2-cluster example. Optimize 2 cluster centers for generated two-dimensional data. |
||
3-cluster example. Optimize 3 cluster centers for generated two-dimensional data. |