pyerualjetwork 2.6.6__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.
pyerualjetwork/plan.py ADDED
@@ -0,0 +1,645 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+
4
+ MAIN MODULE FOR PLAN
5
+
6
+ PLAN document: https://github.com/HCB06/Anaplan/blob/main/Welcome_to_PLAN/PLAN.pdf
7
+ ANAPLAN document: https://github.com/HCB06/Anaplan/blob/main/Welcome_to_Anaplan/ANAPLAN_USER_MANUEL_AND_LEGAL_INFORMATION(EN).pdf
8
+
9
+ @author: Hasan Can Beydili
10
+ @YouTube: https://www.youtube.com/@HasanCanBeydili
11
+ @Linkedin: https://www.linkedin.com/in/hasan-can-beydili-77a1b9270/
12
+ @Instagram: https://www.instagram.com/canbeydilj/
13
+ @contact: tchasancan@gmail.com
14
+ """
15
+
16
+ import numpy as np
17
+ from colorama import Fore, Style
18
+ import sys
19
+
20
+ ### LIBRARY IMPORTS ###
21
+ from .ui import loading_bars, initialize_loading_bar
22
+ from .data_operations import normalization, decode_one_hot, batcher
23
+ from .loss_functions import binary_crossentropy, categorical_crossentropy
24
+ from .activation_functions import apply_activation, Softmax, all_activations
25
+ from .metrics import metrics
26
+ from.model_operations import get_acc, get_preds, get_preds_softmax
27
+ from .visualizations import (
28
+ draw_neural_web,
29
+ plot_evaluate,
30
+ neuron_history,
31
+ initialize_visualization_for_fit,
32
+ update_weight_visualization_for_fit,
33
+ update_decision_boundary_for_fit,
34
+ update_validation_history_for_fit,
35
+ display_visualization_for_fit,
36
+ display_visualizations_for_learner,
37
+ update_history_plots_for_learner,
38
+ initialize_visualization_for_learner
39
+ )
40
+
41
+ ### GLOBAL VARIABLES ###
42
+ bar_format_normal = loading_bars()[0]
43
+ bar_format_learner = loading_bars()[1]
44
+
45
+ # BUILD -----
46
+
47
+ def fit(
48
+ x_train,
49
+ y_train,
50
+ val=None,
51
+ val_count=None,
52
+ activation_potentiation=['linear'],
53
+ x_val=None,
54
+ y_val=None,
55
+ show_training=None,
56
+ interval=100,
57
+ LTD=0,
58
+ decision_boundary_status=True,
59
+ train_bar=True,
60
+ auto_normalization=True,
61
+ neurons_history=False
62
+ ):
63
+ """
64
+ Creates a model to fitting data.
65
+
66
+ fit Args:
67
+
68
+ x_train (list[num]): List or numarray of input data.
69
+
70
+ y_train (list[num]): List or numarray of target labels. (one hot encoded)
71
+
72
+ val (None or True): validation in training process ? None or True default: None (optional)
73
+
74
+ val_count (None or int): After how many examples learned will an accuracy test be performed? default: 10=(%10) it means every approximately 10 step (optional)
75
+
76
+ activation_potentiation (list): For deeper PLAN networks, activation function parameters. For more information please run this code: plan.activations_list() default: [None] (optional)
77
+
78
+ x_val (list[num]): List of validation data. default: x_train (optional)
79
+
80
+ y_val (list[num]): (list[num]): List of target labels. (one hot encoded) default: y_train (optional)
81
+
82
+ show_training (bool, str): True or None default: None (optional)
83
+
84
+ LTD (int): Long Term Depression Hyperparameter for train PLAN neural network default: 0 (optional)
85
+
86
+ interval (float, int): frame delay (milisecond) parameter for Training Report (show_training=True) This parameter effects to your Training Report performance. Lower value is more diffucult for Low end PC's (33.33 = 30 FPS, 16.67 = 60 FPS) default: 100 (optional)
87
+
88
+ decision_boundary_status (bool): If the visualization of validation and training history is enabled during training, should the decision boundaries also be visualized? True or False. Default is True. (optional)
89
+
90
+ train_bar (bool): Training loading bar? True or False. Default is True. (optional)
91
+
92
+ auto_normalization(bool): Normalization process during training. May effect training time and model quality. True or False. Default is True. (optional)
93
+
94
+ neurons_history (bool, optional): Shows the history of changes that neurons undergo during the CL (Cumulative Learning) stages. True or False. Default is False. (optional)
95
+
96
+ Returns:
97
+ numpyarray([num]): (Weight matrix).
98
+ """
99
+ # Pre-checks
100
+
101
+ if train_bar and val:
102
+ train_progress = initialize_loading_bar(total=len(x_train), ncols=71, desc='Fitting', bar_format=bar_format_normal)
103
+ elif train_bar and val == False:
104
+ train_progress = initialize_loading_bar(total=len(x_train), ncols=44, desc='Fitting', bar_format=bar_format_normal)
105
+
106
+ if len(x_train) != len(y_train):
107
+ raise ValueError("x_train and y_train must have the same length.")
108
+
109
+ if val and (x_val is None or y_val is None):
110
+ x_val, y_val = x_train, y_train
111
+
112
+ val_list = [] if val else None
113
+ val_count = val_count or 10
114
+ # Defining weights
115
+ STPW = np.ones((len(y_train[0]), len(x_train[0].ravel()))) # STPW = SHORT TIME POTENTIATION WEIGHT
116
+ LTPW = np.zeros((len(y_train[0]), len(x_train[0].ravel()))) # LTPW = LONG TIME POTENTIATION WEIGHT
117
+ # Initialize visualization
118
+ vis_objects = initialize_visualization_for_fit(val, show_training, neurons_history, x_train, y_train)
119
+
120
+ # Training process
121
+ for index, inp in enumerate(x_train):
122
+ inp = np.array(inp).ravel()
123
+ y_decoded = decode_one_hot(y_train)
124
+ # Weight updates
125
+ STPW = feed_forward(inp, STPW, is_training=True, Class=y_decoded[index], activation_potentiation=activation_potentiation, LTD=LTD)
126
+ LTPW += normalization(STPW) if auto_normalization else STPW
127
+
128
+ # Visualization updates
129
+ if show_training:
130
+ update_weight_visualization_for_fit(vis_objects['ax'][0, 0], LTPW, vis_objects['artist2'])
131
+ if decision_boundary_status:
132
+ update_decision_boundary_for_fit(vis_objects['ax'][0, 1], x_val, y_val, activation_potentiation, LTPW, vis_objects['artist1'])
133
+ update_validation_history_for_fit(vis_objects['ax'][1, 1], val_list, vis_objects['artist3'])
134
+ if train_bar:
135
+ train_progress.update(1)
136
+
137
+ STPW = np.ones((len(y_train[0]), len(x_train[0].ravel())))
138
+
139
+ # Finalize visualization
140
+ if show_training:
141
+ display_visualization_for_fit(vis_objects['fig'], vis_objects['artist1'], interval)
142
+
143
+ return normalization(LTPW)
144
+
145
+
146
+ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', batch_size=1,
147
+ neural_web_history=False, show_current_activations=False, auto_normalization=True,
148
+ neurons_history=False, patience=None, depth=None, early_shifting=False,
149
+ early_stop=False, loss='categorical_crossentropy', show_history=False,
150
+ interval=33.33, target_acc=None, target_loss=None, except_this=None,
151
+ only_this=None, start_this=None):
152
+ """
153
+ Optimizes the activation functions for a neural network by leveraging train data to find
154
+ the most accurate combination of activation potentiation for the given dataset.
155
+
156
+ Args:
157
+
158
+ x_train (array-like): Training input data.
159
+
160
+ y_train (array-like): Labels for training data.
161
+
162
+ x_test (array-like, optional): Test input data (for improve next gen generilization). If test data is not given then train feedback learning active
163
+
164
+ y_test (array-like, optional): Test Labels (for improve next gen generilization). If test data is not given then train feedback learning active
165
+
166
+ strategy (str, optional): Learning strategy. (options: 'accuracy', 'loss', 'f1', 'precision', 'recall', 'adaptive_accuracy', 'adaptive_loss', 'all'): 'accuracy', Maximizes test accuracy during learning. 'f1', Maximizes test f1 score during learning. 'precision', Maximizes test preciison score during learning. 'recall', Maximizes test recall during learning. loss', Minimizes test loss during learning. 'adaptive_accuracy', The model compares the current accuracy with the accuracy from the past based on the number specified by the patience value. If no improvement is observed it adapts to the condition by switching to the 'loss' strategy quickly starts minimizing loss and continues learning. 'adaptive_loss',The model adopts the 'loss' strategy until the loss reaches or falls below the value specified by the patience parameter. However, when the patience threshold is reached, it automatically switches to the 'accuracy' strategy and begins to maximize accuracy. 'all', Maximizes all test scores and minimizes test loss, 'all' strategy most strong and most robust strategy. Default is 'accuracy'.
167
+
168
+ patience ((int, float), optional): patience value for adaptive strategies. For 'adaptive_accuracy' Default value: 5. For 'adaptive_loss' Default value: 0.150.
169
+
170
+ depth (int, optional): The depth of the PLAN neural networks Aggreagation layers.
171
+
172
+ batch_size (float, optional): Batch size is used in the prediction process to receive test feedback by dividing the test data into chunks and selecting activations based on randomly chosen partitions. This process reduces computational cost and time while still covering the entire test set due to random selection, so it doesn't significantly impact accuracy. For example, a batch size of 0.08 means each test batch represents 8% of the test set. Default is 1. (%100 of test)
173
+
174
+ auto_normalization (bool, optional): If auto normalization=False this makes more faster training times and much better accuracy performance for some datasets. Default is True.
175
+
176
+ early_shifting (int, optional): Early shifting checks if the test accuracy improves after a given number of activation attempts while inside a depth. If there's no improvement, it automatically shifts to the next depth. Basically, if no progress, it’s like, “Alright, let’s move on!” Default is False
177
+
178
+ early_stop (bool, optional): If True, implements early stopping during training.(If test accuracy not improves in two depth stops learning.) Default is False.
179
+
180
+ show_current_activations (bool, optional): Should it display the activations selected according to the current strategies during learning, or not? (True or False) This can be very useful if you want to cancel the learning process and resume from where you left off later. After canceling, you will need to view the live training activations in order to choose the activations to be given to the 'start_this' parameter. Default is False
181
+
182
+ show_history (bool, optional): If True, displays the training history after optimization. Default is False.
183
+
184
+ loss (str, optional): For visualizing and monitoring. PLAN neural networks doesn't need any loss function in training(if strategy not 'loss'). options: ('categorical_crossentropy' or 'binary_crossentropy') Default is 'categorical_crossentropy'.
185
+
186
+ interval (int, optional): The interval at which evaluations are conducted during training. (33.33 = 30 FPS, 16.67 = 60 FPS) Default is 100.
187
+
188
+ target_acc (int, optional): The target accuracy to stop training early when achieved. Default is None.
189
+
190
+ target_loss (float, optional): The target loss to stop training early when achieved. Default is None.
191
+
192
+ except_this (list, optional): A list of activations to exclude from optimization. Default is None. (For avaliable activation functions, run this code: plan.activations_list())
193
+
194
+ only_this (list, optional): A list of activations to focus on during optimization. Default is None. (For avaliable activation functions, run this code: plan.activations_list())
195
+
196
+ start_this (list, optional): To resume a previously canceled or interrupted training from where it left off, or to continue from that point with a different strategy, provide the list of activation functions selected up to the learned portion to this parameter. Default is None
197
+
198
+ neurons_history (bool, optional): Shows the history of changes that neurons undergo during the TFL (Test or Train Feedback Learning) stages. True or False. Default is False.
199
+
200
+ neural_web_history (bool, optional): Draws history of neural web. Default is False.
201
+
202
+ Returns:
203
+ tuple: A list for model parameters: [Weight matrix, Test loss, Test Accuracy, [Activations functions]].
204
+
205
+ """
206
+ print(Fore.WHITE + "\nRemember, optimization on large datasets can be very time-consuming and computationally expensive. Therefore, if you are working with such a dataset, our recommendation is to include activation function: ['circular'] in the 'except_this' parameter unless absolutely necessary, as they can significantly prolong the process. from: learner\n" + Fore.RESET)
207
+
208
+ activation_potentiation = all_activations()
209
+
210
+ if x_test is None and y_test is None:
211
+ x_test = x_train
212
+ y_test = y_train
213
+ data = 'Train'
214
+ else:
215
+ data = 'Test'
216
+
217
+ if early_shifting != False:
218
+ shift_patience = early_shifting
219
+
220
+ # Strategy initialization
221
+ if strategy == 'adaptive_accuracy':
222
+ strategy = 'accuracy'
223
+ adaptive = True
224
+ if patience == None:
225
+ patience = 5
226
+ elif strategy == 'adaptive_loss':
227
+ strategy = 'loss'
228
+ adaptive = True
229
+ if patience == None:
230
+ patience = 0.150
231
+ else:
232
+ adaptive = False
233
+
234
+ # Filter activation functions
235
+ if only_this != None:
236
+ activation_potentiation = only_this
237
+ if except_this != None:
238
+ activation_potentiation = [item for item in activation_potentiation if item not in except_this]
239
+ if depth is None:
240
+ depth = len(activation_potentiation)
241
+
242
+ # Initialize visualization components
243
+ viz_objects = initialize_visualization_for_learner(show_history, neurons_history, neural_web_history, x_train, y_train)
244
+
245
+ # Initialize progress bar
246
+ if batch_size == 1:
247
+ ncols = 76
248
+ else:
249
+ ncols = 89
250
+ progress = initialize_loading_bar(total=len(activation_potentiation), desc="", ncols=ncols, bar_format=bar_format_learner)
251
+
252
+ # Initialize variables
253
+ activations = []
254
+ if start_this is None:
255
+ best_activations = []
256
+ best_acc = 0
257
+ else:
258
+ best_activations = start_this
259
+ x_test_batch, y_test_batch = batcher(x_test, y_test, batch_size=batch_size)
260
+ W = fit(x_train, y_train, activation_potentiation=best_activations, train_bar=False, auto_normalization=auto_normalization)
261
+ model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations)
262
+
263
+ if loss == 'categorical_crossentropy':
264
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
265
+ else:
266
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
267
+
268
+ best_acc = model[get_acc()]
269
+ best_loss = test_loss
270
+
271
+ best_acc_per_depth_list = []
272
+ postfix_dict = {}
273
+ loss_list = []
274
+
275
+ for i in range(depth):
276
+ postfix_dict["Depth"] = str(i+1) + '/' + str(depth)
277
+ progress.set_postfix(postfix_dict)
278
+
279
+ progress.n = 0
280
+ progress.last_print_n = 0
281
+ progress.update(0)
282
+
283
+ for j in range(len(activation_potentiation)):
284
+ for k in range(len(best_activations)):
285
+ activations.append(best_activations[k])
286
+
287
+ activations.append(activation_potentiation[j])
288
+
289
+ x_test_batch, y_test_batch = batcher(x_test, y_test, batch_size=batch_size)
290
+ W = fit(x_train, y_train, activation_potentiation=activations, train_bar=False, auto_normalization=auto_normalization)
291
+ model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations)
292
+
293
+ acc = model[get_acc()]
294
+
295
+ if strategy == 'loss' or strategy == 'all':
296
+ if loss == 'categorical_crossentropy':
297
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
298
+ else:
299
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
300
+
301
+ if i == 0 and j == 0 and start_this is None:
302
+ best_loss = test_loss
303
+
304
+ if strategy == 'f1' or strategy == 'precision' or strategy == 'recall' or strategy == 'all':
305
+ precision_score, recall_score, f1_score = metrics(y_test_batch, model[get_preds()])
306
+
307
+ if strategy == 'precision' or strategy == 'all':
308
+ if i == 0 and j == 0:
309
+ best_precision = precision_score
310
+
311
+ if strategy == 'recall' or strategy == 'all':
312
+ if i == 0 and j == 0:
313
+ best_recall = recall_score
314
+
315
+ if strategy == 'f1' or strategy == 'all':
316
+ if i == 0 and j == 0:
317
+ best_f1 = f1_score
318
+
319
+ if early_shifting != False:
320
+ if acc <= best_acc:
321
+ early_shifting -= 1
322
+ if early_shifting == 0:
323
+ early_shifting = shift_patience
324
+ break
325
+
326
+ if ((strategy == 'accuracy' and acc >= best_acc) or
327
+ (strategy == 'loss' and test_loss <= best_loss) or
328
+ (strategy == 'f1' and f1_score >= best_f1) or
329
+ (strategy == 'precision' and precision_score >= best_precision) or
330
+ (strategy == 'recall' and recall_score >= best_recall) or
331
+ (strategy == 'all' and f1_score >= best_f1 and acc >= best_acc and
332
+ test_loss <= best_loss and precision_score >= best_precision and
333
+ recall_score >= best_recall)):
334
+
335
+ current_best_activation = activation_potentiation[j]
336
+ best_acc = acc
337
+
338
+ if batch_size == 1:
339
+ postfix_dict[f"{data} Accuracy"] = best_acc
340
+ else:
341
+ postfix_dict[f"{data} Batch Accuracy"] = acc
342
+ progress.set_postfix(postfix_dict)
343
+
344
+ final_activations = activations
345
+
346
+ if show_current_activations:
347
+ print(f", Current Activations={final_activations}", end='')
348
+
349
+ best_weights = W
350
+ best_model = model
351
+
352
+ if strategy != 'loss':
353
+ if loss == 'categorical_crossentropy':
354
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
355
+ else:
356
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
357
+
358
+ if batch_size == 1:
359
+ postfix_dict[f"{data} Loss"] = test_loss
360
+ best_loss = test_loss
361
+ else:
362
+ postfix_dict[f"{data} Batch Loss"] = test_loss
363
+ progress.set_postfix(postfix_dict)
364
+ best_loss = test_loss
365
+
366
+ # Update visualizations during training
367
+ if show_history:
368
+ depth_list = range(1, len(best_acc_per_depth_list) + 2)
369
+ update_history_plots_for_learner(viz_objects, depth_list, loss_list + [test_loss],
370
+ best_acc_per_depth_list + [best_acc], x_train, final_activations)
371
+
372
+ if neurons_history:
373
+ viz_objects['neurons']['artists'] = (
374
+ neuron_history(np.copy(best_weights), viz_objects['neurons']['ax'],
375
+ viz_objects['neurons']['row'], viz_objects['neurons']['col'],
376
+ y_train[0], viz_objects['neurons']['artists'],
377
+ data=data, fig1=viz_objects['neurons']['fig'],
378
+ acc=best_acc, loss=test_loss)
379
+ )
380
+
381
+ if neural_web_history:
382
+ art5_1, art5_2, art5_3 = draw_neural_web(W=best_weights, ax=viz_objects['web']['ax'],
383
+ G=viz_objects['web']['G'], return_objs=True)
384
+ art5_list = [art5_1] + [art5_2] + list(art5_3.values())
385
+ viz_objects['web']['artists'].append(art5_list)
386
+
387
+ # Check target accuracy
388
+ if target_acc is not None and best_acc >= target_acc:
389
+ progress.close()
390
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
391
+ activation_potentiation=final_activations)
392
+
393
+ if loss == 'categorical_crossentropy':
394
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
395
+ y_pred_batch=train_model[get_preds_softmax()])
396
+ else:
397
+ train_loss = binary_crossentropy(y_true_batch=y_train,
398
+ y_pred_batch=train_model[get_preds_softmax()])
399
+
400
+ print('\nActivations: ', final_activations)
401
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
402
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
403
+ if data == 'Test':
404
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
405
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
406
+
407
+ # Display final visualizations
408
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
409
+ test_loss, y_train, interval)
410
+ return best_weights, best_model[get_preds()], best_acc, final_activations
411
+
412
+ # Check target loss
413
+ if target_loss is not None and best_loss <= target_loss:
414
+ progress.close()
415
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
416
+ activation_potentiation=final_activations)
417
+
418
+ if loss == 'categorical_crossentropy':
419
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
420
+ y_pred_batch=train_model[get_preds_softmax()])
421
+ else:
422
+ train_loss = binary_crossentropy(y_true_batch=y_train,
423
+ y_pred_batch=train_model[get_preds_softmax()])
424
+
425
+ print('\nActivations: ', final_activations)
426
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
427
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
428
+ if data == 'Test':
429
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
430
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
431
+
432
+ # Display final visualizations
433
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
434
+ test_loss, y_train, interval)
435
+ return best_weights, best_model[get_preds()], best_acc, final_activations
436
+
437
+ progress.update(1)
438
+ activations = []
439
+
440
+ best_activations.append(current_best_activation)
441
+ best_acc_per_depth_list.append(best_acc)
442
+ loss_list.append(best_loss)
443
+
444
+ # Check adaptive strategy conditions
445
+ if adaptive == True and strategy == 'accuracy' and i + 1 >= patience:
446
+ check = best_acc_per_depth_list[-patience:]
447
+ if all(x == check[0] for x in check):
448
+ strategy = 'loss'
449
+ adaptive = False
450
+ elif adaptive == True and strategy == 'loss' and best_loss <= patience:
451
+ strategy = 'accuracy'
452
+ adaptive = False
453
+
454
+ # Early stopping check
455
+ if early_stop == True and i > 0:
456
+ if best_acc_per_depth_list[i] == best_acc_per_depth_list[i-1]:
457
+ progress.close()
458
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
459
+ activation_potentiation=final_activations)
460
+
461
+ if loss == 'categorical_crossentropy':
462
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
463
+ y_pred_batch=train_model[get_preds_softmax()])
464
+ else:
465
+ train_loss = binary_crossentropy(y_true_batch=y_train,
466
+ y_pred_batch=train_model[get_preds_softmax()])
467
+
468
+ print('\nActivations: ', final_activations)
469
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
470
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
471
+ if data == 'Test':
472
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
473
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
474
+
475
+ # Display final visualizations
476
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
477
+ test_loss, y_train, interval)
478
+ return best_weights, best_model[get_preds()], best_acc, final_activations
479
+
480
+ # Final evaluation
481
+ progress.close()
482
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
483
+ activation_potentiation=final_activations)
484
+
485
+ if loss == 'categorical_crossentropy':
486
+ train_loss = categorical_crossentropy(y_true_batch=y_train, y_pred_batch=train_model[get_preds_softmax()])
487
+ else:
488
+ train_loss = binary_crossentropy(y_true_batch=y_train, y_pred_batch=train_model[get_preds_softmax()])
489
+
490
+ print('\nActivations: ', final_activations)
491
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
492
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
493
+ if data == 'Test':
494
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
495
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
496
+
497
+ # Display final visualizations
498
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc, test_loss, y_train, interval)
499
+ return best_weights, best_model[get_preds()], best_acc, final_activations
500
+
501
+
502
+
503
+ def feed_forward(
504
+ Input, # list[num]: Input data.
505
+ w, # num: Weight matrix of the neural network.
506
+ is_training, # bool: Flag indicating if the function is called during training (True or False).
507
+ activation_potentiation,
508
+ Class='?', # int: Which class is, if training. # (list): Activation potentiation list for deep PLAN. (optional)
509
+ LTD=0
510
+ ) -> tuple:
511
+ """
512
+ Applies feature extraction process to the input data using synaptic potentiation.
513
+
514
+ Args:
515
+ Input (num): Input data.
516
+ w (num): Weight matrix of the neural network.
517
+ is_training (bool): Flag indicating if the function is called during training (True or False).
518
+ Class (int): if is during training then which class(label) ? is isnt then put None.
519
+ # activation_potentiation (list): ac list for deep PLAN. default: [None] ('linear') (optional)
520
+
521
+ Returns:
522
+ tuple: A tuple (vector) containing the neural layer result and the updated weight matrix.
523
+ or
524
+ num: neural network output
525
+ """
526
+
527
+ Output = apply_activation(Input, activation_potentiation)
528
+
529
+ Input = Output
530
+
531
+ if is_training == True:
532
+
533
+ for _ in range(LTD):
534
+
535
+ depression_vector = np.random.rand(*Input.shape)
536
+
537
+ Input -= depression_vector
538
+
539
+ w[Class, :] = Input
540
+ return w
541
+
542
+ else:
543
+
544
+ neural_layer = np.dot(w, Input)
545
+
546
+ return neural_layer
547
+
548
+
549
+ def evaluate(
550
+ x_test, # list[num]: Test input data.
551
+ y_test, # list[num]: Test labels.
552
+ W, # list[num]: Weight matrix list of the neural network.
553
+ activation_potentiation=['linear'], # (list): Activation potentiation list for deep PLAN. (optional)
554
+ loading_bar_status=True, # bar_status (bool): Loading bar for accuracy (True or None) (optional) Default: True
555
+ show_metrics=None, # show_metrices (bool): (True or None) (optional) Default: None
556
+ ) -> tuple:
557
+ """
558
+ Tests the neural network model with the given test data.
559
+
560
+ Args:
561
+
562
+ x_test (list[num]): Test input data.
563
+
564
+ y_test (list[num]): Test labels.
565
+
566
+ W (list[num]): Weight matrix list of the neural network.
567
+
568
+ activation_potentiation (list): For deeper PLAN networks, activation function parameters. For more information please run this code: plan.activations_list() default: [None]
569
+
570
+ loading_bar_status: Evaluate progress have a loading bar ? (True or False) Default: True.
571
+
572
+ show_metrics (bool): (True or None) (optional) Default: None
573
+
574
+ Returns:
575
+ tuple: A tuple containing the predicted labels and the accuracy of the model.
576
+ """
577
+ predict_probabilitys = []
578
+ real_classes = []
579
+ predict_classes = []
580
+
581
+ try:
582
+
583
+ Wc = [0] * len(W) # Wc = Weight copy
584
+ true_predict = 0
585
+ y_preds = []
586
+ y_preds_raw = []
587
+ acc_list = []
588
+
589
+ Wc = np.copy(W)
590
+
591
+
592
+ if loading_bar_status == True:
593
+
594
+ loading_bar = initialize_loading_bar(total=len(x_test), ncols=64, desc='Testing', bar_format=bar_format_normal)
595
+
596
+ for inpIndex, Input in enumerate(x_test):
597
+ Input = np.array(Input)
598
+ Input = Input.ravel()
599
+ neural_layer = Input
600
+
601
+
602
+ neural_layer = feed_forward(neural_layer, W, is_training=False, Class='?', activation_potentiation=activation_potentiation)
603
+
604
+
605
+ W = np.copy(Wc)
606
+
607
+ neural_layer = Softmax(neural_layer)
608
+
609
+ max_value = max(neural_layer)
610
+
611
+ predict_probabilitys.append(max_value)
612
+
613
+ RealOutput = np.argmax(y_test[inpIndex])
614
+ real_classes.append(RealOutput)
615
+ PredictedOutput = np.argmax(neural_layer)
616
+ predict_classes.append(PredictedOutput)
617
+
618
+ if RealOutput == PredictedOutput:
619
+ true_predict += 1
620
+ acc = true_predict / len(y_test)
621
+
622
+
623
+ acc_list.append(acc)
624
+ y_preds.append(PredictedOutput)
625
+ y_preds_raw.append(Softmax(neural_layer))
626
+
627
+ if loading_bar_status == True:
628
+ loading_bar.update(1)
629
+
630
+ if inpIndex > 0 and loading_bar_status == True:
631
+ loading_bar.set_postfix({"Test Accuracy": acc})
632
+
633
+ if show_metrics == True:
634
+
635
+ loading_bar.close()
636
+ plot_evaluate(x_test, y_test, y_preds, acc_list, W=W, activation_potentiation=activation_potentiation)
637
+
638
+ W = np.copy(Wc)
639
+
640
+ except Exception as e:
641
+
642
+ print(Fore.RED + 'ERROR:' + str(e) + Style.RESET_ALL)
643
+ sys.exit()
644
+
645
+ return W, y_preds, acc, None, None, y_preds_raw