Skip to content

Commit 2c6c6d8

Browse files
committed
Optimize code
1 parent 468d36a commit 2c6c6d8

16 files changed

+138
-485
lines changed

example2.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import pygad
2+
import numpy
3+
4+
function_inputs = [4,-2,3.5,5,-11,-4.7]
5+
desired_output = 44
6+
7+
def fitness_func(ga_instance, solution, solution_idx):
8+
output = numpy.sum(solution*function_inputs)
9+
fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001)
10+
return fitness
11+
12+
num_genes = len(function_inputs)
13+
14+
ga_instance = pygad.GA(num_generations=100,
15+
num_parents_mating=10,
16+
sol_per_pop=20,
17+
num_genes=num_genes,
18+
mutation_num_genes=6,
19+
fitness_func=fitness_func,
20+
init_range_low=1,
21+
init_range_high=100,
22+
# suppress_warnings=True,
23+
random_mutation_min_val=1,
24+
random_mutation_max_val=100,
25+
mutation_by_replacement=True,
26+
gene_type=[float, 1],
27+
save_solutions=True,
28+
allow_duplicate_genes=False,
29+
# gene_space=numpy.unique(numpy.random.uniform(1, 100, size=100)),
30+
gene_space=[range(0, 100), {"low": 0, "high": 100, 'step': 1}, 2.5891221, [1,2,3,4], None, numpy.unique(numpy.random.uniform(1, 100, size=4))],
31+
gene_constraint=[lambda x: x[0]>=95,lambda x: x[1]>=95,lambda x: x[2]<98,lambda x: x[3]<98,lambda x: x[4]<98,lambda x: x[5]<98],
32+
)
33+
34+
print(ga_instance.initial_population)
35+
36+
# ga_instance.run()
37+
38+
# print(ga_instance.gene_space_unpacked)
39+
# print(ga_instance.population)
227 Bytes
Binary file not shown.
-2.43 KB
Binary file not shown.
282 Bytes
Binary file not shown.
62 Bytes
Binary file not shown.
-1.78 KB
Binary file not shown.

pygad/helper/misc.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,12 @@ def generate_gene_value_from_space(self,
229229
-An array with number of maximum number of values equal to sample_size if sample_size>1.
230230
"""
231231

232-
range_min, range_max = self.get_random_mutation_range(gene_idx)
232+
if gene_value is None:
233+
# Use the initial population range.
234+
range_min, range_max = self.get_initial_population_range(gene_index=gene_idx)
235+
else:
236+
# Use the mutation range.
237+
range_min, range_max = self.get_random_mutation_range(gene_idx)
233238

234239
if self.gene_space_nested:
235240
# Returning the current gene space from the 'gene_space' attribute.

pygad/helper/unique.py

Lines changed: 18 additions & 224 deletions
Large diffs are not rendered by default.

pygad/pygad.py

Lines changed: 75 additions & 260 deletions
Large diffs are not rendered by default.
354 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)