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