pyerualjetwork 4.0.5__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,736 @@
1
+ """
2
+ MAIN MODULE FOR PLANEAT
3
+
4
+ ANAPLAN document: https://github.com/HCB06/Anaplan/blob/main/Welcome_to_Anaplan/ANAPLAN_USER_MANUEL_AND_LEGAL_INFORMATION(EN).pdf
5
+
6
+ @author: Hasan Can Beydili
7
+ @YouTube: https://www.youtube.com/@HasanCanBeydili
8
+ @Linkedin: https://www.linkedin.com/in/hasan-can-beydili-77a1b9270/
9
+ @Instagram: https://www.instagram.com/canbeydili.06/
10
+ @contact: tchasancan@gmail.com
11
+ """
12
+
13
+ import cupy as cp
14
+ import numpy as np
15
+ import random
16
+ from tqdm import tqdm
17
+
18
+ ### LIBRARY IMPORTS ###
19
+ from plan_cuda import feed_forward
20
+ from data_operations_cuda import normalization
21
+ from ui import loading_bars
22
+ from activation_functions_cuda import apply_activation, all_activations
23
+
24
+ def define_genomes(input_shape, output_shape, population_size, dtype=cp.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 (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)
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] = cp.random.uniform(-1, 1, (output_shape, input_shape)).astype(dtype, copy=False)
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 cp.array(population_weights), population_activations
71
+
72
+
73
+ def evolve(weights, activation_potentiations, what_gen, y_reward, show_info=False, strategy='cross_over', policy='normal_selective', mutations=True, bad_genoms_mutation_prob=None, activation_mutate_prob=0.5, save_best_genom=True, cross_over_mode='tpm', activation_add_prob=0.5, activation_delete_prob=0.5, activation_change_prob=0.5, weight_mutate_prob=1, weight_mutate_rate=32, activation_selection_add_prob=0.5, activation_selection_change_prob=0.5, activation_selection_rate=2, dtype=cp.float32):
74
+ """
75
+ Applies the evolving process of a population of genomes using selection, crossover, mutation, and activation function potentiation.
76
+ The function modifies the population's weights and activation functions based on a specified policy, mutation probabilities, and strategy.
77
+
78
+ Args:
79
+ weights (numpy.ndarray): Array of weights for each genome.
80
+ (first returned value of define_genomes function)
81
+
82
+ activation_potentiations (list): A list of activation functions for each genome.
83
+ (second returned value of define_genomes function)
84
+
85
+ what_gen (int): The current generation number, used for informational purposes or logging.
86
+
87
+ y_reward (numpy.ndarray): A 1D array containing the fitness or reward values of each genome.
88
+ The array is used to rank the genomes based on their performance. PLANEAT maximizes the reward.
89
+
90
+ show_info (bool, optional): If True, prints information about the current generation and the
91
+ maximum reward obtained. Also shows the current configuration. Default is False.
92
+
93
+ strategy (str, optional): The strategy for combining the best and bad genomes. Options:
94
+ - 'cross_over': Perform crossover between the best genomes and replace bad genomes.
95
+ (Classic NEAT crossover)
96
+ - 'potentiate': Cumulate the weight of the best genomes and replace bad genomes.
97
+ (PLAN feature, similar to arithmetic crossover but different.)
98
+ Default is 'cross_over'.
99
+
100
+ policy (str, optional): The selection policy that governs how genomes are selected for reproduction. Options:
101
+ - 'normal_selective': Normal selection based on reward, where a portion of the bad genes are discarded.
102
+ - 'more_selective': A more selective policy, where fewer bad genes survive.
103
+ - 'less_selective': A less selective policy, where more bad genes survive.
104
+ Default is 'normal_selective'.
105
+
106
+ mutations (bool, optional): If True, mutations are applied to the bad genomes and potentially
107
+ to the best genomes as well. Default is True.
108
+
109
+ bad_genoms_mutation_prob (float, optional): The probability of applying mutation to the bad genomes.
110
+ Must be in the range [0, 1]. Also affects the mutation probability of the best genomes inversely.
111
+ For example, a value of 0.7 for bad genomes implies 0.3 for best genomes. Default is None,
112
+ which means it is determined by the `policy` argument.
113
+
114
+ activation_mutate_prob (float, optional): The probability of applying mutation to the activation functions.
115
+ Must be in the range [0, 1]. Default is 0.5 (50%).
116
+
117
+ save_best_genom (bool, optional): If True, ensures that the best genomes are saved and not mutated
118
+ or altered during reproduction. Default is True.
119
+
120
+ cross_over_mode (str, optional): Specifies the crossover method to use. Options:
121
+ - 'tpm': Two-Point Matrix Crossover
122
+ - 'plantic': plantic Crossover
123
+ Default is 'tpm'.
124
+
125
+ activation_add_prob (float, optional): The probability of adding a new activation function to the genome for mutation.
126
+ Must be in the range [0, 1]. Default is 0.5.
127
+
128
+ activation_delete_prob (float, optional): The probability of deleting an existing activation function
129
+ from the genome for mutation. Must be in the range [0, 1]. Default is 0.5.
130
+
131
+ activation_change_prob (float, optional): The probability of changing an activation function in the genome for mutation.
132
+ Must be in the range [0, 1]. Default is 0.5.
133
+
134
+ weight_mutate_prob (float, optional): The probability of mutating a weight in the genome.
135
+ Must be in the range [0, 1]. Default is 1.
136
+
137
+ weight_mutate_rate (int, optional): If the value you enter here is equal to the result of input layer * output layer,
138
+ only a single weight will be mutated during each mutation process. If the value you enter here is half
139
+ of the result of input layer * output layer, two weights in the weight matrix will be mutated.
140
+ WARNING: if you don't understand do NOT change this value. Default is 32.
141
+
142
+ activation_selection_add_prob (float, optional): The probability of adding an existing activation function for cross over.
143
+ from the genome. Must be in the range [0, 1]. Default is 0.5.
144
+
145
+ activation_selection_change_prob (float, optional): The probability of changing an activation function in the genome for cross over.
146
+ Must be in the range [0, 1]. Default is 0.5.
147
+
148
+ activation_selection_rate (int, optional): If the activation list of a good genome is smaller than the value entered here, only one activation will undergo a crossover operation. In other words, this parameter controls the model complexity. Default is 2.
149
+
150
+ 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)
151
+
152
+ Raises:
153
+ ValueError:
154
+ - If `policy` is not one of the specified values ('normal_selective', 'more_selective', 'less_selective').
155
+ - If `cross_over_mode` is not one of the specified values ('tpm', 'plantic').
156
+ - If `bad_genoms_mutation_prob`, `activation_mutate_prob`, or other probability parameters are not in the range [0, 1].
157
+ - If the population size is odd (ensuring an even number of genomes is required for proper selection).
158
+
159
+ Returns:
160
+ tuple: A tuple containing:
161
+ - weights (numpy.ndarray): The updated weights for the population after selection, crossover, and mutation.
162
+ The shape is (population_size, output_shape, input_shape).
163
+ - activation_potentiations (list): The updated list of activation functions for the population.
164
+
165
+ Notes:
166
+ - **Selection Process**:
167
+ - The genomes are sorted by their fitness (based on `y_reward`), and then split into "best" and "bad" halves.
168
+ - The best genomes are retained, and the bad genomes are modified based on the selected strategy.
169
+
170
+ - **Crossover and Potentiation Strategies**:
171
+ - The **'cross_over'** strategy performs crossover, where parts of the best genomes' weights are combined with the other good genomes to create new weight matrices.
172
+ - The **'potentiate'** strategy strengthens the best genomes by potentiating their weights towards the other good genomes.
173
+
174
+ - **Mutation**:
175
+ - Mutation is applied to both the best and bad genomes, depending on the mutation probability and the `policy`.
176
+ - `bad_genoms_mutation_prob` determines the probability of applying mutations to the bad genomes.
177
+ - If `activation_mutate_prob` is provided, activation function mutations are applied to the genomes based on this probability.
178
+
179
+ - **Population Size**: The population size must be an even number to properly split the best and bad genomes. If `y_reward` has an odd length, an error is raised.
180
+
181
+ - **Logging**: If `show_info=True`, the current generation and the maximum reward from the population are printed for tracking the learning progress.
182
+
183
+ Example:
184
+ ```python
185
+ weights, activation_potentiations = learner(weights, activation_potentiations, 1, y_reward, info=True, strategy='cross_over', policy='normal_selective')
186
+ ```
187
+
188
+ - The function returns the updated weights and activations after processing based on the chosen strategy, policy, and mutation parameters.
189
+ """
190
+
191
+ ### ERROR AND CONFIGURATION CHECKS:
192
+
193
+ if policy == 'normal_selective':
194
+ if bad_genoms_mutation_prob == None:
195
+ bad_genoms_mutation_prob = 0.7
196
+
197
+ elif policy == 'more_selective':
198
+ if bad_genoms_mutation_prob == None:
199
+ bad_genoms_mutation_prob = 0.85
200
+
201
+ elif policy == 'less_selective':
202
+ if bad_genoms_mutation_prob == None:
203
+ bad_genoms_mutation_prob = 0.6
204
+
205
+ else:
206
+ raise ValueError("policy parameter must be: 'normal_selective' or 'more_selective' or 'less_selective'")
207
+
208
+
209
+ if (activation_add_prob < 0 or activation_add_prob > 1) or (activation_change_prob < 0 or activation_change_prob > 1) or (activation_delete_prob < 0 or activation_delete_prob > 1) or (weight_mutate_prob < 0 or weight_mutate_prob > 1) or (activation_selection_add_prob < 0 or activation_selection_add_prob > 1) or (activation_selection_change_prob < 0 or activation_selection_change_prob > 1):
210
+ raise ValueError("All hyperparameters ending with 'prob' must be a number between 0 and 1.")
211
+
212
+ if cross_over_mode != 'tpm' and cross_over_mode != 'plantic':
213
+ raise ValueError("cross_over_mode parameter must be 'tpm' or 'plantic'")
214
+
215
+ if bad_genoms_mutation_prob is not None:
216
+ if not isinstance(bad_genoms_mutation_prob, float) or bad_genoms_mutation_prob < 0 or bad_genoms_mutation_prob > 1:
217
+ raise ValueError("bad_genoms_mutation_prob parameter must be float and 0-1 range")
218
+
219
+ if activation_mutate_prob is not None:
220
+ if not isinstance(activation_mutate_prob, float) or activation_mutate_prob < 0 or activation_mutate_prob > 1:
221
+ raise ValueError("activation_mutate_prob parameter must be float and 0-1 range")
222
+
223
+ if len(y_reward) % 2 == 0:
224
+ slice_center = int(len(y_reward) / 2)
225
+
226
+ else:
227
+ raise ValueError("genome population size must be even number. for example: not 99, make 100 or 98.")
228
+
229
+ sort_indices = cp.argsort(y_reward)
230
+
231
+ ### REWARD LIST IS SORTED IN ASCENDING ORDER, AND THE WEIGHT AND ACTIVATIONS OF EACH GENOME ARE SORTED ACCORDING TO THIS ORDER:
232
+
233
+ y_reward = y_reward[sort_indices]
234
+ weights = weights[sort_indices]
235
+
236
+ activation_potentiations = [activation_potentiations[i] for i in sort_indices]
237
+
238
+ ### GENOMES ARE DIVIDED INTO TWO GROUPS: GOOD GENOMES AND BAD GENOMES:
239
+
240
+ best_weights = weights[slice_center:]
241
+ bad_weights = weights[:slice_center]
242
+ best_weight = best_weights[len(best_weights)-1]
243
+
244
+ best_activations = list(activation_potentiations[slice_center:])
245
+ bad_activations = list(activation_potentiations[:slice_center])
246
+ best_activation = best_activations[len(best_activations) - 1]
247
+
248
+
249
+ ### NEAT IS APPLIED ACCORDING TO THE SPECIFIED POLICY, STRATEGY, AND PROBABILITY CONFIGURATION:
250
+
251
+ bar_format = loading_bars()[0]
252
+
253
+ for i in tqdm(range(len(bad_weights)), desc="GENERATION: " + str(what_gen), bar_format=bar_format, ncols=50, ascii="▱▰"):
254
+
255
+ if policy == 'normal_selective':
256
+
257
+ if strategy == 'cross_over':
258
+ bad_weights[i], bad_activations[i] = cross_over(best_weight, best_weights[i], best_activations=best_activation, good_activations=best_activations[i], cross_over_mode=cross_over_mode, activation_selection_add_prob=activation_selection_add_prob, activation_selection_change_prob=activation_selection_change_prob, activation_selection_rate=activation_selection_rate)
259
+
260
+
261
+ elif strategy == 'potentiate':
262
+ bad_weights[i], bad_activations[i] = potentiate(best_weight, best_weights[i], best_activations=best_activation, good_activations=best_activations[i], dtype=dtype)
263
+
264
+
265
+ if mutations is True:
266
+
267
+ mutation_prob = random.uniform(0, 1)
268
+
269
+ if mutation_prob > bad_genoms_mutation_prob:
270
+ if (save_best_genom == True and not cp.array_equal(best_weights[i], best_weight)) or save_best_genom == False:
271
+ best_weights[i], best_activations[i] = mutation(best_weights[i], best_activations[i], activation_mutate_prob=activation_mutate_prob, activation_add_prob=activation_add_prob, activation_delete_prob=activation_delete_prob, activation_change_prob=activation_change_prob, weight_mutate_prob=weight_mutate_prob, threshold=weight_mutate_rate, dtype=dtype)
272
+
273
+ elif mutation_prob < bad_genoms_mutation_prob:
274
+ bad_weights[i], bad_activations[i] = mutation(bad_weights[i], bad_activations[i], activation_mutate_prob=activation_mutate_prob, activation_add_prob=activation_add_prob, activation_delete_prob=activation_delete_prob, activation_change_prob=activation_change_prob, weight_mutate_prob=weight_mutate_prob, threshold=weight_mutate_rate, dtype=dtype)
275
+
276
+ if policy == 'more_selective':
277
+
278
+ if strategy == 'cross_over':
279
+ bad_weights[i], bad_activations[i] = cross_over(best_weight, best_weights[i], best_activations=best_activation, good_activations=best_activations[i], cross_over_mode=cross_over_mode, activation_selection_add_prob=activation_selection_add_prob, activation_selection_change_prob=activation_selection_change_prob, activation_selection_rate=activation_selection_rate)
280
+
281
+ elif strategy == 'potentiate':
282
+ bad_weights[i], bad_activations[i] = potentiate(best_weight, best_weights[i], best_activations=best_activation, good_activations=best_activations[i], dtype=dtype)
283
+
284
+ if mutations is True:
285
+
286
+ mutation_prob = random.uniform(0, 1)
287
+
288
+ if mutation_prob > bad_genoms_mutation_prob:
289
+ if (save_best_genom == True and not cp.array_equal(best_weights[i], best_weight)) or save_best_genom == False:
290
+ best_weights[i], best_activations[i] = mutation(best_weights[i], best_activations[i], activation_mutate_prob=activation_mutate_prob, activation_add_prob=activation_add_prob, activation_delete_prob=activation_delete_prob, activation_change_prob=activation_change_prob, weight_mutate_prob=weight_mutate_prob, threshold=weight_mutate_rate, dtype=dtype)
291
+
292
+ elif mutation_prob < bad_genoms_mutation_prob:
293
+ bad_weights[i], bad_activations[i] = mutation(bad_weights[i], bad_activations[i], activation_mutate_prob=activation_mutate_prob, activation_add_prob=activation_add_prob, activation_delete_prob=activation_delete_prob, activation_change_prob=activation_change_prob, weight_mutate_prob=weight_mutate_prob, threshold=weight_mutate_rate, dtype=dtype)
294
+
295
+
296
+
297
+ if policy == 'less_selective':
298
+
299
+ random_index = int(random.uniform(0, len(best_weights) - 1))
300
+
301
+ if strategy == 'cross_over':
302
+ bad_weights[i], bad_activations[i] = cross_over(best_weights[random_index], best_weights[i], best_activations=best_activations[random_index], good_activations=best_activations[i], cross_over_mode=cross_over_mode, activation_selection_add_prob=activation_selection_add_prob, activation_selection_change_prob=activation_selection_change_prob, activation_selection_rate=activation_selection_rate)
303
+
304
+ elif strategy == 'potentiate':
305
+ bad_weights[i], bad_activations[i] = potentiate(best_weights[random_index], best_weights[i], best_activations=best_activations[random_index], good_activations=best_activations[i], dtype=dtype)
306
+
307
+ if mutations is True:
308
+
309
+ mutation_prob = random.uniform(0, 1)
310
+
311
+ if mutation_prob > bad_genoms_mutation_prob:
312
+ if (save_best_genom == True and not cp.array_equal(best_weights[i], best_weight)) or save_best_genom == False:
313
+ best_weights[i], best_activations[i] = mutation(best_weights[i], best_activations[i], activation_mutate_prob=activation_mutate_prob, activation_add_prob=activation_add_prob, activation_delete_prob=activation_delete_prob, activation_change_prob=activation_change_prob, weight_mutate_prob=weight_mutate_prob, threshold=weight_mutate_rate, dtype=dtype)
314
+
315
+ elif mutation_prob < bad_genoms_mutation_prob:
316
+ bad_weights[i], bad_activations[i] = mutation(bad_weights[i], bad_activations[i], activation_mutate_prob=activation_mutate_prob, activation_add_prob=activation_add_prob, activation_delete_prob=activation_delete_prob, activation_change_prob=activation_change_prob, weight_mutate_prob=weight_mutate_prob, threshold=weight_mutate_rate, dtype=dtype)
317
+
318
+
319
+ weights = cp.vstack((bad_weights, best_weights))
320
+ activation_potentiations = bad_activations + best_activations
321
+
322
+ ### INFO PRINTING CONSOLE
323
+
324
+ if show_info == True:
325
+ print("\nGENERATION:", str(what_gen) + ' FINISHED \n')
326
+ print("*** Configuration Settings ***")
327
+ print(" POPULATION SIZE: ", str(len(weights)))
328
+ print(" STRATEGY: ", strategy)
329
+
330
+ if strategy == 'cross_over':
331
+ print(" CROSS OVER MODE: ", cross_over_mode)
332
+
333
+ print(" POLICY: ", policy)
334
+ print(" MUTATIONS: ", str(mutations))
335
+ print(" BAD GENOMES MUTATION PROB: ", str(bad_genoms_mutation_prob))
336
+ print(" GOOD GENOMES MUTATION PROB: ", str(round(1 - bad_genoms_mutation_prob, 2)))
337
+ print(" WEIGHT MUTATE PROB: ", str(weight_mutate_prob))
338
+ print(" WEIGHT MUTATE RATE (THRESHOLD VALUE FOR SINGLE MUTATION): ", str(weight_mutate_rate))
339
+ print(" ACTIVATION MUTATE PROB: ", str(activation_mutate_prob))
340
+ print(" ACTIVATION ADD PROB: ", str(activation_add_prob))
341
+ print(" ACTIVATION DELETE PROB: ", str(activation_delete_prob))
342
+ print(" ACTIVATION CHANGE PROB: ", str(activation_change_prob))
343
+ print(" ACTIVATION SELECTION ADD PROB: ", str(activation_selection_add_prob))
344
+ print(" ACTIVATION SELECTION CHANGE PROB: ", str(activation_selection_change_prob))
345
+ print(" ACTIVATION SELECTION RATE (THRESHOLD VALUE FOR SINGLE CROSS OVER):", str(activation_selection_rate) + '\n')
346
+
347
+ print("*** Performance ***")
348
+ print(" MAX REWARD: ", str(round(max(y_reward), 2)))
349
+ print(" MEAN REWARD: ", str(round(cp.mean(y_reward), 2)))
350
+ print(" MIN REWARD: ", str(round(min(y_reward), 2)) + '\n')
351
+
352
+ print(" BEST GENOME INDEX: ", str(len(weights)-1))
353
+ print(" NOTE: Genomes are always sorted from the least successful to the most successful according to their performance ranking. Therefore, the genome at the last index is the king of the previous generation. " + '\n')
354
+
355
+
356
+ return cp.array(weights), activation_potentiations
357
+
358
+
359
+ def evaluate(x_population, weights, activation_potentiations, rl_mode=False, dtype=cp.float32):
360
+ """
361
+ Evaluates the performance of a population of genomes, applying different activation functions
362
+ and weights depending on whether reinforcement learning mode is enabled or not.
363
+
364
+ Args:
365
+ x_population (list or numpy.ndarray): A list or 2D numpy array where each element represents
366
+ a genome (A list of input features for each genome, or a single set of input features for one genome (only in rl_mode)).
367
+ weights (list or numpy.ndarray): A list or 2D numpy array of weights corresponding to each genome
368
+ in `x_population`. This determines the strength of connections.
369
+ activation_potentiations (list or str): A list where each entry represents an activation function
370
+ or a potentiation strategy applied to each genome. If only one
371
+ activation function is used, this can be a single string.
372
+ rl_mode (bool, optional): If True, reinforcement learning mode is activated, this accepts x_population is a single genom. (Also weights and activation_potentations a single genomes part.)
373
+ Default is False.
374
+
375
+
376
+ 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)
377
+
378
+ Returns:
379
+ list: A list of outputs corresponding to each genome in the population after applying the respective
380
+ activation function and weights.
381
+
382
+ Notes:
383
+ - If `rl_mode` is True:
384
+ - Accepts x_population is a single genom
385
+ - The inputs are flattened, and the activation function is applied across the single genom.
386
+
387
+ - If `rl_mode` is False:
388
+ - Accepts x_population is a list of genomes
389
+ - Each genome is processed individually, and the results are stored in the `outputs` list.
390
+
391
+ - `feed_forward()` function is the core function that processes the input with the given weights and activation function.
392
+
393
+ Example:
394
+ ```python
395
+ outputs = evaluate(x_population, weights, activation_potentiations, rl_mode=False)
396
+ ```
397
+
398
+ - The function returns a list of outputs after processing the population, where each element corresponds to
399
+ the output for each genome in `x_population`.
400
+ """
401
+
402
+ ### IF RL_MODE IS TRUE, A SINGLE GENOME IS ASSUMED AS INPUT, A FEEDFORWARD PREDICTION IS MADE, AND THE OUTPUT(NPARRAY) IS RETURNED:
403
+
404
+ ### IF RL_MODE IS FALSE, PREDICTIONS ARE MADE FOR ALL GENOMES IN THE GROUP USING THEIR CORRESPONDING INDEXED INPUTS AND DATA.
405
+ ### THE OUTPUTS ARE RETURNED AS A PYTHON LIST, WHERE EACH GENOME'S OUTPUT MATCHES ITS INDEX:
406
+
407
+ if rl_mode == True:
408
+ Input = cp.array(x_population, dtype=dtype, copy=False)
409
+ Input = Input.ravel()
410
+
411
+ if isinstance(activation_potentiations, str):
412
+ activation_potentiations = [activation_potentiations]
413
+
414
+ outputs = feed_forward(Input=Input, is_training=False, activation_potentiation=activation_potentiations, w=weights)
415
+
416
+ else:
417
+ outputs = [0] * len(x_population)
418
+ for i, genome in enumerate(x_population):
419
+
420
+ Input = cp.array(genome)
421
+ Input = Input.ravel()
422
+
423
+ if isinstance(activation_potentiations[i], str):
424
+ activation_potentiations[i] = [activation_potentiations[i]]
425
+
426
+ outputs[i] = feed_forward(Input=Input, is_training=False, activation_potentiation=activation_potentiations[i], w=weights[i])
427
+
428
+ return outputs
429
+
430
+
431
+ def cross_over(best_weight, good_weight, best_activations, good_activations, cross_over_mode, activation_selection_add_prob, activation_selection_change_prob, activation_selection_rate):
432
+ """
433
+ Performs a selected Crossover operation on two sets of weights and activation functions.
434
+ This function combines two individuals (represented by their weights and activation functions)
435
+ to create a new individual by exchanging parts of their weight matrices and activation functions.
436
+
437
+ Args:
438
+ best_weight (numpy.ndarray): The weight matrix of the first individual (parent).
439
+ good_weight (numpy.ndarray): The weight matrix of the second individual (parent).
440
+ best_activations (str or list): The activation function(s) of the first individual.
441
+ good_activations (str or list): The activation function(s) of the second individual.
442
+ cross_over_mode (str): Determines the crossover method to be used. Options:
443
+ - 'tpm': Two-Point Matrix Crossover, where sub-matrices of weights
444
+ are swapped between parents.
445
+ - 'plan': Output Connections Crossover, where specific connections
446
+ in the weight matrix are crossed over. Default is 'tpm'.
447
+
448
+ Returns:
449
+ tuple: A tuple containing:
450
+ - new_weight (numpy.ndarray): The weight matrix of the new individual created by crossover.
451
+ - new_activations (list): The list of activation functions of the new individual created by crossover.
452
+
453
+ Notes:
454
+ - The crossover is performed based on the selected `cross_over_mode`.
455
+ - In 'tpm', random sub-matrices from the parent weight matrices are swapped.
456
+ - In 'plantic', specific connections in the weight matrix are swapped between parents.
457
+ - The crossover operation combines the activation functions of both parents:
458
+ - If the activation functions are passed as strings, they are converted to lists for uniform handling.
459
+ - The resulting activation functions depend on the crossover method and the parent's configuration.
460
+
461
+ Example:
462
+ ```python
463
+ new_weights, new_activations = cross_over(best_weight, good_weight, best_activations, good_activations, cross_over_mode='tpm')
464
+ ```
465
+ """
466
+
467
+ ### 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:
468
+
469
+ start = 0
470
+
471
+ row_end = best_weight.shape[0]
472
+ col_end = best_weight.shape[1]
473
+
474
+ while True:
475
+
476
+ row_cut_start = int(random.uniform(start, row_end))
477
+ col_cut_start = int(random.uniform(start, col_end))
478
+
479
+ row_cut_end = int(random.uniform(start, row_end))
480
+ col_cut_end = int(random.uniform(start, col_end))
481
+
482
+ if (row_cut_end > row_cut_start) and (col_cut_end > col_cut_start):
483
+ break
484
+
485
+ new_weight = cp.copy(best_weight)
486
+ best_w2 = cp.copy(good_weight)
487
+
488
+ if cross_over_mode == 'tpm':
489
+ new_weight[row_cut_start:row_cut_end, col_cut_start:col_cut_end] = best_w2[row_cut_start:row_cut_end, col_cut_start:col_cut_end]
490
+
491
+ elif cross_over_mode == 'plantic':
492
+ new_weight[row_cut_start:row_cut_end,:] = best_w2[row_cut_start:row_cut_end,:]
493
+
494
+
495
+ if isinstance(best_activations, str):
496
+ best = [best_activations]
497
+
498
+ if isinstance(good_activations, str):
499
+ good = [good_activations]
500
+
501
+ if isinstance(best_activations, list):
502
+ best = best_activations
503
+
504
+ if isinstance(good_activations, list):
505
+ good = good_activations
506
+
507
+ new_activations = list(np.copy(best))
508
+
509
+ 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
510
+ potential_activation_selection_add = random.uniform(0, 1)
511
+
512
+ if potential_activation_selection_add > activation_selection_add_prob:
513
+
514
+ new_threshold = activation_selection_rate
515
+
516
+ while True:
517
+
518
+ random_index_good = int(random.uniform(0, len(good)-1))
519
+ random_good_activation = good[random_index_good]
520
+
521
+ new_activations.append(random_good_activation)
522
+
523
+ if len(best) > new_threshold:
524
+ new_threshold += activation_selection_rate
525
+ pass
526
+
527
+ else:
528
+ break
529
+
530
+ activation_selection_change_prob = 1 - activation_selection_change_prob
531
+ potential_activation_selection_change_prob = random.uniform(0, 1)
532
+
533
+ if potential_activation_selection_change_prob > activation_selection_change_prob:
534
+
535
+ new_threshold = activation_selection_rate
536
+
537
+ while True:
538
+
539
+ random_index_good = int(random.uniform(0, len(good)-1))
540
+ random_index_best = int(random.uniform(0, len(best)-1))
541
+ random_good_activation = good[random_index_good]
542
+
543
+ new_activations[random_index_best] = good[random_index_good]
544
+
545
+ if len(best) > new_threshold:
546
+ new_threshold += activation_selection_rate
547
+ pass
548
+
549
+ else:
550
+ break
551
+
552
+ return new_weight, new_activations
553
+
554
+ def potentiate(best_weight, good_weight, best_activations, good_activations, dtype=cp.float32):
555
+ """
556
+ Combines two sets of weights and activation functions by adding the weight matrices and
557
+ concatenating the activation functions. The resulting weight matrix is normalized. (Max abs normalization.)
558
+
559
+ Args:
560
+ best_weight (numpy.ndarray): The weight matrix of the first individual (parent).
561
+ good_weight (numpy.ndarray): The weight matrix of the second individual (parent).
562
+ best_activations (str or list): The activation function(s) of the first individual.
563
+ good_activations (str or list): The activation function(s) of the second individual.
564
+ 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)
565
+
566
+ Returns:
567
+ tuple: A tuple containing:
568
+ - new_weight (numpy.ndarray): The new weight matrix after potentiation and normalization. (Max abs normalization.)
569
+ - new_activations (list): The new activation functions after concatenation.
570
+
571
+ Notes:
572
+ - The weight matrices are element-wise added and then normalized using the `normalization` function. (Max abs normalization.)
573
+ - The activation functions from both parents are concatenated to form the new activation functions list.
574
+ - If the activation functions are passed as strings, they are converted to lists for uniform handling.
575
+ """
576
+
577
+ new_weight = best_weight + good_weight
578
+ new_weight = normalization(new_weight, dtype=dtype)
579
+
580
+ if isinstance(best_activations, str):
581
+ best = [best_activations]
582
+
583
+ if isinstance(good_activations, str):
584
+ good = [good_activations]
585
+
586
+ if isinstance(best_activations, list):
587
+ best = best_activations
588
+
589
+ if isinstance(good_activations, list):
590
+ good = good_activations
591
+
592
+ new_activations = best + good
593
+
594
+ return new_weight, new_activations
595
+
596
+ def mutation(weight, activations, activation_mutate_prob, activation_add_prob, activation_delete_prob, activation_change_prob, weight_mutate_prob, threshold, dtype=cp.float32):
597
+ """
598
+ Performs mutation on the given weight matrix and activation functions.
599
+ - The weight matrix is mutated by randomly changing its values based on the mutation probability.
600
+ - The activation functions are mutated by adding, removing, or replacing them with predefined probabilities.
601
+
602
+ Args:
603
+ weight (numpy.ndarray): The weight matrix to mutate.
604
+ activations (list): The list of activation functions to mutate.
605
+ activation_mutate_prob (float): The overall probability of mutating activation functions.
606
+ activation_add_prob (float): Probability of adding a new activation function.
607
+ activation_delete_prob (float): Probability of removing an existing activation function.
608
+ activation_change_prob (float): Probability of replacing an existing activation function with a new one.
609
+ weight_mutate_prob (float): The probability of mutating weight matrix.
610
+ threshold (float): If the value you enter here is equal to the result of input layer * output layer, only a single weight will be mutated during each mutation process. If the value you enter here is half of the result of input layer * output layer, two weights in the weight matrix will be mutated.
611
+ 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)
612
+
613
+ Returns:
614
+ tuple: A tuple containing:
615
+ - mutated_weight (numpy.ndarray): The weight matrix after mutation.
616
+ - mutated_activations (list): The list of activation functions after mutation.
617
+
618
+ Notes:
619
+ - Weight mutation:
620
+ - Each weight has a chance defined by `weight_mutate_prob` to be altered by adding a random value
621
+ within the range of [0, 1].
622
+ - Activation mutation:
623
+ - If `activation_mutate_prob` is triggered, one or more activation functions can be added, removed,
624
+ or replaced based on their respective probabilities (`activation_add_prob`, `activation_delete_prob`,
625
+ `activation_change_prob`).
626
+ - The mutation probabilities should be chosen carefully to balance exploration and exploitation during
627
+ the optimization process.
628
+ """
629
+
630
+ if isinstance(activations, str):
631
+ activations = [activations]
632
+
633
+ 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
634
+ potential_weight_mutation = random.uniform(0, 1)
635
+
636
+ if potential_weight_mutation > weight_mutate_prob:
637
+
638
+ start = 0
639
+ row_end = weight.shape[0]
640
+ col_end = weight.shape[1]
641
+ new_threshold = threshold
642
+
643
+ while True:
644
+
645
+ selected_row = int(random.uniform(start, row_end))
646
+ selected_col = int(random.uniform(start, col_end))
647
+
648
+ weight[selected_row, selected_col] = random.uniform(-1, 1)
649
+
650
+ if int(row_end * col_end) > new_threshold:
651
+ new_threshold += threshold
652
+ pass
653
+
654
+ else:
655
+ break
656
+
657
+
658
+ activation_mutate_prob = 1 - activation_mutate_prob
659
+ potential_activation_mutation = random.uniform(0, 1)
660
+
661
+ if potential_activation_mutation > activation_mutate_prob:
662
+
663
+ except_this = ['spiral', 'circular']
664
+ all_acts = [item for item in all_activations() if item not in except_this] # SPIRAL AND CIRCULAR ACTIVATION DISCARDED
665
+
666
+ activation_add_prob = 1 - activation_add_prob
667
+ activation_delete_prob = 1 - activation_delete_prob
668
+ activation_change_prob = 1 - activation_change_prob
669
+
670
+ potential_activation_add_prob = random.uniform(0, 1)
671
+ potential_activation_delete_prob = random.uniform(0, 1)
672
+ potential_activation_change_prob = random.uniform(0, 1)
673
+
674
+ if potential_activation_add_prob > activation_add_prob:
675
+
676
+ try:
677
+
678
+ random_index_all_act = int(random.uniform(0, len(all_acts)-1))
679
+ activations.append(all_acts[random_index_all_act])
680
+
681
+ for i in range(weight.shape[0]):
682
+
683
+ weight[i,:] = apply_activation(weight[i,:], activations[-1])
684
+
685
+ weight = normalization(weight, dtype=dtype)
686
+
687
+ except:
688
+
689
+ activation = activations
690
+ activations = []
691
+
692
+ activations.append(activation)
693
+ activations.append(all_acts[int(random.uniform(0, len(all_acts)-1))])
694
+
695
+ for i in range(weight.shape[0]):
696
+
697
+ weight[i,:] = apply_activation(weight[i,:], activations[-1])
698
+
699
+ weight = normalization(weight, dtype=dtype)
700
+
701
+ if potential_activation_delete_prob > activation_delete_prob and len(activations) > 1:
702
+
703
+ random_index = random.randint(0, len(activations) - 1)
704
+
705
+ wc = cp.copy(weight)
706
+ for i in range(weight.shape[0]):
707
+
708
+ wc[i,:] = apply_activation(wc[i,:], activations[random_index])
709
+ weight[i,:] -= wc[i,:]
710
+
711
+ activations.pop(random_index)
712
+ weight = normalization(weight, dtype=dtype)
713
+
714
+
715
+ if potential_activation_change_prob > activation_change_prob:
716
+
717
+ random_index_all_act = int(random.uniform(0, len(all_acts)-1))
718
+ random_index_genom_act = int(random.uniform(0, len(activations)-1))
719
+
720
+ activations[random_index_genom_act] = all_acts[random_index_all_act]
721
+
722
+ wc = cp.copy(weight)
723
+ for i in range(weight.shape[0]):
724
+
725
+ wc[i,:] = apply_activation(wc[i,:], activations[random_index_genom_act])
726
+ weight[i,:] -= wc[i,:]
727
+
728
+ weight = normalization(weight, dtype=dtype)
729
+
730
+ for i in range(weight.shape[0]):
731
+
732
+ weight[i,:] = apply_activation(weight[i,:], activations[random_index_genom_act])
733
+
734
+ weight = normalization(weight, dtype=dtype)
735
+
736
+ return weight, activations