pyerualjetwork 4.0.5__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,677 @@
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
+ dtype=cp.float32
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
+ 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)
97
+
98
+ Returns:
99
+ numpyarray([num]): (Weight matrix).
100
+ """
101
+ # Pre-checks
102
+
103
+ x_train = cp.array(x_train, copy=False).astype(dtype, copy=False)
104
+
105
+ if len(y_train[0]) < 256:
106
+ if y_train.dtype != cp.uint8:
107
+ y_train = cp.array(y_train, copy=False).astype(cp.uint8, copy=False)
108
+ elif len(y_train[0]) <= 32767:
109
+ if y_train.dtype != cp.uint16:
110
+ y_train = cp.array(y_train, copy=False).astype(cp.uint16, copy=False)
111
+ else:
112
+ if y_train.dtype != cp.uint32:
113
+ y_train = cp.array(y_train, copy=False).astype(cp.uint32, copy=False)
114
+
115
+ if train_bar and val:
116
+ train_progress = initialize_loading_bar(total=len(x_train), ncols=71, desc='Fitting', bar_format=bar_format_normal)
117
+ elif train_bar and val == False:
118
+ train_progress = initialize_loading_bar(total=len(x_train), ncols=44, desc='Fitting', bar_format=bar_format_normal)
119
+
120
+ if len(x_train) != len(y_train):
121
+ raise ValueError("x_train and y_train must have the same length.")
122
+
123
+ if val and (x_val is None or y_val is None):
124
+ x_val, y_val = x_train, y_train
125
+
126
+ val_list = [] if val else None
127
+ val_count = val_count or 10
128
+ # Defining weights
129
+ STPW = cp.ones((len(y_train[0]), len(x_train[0].ravel()))).astype(dtype, copy=False) # STPW = SHORT TERM POTENTIATION WEIGHT
130
+ LTPW = cp.zeros((len(y_train[0]), len(x_train[0].ravel()))).astype(dtype, copy=False) # LTPW = LONG TERM POTENTIATION WEIGHT
131
+ # Initialize visualization
132
+ vis_objects = initialize_visualization_for_fit(val, show_training, neurons_history, x_train, y_train)
133
+
134
+ # Training process
135
+ for index, inp in enumerate(x_train):
136
+ inp = cp.array(inp).ravel()
137
+ y_decoded = decode_one_hot(y_train)
138
+ # Weight updates
139
+ STPW = feed_forward(inp, STPW, is_training=True, Class=y_decoded[index], activation_potentiation=activation_potentiation, LTD=LTD)
140
+ LTPW += normalization(STPW, dtype=dtype) if auto_normalization else STPW
141
+
142
+ # Visualization updates
143
+ if show_training:
144
+ update_weight_visualization_for_fit(vis_objects['ax'][0, 0], LTPW, vis_objects['artist2'])
145
+ if decision_boundary_status:
146
+ update_decision_boundary_for_fit(vis_objects['ax'][0, 1], x_val, y_val, activation_potentiation, LTPW, vis_objects['artist1'])
147
+ update_validation_history_for_fit(vis_objects['ax'][1, 1], val_list, vis_objects['artist3'])
148
+ if train_bar:
149
+ train_progress.update(1)
150
+
151
+ STPW = cp.ones((len(y_train[0]), len(x_train[0].ravel()))).astype(dtype, copy=False)
152
+
153
+ # Finalize visualization
154
+ if show_training:
155
+ display_visualization_for_fit(vis_objects['fig'], vis_objects['artist1'], interval)
156
+
157
+ return normalization(LTPW, dtype=dtype)
158
+
159
+
160
+ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', batch_size=1,
161
+ neural_web_history=False, show_current_activations=False, auto_normalization=True,
162
+ neurons_history=False, patience=None, depth=None, early_shifting=False,
163
+ early_stop=False, loss='categorical_crossentropy', show_history=False,
164
+ interval=33.33, target_acc=None, target_loss=None, except_this=None,
165
+ only_this=None, start_this=None, dtype=cp.float32):
166
+ """
167
+ Optimizes the activation functions for a neural network by leveraging train data to find
168
+ the most accurate combination of activation potentiation for the given dataset.
169
+
170
+ Args:
171
+
172
+ x_train (array-like): Training input data.
173
+
174
+ y_train (array-like): Labels for training data.
175
+
176
+ x_test (array-like, optional): Test input data (for improve next gen generilization). If test data is not given then train feedback learning active
177
+
178
+ y_test (array-like, optional): Test Labels (for improve next gen generilization). If test data is not given then train feedback learning active
179
+
180
+ 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'.
181
+
182
+ patience ((int, float), optional): patience value for adaptive strategies. For 'adaptive_accuracy' Default value: 5. For 'adaptive_loss' Default value: 0.150.
183
+
184
+ depth (int, optional): The depth of the PLAN neural networks Aggreagation layers.
185
+
186
+ 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)
187
+
188
+ 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.
189
+
190
+ 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
191
+
192
+ early_stop (bool, optional): If True, implements early stopping during training.(If test accuracy not improves in two depth stops learning.) Default is False.
193
+
194
+ 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
195
+
196
+ show_history (bool, optional): If True, displays the training history after optimization. Default is False.
197
+
198
+ 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'.
199
+
200
+ interval (int, optional): The interval at which evaluations are conducted during training. (33.33 = 30 FPS, 16.67 = 60 FPS) Default is 100.
201
+
202
+ target_acc (int, optional): The target accuracy to stop training early when achieved. Default is None.
203
+
204
+ target_loss (float, optional): The target loss to stop training early when achieved. Default is None.
205
+
206
+ 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())
207
+
208
+ 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())
209
+
210
+ 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
211
+
212
+ 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.
213
+
214
+ neural_web_history (bool, optional): Draws history of neural web. Default is False.
215
+
216
+ 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)
217
+
218
+ Returns:
219
+ tuple: A list for model parameters: [Weight matrix, Preds, Accuracy, [Activations functions]]. You can acces this parameters in model_operations module. For example: model_operations.get_weights() for Weight matrix.
220
+
221
+ """
222
+ 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)
223
+
224
+ activation_potentiation = all_activations()
225
+
226
+ if x_test is None and y_test is None:
227
+ x_test = x_train
228
+ y_test = y_train
229
+ data = 'Train'
230
+ else:
231
+ data = 'Test'
232
+
233
+ x_train = cp.array(x_train, copy=False)
234
+
235
+ if len(y_train[0]) < 256:
236
+ if y_train.dtype != cp.uint8:
237
+ y_train = cp.array(y_train, copy=False).astype(cp.uint8, copy=False)
238
+ elif len(y_train[0]) <= 32767:
239
+ if y_train.dtype != cp.uint16:
240
+ y_train = cp.array(y_train, copy=False).astype(cp.uint16, copy=False)
241
+ else:
242
+ if y_train.dtype != cp.uint32:
243
+ y_train = cp.array(y_train, copy=False).astype(cp.uint32, copy=False)
244
+
245
+ x_test = cp.array(x_test, copy=False)
246
+
247
+ if len(y_test[0]) < 256:
248
+ if y_test.dtype != cp.uint8:
249
+ y_test = cp.array(y_test, copy=False).astype(cp.uint8, copy=False)
250
+ elif len(y_test[0]) <= 32767:
251
+ if y_test.dtype != cp.uint16:
252
+ y_test = cp.array(y_test, copy=False).astype(cp.uint16, copy=False)
253
+ else:
254
+ if y_test.dtype != cp.uint32:
255
+ y_test = cp.array(y_test, copy=False).astype(cp.uint32, copy=False)
256
+
257
+ if early_shifting != False:
258
+ shift_patience = early_shifting
259
+
260
+ # Strategy initialization
261
+ if strategy == 'adaptive_accuracy':
262
+ strategy = 'accuracy'
263
+ adaptive = True
264
+ if patience == None:
265
+ patience = 5
266
+ elif strategy == 'adaptive_loss':
267
+ strategy = 'loss'
268
+ adaptive = True
269
+ if patience == None:
270
+ patience = 0.150
271
+ else:
272
+ adaptive = False
273
+
274
+ # Filter activation functions
275
+ if only_this != None:
276
+ activation_potentiation = only_this
277
+ if except_this != None:
278
+ activation_potentiation = [item for item in activation_potentiation if item not in except_this]
279
+ if depth is None:
280
+ depth = len(activation_potentiation)
281
+
282
+ # Initialize visualization components
283
+ viz_objects = initialize_visualization_for_learner(show_history, neurons_history, neural_web_history, x_train, y_train)
284
+
285
+ # Initialize progress bar
286
+ if batch_size == 1:
287
+ ncols = 100
288
+ else:
289
+ ncols = 140
290
+ progress = initialize_loading_bar(total=len(activation_potentiation), desc="", ncols=ncols, bar_format=bar_format_learner)
291
+
292
+ # Initialize variables
293
+ activations = []
294
+ if start_this is None:
295
+ best_activations = []
296
+ best_acc = 0
297
+ else:
298
+ best_activations = start_this
299
+ x_test_batch, y_test_batch = batcher(x_test, y_test, batch_size=batch_size)
300
+ W = fit(x_train, y_train, activation_potentiation=best_activations, train_bar=False, auto_normalization=auto_normalization)
301
+ model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations)
302
+
303
+ if loss == 'categorical_crossentropy':
304
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
305
+ else:
306
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
307
+
308
+ best_acc = model[get_acc()]
309
+ best_loss = test_loss
310
+
311
+ best_acc_per_depth_list = []
312
+ postfix_dict = {}
313
+ loss_list = []
314
+
315
+ for i in range(depth):
316
+ postfix_dict["Depth"] = str(i+1) + '/' + str(depth)
317
+ progress.set_postfix(postfix_dict)
318
+
319
+ progress.n = 0
320
+ progress.last_print_n = 0
321
+ progress.update(0)
322
+
323
+ for j in range(len(activation_potentiation)):
324
+ for k in range(len(best_activations)):
325
+ activations.append(best_activations[k])
326
+
327
+ activations.append(activation_potentiation[j])
328
+
329
+ x_test_batch, y_test_batch = batcher(x_test, y_test, batch_size=batch_size)
330
+ W = fit(x_train, y_train, activation_potentiation=activations, train_bar=False, auto_normalization=auto_normalization, dtype=dtype)
331
+ model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations, dtype=dtype)
332
+
333
+ acc = model[get_acc()]
334
+
335
+ if strategy == 'loss' or strategy == 'all':
336
+ if loss == 'categorical_crossentropy':
337
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
338
+ else:
339
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
340
+
341
+ if i == 0 and j == 0 and start_this is None:
342
+ best_loss = test_loss
343
+
344
+ if strategy == 'f1' or strategy == 'precision' or strategy == 'recall' or strategy == 'all':
345
+ precision_score, recall_score, f1_score = metrics(y_test_batch, model[get_preds()])
346
+
347
+ if strategy == 'precision' or strategy == 'all':
348
+ if i == 0 and j == 0:
349
+ best_precision = precision_score
350
+
351
+ if strategy == 'recall' or strategy == 'all':
352
+ if i == 0 and j == 0:
353
+ best_recall = recall_score
354
+
355
+ if strategy == 'f1' or strategy == 'all':
356
+ if i == 0 and j == 0:
357
+ best_f1 = f1_score
358
+
359
+ if early_shifting != False:
360
+ if acc <= best_acc:
361
+ early_shifting -= 1
362
+ if early_shifting == 0:
363
+ early_shifting = shift_patience
364
+ break
365
+
366
+ if ((strategy == 'accuracy' and acc >= best_acc) or
367
+ (strategy == 'loss' and test_loss <= best_loss) or
368
+ (strategy == 'f1' and f1_score >= best_f1) or
369
+ (strategy == 'precision' and precision_score >= best_precision) or
370
+ (strategy == 'recall' and recall_score >= best_recall) or
371
+ (strategy == 'all' and f1_score >= best_f1 and acc >= best_acc and
372
+ test_loss <= best_loss and precision_score >= best_precision and
373
+ recall_score >= best_recall)):
374
+
375
+ current_best_activation = activation_potentiation[j]
376
+ best_acc = acc
377
+
378
+ if batch_size == 1:
379
+ postfix_dict[f"{data} Accuracy"] = best_acc
380
+ else:
381
+ postfix_dict[f"{data} Batch Accuracy"] = acc
382
+ progress.set_postfix(postfix_dict)
383
+
384
+ final_activations = activations
385
+
386
+ if show_current_activations:
387
+ print(f", Current Activations={final_activations}", end='')
388
+
389
+ best_weights = W
390
+ best_model = model
391
+
392
+ if strategy != 'loss':
393
+ if loss == 'categorical_crossentropy':
394
+ test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
395
+ else:
396
+ test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
397
+
398
+ if batch_size == 1:
399
+ postfix_dict[f"{data} Loss"] = test_loss
400
+ best_loss = test_loss
401
+ else:
402
+ postfix_dict[f"{data} Batch Loss"] = test_loss
403
+ progress.set_postfix(postfix_dict)
404
+ best_loss = test_loss
405
+
406
+ # Update visualizations during training
407
+ if show_history:
408
+ depth_list = range(1, len(best_acc_per_depth_list) + 2)
409
+ update_history_plots_for_learner(viz_objects, depth_list, loss_list + [test_loss],
410
+ best_acc_per_depth_list + [best_acc], x_train, final_activations)
411
+
412
+ if neurons_history:
413
+ viz_objects['neurons']['artists'] = (
414
+ neuron_history(cp.copy(best_weights), viz_objects['neurons']['ax'],
415
+ viz_objects['neurons']['row'], viz_objects['neurons']['col'],
416
+ y_train[0], viz_objects['neurons']['artists'],
417
+ data=data, fig1=viz_objects['neurons']['fig'],
418
+ acc=best_acc, loss=test_loss)
419
+ )
420
+
421
+ if neural_web_history:
422
+ art5_1, art5_2, art5_3 = draw_neural_web(W=best_weights, ax=viz_objects['web']['ax'],
423
+ G=viz_objects['web']['G'], return_objs=True)
424
+ art5_list = [art5_1] + [art5_2] + list(art5_3.values())
425
+ viz_objects['web']['artists'].append(art5_list)
426
+
427
+ # Check target accuracy
428
+ if target_acc is not None and best_acc >= target_acc:
429
+ progress.close()
430
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
431
+ activation_potentiation=final_activations)
432
+
433
+ if loss == 'categorical_crossentropy':
434
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
435
+ y_pred_batch=train_model[get_preds_softmax()])
436
+ else:
437
+ train_loss = binary_crossentropy(y_true_batch=y_train,
438
+ y_pred_batch=train_model[get_preds_softmax()])
439
+
440
+ print('\nActivations: ', final_activations)
441
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
442
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
443
+ if data == 'Test':
444
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
445
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
446
+
447
+ # Display final visualizations
448
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
449
+ test_loss, y_train, interval)
450
+ return best_weights, best_model[get_preds()], best_acc, final_activations
451
+
452
+ # Check target loss
453
+ if target_loss is not None and best_loss <= target_loss:
454
+ progress.close()
455
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
456
+ activation_potentiation=final_activations)
457
+
458
+ if loss == 'categorical_crossentropy':
459
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
460
+ y_pred_batch=train_model[get_preds_softmax()])
461
+ else:
462
+ train_loss = binary_crossentropy(y_true_batch=y_train,
463
+ y_pred_batch=train_model[get_preds_softmax()])
464
+
465
+ print('\nActivations: ', final_activations)
466
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
467
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
468
+ if data == 'Test':
469
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
470
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
471
+
472
+ # Display final visualizations
473
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
474
+ test_loss, y_train, interval)
475
+ return best_weights, best_model[get_preds()], best_acc, final_activations
476
+
477
+ progress.update(1)
478
+ activations = []
479
+
480
+ best_activations.append(current_best_activation)
481
+ best_acc_per_depth_list.append(best_acc)
482
+ loss_list.append(best_loss)
483
+
484
+ # Check adaptive strategy conditions
485
+ if adaptive == True and strategy == 'accuracy' and i + 1 >= patience:
486
+ check = best_acc_per_depth_list[-patience:]
487
+ if all(x == check[0] for x in check):
488
+ strategy = 'loss'
489
+ adaptive = False
490
+ elif adaptive == True and strategy == 'loss' and best_loss <= patience:
491
+ strategy = 'accuracy'
492
+ adaptive = False
493
+
494
+ # Early stopping check
495
+ if early_stop == True and i > 0:
496
+ if best_acc_per_depth_list[i] == best_acc_per_depth_list[i-1]:
497
+ progress.close()
498
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
499
+ activation_potentiation=final_activations)
500
+
501
+ if loss == 'categorical_crossentropy':
502
+ train_loss = categorical_crossentropy(y_true_batch=y_train,
503
+ y_pred_batch=train_model[get_preds_softmax()])
504
+ else:
505
+ train_loss = binary_crossentropy(y_true_batch=y_train,
506
+ y_pred_batch=train_model[get_preds_softmax()])
507
+
508
+ print('\nActivations: ', final_activations)
509
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
510
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
511
+ if data == 'Test':
512
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
513
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
514
+
515
+ # Display final visualizations
516
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc,
517
+ test_loss, y_train, interval)
518
+ return best_weights, best_model[get_preds()], best_acc, final_activations
519
+
520
+ # Final evaluation
521
+ progress.close()
522
+ train_model = evaluate(x_train, y_train, W=best_weights, loading_bar_status=False,
523
+ activation_potentiation=final_activations)
524
+
525
+ if loss == 'categorical_crossentropy':
526
+ train_loss = categorical_crossentropy(y_true_batch=y_train, y_pred_batch=train_model[get_preds_softmax()])
527
+ else:
528
+ train_loss = binary_crossentropy(y_true_batch=y_train, y_pred_batch=train_model[get_preds_softmax()])
529
+
530
+ print('\nActivations: ', final_activations)
531
+ print(f'Train Accuracy (%{batch_size * 100} of train samples):', train_model[get_acc()])
532
+ print(f'Train Loss (%{batch_size * 100} of train samples): ', train_loss, '\n')
533
+ if data == 'Test':
534
+ print(f'Test Accuracy (%{batch_size * 100} of test samples): ', best_acc)
535
+ print(f'Test Loss (%{batch_size * 100} of test samples): ', best_loss, '\n')
536
+
537
+ # Display final visualizations
538
+ display_visualizations_for_learner(viz_objects, best_weights, data, best_acc, test_loss, y_train, interval)
539
+ return best_weights, best_model[get_preds()], best_acc, final_activations
540
+
541
+
542
+
543
+ def feed_forward(
544
+ Input, # list[num]: Input data.
545
+ w, # num: Weight matrix of the neural network.
546
+ is_training, # bool: Flag indicating if the function is called during training (True or False).
547
+ activation_potentiation,
548
+ Class='?', # int: Which class is, if training. # (list): Activation potentiation list for deep PLAN. (optional)
549
+ LTD=0
550
+ ) -> tuple:
551
+ """
552
+ Applies feature extraction process to the input data using synaptic potentiation.
553
+
554
+ Args:
555
+ Input (num): Input data.
556
+ w (num): Weight matrix of the neural network.
557
+ is_training (bool): Flag indicating if the function is called during training (True or False).
558
+ Class (int): if is during training then which class(label) ? is isnt then put None.
559
+ # activation_potentiation (list): ac list for deep PLAN. default: [None] ('linear') (optional)
560
+
561
+ Returns:
562
+ tuple: A tuple (vector) containing the neural layer result and the updated weight matrix.
563
+ or
564
+ num: neural network output
565
+ """
566
+
567
+ Output = apply_activation(Input, activation_potentiation)
568
+
569
+ Input = Output
570
+
571
+ if is_training == True:
572
+
573
+ for _ in range(LTD):
574
+
575
+ depression_vector = cp.random.rand(*Input.shape)
576
+
577
+ Input -= depression_vector
578
+
579
+ w[Class, :] = Input
580
+ return w
581
+
582
+ else:
583
+
584
+ neural_layer = cp.dot(w, Input)
585
+
586
+ return neural_layer
587
+
588
+
589
+ def evaluate(
590
+ x_test,
591
+ y_test,
592
+ W,
593
+ activation_potentiation=['linear'],
594
+ loading_bar_status=True,
595
+ show_metrics=False,
596
+ dtype=cp.float32
597
+ ) -> tuple:
598
+ """
599
+ Evaluates the neural network model using the given test data.
600
+
601
+ Args:
602
+ x_test (cp.ndarray): Test data.
603
+
604
+ y_test (cp.ndarray): Test labels (one-hot encoded).
605
+
606
+ W (list[cp.ndarray]): Neural net weight matrix.
607
+
608
+ activation_potentiation (list): Activation list. Default = ['linear'].
609
+
610
+ loading_bar_status (bool): Loading bar (optional). Default = True.
611
+
612
+ show_metrics (bool): Metrikleri gösterme seçeneği (isteğe bağlı). Default = False.
613
+
614
+ 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)
615
+
616
+ Returns:
617
+ tuple: Model (list).
618
+ """
619
+
620
+ x_test = cp.array(x_test, copy=False).astype(dtype, copy=False)
621
+
622
+ if len(y_test[0]) < 256:
623
+ y_type = cp.uint8
624
+ if y_test.dtype != cp.uint8:
625
+ y_test = cp.array(y_test, copy=False).astype(cp.uint8, copy=False)
626
+ elif len(y_test[0]) <= 32767:
627
+ y_type = cp.uint16
628
+ if y_test.dtype != cp.uint16:
629
+ y_test = cp.array(y_test, copy=False).astype(cp.uint16, copy=False)
630
+ else:
631
+ y_type = cp.uint32
632
+ if y_test.dtype != cp.uint32:
633
+ y_test = cp.array(y_test, copy=False).astype(cp.uint32, copy=False)
634
+
635
+
636
+ predict_probabilitys = cp.empty((len(x_test), W.shape[0]), dtype=dtype)
637
+ real_classes = cp.empty(len(x_test), dtype=y_type)
638
+ predict_classes = cp.empty(len(x_test), dtype=y_type)
639
+
640
+ true_predict = 0
641
+ acc_list = cp.empty(len(x_test), dtype=dtype)
642
+
643
+ if loading_bar_status:
644
+ loading_bar = initialize_loading_bar(total=len(x_test), ncols=64, desc='Testing', bar_format=bar_format_normal)
645
+
646
+ for inpIndex in range(len(x_test)):
647
+ Input = x_test[inpIndex].ravel()
648
+ neural_layer = Input
649
+
650
+ # Feedforward işlemi
651
+ neural_layer = feed_forward(neural_layer, cp.copy(W), is_training=False, Class='?', activation_potentiation=activation_potentiation)
652
+
653
+ # Olasılıkları ve tahminleri hesapla
654
+ predict_probabilitys[inpIndex] = Softmax(neural_layer)
655
+
656
+ RealOutput = cp.argmax(y_test[inpIndex])
657
+ real_classes[inpIndex] = RealOutput
658
+ PredictedOutput = cp.argmax(neural_layer)
659
+ predict_classes[inpIndex] = PredictedOutput
660
+
661
+ if RealOutput == PredictedOutput:
662
+ true_predict += 1
663
+
664
+ acc = true_predict / (inpIndex + 1)
665
+ acc_list[inpIndex] = acc
666
+
667
+ if loading_bar_status:
668
+ loading_bar.update(1)
669
+ loading_bar.set_postfix({"Test Accuracy": acc})
670
+
671
+ if loading_bar_status:
672
+ loading_bar.close()
673
+
674
+ if show_metrics:
675
+ plot_evaluate(x_test, y_test, predict_classes, acc_list, W=cp.copy(W), activation_potentiation=activation_potentiation)
676
+
677
+ return W, predict_classes, acc_list[-1], None, None, predict_probabilitys