pyerualjetwork 4.3.8.dev15__py3-none-any.whl → 4.3.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. pyerualjetwork/__init__.py +1 -1
  2. pyerualjetwork/activation_functions.py +2 -2
  3. pyerualjetwork/activation_functions_cuda.py +63 -114
  4. pyerualjetwork/data_operations_cuda.py +1 -1
  5. pyerualjetwork/fitness_functions.py +72 -0
  6. pyerualjetwork/fitness_functions_cuda.py +85 -0
  7. pyerualjetwork/model_operations.py +14 -14
  8. pyerualjetwork/model_operations_cuda.py +16 -17
  9. pyerualjetwork/plan.py +159 -382
  10. pyerualjetwork/plan_cuda.py +149 -387
  11. pyerualjetwork/planeat.py +24 -54
  12. pyerualjetwork/planeat_cuda.py +11 -47
  13. pyerualjetwork/visualizations.py +33 -30
  14. pyerualjetwork/visualizations_cuda.py +22 -24
  15. {pyerualjetwork-4.3.8.dev15.dist-info → pyerualjetwork-4.3.9.dist-info}/METADATA +3 -19
  16. pyerualjetwork-4.3.9.dist-info/RECORD +24 -0
  17. pyerualjetwork-4.3.9.dist-info/top_level.txt +1 -0
  18. pyerualjetwork/loss_functions.py +0 -21
  19. pyerualjetwork/loss_functions_cuda.py +0 -21
  20. pyerualjetwork-4.3.8.dev15.dist-info/RECORD +0 -45
  21. pyerualjetwork-4.3.8.dev15.dist-info/top_level.txt +0 -2
  22. pyerualjetwork_afterburner/__init__.py +0 -11
  23. pyerualjetwork_afterburner/activation_functions.py +0 -290
  24. pyerualjetwork_afterburner/activation_functions_cuda.py +0 -289
  25. pyerualjetwork_afterburner/data_operations.py +0 -406
  26. pyerualjetwork_afterburner/data_operations_cuda.py +0 -461
  27. pyerualjetwork_afterburner/help.py +0 -17
  28. pyerualjetwork_afterburner/loss_functions.py +0 -21
  29. pyerualjetwork_afterburner/loss_functions_cuda.py +0 -21
  30. pyerualjetwork_afterburner/memory_operations.py +0 -298
  31. pyerualjetwork_afterburner/metrics.py +0 -190
  32. pyerualjetwork_afterburner/metrics_cuda.py +0 -163
  33. pyerualjetwork_afterburner/model_operations.py +0 -408
  34. pyerualjetwork_afterburner/model_operations_cuda.py +0 -420
  35. pyerualjetwork_afterburner/parallel.py +0 -118
  36. pyerualjetwork_afterburner/plan.py +0 -432
  37. pyerualjetwork_afterburner/plan_cuda.py +0 -441
  38. pyerualjetwork_afterburner/planeat.py +0 -793
  39. pyerualjetwork_afterburner/planeat_cuda.py +0 -752
  40. pyerualjetwork_afterburner/ui.py +0 -22
  41. pyerualjetwork_afterburner/visualizations.py +0 -823
  42. pyerualjetwork_afterburner/visualizations_cuda.py +0 -825
  43. {pyerualjetwork-4.3.8.dev15.dist-info → pyerualjetwork-4.3.9.dist-info}/WHEEL +0 -0
@@ -1,793 +0,0 @@
1
- """
2
- MAIN MODULE FOR PLANEAT
3
-
4
- Examples: https://github.com/HCB06/PyerualJetwork/tree/main/Welcome_to_PyerualJetwork/ExampleCodes
5
-
6
- ANAPLAN document: https://github.com/HCB06/Anaplan/blob/main/Welcome_to_Anaplan/ANAPLAN_USER_MANUEL_AND_LEGAL_INFORMATION(EN).pdf
7
-
8
- @author: Hasan Can Beydili
9
- @YouTube: https://www.youtube.com/@HasanCanBeydili
10
- @Linkedin: https://www.linkedin.com/in/hasan-can-beydili-77a1b9270/
11
- @Instagram: https://www.instagram.com/canbeydili.06/
12
- @contact: tchasancan@gmail.com
13
- """
14
-
15
- import numpy as np
16
- import random
17
- import math
18
-
19
- ### LIBRARY IMPORTS ###
20
- from .data_operations import normalization
21
- from .ui import loading_bars, initialize_loading_bar
22
- from .activation_functions import apply_activation, all_activations
23
-
24
- def define_genomes(input_shape, output_shape, population_size, dtype=np.float32):
25
- """
26
- Initializes a population of genomes, where each genome is represented by a set of weights
27
- and an associated activation function. Each genome is created with random weights and activation
28
- functions are applied and normalized. (Max abs normalization.)
29
-
30
- Args:
31
-
32
- input_shape (int): The number of input features for the neural network.
33
-
34
- output_shape (int): The number of output features for the neural network.
35
-
36
- population_size (int): The number of genomes (individuals) in the population.
37
-
38
- dtype (numpy.dtype): Data type for the arrays. np.float32 by default. Example: np.float64 or np.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!] (optional)
39
-
40
- Returns:
41
- tuple: A tuple containing:
42
- - population_weights (numpy.ndarray): A 2D numpy array of shape (population_size, output_shape, input_shape) representing the
43
- weight matrices for each genome.
44
- - population_activations (list): A list of activation functions applied to each genome.
45
-
46
- Notes:
47
- The weights are initialized randomly within the range [-1, 1].
48
- Activation functions are selected randomly from a predefined list `all_activations()`.
49
- The weights for each genome are then modified by applying the corresponding activation function
50
- and normalized using the `normalization()` function. (Max abs normalization.)
51
- """
52
- population_weights = [0] * population_size
53
- population_activations = [0] * population_size
54
-
55
- except_this = ['spiral', 'circular']
56
- activations = [item for item in all_activations() if item not in except_this] # SPIRAL AND CIRCULAR ACTIVATION DISCARDED
57
-
58
- for i in range(len(population_weights)):
59
-
60
- population_weights[i] = np.random.uniform(-1, 1, (output_shape, input_shape)).astype(dtype)
61
- population_activations[i] = activations[int(random.uniform(0, len(activations)-1))]
62
-
63
- # ACTIVATIONS APPLYING IN WEIGHTS SPECIFIC OUTPUT CONNECTIONS (MORE PLAN LIKE FEATURES(FOR NON-LINEARITY)):
64
-
65
- for j in range(population_weights[i].shape[0]):
66
-
67
- population_weights[i][j,:] = apply_activation(population_weights[i][j,:], population_activations[i])
68
- population_weights[i][j,:] = normalization(population_weights[i][j,:], dtype=dtype)
69
-
70
- return np.array(population_weights, dtype=dtype), population_activations
71
-
72
-
73
- def evolver(weights,
74
- activation_potentiations,
75
- what_gen,
76
- fitness,
77
- show_info=False,
78
- policy='aggressive',
79
- bad_genomes_selection_prob=None,
80
- bar_status=True,
81
- strategy='normal_selective',
82
- bad_genomes_mutation_prob=None,
83
- fitness_bias=1,
84
- cross_over_mode='tpm',
85
- activation_mutate_add_prob=0.5,
86
- activation_mutate_delete_prob=0.5,
87
- activation_mutate_change_prob=0.5,
88
- activation_selection_add_prob=0.5,
89
- activation_selection_change_prob=0.5,
90
- activation_selection_threshold=2,
91
- activation_mutate_prob=1,
92
- activation_mutate_threshold=2,
93
- weight_mutate_threshold=16,
94
- weight_mutate_prob=1,
95
- dtype=np.float32):
96
- """
97
- Applies the evolving process of a population of genomes using selection, crossover, mutation, and activation function potentiation.
98
- The function modifies the population's weights and activation functions based on a specified policy, mutation probabilities, and strategy.
99
-
100
- 'selection' args effects cross-over.
101
- 'mutate' args effects mutation.
102
-
103
- Args:
104
- weights (numpy.ndarray): Array of weights for each genome.
105
- (first returned value of define_genomes function)
106
-
107
- activation_potentiations (list): A list of activation functions for each genome.
108
- (second returned value of define_genomes function)
109
-
110
- what_gen (int): The current generation number, used for informational purposes or logging.
111
-
112
- fitness (numpy.ndarray): A 1D array containing the fitness values of each genome.
113
- The array is used to rank the genomes based on their performance. PLANEAT maximizes or minimizes this fitness based on the `target_fitness` parameter.
114
-
115
- show_info (bool, optional): If True, prints information about the current generation and the
116
- maximum reward obtained. Also shows the current configuration. Default is False.
117
-
118
- strategy (str, optional): The strategy for combining the best and bad genomes. Options:
119
- - 'normal_selective': Normal selection based on reward, where a portion of the bad genes are discarded.
120
- - 'more_selective': A more selective strategy, where fewer bad genes survive.
121
- - 'less_selective': A less selective strategy, where more bad genes survive.
122
- Default is 'normal_selective'.
123
-
124
- bar_status (bool, optional): Loading bar status during evolving process of genomes. True or False. Default: True
125
-
126
- policy (str, optional): The selection policy that governs how genomes are selected for reproduction. Options:
127
-
128
- - 'aggressive': Aggressive policy using very aggressive selection policy.
129
- Advantages: fast training.
130
- Disadvantages: may lead to fitness stuck in a local maximum or minimum.
131
-
132
- - 'explorer': Explorer policy increases population diversity.
133
- Advantages: fitness does not get stuck at local maximum or minimum.
134
- Disadvantages: slow training.
135
-
136
- Suggestions: Use hybrid and dynamic policy. When fitness appears stuck, switch to the 'explorer' policy.
137
-
138
- Default: 'aggressive'.
139
-
140
- fitness_bias (float, optional): Fitness bias must be a probability value between 0 and 1 that determines the effect of fitness on the crossover process. Default: 1.
141
-
142
- bad_genomes_mutation_prob (float, optional): The probability of applying mutation to the bad genomes.
143
- Must be in the range [0, 1]. Also affects the mutation probability of the best genomes inversely.
144
- For example, a value of 0.7 for bad genomes implies 0.3 for best genomes. Default: Determined by `policy`.
145
-
146
- activation_mutate_prob (float, optional): The probability of applying mutation to the activation functions.
147
- Must be in the range [0, 1]. Default is 1 (%100).
148
-
149
- cross_over_mode (str, optional): Specifies the crossover method to use. Options:
150
- - 'tpm': Two-Point Matrix Crossover.
151
- Default is 'tpm'.
152
-
153
- activation_mutate_add_prob (float, optional): The probability of adding a new activation function to the genome for mutation.
154
- Must be in the range [0, 1]. Default is 0.5.
155
-
156
- activation_mutate_delete_prob (float, optional): The probability of deleting an existing activation function
157
- from the genome for mutation. Must be in the range [0, 1]. Default is 0.5.
158
-
159
- activation_mutate_change_prob (float, optional): The probability of changing an activation function in the genome for mutation.
160
- Must be in the range [0, 1]. Default is 0.5.
161
-
162
- weight_mutate_prob (float, optional): The probability of mutating a weight in the genome.
163
- Must be in the range [0, 1]. Default is 1 (%100).
164
-
165
- weight_mutate_threshold (int): Determines max how much weight mutaiton operation applying. (Function automaticly determines to min) Default: 16
166
-
167
- activation_selection_add_prob (float, optional): The probability of adding an existing activation function for crossover.
168
- Must be in the range [0, 1]. Default is 0.5. (WARNING! Higher values increase complexity. For faster training, increase this value.)
169
-
170
- activation_selection_change_prob (float, optional): The probability of changing an activation function in the genome for crossover.
171
- Must be in the range [0, 1]. Default is 0.5.
172
-
173
- activation_mutate_threshold (int, optional): Determines max how much activation mutaiton operation applying. (Function automaticly determines to min) Default: 2
174
-
175
- activation_selection_threshold (int, optional): Determines max how much activaton transferable to child from undominant parent. (Function automaticly determines to min) Default: 2
176
-
177
- dtype (numpy.dtype, optional): Data type for the arrays. Default: np.float32.
178
- Example: np.float64 or np.float16 [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not recommended!].
179
-
180
- Raises:
181
- ValueError:
182
- - If `policy` is not one of the specified values ('aggressive', 'explorer').
183
- - If 'strategy' is not one of the specified values ('less_selective', 'normal_selective', 'more_selective')
184
- - If `cross_over_mode` is not one of the specified values ('tpm').
185
- - If `bad_genomes_mutation_prob`, `activation_mutate_prob`, or other probability parameters are not in the range 0 and 1.
186
- - If the population size is odd (ensuring an even number of genomes is required for proper selection).
187
- - If 'fitness_bias' value is not in range 0 and 1.
188
-
189
- Returns:
190
- tuple: A tuple containing:
191
- - weights (numpy.ndarray): The updated weights for the population after selection, crossover, and mutation.
192
- The shape is (population_size, output_shape, input_shape).
193
- - activation_potentiations (list): The updated list of activation functions for the population.
194
-
195
- Notes:
196
- - **Selection Process**:
197
- - The genomes are sorted by their fitness (based on `fitness`), and then split into "best" and "bad" halves.
198
- - The best genomes are retained, and the bad genomes are modified based on the selected strategy.
199
-
200
- - **Crossover Strategies**:
201
- - The **'cross_over'** strategy performs crossover, where parts of the best genomes' weights are combined with other good genomes to create new weight matrices.
202
-
203
- - **Mutation**:
204
- - Mutation is applied to both the best and bad genomes, depending on the mutation probability and the `policy`.
205
- - `bad_genomes_mutation_prob` determines the probability of applying mutations to the bad genomes.
206
- - If `activation_mutate_prob` is provided, activation function mutations are applied to the genomes based on this probability.
207
-
208
- - **Population Size**: The population size must be an even number to properly split the best and bad genomes. If `fitness` has an odd length, an error is raised.
209
-
210
- - **Logging**: If `show_info=True`, the current generation and the maximum reward from the population are printed for tracking the learning progress.
211
-
212
- Example:
213
- ```python
214
- weights, activation_potentiations = planeat.evolver(weights, activation_potentiations, 1, fitness, show_info=True, strategy='normal_selective', policy='aggressive')
215
- ```
216
-
217
- - The function returns the updated weights and activations after processing based on the chosen strategy, policy, and mutation parameters.
218
- """
219
-
220
- ### ERROR AND CONFIGURATION CHECKS:
221
-
222
- if strategy == 'normal_selective':
223
- if bad_genomes_mutation_prob is None: bad_genomes_mutation_prob = 0.7 # EFFECTS MUTATION
224
- if bad_genomes_selection_prob is None: bad_genomes_selection_prob = 0.25 # EFFECTS CROSS-OVER
225
-
226
- elif strategy == 'more_selective':
227
- if bad_genomes_mutation_prob is None: bad_genomes_mutation_prob = 0.85 # EFFECTS MUTATION
228
- if bad_genomes_selection_prob is None: bad_genomes_selection_prob = 0.1 # EFFECTS CROSS-OVER
229
-
230
- elif strategy == 'less_selective':
231
- if bad_genomes_mutation_prob is None: bad_genomes_mutation_prob = 0.6 # EFFECTS MUTATION
232
- if bad_genomes_selection_prob is None: bad_genomes_selection_prob = 0.5 # EFFECTS CROSS-OVER
233
-
234
- else:
235
- raise ValueError("strategy parameter must be: 'normal_selective' or 'more_selective' or 'less_selective'")
236
-
237
- if ((activation_mutate_add_prob < 0 or activation_mutate_add_prob > 1) or
238
- (activation_mutate_change_prob < 0 or activation_mutate_change_prob > 1) or
239
- (activation_mutate_delete_prob < 0 or activation_mutate_delete_prob > 1) or
240
- (weight_mutate_prob < 0 or weight_mutate_prob > 1) or
241
- (activation_selection_add_prob < 0 or activation_selection_add_prob > 1) or (
242
- activation_selection_change_prob < 0 or activation_selection_change_prob > 1)):
243
-
244
- raise ValueError("All hyperparameters ending with 'prob' must be a number between 0 and 1.")
245
-
246
- if fitness_bias < 0 or fitness_bias > 1: raise ValueError("fitness_bias value must be a number between 0 and 1.")
247
-
248
- if bad_genomes_mutation_prob is not None:
249
- if bad_genomes_mutation_prob < 0 or bad_genomes_mutation_prob > 1:
250
- raise ValueError("bad_genomes_mutation_prob parameter must be float and 0-1 range")
251
-
252
- if activation_mutate_prob is not None:
253
- if activation_mutate_prob < 0 or activation_mutate_prob > 1:
254
- raise ValueError("activation_mutate_prob parameter must be float and 0-1 range")
255
-
256
- if len(fitness) % 2 == 0:
257
- slice_center = int(len(fitness) / 2)
258
-
259
- else:
260
- raise ValueError("genome population size must be even number. for example: not 99, make 100 or 98.")
261
-
262
-
263
- ### FITNESS IS SORTED IN ASCENDING ORDER, AND THE WEIGHT AND ACTIVATIONS OF EACH GENOME ARE SORTED ACCORDING TO THIS ORDER:
264
-
265
- sort_indices = np.argsort(fitness)
266
-
267
- fitness = fitness[sort_indices]
268
- weights = weights[sort_indices]
269
-
270
- activation_potentiations = [activation_potentiations[i] for i in sort_indices]
271
-
272
- ### GENOMES ARE DIVIDED INTO TWO GROUPS: GOOD GENOMES AND BAD GENOMES:
273
-
274
- good_weights = weights[slice_center:]
275
- bad_weights = weights[:slice_center]
276
- best_weight = np.copy(good_weights[-1])
277
-
278
- good_activations = list(activation_potentiations[slice_center:])
279
- bad_activations = list(activation_potentiations[:slice_center])
280
- best_activations = good_activations[-1].copy() if isinstance(good_activations[-1], list) else good_activations[-1]
281
-
282
-
283
- ### PLANEAT IS APPLIED ACCORDING TO THE SPECIFIED POLICY, STRATEGY, AND PROBABILITY CONFIGURATION:
284
-
285
- bar_format = loading_bars()[0]
286
-
287
- if bar_status: progress = initialize_loading_bar(len(bad_weights), desc="GENERATION: " + str(what_gen), bar_format=bar_format, ncols=50)
288
- normalized_fitness = normalization(fitness, dtype=dtype)
289
-
290
- best_fitness = normalized_fitness[-1]
291
- epsilon = np.finfo(float).eps
292
-
293
- child_W = np.copy(bad_weights)
294
- child_act = bad_activations.copy()
295
-
296
- mutated_W = np.copy(bad_weights)
297
- mutated_act = bad_activations.copy()
298
-
299
-
300
- for i in range(len(bad_weights)):
301
-
302
- if policy == 'aggressive':
303
- first_parent_W = best_weight
304
- first_parent_act = best_activations
305
-
306
- elif policy == 'explorer':
307
- first_parent_W = good_weights[i]
308
- first_parent_act = good_activations[i]
309
-
310
- else: raise ValueError("policy parameter must be: 'aggressive' or 'explorer'")
311
-
312
- second_parent_W, second_parent_act, s_i = second_parent_selection(good_weights, bad_weights, good_activations, bad_activations, bad_genomes_selection_prob)
313
-
314
- child_W[i], child_act[i] = cross_over(first_parent_W,
315
- second_parent_W,
316
- first_parent_act,
317
- second_parent_act,
318
- cross_over_mode=cross_over_mode,
319
- activation_selection_add_prob=activation_selection_add_prob,
320
- activation_selection_change_prob=activation_selection_change_prob,
321
- activation_selection_threshold=activation_selection_threshold,
322
- bad_genomes_selection_prob=bad_genomes_selection_prob,
323
- first_parent_fitness=best_fitness,
324
- fitness_bias=fitness_bias,
325
- second_parent_fitness=normalized_fitness[s_i],
326
- epsilon=epsilon
327
- )
328
-
329
- mutation_prob = random.uniform(0, 1)
330
-
331
- if mutation_prob > bad_genomes_mutation_prob:
332
- genome_W = good_weights[i]
333
- genome_act = good_activations[i]
334
-
335
- fitness_index = int(len(bad_weights) / 2 + i)
336
-
337
- else:
338
- genome_W = bad_weights[i]
339
- genome_act = bad_activations[i]
340
-
341
- fitness_index = i
342
-
343
- mutated_W[i], mutated_act[i] = mutation(genome_W,
344
- genome_act,
345
- activation_mutate_prob=activation_mutate_prob,
346
- activation_add_prob=activation_mutate_add_prob,
347
- activation_delete_prob=activation_mutate_delete_prob,
348
- activation_change_prob=activation_mutate_change_prob,
349
- weight_mutate_prob=weight_mutate_prob,
350
- weight_mutate_threshold=weight_mutate_threshold,
351
- genome_fitness=normalized_fitness[fitness_index],
352
- activation_mutate_threshold=activation_mutate_threshold,
353
- epsilon=epsilon
354
- )
355
-
356
- if bar_status: progress.update(1)
357
-
358
- child_W[0] = best_weight
359
- child_act[0] = best_activations
360
-
361
- weights = np.vstack((child_W, mutated_W))
362
- activation_potentiations = child_act + mutated_act
363
-
364
- ### INFO PRINTING CONSOLE
365
-
366
- if show_info == True:
367
- print("\nGENERATION:", str(what_gen) + ' FINISHED \n')
368
- print("*** Configuration Settings ***")
369
- print(" POPULATION SIZE: ", str(len(weights)))
370
- print(" STRATEGY: ", strategy)
371
- print(" CROSS OVER MODE: ", cross_over_mode)
372
- print(" POLICY: ", policy)
373
- print(" BAD GENOMES MUTATION PROB: ", str(bad_genomes_mutation_prob))
374
- print(" GOOD GENOMES MUTATION PROB: ", str(round(1 - bad_genomes_mutation_prob, 2)))
375
- print(" BAD GENOMES SELECTION PROB: ", str(bad_genomes_selection_prob))
376
- print(" WEIGHT MUTATE PROB: ", str(weight_mutate_prob))
377
- print(" WEIGHT MUTATE THRESHOLD: ", str(weight_mutate_threshold))
378
- print(" ACTIVATION MUTATE PROB: ", str(activation_mutate_prob))
379
- print(" ACTIVATION MUTATE THRESHOLD: ", str(activation_mutate_threshold))
380
- print(" ACTIVATION MUTATE ADD PROB: ", str(activation_mutate_add_prob))
381
- print(" ACTIVATION MUTATE DELETE PROB: ", str(activation_mutate_delete_prob))
382
- print(" ACTIVATION MUTATE CHANGE PROB: ", str(activation_mutate_change_prob))
383
- print(" ACTIVATION SELECTION THRESHOLD:", str(activation_selection_threshold))
384
- print(" ACTIVATION SELECTION ADD PROB: ", str(activation_selection_add_prob))
385
- print(" ACTIVATION SELECTION CHANGE PROB: ", str(activation_selection_change_prob))
386
- print(" FITNESS BIAS: ", str(fitness_bias) + '\n')
387
-
388
-
389
- print("*** Performance ***")
390
- print(" MAX FITNESS: ", str(round(max(fitness), 2)))
391
- print(" MEAN FITNESS: ", str(round(np.mean(fitness), 2)))
392
- print(" MIN FITNESS: ", str(round(min(fitness), 2)) + '\n')
393
-
394
- print(" BEST GENOME ACTIVATION LENGTH: ", str(len(best_activations)))
395
- print(" BEST GENOME INDEX: ", str(0))
396
- print(" NOTE: The returned genome at the first index is the best of the previous generation." + '\n')
397
-
398
-
399
- return weights, activation_potentiations
400
-
401
-
402
- def evaluate(x_population, weights, activation_potentiations):
403
- """
404
- Evaluates the performance of a population of genomes, applying different activation functions
405
- and weights depending on whether reinforcement learning mode is enabled or not.
406
-
407
- Args:
408
- x_population (list or numpy.ndarray): A list or 2D numpy array where each element represents
409
- a genome (A list of input features for each genome, or a single set of input features for one genome (only in rl_mode)).
410
- weights (list or numpy.ndarray): A list or 2D numpy array of weights corresponding to each genome
411
- in `x_population`. This determines the strength of connections.
412
- activation_potentiations (list or str): A list where each entry represents an activation function
413
- or a potentiation strategy applied to each genome. If only one
414
- activation function is used, this can be a single string.
415
- Returns:
416
- list: A list of outputs corresponding to each genome in the population after applying the respective
417
- activation function and weights.
418
-
419
- Example:
420
- ```python
421
- outputs = evaluate(x_population, weights, activation_potentiations)
422
- ```
423
-
424
- - The function returns a list of outputs after processing the population, where each element corresponds to
425
- the output for each genome in `x_population`.
426
- """
427
- ### THE OUTPUTS ARE RETURNED AS A PYTHON LIST, WHERE EACH GENOME'S OUTPUT MATCHES ITS INDEX:
428
-
429
-
430
- if isinstance(activation_potentiations, str):
431
- activation_potentiations = [activation_potentiations]
432
- else:
433
- activation_potentiations = [item if isinstance(item, list) else [item] for item in activation_potentiations]
434
-
435
- x_population = apply_activation(x_population, activation_potentiations)
436
- result = x_population @ weights.T
437
-
438
- return result
439
-
440
-
441
- def cross_over(first_parent_W,
442
- second_parent_W,
443
- first_parent_act,
444
- second_parent_act,
445
- cross_over_mode,
446
- activation_selection_add_prob,
447
- activation_selection_change_prob,
448
- activation_selection_threshold,
449
- bad_genomes_selection_prob,
450
- first_parent_fitness,
451
- second_parent_fitness,
452
- fitness_bias,
453
- epsilon):
454
- """
455
- Performs a crossover operation on two sets of weights and activation functions.
456
- This function combines two individuals (represented by their weights and activation functions)
457
- to create a new individual by exchanging parts of their weight matrices and activation functions.
458
-
459
- Args:
460
- first_parent_W (numpy.ndarray): The weight matrix of the first individual (parent).
461
-
462
- second_parent_W (numpy.ndarray): The weight matrix of the second individual (parent).
463
-
464
- first_parent_act (str or list): The activation function(s) of the first individual.
465
-
466
- second_parent_act (str or list): The activation function(s) of the second individual.
467
-
468
- cross_over_mode (str): Determines the crossover method to be used. Options:
469
- - 'tpm': Two-Point Matrix Crossover, where sub-matrices of weights are swapped between parents.
470
-
471
- activation_selection_add_prob (float): Probability of adding new activation functions
472
- from the second parent to the child genome.
473
-
474
- activation_selection_change_prob (float): Probability of replacing an activation function in the child genome
475
- with one from the second parent.
476
-
477
- activation_selection_threshold (float): (float): Determines max how much activaton transferable to child from undominant parent. (Function automaticly determines to min)
478
-
479
- bad_genomes_selection_prob (float): Probability of selecting a "bad" genome for replacement with the offspring.
480
-
481
- first_parent_fitness (float): Fitness score of the first parent.
482
-
483
- second_parent_fitness (float): Fitness score of the second parent.
484
-
485
- fitness_bias (float): A bias factor used to favor fitter parents during crossover operations.
486
-
487
- epsilon (float): Small epsilon constant
488
-
489
- Returns:
490
- tuple: A tuple containing:
491
- - child_W (numpy.ndarray): The weight matrix of the new individual created by crossover.
492
- - child_act (list): The list of activation functions of the new individual created by crossover.
493
-
494
- Notes:
495
- - The crossover is performed based on the selected `cross_over_mode`.
496
- - In 'tpm' mode, random sub-matrices from the parent weight matrices are swapped.
497
- - Activation functions from both parents are combined using the probabilities and rates provided.
498
-
499
- Example:
500
- ```python
501
- new_weights, new_activations = cross_over(
502
- first_parent_W=parent1_weights,
503
- second_parent_W=parent2_weights,
504
- first_parent_act=parent1_activations,
505
- second_parent_act=parent2_activations,
506
- cross_over_mode='tpm',
507
- activation_selection_add_prob=0.8,
508
- activation_selection_change_prob=0.5,
509
- activation_selection_threshold=2,
510
- bad_genomes_selection_prob=0.7,
511
- first_parent_fitness=0.9,
512
- second_parent_fitness=0.85,
513
- fitness_bias=0.6,
514
- epsilon=np.finfo(float).eps
515
- )
516
- ```
517
- """
518
-
519
- ### THE GIVEN GENOMES' WEIGHTS ARE RANDOMLY SELECTED AND COMBINED OVER A RANDOM RANGE. SIMILARLY, THEIR ACTIVATIONS ARE COMBINED. A NEW GENOME IS RETURNED WITH THE COMBINED WEIGHTS FIRST, FOLLOWED BY THE ACTIVATIONS:
520
-
521
- start = 0
522
-
523
- row_end = first_parent_W.shape[0]
524
- col_end = first_parent_W.shape[1]
525
-
526
- total_gene = row_end * col_end
527
- half_of_gene = int(total_gene / 2)
528
-
529
- decision = dominant_parent_selection(bad_genomes_selection_prob)
530
-
531
- if decision == 'first_parent':
532
- dominant_parent_W = np.copy(first_parent_W)
533
- dominant_parent_act = first_parent_act
534
-
535
- undominant_parent_W = np.copy(second_parent_W)
536
- undominant_parent_act = second_parent_act
537
- succes = second_parent_fitness + epsilon
538
-
539
- elif decision == 'second_parent':
540
- dominant_parent_W = np.copy(second_parent_W)
541
- dominant_parent_act = second_parent_act
542
-
543
- undominant_parent_W = np.copy(first_parent_W)
544
- undominant_parent_act = first_parent_act
545
- succes = first_parent_fitness + epsilon
546
-
547
- while True:
548
-
549
- row_cut_start = int(random.uniform(start, row_end))
550
- col_cut_start = int(random.uniform(start, col_end))
551
-
552
- row_cut_end = int(random.uniform(start, row_end))
553
- col_cut_end = int(random.uniform(start, col_end))
554
-
555
- if ((row_cut_end > row_cut_start) and
556
- (col_cut_end > col_cut_start) and
557
- (((row_cut_end + 1) - (row_cut_start + 1) * 2) + ((col_cut_end + 1) - (col_cut_start + 1) * 2) <= half_of_gene)):
558
- break
559
-
560
- selection_bias = random.uniform(0, 1)
561
-
562
- if fitness_bias > selection_bias:
563
- row_cut_start = math.floor(row_cut_start * (succes + epsilon))
564
- row_cut_end = math.ceil(row_cut_end * (succes + epsilon))
565
-
566
- col_cut_start = math.floor(col_cut_start * (succes + epsilon))
567
- col_cut_end = math.ceil(col_cut_end * (succes + epsilon))
568
-
569
- child_W = dominant_parent_W
570
-
571
- if cross_over_mode == 'tpm':
572
- child_W[row_cut_start:row_cut_end, col_cut_start:col_cut_end] = undominant_parent_W[row_cut_start:row_cut_end, col_cut_start:col_cut_end]
573
-
574
- if isinstance(dominant_parent_act, str): dominant_parent_act = [dominant_parent_act]
575
- if isinstance(undominant_parent_act, str): undominant_parent_act = [undominant_parent_act]
576
-
577
- child_act = list(np.copy(dominant_parent_act))
578
-
579
- activation_selection_add_prob = 1 - activation_selection_add_prob # if prob 0.8 (%80) then 1 - 0.8. Because 0-1 random number probably greater than 0.2
580
- potential_activation_selection_add = random.uniform(0, 1)
581
-
582
- if potential_activation_selection_add > activation_selection_add_prob:
583
-
584
- threshold = abs(activation_selection_threshold / succes)
585
- new_threshold = threshold
586
-
587
- while True:
588
-
589
- random_index = int(random.uniform(0, len(undominant_parent_act)-1))
590
- random_undominant_activation = undominant_parent_act[random_index]
591
-
592
- child_act.append(random_undominant_activation)
593
-
594
- if len(dominant_parent_act) > new_threshold:
595
- new_threshold += threshold
596
-
597
- else:
598
- break
599
-
600
- activation_selection_change_prob = 1 - activation_selection_change_prob
601
- potential_activation_selection_change_prob = random.uniform(0, 1)
602
-
603
- if potential_activation_selection_change_prob > activation_selection_change_prob:
604
-
605
- threshold = abs(activation_selection_threshold / succes)
606
- new_threshold = threshold
607
-
608
- while True:
609
-
610
- random_index_undominant = int(random.uniform(0, len(undominant_parent_act)-1))
611
- random_index_dominant = int(random.uniform(0, len(dominant_parent_act)-1))
612
- random_undominant_activation = undominant_parent_act[random_index_undominant]
613
-
614
- child_act[random_index_dominant] = random_undominant_activation
615
-
616
- if len(dominant_parent_act) > new_threshold:
617
- new_threshold += threshold
618
-
619
- else:
620
- break
621
-
622
- return child_W, child_act
623
-
624
- def mutation(weight,
625
- activations,
626
- activation_mutate_prob,
627
- activation_add_prob,
628
- activation_delete_prob,
629
- activation_change_prob,
630
- weight_mutate_prob,
631
- weight_mutate_threshold,
632
- genome_fitness,
633
- activation_mutate_threshold,
634
- epsilon):
635
- """
636
- Performs mutation on the given weight matrix and activation functions.
637
- - The weight matrix is mutated by randomly changing its values based on the mutation probability.
638
- - The activation functions are mutated by adding, removing, or replacing them with predefined probabilities.
639
-
640
- Args:
641
- weight (numpy.ndarray): The weight matrix to mutate.
642
-
643
- activations (list): The list of activation functions to mutate.
644
-
645
- activation_mutate_prob (float): The overall probability of mutating activation functions.
646
-
647
- activation_add_prob (float): Probability of adding a new activation function.
648
-
649
- activation_delete_prob (float): Probability of removing an existing activation function.
650
-
651
- activation_change_prob (float): Probability of replacing an existing activation function with a new one.
652
-
653
- weight_mutate_prob (float): The probability of mutating weight matrix.
654
-
655
- weight_mutate_threshold (float): Determines max how much weight mutaiton operation applying. (Function automaticly determines to min)
656
-
657
- genome_fitness (float): Fitness (0-1) value of genome
658
-
659
- activation_mutate_threshold (float): Determines max how much activation mutaiton operation applying. (Function automaticly determines to min)
660
-
661
- epsilon (float): Small epsilon constant
662
-
663
- Returns:
664
- tuple: A tuple containing:
665
- - mutated_weight (numpy.ndarray): The weight matrix after mutation.
666
- - mutated_activations (list): The list of activation functions after mutation.
667
-
668
- Notes:
669
- - Weight mutation:
670
- - Each weight has a chance defined by `weight_mutate_prob` to be altered by adding a random value
671
- within the range of [0, 1].
672
- - Activation mutation:
673
- - If `activation_mutate_prob` is triggered, one or more activation functions can be added, removed,
674
- or replaced based on their respective probabilities (`activation_add_prob`, `activation_delete_prob`,
675
- `activation_change_prob`).
676
- - The mutation probabilities should be chosen carefully to balance exploration and exploitation during
677
- the optimization process.
678
- """
679
-
680
- if isinstance(activations, str): activations = [activations]
681
-
682
- weight_mutate_prob = 1 - weight_mutate_prob # if prob 0.8 (%80) then 1 - 0.8. Because 0-1 random number probably greater than 0.2
683
- potential_weight_mutation = random.uniform(0, 1)
684
-
685
- if potential_weight_mutation > weight_mutate_prob:
686
-
687
- start = 0
688
- row_end = weight.shape[0]
689
- col_end = weight.shape[1]
690
-
691
- max_threshold = row_end * col_end
692
-
693
- threshold = weight_mutate_threshold * genome_fitness
694
- new_threshold = threshold
695
-
696
- for _ in range(max_threshold):
697
-
698
- selected_row = int(random.uniform(start, row_end))
699
- selected_col = int(random.uniform(start, col_end))
700
-
701
- weight[selected_row, selected_col] = random.uniform(-1, 1)
702
- new_threshold += threshold
703
-
704
- if max_threshold > new_threshold:
705
- pass
706
-
707
- else:
708
- break
709
-
710
- activation_mutate_prob = 1 - activation_mutate_prob
711
- potential_activation_mutation = random.uniform(0, 1)
712
-
713
- if potential_activation_mutation > activation_mutate_prob:
714
-
715
- genome_fitness += epsilon
716
- threshold = abs(activation_mutate_threshold / genome_fitness)
717
- max_threshold = len(activations)
718
-
719
- new_threshold = threshold
720
-
721
- except_this = ['spiral', 'circular']
722
- all_acts = [item for item in all_activations() if item not in except_this] # SPIRAL AND CIRCULAR ACTIVATION DISCARDED
723
-
724
- activation_add_prob = 1 - activation_add_prob
725
- activation_delete_prob = 1 - activation_delete_prob
726
- activation_change_prob = 1 - activation_change_prob
727
-
728
- for _ in range(max_threshold):
729
-
730
- potential_activation_add_prob = random.uniform(0, 1)
731
- potential_activation_delete_prob = random.uniform(0, 1)
732
- potential_activation_change_prob = random.uniform(0, 1)
733
-
734
-
735
- if potential_activation_delete_prob > activation_delete_prob and len(activations) > 1:
736
-
737
- random_index = random.randint(0, len(activations) - 1)
738
- activations.pop(random_index)
739
-
740
-
741
- if potential_activation_add_prob > activation_add_prob:
742
-
743
- try:
744
-
745
- random_index_all_act = int(random.uniform(0, len(all_acts)-1))
746
- activations.append(all_acts[random_index_all_act])
747
-
748
- except:
749
-
750
- activation = activations
751
- activations = []
752
-
753
- activations.append(activation)
754
- activations.append(all_acts[int(random.uniform(0, len(all_acts)-1))])
755
-
756
-
757
- if potential_activation_change_prob > activation_change_prob:
758
-
759
- random_index_all_act = int(random.uniform(0, len(all_acts)-1))
760
- random_index_genom_act = int(random.uniform(0, len(activations)-1))
761
-
762
- activations[random_index_genom_act] = all_acts[random_index_all_act]
763
-
764
- new_threshold += threshold
765
-
766
- if max_threshold > new_threshold: pass
767
- else: break
768
-
769
- return weight, activations
770
-
771
- def second_parent_selection(good_weights, bad_weights, good_activations, bad_activations, bad_genomes_selection_prob):
772
-
773
- selection_prob = random.uniform(0, 1)
774
- random_index = int(random.uniform(0, len(good_weights) - 1))
775
-
776
- if selection_prob > bad_genomes_selection_prob:
777
- second_selected_W = good_weights[random_index]
778
- second_selected_act = good_activations[random_index]
779
-
780
- else:
781
- second_selected_W = bad_weights[random_index]
782
- second_selected_act = bad_activations[random_index]
783
-
784
- return second_selected_W, second_selected_act, random_index
785
-
786
- def dominant_parent_selection(bad_genomes_selection_prob):
787
-
788
- selection_prob = random.uniform(0, 1)
789
-
790
- if selection_prob > bad_genomes_selection_prob: decision = 'first_parent'
791
- else: decision = 'second_parent'
792
-
793
- return decision