pyerualjetwork 4.0.2__py3-none-any.whl → 4.0.3__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,615 @@
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 cupy as cp
17
+ from colorama import Fore
18
+
19
+ ### LIBRARY IMPORTS ###
20
+ from .ui import loading_bars, initialize_loading_bar
21
+ from .data_operations_cuda import normalization, decode_one_hot, batcher
22
+ from .loss_functions_cuda import binary_crossentropy, categorical_crossentropy
23
+ from .activation_functions_cuda import apply_activation, Softmax, all_activations
24
+ from .metrics_cuda import metrics
25
+ from .model_operations_cuda import get_acc, get_preds, get_preds_softmax
26
+ from .visualizations_cuda import (
27
+ draw_neural_web,
28
+ plot_evaluate,
29
+ neuron_history,
30
+ initialize_visualization_for_fit,
31
+ update_weight_visualization_for_fit,
32
+ update_decision_boundary_for_fit,
33
+ update_validation_history_for_fit,
34
+ display_visualization_for_fit,
35
+ display_visualizations_for_learner,
36
+ update_history_plots_for_learner,
37
+ initialize_visualization_for_learner
38
+ )
39
+
40
+ ### GLOBAL VARIABLES ###
41
+ bar_format_normal = loading_bars()[0]
42
+ bar_format_learner = loading_bars()[1]
43
+
44
+ # BUILD -----
45
+
46
+ def fit(
47
+ x_train,
48
+ y_train,
49
+ val=False,
50
+ val_count=None,
51
+ activation_potentiation=['linear'],
52
+ x_val=None,
53
+ y_val=None,
54
+ show_training=None,
55
+ interval=100,
56
+ LTD=0,
57
+ decision_boundary_status=True,
58
+ train_bar=True,
59
+ auto_normalization=True,
60
+ neurons_history=False
61
+ ):
62
+ """
63
+ Creates a model to fitting data.
64
+
65
+ fit Args:
66
+
67
+ x_train (list[cupy-array]): List or numarray of input data.
68
+
69
+ y_train (list[cupy-array]): List or numarray of target labels. (one hot encoded)
70
+
71
+ val (None or True): validation in training process ? None or True default: None (optional)
72
+
73
+ 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)
74
+
75
+ activation_potentiation (list): For deeper PLAN networks, activation function parameters. For more information please run this code: plan.activations_list() default: [None] (optional)
76
+
77
+ x_val (list[cupy-array]): List of validation data. default: x_train (optional)
78
+
79
+ y_val (list[cupy-array]): List of target labels. (one hot encoded) default: y_train (optional)
80
+
81
+ show_training (bool, str): True or None default: None (optional)
82
+
83
+ LTD (int): Long Term Depression Hyperparameter for train PLAN neural network default: 0 (optional)
84
+
85
+ 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)
86
+
87
+ 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)
88
+
89
+ train_bar (bool): Training loading bar? True or False. Default is True. (optional)
90
+
91
+ auto_normalization(bool): Normalization process during training. May effect training time and model quality. True or False. Default is True. (optional)
92
+
93
+ 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)
94
+
95
+ Returns:
96
+ numpyarray([num]): (Weight matrix).
97
+ """
98
+ # Pre-checks
99
+
100
+ if train_bar and val:
101
+ train_progress = initialize_loading_bar(total=len(x_train), ncols=71, desc='Fitting', bar_format=bar_format_normal)
102
+ elif train_bar and val == False:
103
+ train_progress = initialize_loading_bar(total=len(x_train), ncols=44, desc='Fitting', bar_format=bar_format_normal)
104
+
105
+ if len(x_train) != len(y_train):
106
+ raise ValueError("x_train and y_train must have the same length.")
107
+
108
+ if val and (x_val is None or y_val is None):
109
+ x_val, y_val = x_train, y_train
110
+
111
+ val_list = [] if val else None
112
+ val_count = val_count or 10
113
+ # Defining weights
114
+ STPW = cp.ones((len(y_train[0]), len(x_train[0].ravel()))) # STPW = SHORT TIME POTENTIATION WEIGHT
115
+ LTPW = cp.zeros((len(y_train[0]), len(x_train[0].ravel()))) # LTPW = LONG TIME POTENTIATION WEIGHT
116
+ # Initialize visualization
117
+ vis_objects = initialize_visualization_for_fit(val, show_training, neurons_history, x_train, y_train)
118
+
119
+ # Training process
120
+ for index, inp in enumerate(x_train):
121
+ inp = cp.array(inp).ravel()
122
+ y_decoded = decode_one_hot(y_train)
123
+ # Weight updates
124
+ STPW = feed_forward(inp, STPW, is_training=True, Class=y_decoded[index], activation_potentiation=activation_potentiation, LTD=LTD)
125
+ LTPW += normalization(STPW) if auto_normalization else STPW
126
+
127
+ # Visualization updates
128
+ if show_training:
129
+ update_weight_visualization_for_fit(vis_objects['ax'][0, 0], LTPW, vis_objects['artist2'])
130
+ if decision_boundary_status:
131
+ update_decision_boundary_for_fit(vis_objects['ax'][0, 1], x_val, y_val, activation_potentiation, LTPW, vis_objects['artist1'])
132
+ update_validation_history_for_fit(vis_objects['ax'][1, 1], val_list, vis_objects['artist3'])
133
+ if train_bar:
134
+ train_progress.update(1)
135
+
136
+ STPW = cp.ones((len(y_train[0]), len(x_train[0].ravel())))
137
+
138
+ # Finalize visualization
139
+ if show_training:
140
+ display_visualization_for_fit(vis_objects['fig'], vis_objects['artist1'], interval)
141
+
142
+ return normalization(LTPW)
143
+
144
+
145
+ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', batch_size=1,
146
+ neural_web_history=False, show_current_activations=False, auto_normalization=True,
147
+ neurons_history=False, patience=None, depth=None, early_shifting=False,
148
+ early_stop=False, loss='categorical_crossentropy', show_history=False,
149
+ interval=33.33, target_acc=None, target_loss=None, except_this=None,
150
+ only_this=None, start_this=None):
151
+ """
152
+ Optimizes the activation functions for a neural network by leveraging train data to find
153
+ the most accurate combination of activation potentiation for the given dataset.
154
+
155
+ Args:
156
+
157
+ x_train (array-like): Training input data.
158
+
159
+ y_train (array-like): Labels for training data.
160
+
161
+ x_test (array-like, optional): Test input data (for improve next gen generilization). If test data is not given then train feedback learning active
162
+
163
+ y_test (array-like, optional): Test Labels (for improve next gen generilization). If test data is not given then train feedback learning active
164
+
165
+ 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'.
166
+
167
+ patience ((int, float), optional): patience value for adaptive strategies. For 'adaptive_accuracy' Default value: 5. For 'adaptive_loss' Default value: 0.150.
168
+
169
+ depth (int, optional): The depth of the PLAN neural networks Aggreagation layers.
170
+
171
+ 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)
172
+
173
+ 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.
174
+
175
+ 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
176
+
177
+ early_stop (bool, optional): If True, implements early stopping during training.(If test accuracy not improves in two depth stops learning.) Default is False.
178
+
179
+ 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
180
+
181
+ show_history (bool, optional): If True, displays the training history after optimization. Default is False.
182
+
183
+ 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'.
184
+
185
+ interval (int, optional): The interval at which evaluations are conducted during training. (33.33 = 30 FPS, 16.67 = 60 FPS) Default is 100.
186
+
187
+ target_acc (int, optional): The target accuracy to stop training early when achieved. Default is None.
188
+
189
+ target_loss (float, optional): The target loss to stop training early when achieved. Default is None.
190
+
191
+ 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())
192
+
193
+ 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())
194
+
195
+ 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
196
+
197
+ 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.
198
+
199
+ neural_web_history (bool, optional): Draws history of neural web. Default is False.
200
+
201
+ Returns:
202
+ tuple: A list for model parameters: [Weight matrix, Test loss, Test Accuracy, [Activations functions]].
203
+
204
+ """
205
+ 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)
206
+
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
+ x_train = cp.array(x_train, copy=False)
218
+ y_train = cp.array(y_train, copy=False)
219
+ x_test = cp.array(x_test, copy=False)
220
+ y_test = cp.array(y_test, copy=False)
221
+
222
+ if early_shifting != False:
223
+ shift_patience = early_shifting
224
+
225
+ # Strategy initialization
226
+ if strategy == 'adaptive_accuracy':
227
+ strategy = 'accuracy'
228
+ adaptive = True
229
+ if patience == None:
230
+ patience = 5
231
+ elif strategy == 'adaptive_loss':
232
+ strategy = 'loss'
233
+ adaptive = True
234
+ if patience == None:
235
+ patience = 0.150
236
+ else:
237
+ adaptive = False
238
+
239
+ # Filter activation functions
240
+ if only_this != None:
241
+ activation_potentiation = only_this
242
+ if except_this != None:
243
+ activation_potentiation = [item for item in activation_potentiation if item not in except_this]
244
+ if depth is None:
245
+ depth = len(activation_potentiation)
246
+
247
+ # Initialize visualization components
248
+ viz_objects = initialize_visualization_for_learner(show_history, neurons_history, neural_web_history, x_train, y_train)
249
+
250
+ # Initialize progress bar
251
+ if batch_size == 1:
252
+ ncols = 100
253
+ else:
254
+ ncols = 120
255
+ progress = initialize_loading_bar(total=len(activation_potentiation), desc="", ncols=ncols, bar_format=bar_format_learner)
256
+
257
+ # Initialize variables
258
+ activations = []
259
+ if start_this is None:
260
+ best_activations = []
261
+ best_acc = 0
262
+ else:
263
+ best_activations = start_this
264
+ x_test_batch, y_test_batch = batcher(x_test, y_test, batch_size=batch_size)
265
+ W = fit(x_train, y_train, activation_potentiation=best_activations, train_bar=False, auto_normalization=auto_normalization)
266
+ model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations)
267
+
268
+ if loss == 'categorical_crossentropy':
269
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
270
+ else:
271
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
272
+
273
+ best_acc = model[get_acc()]
274
+ best_loss = test_loss
275
+
276
+ best_acc_per_depth_list = []
277
+ postfix_dict = {}
278
+ loss_list = []
279
+
280
+ for i in range(depth):
281
+ postfix_dict["Depth"] = str(i+1) + '/' + str(depth)
282
+ progress.set_postfix(postfix_dict)
283
+
284
+ progress.n = 0
285
+ progress.last_print_n = 0
286
+ progress.update(0)
287
+
288
+ for j in range(len(activation_potentiation)):
289
+ for k in range(len(best_activations)):
290
+ activations.append(best_activations[k])
291
+
292
+ activations.append(activation_potentiation[j])
293
+
294
+ x_test_batch, y_test_batch = batcher(x_test, y_test, batch_size=batch_size)
295
+ W = fit(x_train, y_train, activation_potentiation=activations, train_bar=False, auto_normalization=auto_normalization)
296
+ model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations)
297
+
298
+ acc = model[get_acc()]
299
+
300
+ if strategy == 'loss' or strategy == 'all':
301
+ if loss == 'categorical_crossentropy':
302
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
303
+ else:
304
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
305
+
306
+ if i == 0 and j == 0 and start_this is None:
307
+ best_loss = test_loss
308
+
309
+ if strategy == 'f1' or strategy == 'precision' or strategy == 'recall' or strategy == 'all':
310
+ precision_score, recall_score, f1_score = metrics(y_test_batch, model[get_preds()])
311
+
312
+ if strategy == 'precision' or strategy == 'all':
313
+ if i == 0 and j == 0:
314
+ best_precision = precision_score
315
+
316
+ if strategy == 'recall' or strategy == 'all':
317
+ if i == 0 and j == 0:
318
+ best_recall = recall_score
319
+
320
+ if strategy == 'f1' or strategy == 'all':
321
+ if i == 0 and j == 0:
322
+ best_f1 = f1_score
323
+
324
+ if early_shifting != False:
325
+ if acc <= best_acc:
326
+ early_shifting -= 1
327
+ if early_shifting == 0:
328
+ early_shifting = shift_patience
329
+ break
330
+
331
+ if ((strategy == 'accuracy' and acc >= best_acc) or
332
+ (strategy == 'loss' and test_loss <= best_loss) or
333
+ (strategy == 'f1' and f1_score >= best_f1) or
334
+ (strategy == 'precision' and precision_score >= best_precision) or
335
+ (strategy == 'recall' and recall_score >= best_recall) or
336
+ (strategy == 'all' and f1_score >= best_f1 and acc >= best_acc and
337
+ test_loss <= best_loss and precision_score >= best_precision and
338
+ recall_score >= best_recall)):
339
+
340
+ current_best_activation = activation_potentiation[j]
341
+ best_acc = acc
342
+
343
+ if batch_size == 1:
344
+ postfix_dict[f"{data} Accuracy"] = best_acc
345
+ else:
346
+ postfix_dict[f"{data} Batch Accuracy"] = acc
347
+ progress.set_postfix(postfix_dict)
348
+
349
+ final_activations = activations
350
+
351
+ if show_current_activations:
352
+ print(f", Current Activations={final_activations}", end='')
353
+
354
+ best_weights = W
355
+ best_model = model
356
+
357
+ if strategy != 'loss':
358
+ if loss == 'categorical_crossentropy':
359
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
360
+ else:
361
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
362
+
363
+ if batch_size == 1:
364
+ postfix_dict[f"{data} Loss"] = test_loss
365
+ best_loss = test_loss
366
+ else:
367
+ postfix_dict[f"{data} Batch Loss"] = test_loss
368
+ progress.set_postfix(postfix_dict)
369
+ best_loss = test_loss
370
+
371
+ # Update visualizations during training
372
+ if show_history:
373
+ depth_list = range(1, len(best_acc_per_depth_list) + 2)
374
+ update_history_plots_for_learner(viz_objects, depth_list, loss_list + [test_loss],
375
+ best_acc_per_depth_list + [best_acc], x_train, final_activations)
376
+
377
+ if neurons_history:
378
+ viz_objects['neurons']['artists'] = (
379
+ neuron_history(cp.copy(best_weights), viz_objects['neurons']['ax'],
380
+ viz_objects['neurons']['row'], viz_objects['neurons']['col'],
381
+ y_train[0], viz_objects['neurons']['artists'],
382
+ data=data, fig1=viz_objects['neurons']['fig'],
383
+ acc=best_acc, loss=test_loss)
384
+ )
385
+
386
+ if neural_web_history:
387
+ art5_1, art5_2, art5_3 = draw_neural_web(W=best_weights, ax=viz_objects['web']['ax'],
388
+ G=viz_objects['web']['G'], return_objs=True)
389
+ art5_list = [art5_1] + [art5_2] + list(art5_3.values())
390
+ viz_objects['web']['artists'].append(art5_list)
391
+
392
+ # Check target accuracy
393
+ if target_acc is not None and best_acc >= target_acc:
394
+ progress.close()
395
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
396
+ activation_potentiation=final_activations)
397
+
398
+ if loss == 'categorical_crossentropy':
399
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
400
+ y_pred_batch=train_model[get_preds_softmax()])
401
+ else:
402
+ train_loss = binary_crossentropy(y_true_batch=y_train,
403
+ y_pred_batch=train_model[get_preds_softmax()])
404
+
405
+ print('\nActivations: ', final_activations)
406
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
407
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
408
+ if data == 'Test':
409
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
410
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
411
+
412
+ # Display final visualizations
413
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
414
+ test_loss, y_train, interval)
415
+ return best_weights, best_model[get_preds()], best_acc, final_activations
416
+
417
+ # Check target loss
418
+ if target_loss is not None and best_loss <= target_loss:
419
+ progress.close()
420
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
421
+ activation_potentiation=final_activations)
422
+
423
+ if loss == 'categorical_crossentropy':
424
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
425
+ y_pred_batch=train_model[get_preds_softmax()])
426
+ else:
427
+ train_loss = binary_crossentropy(y_true_batch=y_train,
428
+ y_pred_batch=train_model[get_preds_softmax()])
429
+
430
+ print('\nActivations: ', final_activations)
431
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
432
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
433
+ if data == 'Test':
434
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
435
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
436
+
437
+ # Display final visualizations
438
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
439
+ test_loss, y_train, interval)
440
+ return best_weights, best_model[get_preds()], best_acc, final_activations
441
+
442
+ progress.update(1)
443
+ activations = []
444
+
445
+ best_activations.append(current_best_activation)
446
+ best_acc_per_depth_list.append(best_acc)
447
+ loss_list.append(best_loss)
448
+
449
+ # Check adaptive strategy conditions
450
+ if adaptive == True and strategy == 'accuracy' and i + 1 >= patience:
451
+ check = best_acc_per_depth_list[-patience:]
452
+ if all(x == check[0] for x in check):
453
+ strategy = 'loss'
454
+ adaptive = False
455
+ elif adaptive == True and strategy == 'loss' and best_loss <= patience:
456
+ strategy = 'accuracy'
457
+ adaptive = False
458
+
459
+ # Early stopping check
460
+ if early_stop == True and i > 0:
461
+ if best_acc_per_depth_list[i] == best_acc_per_depth_list[i-1]:
462
+ progress.close()
463
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
464
+ activation_potentiation=final_activations)
465
+
466
+ if loss == 'categorical_crossentropy':
467
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
468
+ y_pred_batch=train_model[get_preds_softmax()])
469
+ else:
470
+ train_loss = binary_crossentropy(y_true_batch=y_train,
471
+ y_pred_batch=train_model[get_preds_softmax()])
472
+
473
+ print('\nActivations: ', final_activations)
474
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
475
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
476
+ if data == 'Test':
477
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
478
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
479
+
480
+ # Display final visualizations
481
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
482
+ test_loss, y_train, interval)
483
+ return best_weights, best_model[get_preds()], best_acc, final_activations
484
+
485
+ # Final evaluation
486
+ progress.close()
487
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
488
+ activation_potentiation=final_activations)
489
+
490
+ if loss == 'categorical_crossentropy':
491
+ train_loss = categorical_crossentropy(y_true_batch=y_train, y_pred_batch=train_model[get_preds_softmax()])
492
+ else:
493
+ train_loss = binary_crossentropy(y_true_batch=y_train, y_pred_batch=train_model[get_preds_softmax()])
494
+
495
+ print('\nActivations: ', final_activations)
496
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
497
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
498
+ if data == 'Test':
499
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
500
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
501
+
502
+ # Display final visualizations
503
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc, test_loss, y_train, interval)
504
+ return best_weights, best_model[get_preds()], best_acc, final_activations
505
+
506
+
507
+
508
+ def feed_forward(
509
+ Input, # cupy-array: Input data.
510
+ w, # cupy-array: Weight matrix of the neural network.
511
+ is_training, # bool: Flag indicating if the function is called during training (True or False).
512
+ activation_potentiation, # (list): Activation potentiation list for deep PLAN. (optional)
513
+ Class='?', # int: Which class is, if training.
514
+ LTD=0
515
+ ) -> tuple:
516
+ """
517
+ Applies feature extraction process to the input data using synaptic potentiation.
518
+
519
+ Args:
520
+ Input (cupy-array): Input data.
521
+ w (cupy-array): Weight matrix of the neural network.
522
+ is_training (bool): Flag indicating if the function is called during training (True or False).
523
+ Class (int): if is during training then which class(label) ? is isnt then put None.
524
+ activation_potentiation (list): ac list for deep PLAN. default: [None] ('linear') (optional)
525
+
526
+ Returns:
527
+ tuple: A tuple (vector) containing the neural layer result and the updated weight matrix.
528
+ or
529
+ num: neural network output
530
+ """
531
+
532
+ Output = apply_activation(Input, activation_potentiation)
533
+
534
+ Input = Output
535
+
536
+ if is_training == True:
537
+
538
+ for _ in range(LTD):
539
+
540
+ depression_vector = cp.random.rand(*Input.shape)
541
+
542
+ Input -= depression_vector
543
+
544
+ w[Class, :] = Input
545
+ return w
546
+
547
+ else:
548
+
549
+ neural_layer = cp.dot(w, Input)
550
+
551
+ return neural_layer
552
+
553
+
554
+ def evaluate(
555
+ x_test, # GPU'da CuPy dizisi: Test giriş verileri.
556
+ y_test, # GPU'da CuPy dizisi: Test etiketleri.
557
+ W, # GPU'da CuPy dizisi: Sinir ağı ağırlık matrisi.
558
+ activation_potentiation=['linear'], # Aktivasyon fonksiyonları listesi.
559
+ loading_bar_status=True, # Yükleme çubuğu durumu (isteğe bağlı).
560
+ show_metrics=None, # Metrikleri gösterme seçeneği (isteğe bağlı).
561
+ ) -> tuple:
562
+ """
563
+ Evaluates the neural network model with the given test data.
564
+
565
+ Args:
566
+ x_test (cupy-array): Test input data.
567
+ y_test (cupy-array): Test labels.
568
+ W (list[cupy-array]): Neural network weight matrix.
569
+ activation_potentiation (list): Activation functions.
570
+ loading_bar_status (bool): Loading bar status (optional).
571
+ show_metrics (bool): Option to display metrics (optional).
572
+
573
+ Returns:
574
+ tuple: model.
575
+ """
576
+
577
+ predict_probabilitys = cp.empty((len(x_test), W.shape[0]), dtype=cp.float32)
578
+ real_classes = cp.empty(len(x_test), dtype=cp.int32)
579
+ predict_classes = cp.empty(len(x_test), dtype=cp.int32)
580
+
581
+ true_predict = 0
582
+ acc_list = cp.empty(len(x_test), dtype=cp.float32)
583
+
584
+ if loading_bar_status:
585
+ loading_bar = initialize_loading_bar(total=len(x_test), ncols=64, desc='Testing', bar_format=bar_format_normal)
586
+
587
+ for inpIndex in range(len(x_test)):
588
+ Input = x_test[inpIndex].ravel()
589
+ neural_layer = Input
590
+ neural_layer = feed_forward(neural_layer, cp.copy(W), is_training=False, Class='?', activation_potentiation=activation_potentiation)
591
+
592
+ predict_probabilitys[inpIndex] = Softmax(neural_layer)
593
+
594
+ RealOutput = cp.argmax(y_test[inpIndex])
595
+ real_classes[inpIndex] = RealOutput
596
+ PredictedOutput = cp.argmax(neural_layer)
597
+ predict_classes[inpIndex] = PredictedOutput
598
+
599
+ if RealOutput == PredictedOutput:
600
+ true_predict += 1
601
+
602
+ acc = true_predict / (inpIndex + 1)
603
+ acc_list[inpIndex] = acc
604
+
605
+ if loading_bar_status:
606
+ loading_bar.update(1)
607
+ loading_bar.set_postfix({"Test Accuracy": acc})
608
+
609
+ if loading_bar_status:
610
+ loading_bar.close()
611
+
612
+ if show_metrics:
613
+ plot_evaluate(x_test, y_test, predict_classes, acc_list, W=cp.copy(W), activation_potentiation=activation_potentiation)
614
+
615
+ return W, predict_classes, acc_list[-1], None, None, predict_probabilitys