pyerualjetwork 4.5.2b0__py3-none-any.whl → 4.6__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.
pyerualjetwork/planeat.py CHANGED
@@ -17,11 +17,11 @@ import random
17
17
  import math
18
18
 
19
19
  ### LIBRARY IMPORTS ###
20
- from .data_operations import normalization, non_neg_normalization
20
+ from .data_operations import normalization, non_neg_normalization, split_nested_arrays, reconstruct_nested_arrays
21
21
  from .ui import loading_bars, initialize_loading_bar
22
22
  from .activation_functions import apply_activation, all_activations
23
23
 
24
- def define_genomes(input_shape, output_shape, population_size, dtype=np.float32):
24
+ def define_genomes(input_shape, output_shape, population_size, hidden=0, neurons=None, activation_functions=None, dtype=np.float32):
25
25
  """
26
26
  Initializes a population of genomes, where each genome is represented by a set of weights
27
27
  and an associated activation function. Each genome is created with random weights and activation
@@ -35,6 +35,12 @@ def define_genomes(input_shape, output_shape, population_size, dtype=np.float32)
35
35
 
36
36
  population_size (int): The number of genomes (individuals) in the population.
37
37
 
38
+ hidden (int, optional): If you dont want train PLAN model this parameter represents a hidden layer count for MLP model. Default: 0 (PLAN)
39
+
40
+ neurons (list[int], optional): If you dont want train PLAN model this parameter represents neuron count of each hidden layer for MLP. Default: None (PLAN)
41
+
42
+ activation_functions (list[str], optional): If you dont want train PLAN model this parameter represents activation function of each hidden layer for MLP. Default: None (PLAN) NOTE: THIS EFFECTS HIDDEN LAYERS OUTPUT. NOT OUTPUT LAYER!
43
+
38
44
  dtype (numpy.dtype): Data type for the arrays. np.float32 by default. Example: np.float64 or np.float16.
39
45
 
40
46
  Returns:
@@ -42,36 +48,70 @@ def define_genomes(input_shape, output_shape, population_size, dtype=np.float32)
42
48
  - population_weights (numpy.ndarray): A 2D numpy array of shape (population_size, output_shape, input_shape) representing the
43
49
  weight matrices for each genome.
44
50
  - population_activations (list): A list of activation functions applied to each genome.
45
-
51
+
46
52
  Notes:
47
53
  The weights are initialized randomly within the range [-1, 1].
48
54
  Activation functions are selected randomly from a predefined list `all_activations()`.
49
55
  The weights for each genome are then modified by applying the corresponding activation function
50
56
  and normalized using the `normalization()` function. (Max abs normalization.)
51
57
  """
52
- population_weights = [0] * population_size
53
- population_activations = [0] * population_size
58
+ if hidden > 0:
59
+ population_weights = [[0] * (hidden + 1) for _ in range(population_size)]
60
+ population_activations = [[0] * (hidden) for _ in range(population_size)]
61
+
62
+ if len(neurons) != hidden:
63
+ raise ValueError('hidden parameter and neurons list length must be equal.')
64
+
65
+
66
+ for i in range(len(population_weights)):
67
+
68
+ for l in range(hidden + 1):
69
+
70
+ if l == 0:
71
+ population_weights[i][l] = np.random.uniform(-1, 1, (neurons[l], input_shape)).astype(dtype)
72
+
73
+ elif l == hidden:
74
+ population_weights[i][l] = np.random.uniform(-1, 1, (output_shape, neurons[l-1])).astype(dtype)
75
+
76
+ else:
77
+ population_weights[i][l] = np.random.uniform(-1, 1, (neurons[l], neurons[l-1])).astype(dtype)
78
+
79
+ if l != hidden:
80
+ population_activations[i][l] = activation_functions[l]
81
+
82
+ # ACTIVATIONS APPLYING IN WEIGHTS SPECIFIC OUTPUT CONNECTIONS (MORE PLAN LIKE FEATURES(FOR NON-LINEARITY)):
83
+
84
+ for j in range(population_weights[i][l].shape[0]):
85
+
86
+ population_weights[i][l][j,:] = apply_activation(population_weights[i][l][j,:], population_activations[i])
87
+ population_weights[i][l][j,:] = normalization(population_weights[i][l][j,:], dtype=dtype)
88
+
89
+ return population_weights, population_activations
90
+
91
+ else:
92
+ population_weights = [0] * population_size
93
+ population_activations = [0] * population_size
54
94
 
55
- except_this = ['spiral', 'circular']
56
- activations = [item for item in all_activations() if item not in except_this] # SPIRAL AND CIRCULAR ACTIVATION DISCARDED
95
+ except_this = ['spiral', 'circular']
96
+ activations = [item for item in all_activations() if item not in except_this] # SPIRAL AND CIRCULAR ACTIVATION DISCARDED
57
97
 
58
- for i in range(len(population_weights)):
98
+ for i in range(len(population_weights)):
59
99
 
60
- population_weights[i] = np.random.uniform(-1, 1, (output_shape, input_shape)).astype(dtype)
61
- population_activations[i] = activations[int(random.uniform(0, len(activations)-1))]
100
+ population_weights[i] = np.random.uniform(-1, 1, (output_shape, input_shape)).astype(dtype)
101
+ population_activations[i] = activations[int(random.uniform(0, len(activations)-1))]
62
102
 
63
- # ACTIVATIONS APPLYING IN WEIGHTS SPECIFIC OUTPUT CONNECTIONS (MORE PLAN LIKE FEATURES(FOR NON-LINEARITY)):
103
+ # ACTIVATIONS APPLYING IN WEIGHTS SPECIFIC OUTPUT CONNECTIONS (MORE PLAN LIKE FEATURES(FOR NON-LINEARITY)):
64
104
 
65
- for j in range(population_weights[i].shape[0]):
105
+ for j in range(population_weights[i].shape[0]):
66
106
 
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)
107
+ population_weights[i][j,:] = apply_activation(population_weights[i][j,:], population_activations[i])
108
+ population_weights[i][j,:] = normalization(population_weights[i][j,:], dtype=dtype)
69
109
 
70
- return np.array(population_weights, dtype=dtype), population_activations
110
+ return np.array(population_weights, dtype=dtype), population_activations
71
111
 
72
112
 
73
113
  def evolver(weights,
74
- activation_potentiations,
114
+ activation_potentiations,
75
115
  what_gen,
76
116
  fitness,
77
117
  weight_evolve=True,
@@ -88,11 +128,12 @@ def evolver(weights,
88
128
  activation_mutate_change_prob=0.5,
89
129
  activation_selection_add_prob=0.5,
90
130
  activation_selection_change_prob=0.5,
91
- activation_selection_threshold=2,
131
+ activation_selection_threshold=20,
92
132
  activation_mutate_prob=1,
93
- activation_mutate_threshold=2,
133
+ activation_mutate_threshold=20,
94
134
  weight_mutate_threshold=16,
95
135
  weight_mutate_prob=1,
136
+ is_mlp=False,
96
137
  dtype=np.float32):
97
138
  """
98
139
  Applies the evolving process of a population of genomes using selection, crossover, mutation, and activation function potentiation.
@@ -105,8 +146,8 @@ def evolver(weights,
105
146
  weights (numpy.ndarray): Array of weights for each genome.
106
147
  (first returned value of define_genomes function)
107
148
 
108
- activation_potentiations (list): A list of activation functions for each genome.
109
- (second returned value of define_genomes function)
149
+ activation_potentiations (list[str]): A list of activation functions for each genome.
150
+ (second returned value of define_genomes function) NOTE!: 'activation potentiations' for PLAN 'activation functions' for MLP.
110
151
 
111
152
  what_gen (int): The current generation number, used for informational purposes or logging.
112
153
 
@@ -175,10 +216,12 @@ def evolver(weights,
175
216
  activation_selection_change_prob (float, optional): The probability of changing an activation function in the genome for crossover.
176
217
  Must be in the range [0, 1]. Default is 0.5.
177
218
 
178
- activation_mutate_threshold (int, optional): Determines max how much activation mutaiton operation applying. (Function automaticly determines to min) Default: 2
219
+ activation_mutate_threshold (int, optional): Determines max how much activation mutaiton operation applying. (Function automaticly determines to min) Default: 20
179
220
 
180
- activation_selection_threshold (int, optional): Determines max how much activaton transferable to child from undominant parent. (Function automaticly determines to min) Default: 2
221
+ activation_selection_threshold (int, optional): Determines max how much activaton transferable to child from undominant parent. (Function automaticly determines to min) Default: 20
181
222
 
223
+ is_mlp (bool, optional): Evolve PLAN model or MLP model ? Default: False (PLAN)
224
+
182
225
  dtype (numpy.dtype, optional): Data type for the arrays. Default: np.float32.
183
226
  Example: np.float64 or np.float16 [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not recommended!].
184
227
 
@@ -266,6 +309,34 @@ def evolver(weights,
266
309
 
267
310
  if weight_evolve is False: origin_weights = np.copy(weights)
268
311
 
312
+ if is_mlp: ### IF EACH GENOME HAVE MORE THEN 1 WEIGHT MATRIX IT IS NOT PLAN MODEL. IT IS MLP MODEL.
313
+
314
+ activations = activation_potentiations.copy()
315
+
316
+ return mlp_evolver(weights,
317
+ activations,
318
+ what_gen,
319
+ dtype,
320
+ fitness,
321
+ policy,
322
+ bad_genomes_selection_prob,
323
+ bar_status,
324
+ strategy,
325
+ bad_genomes_mutation_prob,
326
+ fitness_bias,
327
+ cross_over_mode,
328
+ activation_mutate_change_prob,
329
+ activation_selection_change_prob,
330
+ activation_selection_threshold,
331
+ activation_mutate_prob,
332
+ activation_mutate_threshold,
333
+ weight_mutate_threshold,
334
+ show_info,
335
+ weight_mutate_prob,
336
+ )
337
+
338
+ if isinstance(weights, list): weights = np.array(weights, dtype=dtype)
339
+
269
340
  ### FITNESS IS SORTED IN ASCENDING ORDER, AND THE WEIGHT AND ACTIVATIONS OF EACH GENOME ARE SORTED ACCORDING TO THIS ORDER:
270
341
 
271
342
  sort_indices = np.argsort(fitness)
@@ -408,44 +479,114 @@ def evolver(weights,
408
479
  return weights, activation_potentiations
409
480
 
410
481
 
411
- def evaluate(x_population, weights, activation_potentiations):
482
+ def evaluate(Input, weights, activation_potentiations, is_mlp=False):
412
483
  """
413
484
  Evaluates the performance of a population of genomes, applying different activation functions
414
485
  and weights depending on whether reinforcement learning mode is enabled or not.
415
486
 
416
487
  Args:
417
- x_population (list or numpy.ndarray): A list or 2D numpy array where each element represents
418
- a genome (A list of input features for each genome, or a single set of input features for one genome (only in rl_mode)).
488
+ Input (list or numpy.ndarray): A list or 2D numpy array where each element represents
489
+ a genome (A list of input features for each genome, or a single set of input features for one genome).
419
490
  weights (list or numpy.ndarray): A list or 2D numpy array of weights corresponding to each genome
420
491
  in `x_population`. This determines the strength of connections.
421
492
  activation_potentiations (list or str): A list where each entry represents an activation function
422
493
  or a potentiation strategy applied to each genome. If only one
423
494
  activation function is used, this can be a single string.
495
+ is_mlp (bool, optional): Evaluate PLAN model or MLP model ? Default: False (PLAN)
496
+
424
497
  Returns:
425
498
  list: A list of outputs corresponding to each genome in the population after applying the respective
426
499
  activation function and weights.
427
500
 
428
501
  Example:
429
502
  ```python
430
- outputs = evaluate(x_population, weights, activation_potentiations)
503
+ outputs = evaluate(Input, weights, activation_potentiations)
431
504
  ```
432
505
 
433
506
  - The function returns a list of outputs after processing the population, where each element corresponds to
434
- the output for each genome in `x_population`.
435
- """
507
+ the output for each genome in population.
508
+ """
436
509
  ### THE OUTPUTS ARE RETURNED, WHERE EACH GENOME'S OUTPUT MATCHES ITS INDEX:
437
-
510
+
438
511
 
439
512
  if isinstance(activation_potentiations, str):
440
513
  activation_potentiations = [activation_potentiations]
441
514
  else:
442
515
  activation_potentiations = [item if isinstance(item, list) else [item] for item in activation_potentiations]
443
516
 
444
- x_population = apply_activation(x_population, activation_potentiations)
445
- result = x_population @ weights.T
517
+ if is_mlp:
518
+ layer = Input
519
+ for i in range(len(weights)):
520
+ if i != len(weights) - 1: layer = apply_activation(layer, activation_potentiations[i])
521
+ layer = layer @ weights[i].T
522
+
523
+ return layer
446
524
 
447
- return result
525
+ else:
448
526
 
527
+ Input = apply_activation(Input, activation_potentiations)
528
+ result = Input @ weights.T
529
+
530
+ return result
531
+
532
+ def mlp_evolver(weights,
533
+ activations,
534
+ generation,
535
+ dtype,
536
+ fitness,
537
+ policy,
538
+ bad_genomes_selection_prob,
539
+ bar_status,
540
+ strategy,
541
+ bad_genomes_mutation_prob,
542
+ fitness_bias,
543
+ cross_over_mode,
544
+ activation_mutate_change_prob,
545
+ activation_selection_change_prob,
546
+ activation_selection_threshold,
547
+ activation_mutate_prob,
548
+ activation_mutate_threshold,
549
+ weight_mutate_threshold,
550
+ show_info,
551
+ weight_mutate_prob,
552
+ ):
553
+
554
+ weights = split_nested_arrays(weights)
555
+
556
+ for layer in range(len(weights)):
557
+ if show_info == True:
558
+ if layer == len(weights) - 1:
559
+ show = True
560
+ else:
561
+ show = False
562
+ else:
563
+ show = False
564
+
565
+ weights[layer], activations = evolver(weights[layer], activations,
566
+ fitness=fitness,
567
+ what_gen=generation,
568
+ show_info=show,
569
+ policy=policy,
570
+ bad_genomes_selection_prob=bad_genomes_selection_prob,
571
+ bar_status=bar_status,
572
+ strategy=strategy,
573
+ bad_genomes_mutation_prob=bad_genomes_mutation_prob,
574
+ fitness_bias=fitness_bias,
575
+ cross_over_mode=cross_over_mode,
576
+ activation_mutate_add_prob=0,
577
+ activation_mutate_delete_prob=0,
578
+ activation_mutate_change_prob=activation_mutate_change_prob,
579
+ activation_selection_add_prob=0,
580
+ activation_selection_change_prob=activation_selection_change_prob,
581
+ activation_selection_threshold=activation_selection_threshold,
582
+ activation_mutate_prob=activation_mutate_prob,
583
+ activation_mutate_threshold=activation_mutate_threshold,
584
+ weight_mutate_threshold=weight_mutate_threshold,
585
+ weight_mutate_prob=weight_mutate_prob,
586
+ dtype=dtype
587
+ )
588
+
589
+ return reconstruct_nested_arrays(weights), activations
449
590
 
450
591
  def cross_over(first_parent_W,
451
592
  second_parent_W,
@@ -748,7 +889,7 @@ def mutation(weight,
748
889
 
749
890
  if potential_activation_delete_prob > activation_delete_prob and len(activations) > 1:
750
891
 
751
- random_index = random.randint(0, len(activations) - 1)
892
+ random_index = random.randint(0, len(activations)-1)
752
893
  activations.pop(random_index)
753
894
 
754
895
 
@@ -785,7 +926,7 @@ def mutation(weight,
785
926
  def second_parent_selection(good_weights, bad_weights, good_activations, bad_activations, bad_genomes_selection_prob):
786
927
 
787
928
  selection_prob = random.uniform(0, 1)
788
- random_index = int(random.uniform(0, len(good_weights) - 1))
929
+ random_index = int(random.uniform(0, len(good_weights)-1))
789
930
 
790
931
  if selection_prob > bad_genomes_selection_prob:
791
932
  second_selected_W = good_weights[random_index]