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