Skip to content

Commit f60b3ba

Browse files
authored
Add files via upload
1 parent a648669 commit f60b3ba

File tree

1 file changed

+132
-1
lines changed

1 file changed

+132
-1
lines changed

README.md

+132-1
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,9 @@ The source code of the PyGAD' modules is found in the following GitHub projects:
3838

3939
- [pygad](https://github.com/ahmedfgad/GeneticAlgorithmPython): (https://github.com/ahmedfgad/GeneticAlgorithmPython)
4040
- [pygad.nn](https://github.com/ahmedfgad/NumPyANN): https://github.com/ahmedfgad/NumPyANN
41-
4241
- [pygad.gann](https://github.com/ahmedfgad/NeuralGenetic): https://github.com/ahmedfgad/NeuralGenetic
42+
- [pygad.cnn](https://github.com/ahmedfgad/NumPyCNN): https://github.com/ahmedfgad/NumPyCNN
43+
- [pygad.gacnn](https://github.com/ahmedfgad/CNNGenetic): https://github.com/ahmedfgad/CNNGenetic
4344

4445
The documentation of PyGAD is available at [Read The Docs](https://pygad.readthedocs.io/) https://pygad.readthedocs.io.
4546

@@ -57,6 +58,136 @@ If you built a project that uses PyGAD, then please drop an e-mail to ahmed.f.ga
5758

5859
Please check the **Contact Us** section for more contact details.
5960

61+
# Example
62+
63+
Check the [PyGAD's documentation](https://pygad.readthedocs.io/en/latest/README_pygad_gann_ReadTheDocs.html) for information about the implementation of this example.
64+
65+
```python
66+
import numpy
67+
import pygad
68+
import pygad.nn
69+
import pygad.gann
70+
71+
def fitness_func(solution, sol_idx):
72+
global GANN_instance, data_inputs, data_outputs
73+
74+
predictions = pygad.nn.predict(last_layer=GANN_instance.population_networks[sol_idx],
75+
data_inputs=data_inputs)
76+
correct_predictions = numpy.where(predictions == data_outputs)[0].size
77+
solution_fitness = (correct_predictions/data_outputs.size)*100
78+
79+
return solution_fitness
80+
81+
def callback_generation(ga_instance):
82+
global GANN_instance, last_fitness
83+
84+
population_matrices = pygad.gann.population_as_matrices(population_networks=GANN_instance.population_networks,
85+
population_vectors=ga_instance.population)
86+
87+
GANN_instance.update_population_trained_weights(population_trained_weights=population_matrices)
88+
89+
print("Generation = {generation}".format(generation=ga_instance.generations_completed))
90+
print("Fitness = {fitness}".format(fitness=ga_instance.best_solution()[1]))
91+
print("Change = {change}".format(change=ga_instance.best_solution()[1] - last_fitness))
92+
93+
last_fitness = ga_instance.best_solution()[1].copy()
94+
95+
# Holds the fitness value of the previous generation.
96+
last_fitness = 0
97+
98+
# Preparing the NumPy array of the inputs.
99+
data_inputs = numpy.array([[1, 1],
100+
[1, 0],
101+
[0, 1],
102+
[0, 0]])
103+
104+
# Preparing the NumPy array of the outputs.
105+
data_outputs = numpy.array([0,
106+
1,
107+
1,
108+
0])
109+
110+
# The length of the input vector for each sample (i.e. number of neurons in the input layer).
111+
num_inputs = data_inputs.shape[1]
112+
# The number of neurons in the output layer (i.e. number of classes).
113+
num_classes = 2
114+
115+
# Creating an initial population of neural networks. The return of the initial_population() function holds references to the networks, not their weights. Using such references, the weights of all networks can be fetched.
116+
num_solutions = 6 # A solution or a network can be used interchangeably.
117+
GANN_instance = pygad.gann.GANN(num_solutions=num_solutions,
118+
num_neurons_input=num_inputs,
119+
num_neurons_hidden_layers=[2],
120+
num_neurons_output=num_classes,
121+
hidden_activations=["relu"],
122+
output_activation="softmax")
123+
124+
# population does not hold the numerical weights of the network instead it holds a list of references to each last layer of each network (i.e. solution) in the population. A solution or a network can be used interchangeably.
125+
# If there is a population with 3 solutions (i.e. networks), then the population is a list with 3 elements. Each element is a reference to the last layer of each network. Using such a reference, all details of the network can be accessed.
126+
population_vectors = pygad.gann.population_as_vectors(population_networks=GANN_instance.population_networks)
127+
128+
# To prepare the initial population, there are 2 ways:
129+
# 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.
130+
# 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.
131+
initial_population = population_vectors.copy()
132+
133+
num_parents_mating = 4 # Number of solutions to be selected as parents in the mating pool.
134+
135+
num_generations = 500 # Number of generations.
136+
137+
mutation_percent_genes = 5 # Percentage of genes to mutate. This parameter has no action if the parameter mutation_num_genes exists.
138+
139+
parent_selection_type = "sss" # Type of parent selection.
140+
141+
crossover_type = "single_point" # Type of the crossover operator.
142+
143+
mutation_type = "random" # Type of the mutation operator.
144+
145+
keep_parents = 1 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing.
146+
147+
init_range_low = -2
148+
init_range_high = 5
149+
150+
ga_instance = pygad.GA(num_generations=num_generations,
151+
num_parents_mating=num_parents_mating,
152+
initial_population=initial_population,
153+
fitness_func=fitness_func,
154+
mutation_percent_genes=mutation_percent_genes,
155+
init_range_low=init_range_low,
156+
init_range_high=init_range_high,
157+
parent_selection_type=parent_selection_type,
158+
crossover_type=crossover_type,
159+
mutation_type=mutation_type,
160+
keep_parents=keep_parents,
161+
callback_generation=callback_generation)
162+
163+
ga_instance.run()
164+
165+
# After the generations complete, some plots are showed that summarize how the outputs/fitness values evolve over generations.
166+
ga_instance.plot_result()
167+
168+
# Returning the details of the best solution.
169+
solution, solution_fitness, solution_idx = ga_instance.best_solution()
170+
print("Parameters of the best solution : {solution}".format(solution=solution))
171+
print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness))
172+
print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx))
173+
174+
if ga_instance.best_solution_generation != -1:
175+
print("Best fitness value reached after {best_solution_generation} generations.".format(best_solution_generation=ga_instance.best_solution_generation))
176+
177+
# Predicting the outputs of the data using the best solution.
178+
predictions = pygad.nn.predict(last_layer=GANN_instance.population_networks[solution_idx],
179+
data_inputs=data_inputs)
180+
print("Predictions of the trained network : {predictions}".format(predictions=predictions))
181+
182+
# Calculating some statistics
183+
num_wrong = numpy.where(predictions != data_outputs)[0]
184+
num_correct = data_outputs.size - num_wrong.size
185+
accuracy = 100 * (num_correct/data_outputs.size)
186+
print("Number of correct classifications : {num_correct}.".format(num_correct=num_correct))
187+
print("Number of wrong classifications : {num_wrong}.".format(num_wrong=num_wrong.size))
188+
print("Classification accuracy : {accuracy}.".format(accuracy=accuracy))
189+
```
190+
60191
# For More Information
61192

62193
There are different resources that can be used to get started with the genetic algorithm and building it in Python.

0 commit comments

Comments
 (0)