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