pyerualjetwork 2.0.4__py3-none-any.whl → 2.0.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.
plan/plan_bi.py ADDED
@@ -0,0 +1,1004 @@
1
+ """
2
+ Created on Thu May 30 22:12:49 2024
3
+
4
+ @author: hasan can beydili
5
+ """
6
+ import numpy as np
7
+ import time
8
+ from colorama import Fore,Style
9
+ from typing import List, Union
10
+ import math
11
+ from scipy.special import expit, softmax
12
+ import matplotlib.pyplot as plt
13
+ import seaborn as sns
14
+
15
+ # BUILD -----
16
+ def fit(
17
+ x_train: List[Union[int, float]],
18
+ y_train: List[Union[int, float, str]], # At least two.. and one hot encoded
19
+ activation_potential: Union[float],
20
+ ) -> str:
21
+
22
+ infoPLAN = """
23
+ Creates and configures a PLAN model.
24
+
25
+ Args:
26
+ x_train (list[num]): List of input data.
27
+ y_train (list[num]): List of y_train. (one hot encoded)
28
+ activation_potential (float): Input activation potential
29
+
30
+ Returns:
31
+ list([num]): (Weight matrices list, train_predictions list, Train_acc).
32
+ error handled ?: Process status ('e')
33
+ """
34
+
35
+ if activation_potential < 0 or activation_potential > 1:
36
+
37
+ print(Fore.RED + "ERROR101: ACTIVATION potential value must be in range 0-1. from: fit",infoPLAN)
38
+ return 'e'
39
+
40
+ if len(x_train) != len(y_train):
41
+ print(Fore.RED + "ERROR301: x_train list and y_train list must be same length. from: fit",infoPLAN)
42
+ return 'e'
43
+
44
+ class_count = set()
45
+ for sublist in y_train:
46
+
47
+ class_count.add(tuple(sublist))
48
+
49
+
50
+ class_count = list(class_count)
51
+
52
+ y_train = [tuple(sublist) for sublist in y_train]
53
+
54
+ neurons = [len(class_count),len(class_count)]
55
+ layers = ['fex','cat']
56
+
57
+ x_train[0] = np.array(x_train[0])
58
+ x_train[0] = x_train[0].ravel()
59
+ x_train_size = len(x_train[0])
60
+
61
+ W = weight_identification(len(layers) - 1,len(class_count),neurons,x_train_size)
62
+ Divides, Piece = synaptic_dividing(len(class_count),W)
63
+ trained_W = [1] * len(W)
64
+ print(Fore.GREEN + "Train Started with 0 ERROR" + Style.RESET_ALL,)
65
+ train_predictions = [None] * len(y_train)
66
+ true = 0
67
+ start_time = time.time()
68
+ for index, inp in enumerate(x_train):
69
+ uni_start_time = time.time()
70
+ inp = np.array(inp)
71
+ inp = inp.ravel()
72
+
73
+ if x_train_size != len(inp):
74
+ print(Fore.RED +"ERROR304: All input matrices or vectors in x_train list, must be same size. from: fit",infoPLAN + Style.RESET_ALL)
75
+ return 'e'
76
+
77
+
78
+ for Ulindex, Ul in enumerate(class_count):
79
+
80
+ if Ul == y_train[index]:
81
+ for Windex, w in enumerate(W):
82
+ for i, ul in enumerate(Ul):
83
+ if ul == 1.0:
84
+ k = i
85
+
86
+ cs = Divides[int(k)][Windex][0]
87
+
88
+
89
+ W[Windex] = synaptic_pruning(w, cs, 'row', int(k),len(class_count),Piece[Windex],1)
90
+
91
+ neural_layer = inp
92
+
93
+ for Lindex, Layer in enumerate(layers):
94
+
95
+
96
+ neural_layer = normalization(neural_layer)
97
+
98
+
99
+ if Layer == 'fex':
100
+ neural_layer,W[Lindex] = fex(neural_layer, W[Lindex], activation_potential, Piece[Windex], 1)
101
+ elif Layer == 'cat':
102
+ neural_layer,W[Lindex] = cat(neural_layer, W[Lindex], activation_potential, 1, Piece[Windex])
103
+
104
+ RealOutput = np.argmax(y_train[index])
105
+ PredictedOutput = np.argmax(neural_layer)
106
+ if RealOutput == PredictedOutput:
107
+ true += 1
108
+ acc = true / len(y_train)
109
+ train_predictions[index] = PredictedOutput
110
+
111
+ for i, w in enumerate(W):
112
+ trained_W[i] = trained_W[i] + w
113
+
114
+
115
+ W = weight_identification(len(layers) - 1, len(class_count), neurons, x_train_size)
116
+
117
+
118
+ uni_end_time = time.time()
119
+
120
+ calculating_est = round((uni_end_time - uni_start_time) * (len(x_train) - index),3)
121
+
122
+ if calculating_est < 60:
123
+ print('\rest......(sec):',calculating_est,'\n',end= "")
124
+ print('\rTrain accuracy: ' ,acc ,"\n", end="")
125
+
126
+ elif calculating_est > 60 and calculating_est < 3600:
127
+ print('\rest......(min):',calculating_est/60,'\n',end= "")
128
+ print('\rTrain accuracy: ' ,acc ,"\n", end="")
129
+
130
+ elif calculating_est > 3600:
131
+ print('\rest......(h):',calculating_est/3600,'\n',end= "")
132
+ print('\rTrain accuracy: ' ,acc ,"\n", end="")
133
+
134
+ EndTime = time.time()
135
+
136
+ calculating_est = round(EndTime - start_time,2)
137
+
138
+ print(Fore.GREEN + " \nTrain Finished with 0 ERROR\n")
139
+
140
+ if calculating_est < 60:
141
+ print('Total training time(sec): ',calculating_est)
142
+
143
+ elif calculating_est > 60 and calculating_est < 3600:
144
+ print('Total training time(min): ',calculating_est/60)
145
+
146
+ elif calculating_est > 3600:
147
+ print('Total training time(h): ',calculating_est/3600)
148
+
149
+ if acc > 0.8:
150
+ print(Fore.GREEN + '\nTotal Train accuracy: ' ,acc, '\n',Style.RESET_ALL)
151
+
152
+ elif acc < 0.8 and acc > 0.6:
153
+ print(Fore.MAGENTA + '\nTotal Train accuracy: ' ,acc, '\n',Style.RESET_ALL)
154
+
155
+ elif acc < 0.6:
156
+ print(Fore.RED+ '\nTotal Train accuracy: ' ,acc, '\n',Style.RESET_ALL)
157
+
158
+
159
+
160
+
161
+ return trained_W,train_predictions,acc
162
+
163
+ # FUNCTIONS -----
164
+
165
+ def weight_identification(
166
+ layer_count, # int: Number of layers in the neural network.
167
+ class_count, # int: Number of classes in the classification task.
168
+ neurons, # list[num]: List of neuron counts for each layer.
169
+ x_train_size # int: Size of the input data.
170
+ ) -> str:
171
+ """
172
+ Identifies the weights for a neural network model.
173
+
174
+ Args:
175
+ layer_count (int): Number of layers in the neural network.
176
+ class_count (int): Number of classes in the classification task.
177
+ neurons (list[num]): List of neuron counts for each layer.
178
+ x_train_size (int): Size of the input data.
179
+
180
+ Returns:
181
+ list([numpy_arrays],[...]): Weight matices of the model. .
182
+ """
183
+
184
+
185
+ Wlen = layer_count + 1
186
+ W = [None] * Wlen
187
+ W[0] = np.ones((neurons[0],x_train_size))
188
+ ws = layer_count - 1
189
+ for w in range(ws):
190
+ W[w + 1] = np.ones((neurons[w + 1],neurons[w]))
191
+ W[layer_count] = np.ones((class_count,neurons[layer_count - 1]))
192
+ return W
193
+
194
+ def synaptic_pruning(
195
+ w, # list[list[num]]: Weight matrix of the neural network.
196
+ cs, # list[list[num]]: Synaptic connections between neurons.
197
+ key, # int: key for identifying synaptic connections.
198
+ Class, # int: Class label for the current training instance.
199
+ class_count, # int: Total number of classes in the dataset.
200
+ piece, # ???
201
+ is_training # int: 1 or 0
202
+
203
+ ) -> str:
204
+ infoPruning = """
205
+ Performs synaptic pruning in a neural network model.
206
+
207
+ Args:
208
+ w (list[list[num]]): Weight matrix of the neural network.
209
+ cs (list[list[num]]): Synaptic connections between neurons.
210
+ key (str): key for identifying synaptic row or col connections.
211
+ Class (int): Class label for the current training instance.
212
+ class_count (int): Total number of classes in the dataset.
213
+
214
+ Returns:
215
+ numpy array: Weight matrix.
216
+ """
217
+
218
+
219
+ Class += 1 # because index start 0
220
+
221
+ if Class != 1:
222
+
223
+
224
+
225
+ ce = cs / Class
226
+
227
+ if is_training == 1:
228
+
229
+ p = piece
230
+
231
+ for i in range(Class - 3):
232
+
233
+ piece+=p
234
+
235
+ if Class!= 2:
236
+ ce += piece
237
+
238
+ w[int(ce)-1::-1,:] = 0
239
+
240
+
241
+ w[cs:,:] = 0
242
+
243
+ else:
244
+
245
+ if Class == 1:
246
+ if key == 'row':
247
+
248
+ w[cs:,:] = 0
249
+
250
+ elif key == 'col':
251
+
252
+ w[:,cs] = 0
253
+
254
+ else:
255
+ print(Fore.RED + "ERROR103: synaptic_pruning func's key parameter must be 'row' or 'col' from: synaptic_pruning" + infoPruning)
256
+ return 'e'
257
+ else:
258
+ if key == 'row':
259
+
260
+ w[cs:,:] = 0
261
+
262
+ ce = int(round(w.shape[0] - cs / class_count))
263
+ w[ce-1::-1,:] = 0
264
+
265
+ elif key == 'col':
266
+
267
+ w[:,cs] = 0
268
+
269
+ else:
270
+ print(Fore.RED + "ERROR103: synaptic_pruning func's key parameter must be 'row' or 'col' from: synaptic_pruning" + infoPruning + Style.RESET_ALL)
271
+ return 'e'
272
+ return w
273
+
274
+ def synaptic_dividing(
275
+ class_count, # int: Total number of classes in the dataset.
276
+ W # list[list[num]]: Weight matrix of the neural network.
277
+ ) -> str:
278
+ """
279
+ Divides the synaptic weights of a neural network model based on class count.
280
+
281
+ Args:
282
+ class_count (int): Total number of classes in the dataset.
283
+ W (list[list[num]]): Weight matrix of the neural network.
284
+
285
+ Returns:
286
+ list: a 3D list holds informations of divided net.
287
+ """
288
+
289
+
290
+ Piece = [1] * len(W)
291
+ #print('Piece:' + Piece)
292
+ #input()
293
+ # Boş bir üç boyutlu liste oluşturma
294
+ Divides = [[[0] for _ in range(len(W))] for _ in range(class_count)]
295
+
296
+
297
+ for i in range(len(W)):
298
+
299
+
300
+ Piece[i] = int(math.floor(W[i].shape[0] / class_count))
301
+
302
+ cs = 0
303
+ # j = Classes, i = Weights, [0] = CutStart.
304
+
305
+ for i in range(len(W)):
306
+ for j in range(class_count):
307
+ cs = cs + Piece[i]
308
+ Divides[j][i][0] = cs
309
+ #pruning_param[i] = cs
310
+ #print('Divides: ' + j + i + ' = ' + Divides[j][i][0])
311
+ #input()
312
+
313
+ j = 0
314
+ cs = 0
315
+
316
+ return Divides, Piece
317
+
318
+
319
+ def fex(
320
+ Input, # list[num]: Input data.
321
+ w, # list[list[num]]: Weight matrix of the neural network.,
322
+ activation_potential, # num: Threshold value for comparison.
323
+ piece, # ???
324
+ is_training # num: 1 or 0
325
+ ) -> tuple:
326
+ """
327
+ Applies feature extraction process to the input data using synaptic pruning.
328
+
329
+ Args:
330
+ Input (list[num]): Input data.
331
+ w (list[list[num]]): Weight matrix of the neural network.
332
+ ACTIVATION_threshold (str): Sign for threshold comparison ('<', '>', '==', '!=').
333
+ activation_potential (num): Threshold value for comparison.
334
+
335
+ Returns:
336
+ tuple: A tuple (vector) containing the neural layer result and the updated weight matrix.
337
+ """
338
+
339
+
340
+ PruneIndex = np.where(Input < activation_potential)
341
+ w = synaptic_pruning(w, PruneIndex, 'col', 0, 0, piece, is_training)
342
+
343
+ neural_layer = np.dot(w, Input)
344
+
345
+ return neural_layer,w
346
+
347
+ def cat(
348
+ Input, # list[num]: Input data.
349
+ w, # list[list[num]]: Weight matrix of the neural network.
350
+ activation_potential, # num: Threshold value for comparison.
351
+ isTrain,
352
+ piece # int: Flag indicating if the function is called during training (1 for training, 0 otherwise).
353
+ ) -> tuple:
354
+ """
355
+ Applies categorization process to the input data using synaptic pruning if specified.
356
+
357
+ Args:
358
+ Input (list[num]): Input data.
359
+ w (list[list[num]]): Weight matrix of the neural network.
360
+ ACTIVATION_threshold (str): Sign for threshold comparison ('<', '>', '==', '!=').
361
+ activation_potential (num): Threshold value for comparison.
362
+ isTrain (int): Flag indicating if the function is called during training (1 for training, 0 otherwise).
363
+
364
+ Returns:
365
+ tuple: A tuple containing the neural layer (vector) result and the possibly updated weight matrix.
366
+ """
367
+
368
+ PruneIndex = np.where(Input == 0)
369
+
370
+ if isTrain == 1:
371
+
372
+ w = synaptic_pruning(w, PruneIndex, 'col', 0, 0, piece, isTrain)
373
+
374
+
375
+ neural_layer = np.dot(w, Input)
376
+
377
+ return neural_layer,w
378
+
379
+
380
+ def normalization(
381
+ Input # list[num]: Input data to be normalized.
382
+ ):
383
+ """
384
+ Normalizes the input data using maximum absolute scaling.
385
+
386
+ Args:
387
+ Input (list[num]): Input data to be normalized.
388
+
389
+ Returns:
390
+ list[num]: Scaled input data after normalization.
391
+ """
392
+
393
+
394
+ AbsVector = np.abs(Input)
395
+
396
+ MaxAbs = np.max(AbsVector)
397
+
398
+ ScaledInput = Input / MaxAbs
399
+
400
+ return ScaledInput
401
+
402
+
403
+ def Softmax(
404
+ x # list[num]: Input data to be transformed using softmax function.
405
+ ):
406
+ """
407
+ Applies the softmax function to the input data.
408
+
409
+ Args:
410
+ x (list[num]): Input data to be transformed using softmax function.
411
+
412
+ Returns:
413
+ list[num]: Transformed data after applying softmax function.
414
+ """
415
+
416
+ return softmax(x)
417
+
418
+
419
+ def Sigmoid(
420
+ x # list[num]: Input data to be transformed using sigmoid function.
421
+ ):
422
+ """
423
+ Applies the sigmoid function to the input data.
424
+
425
+ Args:
426
+ x (list[num]): Input data to be transformed using sigmoid function.
427
+
428
+ Returns:
429
+ list[num]: Transformed data after applying sigmoid function.
430
+ """
431
+ return expit(x)
432
+
433
+
434
+ def Relu(
435
+ x # list[num]: Input data to be transformed using ReLU function.
436
+ ):
437
+ """
438
+ Applies the Rectified Linear Unit (ReLU) function to the input data.
439
+
440
+ Args:
441
+ x (list[num]): Input data to be transformed using ReLU function.
442
+
443
+ Returns:
444
+ list[num]: Transformed data after applying ReLU function.
445
+ """
446
+
447
+
448
+ return np.maximum(0, x)
449
+
450
+
451
+
452
+
453
+ def evaluate(
454
+ x_test, # list[list[num]]: Test input data.
455
+ y_test, # list[num]: Test labels.
456
+ activation_potential, # list[num]: List of ACTIVATION POTENTIALS for each layer.
457
+ visualize, # visualize Testing procces or not visualize ('y' or 'n')
458
+ W # list[list[num]]: Weight matrix of the neural network.
459
+ ) -> tuple:
460
+ infoTestModel = """
461
+ Tests the neural network model with the given test data.
462
+
463
+ Args:
464
+ x_test (list[list[num]]): Test input data.
465
+ y_test (list[num]): Test labels.
466
+ activation_potential (float): Input activation potential
467
+ visualize (str): Visualize test progress ? ('y' or 'n')
468
+ W (list[list[num]]): Weight matrix of the neural network.
469
+
470
+ Returns:
471
+ tuple: A tuple containing the predicted labels and the accuracy of the model.
472
+ """
473
+
474
+ layers = ['fex','cat']
475
+
476
+
477
+ try:
478
+ Wc = [0] * len(W)
479
+ true = 0
480
+ TestPredictions = [None] * len(y_test)
481
+ for i, w in enumerate(W):
482
+ Wc[i] = np.copy(w)
483
+ print('\rCopying weights.....',i+1,'/',len(W),end = "")
484
+
485
+ print(Fore.GREEN + "\n\nTest Started with 0 ERROR\n" + Style.RESET_ALL)
486
+ start_time = time.time()
487
+ for inpIndex,Input in enumerate(x_test):
488
+ Input = np.array(Input)
489
+ Input = Input.ravel()
490
+ uni_start_time = time.time()
491
+ neural_layer = Input
492
+
493
+ for index, Layer in enumerate(layers):
494
+
495
+ neural_layer = normalization(neural_layer)
496
+
497
+ if layers[index] == 'fex':
498
+ neural_layer = fex(neural_layer, W[index], activation_potential, 0, 0)[0]
499
+ if layers[index] == 'cat':
500
+ neural_layer = cat(neural_layer, W[index], activation_potential, 0, 0)[0]
501
+
502
+ for i, w in enumerate(Wc):
503
+ W[i] = np.copy(w)
504
+ RealOutput = np.argmax(y_test[inpIndex])
505
+ PredictedOutput = np.argmax(neural_layer)
506
+ if RealOutput == PredictedOutput:
507
+ true += 1
508
+ acc = true / len(y_test)
509
+ TestPredictions[inpIndex] = PredictedOutput
510
+
511
+ if visualize == 'y':
512
+
513
+ y_testVisual = np.copy(y_test)
514
+ y_testVisual = np.argmax(y_testVisual, axis=1)
515
+
516
+ plt.figure(figsize=(12, 6))
517
+ sns.kdeplot(y_testVisual, label='Real Outputs', fill=True)
518
+ sns.kdeplot(TestPredictions, label='Predictions', fill=True)
519
+ plt.legend()
520
+ plt.xlabel('Class')
521
+ plt.ylabel('Data size')
522
+ plt.title('Predictions and Real Outputs for Testing KDE Plot')
523
+ plt.show()
524
+
525
+ if inpIndex + 1 != len(x_test):
526
+
527
+ plt.close('all')
528
+
529
+ uni_end_time = time.time()
530
+
531
+ calculating_est = round((uni_end_time - uni_start_time) * (len(x_test) - inpIndex),3)
532
+
533
+ if calculating_est < 60:
534
+ print('\rest......(sec):',calculating_est,'\n',end= "")
535
+ print('\rTest accuracy: ' ,acc ,"\n", end="")
536
+
537
+ elif calculating_est > 60 and calculating_est < 3600:
538
+ print('\rest......(min):',calculating_est/60,'\n',end= "")
539
+ print('\rTest accuracy: ' ,acc ,"\n", end="")
540
+
541
+ elif calculating_est > 3600:
542
+ print('\rest......(h):',calculating_est/3600,'\n',end= "")
543
+ print('\rTest accuracy: ' ,acc ,"\n", end="")
544
+
545
+ EndTime = time.time()
546
+ for i, w in enumerate(Wc):
547
+ W[i] = np.copy(w)
548
+
549
+ calculating_est = round(EndTime - start_time,2)
550
+
551
+ print(Fore.GREEN + "\nTest Finished with 0 ERROR\n")
552
+
553
+ if calculating_est < 60:
554
+ print('Total testing time(sec): ',calculating_est)
555
+
556
+ elif calculating_est > 60 and calculating_est < 3600:
557
+ print('Total testing time(min): ',calculating_est/60)
558
+
559
+ elif calculating_est > 3600:
560
+ print('Total testing time(h): ',calculating_est/3600)
561
+
562
+ if acc >= 0.8:
563
+ print(Fore.GREEN + '\nTotal Test accuracy: ' ,acc, '\n' + Style.RESET_ALL)
564
+
565
+ elif acc < 0.8 and acc > 0.6:
566
+ print(Fore.MAGENTA + '\nTotal Test accuracy: ' ,acc, '\n' + Style.RESET_ALL)
567
+
568
+ elif acc <= 0.6:
569
+ print(Fore.RED+ '\nTotal Test accuracy: ' ,acc, '\n' + Style.RESET_ALL)
570
+
571
+
572
+
573
+ except:
574
+
575
+ print(Fore.RED + "ERROR: Testing model parameters like 'activation_potential' must be same as trained model. Check parameters. Are you sure weights are loaded ? from: evaluate" + infoTestModel + Style.RESET_ALL)
576
+ return 'e'
577
+
578
+
579
+
580
+ return W,TestPredictions,acc
581
+
582
+ def save_model(model_name,
583
+ model_type,
584
+ class_count,
585
+ activation_potential,
586
+ test_acc,
587
+ weights_type,
588
+ weights_format,
589
+ model_path,
590
+ W
591
+ ):
592
+
593
+ infosave_model = """
594
+ Function to save a pruning learning model.
595
+
596
+ Arguments:
597
+ model_name (str): Name of the model.
598
+ model_type (str): Type of the model.(options: PLAN)
599
+ class_count (int): Number of classes.
600
+ activation_potential (float): Activation potential.
601
+ test_acc (float): Test accuracy of the model.
602
+ weights_type (str): Type of weights to save (options: 'txt', 'npy', 'mat').
603
+ WeightFormat (str): Format of the weights (options: 'd', 'f', 'raw').
604
+ model_path (str): Path where the model will be saved. For example: C:/Users/beydili/Desktop/denemePLAN/
605
+ W: Weights of the model.
606
+
607
+ Returns:
608
+ str: Message indicating if the model was saved successfully or encountered an error.
609
+ """
610
+
611
+ # Operations to be performed by the function will be written here
612
+ pass
613
+
614
+ layers = ['fex','cat']
615
+
616
+ if weights_type != 'txt' and weights_type != 'npy' and weights_type != 'mat':
617
+ print(Fore.RED + "ERROR110: Save Weight type (File Extension) Type must be 'txt' or 'npy' or 'mat' from: save_model" + infosave_model + Style.RESET_ALL)
618
+ return 'e'
619
+
620
+ if weights_format != 'd' and weights_format != 'f' and weights_format != 'raw':
621
+ print(Fore.RED + "ERROR111: Weight Format Type must be 'd' or 'f' or 'raw' from: save_model" + infosave_model + Style.RESET_ALL)
622
+ return 'e'
623
+
624
+ NeuronCount = 0
625
+ SynapseCount = 0
626
+
627
+ try:
628
+ for w in W:
629
+ NeuronCount += np.shape(w)[0]
630
+ SynapseCount += np.shape(w)[0] * np.shape(w)[1]
631
+ except:
632
+
633
+ print(Fore.RED + "ERROR: Weight matrices has a problem from: save_model" + infosave_model + Style.RESET_ALL)
634
+ return 'e'
635
+ import pandas as pd
636
+ from datetime import datetime
637
+ from scipy import io
638
+
639
+ data = {'MODEL NAME': model_name,
640
+ 'MODEL TYPE': model_type,
641
+ 'LAYERS': layers,
642
+ 'LAYER COUNT': len(layers),
643
+ 'CLASS COUNT': class_count,
644
+ 'ACTIVATION POTENTIAL': activation_potential,
645
+ 'NEURON COUNT': NeuronCount,
646
+ 'SYNAPSE COUNT': SynapseCount,
647
+ 'TEST ACCURACY': test_acc,
648
+ 'SAVE DATE': datetime.now(),
649
+ 'WEIGHTS TYPE': weights_type,
650
+ 'WEIGHTS FORMAT': weights_format,
651
+ 'MODEL PATH': model_path
652
+ }
653
+ try:
654
+
655
+ df = pd.DataFrame(data)
656
+
657
+
658
+ df.to_csv(model_path + model_name + '.txt', sep='\t', index=False)
659
+
660
+
661
+ except:
662
+
663
+ print(Fore.RED + "ERROR: Model log not saved probably model_path incorrect. Check the log parameters from: save_model" + infosave_model + Style.RESET_ALL)
664
+ return 'e'
665
+ try:
666
+
667
+ if weights_type == 'txt' and weights_format == 'd':
668
+
669
+ for i, w in enumerate(W):
670
+ np.savetxt(model_path + model_name + str(i+1) + 'w.txt' , w, fmt='%d')
671
+
672
+ if weights_type == 'txt' and weights_format == 'f':
673
+
674
+ for i, w in enumerate(W):
675
+ np.savetxt(model_path + model_name + str(i+1) + 'w.txt' , w, fmt='%f')
676
+
677
+ if weights_type == 'txt' and weights_format == 'raw':
678
+
679
+ for i, w in enumerate(W):
680
+ np.savetxt(model_path + model_name + str(i+1) + 'w.txt' , w)
681
+
682
+
683
+ ###
684
+
685
+
686
+ if weights_type == 'npy' and weights_format == 'd':
687
+
688
+ for i, w in enumerate(W):
689
+ np.save(model_path + model_name + str(i+1) + 'w.npy', w.astype(int))
690
+
691
+ if weights_type == 'npy' and weights_format == 'f':
692
+
693
+ for i, w in enumerate(W):
694
+ np.save(model_path + model_name + str(i+1) + 'w.npy' , w, w.astype(float))
695
+
696
+ if weights_type == 'npy' and weights_format == 'raw':
697
+
698
+ for i, w in enumerate(W):
699
+ np.save(model_path + model_name + str(i+1) + 'w.npy' , w)
700
+
701
+
702
+ ###
703
+
704
+
705
+ if weights_type == 'mat' and weights_format == 'd':
706
+
707
+ for i, w in enumerate(W):
708
+ w = {'w': w.astype(int)}
709
+ io.savemat(model_path + model_name + str(i+1) + 'w.mat', w)
710
+
711
+ if weights_type == 'mat' and weights_format == 'f':
712
+
713
+ for i, w in enumerate(W):
714
+ w = {'w': w.astype(float)}
715
+ io.savemat(model_path + model_name + str(i+1) + 'w.mat', w)
716
+
717
+ if weights_type == 'mat' and weights_format == 'raw':
718
+
719
+ for i, w in enumerate(W):
720
+ w = {'w': w}
721
+ io.savemat(model_path + model_name + str(i+1) + 'w.mat', w)
722
+
723
+ except:
724
+
725
+ print(Fore.RED + "ERROR: Model Weights not saved. Check the Weight parameters. SaveFilePath expl: 'C:/Users/hasancanbeydili/Desktop/denemePLAN/' from: save_model" + infosave_model + Style.RESET_ALL)
726
+ return 'e'
727
+ print(df)
728
+ message = (
729
+ Fore.GREEN + "Model Saved Successfully\n" +
730
+ Fore.MAGENTA + "Don't forget, if you want to load model: model log file and weight files must be in the same directory." +
731
+ Style.RESET_ALL
732
+ )
733
+
734
+ return print(message)
735
+
736
+
737
+ def load_model(model_name,
738
+ model_path,
739
+ ):
740
+ infoload_model = """
741
+ Function to load a pruning learning model.
742
+
743
+ Arguments:
744
+ model_name (str): Name of the model.
745
+ model_path (str): Path where the model is saved.
746
+ log_type (str): Type of log to load (options: 'csv', 'txt', 'hdf5').
747
+
748
+ Returns:
749
+ lists: W(list[num]), activation_potential, df (DataFrame of the model)
750
+ """
751
+ pass
752
+
753
+
754
+ import pandas as pd
755
+ import scipy.io as sio
756
+
757
+ try:
758
+
759
+ df = pd.read_csv(model_path + model_name + '.' + 'txt', delimiter='\t')
760
+
761
+ except:
762
+
763
+ print(Fore.RED + "ERROR: Model Path error. accaptable form: 'C:/Users/hasancanbeydili/Desktop/denemePLAN/' from: load_model" + infoload_model + Style.RESET_ALL)
764
+
765
+ model_name = str(df['MODEL NAME'].iloc[0])
766
+ layers = df['LAYERS'].tolist()
767
+ layer_count = int(df['LAYER COUNT'].iloc[0])
768
+ class_count = int(df['CLASS COUNT'].iloc[0])
769
+ activation_potential = int(df['ACTIVATION POTENTIAL'].iloc[0])
770
+ NeuronCount = int(df['NEURON COUNT'].iloc[0])
771
+ SynapseCount = int(df['SYNAPSE COUNT'].iloc[0])
772
+ test_acc = int(df['TEST ACCURACY'].iloc[0])
773
+ model_type = str(df['MODEL TYPE'].iloc[0])
774
+ WeightType = str(df['WEIGHTS TYPE'].iloc[0])
775
+ WeightFormat = str(df['WEIGHTS FORMAT'].iloc[0])
776
+ model_path = str(df['MODEL PATH'].iloc[0])
777
+
778
+ W = [0] * layer_count
779
+
780
+ if WeightType == 'txt':
781
+ for i in range(layer_count):
782
+ W[i] = np.loadtxt(model_path + model_name + str(i+1) + 'w.txt')
783
+ elif WeightType == 'npy':
784
+ for i in range(layer_count):
785
+ W[i] = np.load(model_path + model_name + str(i+1) + 'w.npy')
786
+ elif WeightType == 'mat':
787
+ for i in range(layer_count):
788
+ W[i] = sio.loadmat(model_path + model_name + str(i+1) + 'w.mat')
789
+ else:
790
+ raise ValueError(Fore.RED + "Incorrect weight type value. Value must be 'txt', 'npy' or 'mat' from: load_model." + infoload_model + Style.RESET_ALL)
791
+ print(Fore.GREEN + "Model loaded succesfully" + Style.RESET_ALL)
792
+ return W,activation_potential,df
793
+
794
+ def predict_model_ssd(Input,model_name,model_path):
795
+
796
+ infopredict_model_ssd = """
797
+ Function to make a prediction using a divided pruning learning artificial neural network (PLAN).
798
+
799
+ Arguments:
800
+ Input (list or ndarray): Input data for the model (single vector or single matrix).
801
+ model_name (str): Name of the model.
802
+ model_path (str): Path where the model is saved.
803
+ Returns:
804
+ ndarray: Output from the model.
805
+ """
806
+ W,activation_potential = load_model(model_name,model_path)[0:2]
807
+
808
+ layers = ['fex','cat']
809
+
810
+ Wc = [0] * len(W)
811
+ for i, w in enumerate(W):
812
+ Wc[i] = np.copy(w)
813
+ try:
814
+ neural_layer = Input
815
+ neural_layer = np.array(neural_layer)
816
+ neural_layer = neural_layer.ravel()
817
+ for index, Layer in enumerate(layers):
818
+
819
+ neural_layer = normalization(neural_layer)
820
+
821
+ if layers[index] == 'fex':
822
+ neural_layer = fex(neural_layer, W[index], activation_potential,0, 0)[0]
823
+ if layers[index] == 'cat':
824
+ neural_layer = cat(neural_layer, W[index], activation_potential, 0, 0)[0]
825
+ except:
826
+ print(Fore.RED + "ERROR: The input was probably entered incorrectly. from: predict_model_ssd" + infopredict_model_ssd + Style.RESET_ALL)
827
+ return 'e'
828
+ for i, w in enumerate(Wc):
829
+ W[i] = np.copy(w)
830
+ return neural_layer
831
+
832
+
833
+ def predict_model_ram(Input,activation_potential,W):
834
+
835
+ infopredict_model_ram = """
836
+ Function to make a prediction using a divided pruning learning artificial neural network (PLAN).
837
+ from weights and parameters stored in memory.
838
+
839
+ Arguments:
840
+ Input (list or ndarray): Input data for the model (single vector or single matrix).
841
+ activation_potential (float): Activation potential.
842
+ W (list of ndarrays): Weights of the model.
843
+
844
+ Returns:
845
+ ndarray: Output from the model.
846
+ """
847
+
848
+ layers = ['fex','cat']
849
+
850
+ Wc = [0] * len(W)
851
+ for i, w in enumerate(W):
852
+ Wc[i] = np.copy(w)
853
+ try:
854
+ neural_layer = Input
855
+ neural_layer = np.array(neural_layer)
856
+ neural_layer = neural_layer.ravel()
857
+ for index, Layer in enumerate(layers):
858
+
859
+ neural_layer = normalization(neural_layer)
860
+
861
+ if layers[index] == 'fex':
862
+ neural_layer = fex(neural_layer, W[index], activation_potential,0, 0)[0]
863
+ if layers[index] == 'cat':
864
+ neural_layer = cat(neural_layer, W[index], activation_potential, 0, 0)[0]
865
+
866
+ except:
867
+ print(Fore.RED + "ERROR: Unexpected input or wrong model parameters from: predict_model_ram." + infopredict_model_ram + Style.RESET_ALL)
868
+ return 'e'
869
+ for i, w in enumerate(Wc):
870
+ W[i] = np.copy(w)
871
+ return neural_layer
872
+
873
+
874
+ def auto_balancer(x_train, y_train, class_count):
875
+
876
+ infoauto_balancer = """
877
+ Function to balance the training data across different classes.
878
+
879
+ Arguments:
880
+ x_train (list): Input data for training.
881
+ y_train (list): Labels corresponding to the input data.
882
+ class_count (int): Number of classes.
883
+
884
+ Returns:
885
+ tuple: A tuple containing balanced input data and labels.
886
+ """
887
+ try:
888
+ ClassIndices = {i: np.where(np.array(y_train)[:, i] == 1)[0] for i in range(class_count)}
889
+ classes = [len(ClassIndices[i]) for i in range(class_count)]
890
+
891
+ if len(set(classes)) == 1:
892
+ print(Fore.WHITE + "INFO: All training data have already balanced. from: auto_balancer" + Style.RESET_ALL)
893
+ return x_train, y_train
894
+
895
+ MinCount = min(classes)
896
+
897
+ BalancedIndices = []
898
+ for i in range(class_count):
899
+ if len(ClassIndices[i]) > MinCount:
900
+ SelectedIndices = np.random.choice(ClassIndices[i], MinCount, replace=False)
901
+ else:
902
+ SelectedIndices = ClassIndices[i]
903
+ BalancedIndices.extend(SelectedIndices)
904
+
905
+ BalancedInputs = [x_train[idx] for idx in BalancedIndices]
906
+ BalancedLabels = [y_train[idx] for idx in BalancedIndices]
907
+
908
+ print(Fore.GREEN + "All Training Data Succesfully Balanced from: " + str(len(x_train)) + " to: " + str(len(BalancedInputs)) + ". from: auto_balancer " + Style.RESET_ALL)
909
+ except:
910
+ print(Fore.RED + "ERROR: Inputs and labels must be same length check parameters" + infoauto_balancer)
911
+ return 'e'
912
+
913
+ return BalancedInputs, BalancedLabels
914
+
915
+ def synthetic_augmentation(x, y, class_count):
916
+ """
917
+ Generates synthetic examples to balance classes with fewer examples.
918
+
919
+ Arguments:
920
+ x -- Input dataset (examples) - list format
921
+ y -- Class labels (one-hot encoded) - list format
922
+ class_count -- Number of classes
923
+
924
+ Returns:
925
+ x_balanced -- Balanced input dataset (list format)
926
+ y_balanced -- Balanced class labels (one-hot encoded, list format)
927
+ """
928
+ # Calculate class distribution
929
+ class_distribution = {i: 0 for i in range(class_count)}
930
+ for label in y:
931
+ class_distribution[np.argmax(label)] += 1
932
+
933
+ max_class_count = max(class_distribution.values())
934
+
935
+ x_balanced = list(x)
936
+ y_balanced = list(y)
937
+
938
+ for class_label in range(class_count):
939
+ class_indices = [i for i, label in enumerate(y) if np.argmax(label) == class_label]
940
+ num_samples = len(class_indices)
941
+
942
+ if num_samples < max_class_count:
943
+ while num_samples < max_class_count:
944
+ # Select two random examples
945
+ random_indices = np.random.choice(class_indices, 2, replace=False)
946
+ sample1 = x[random_indices[0]]
947
+ sample2 = x[random_indices[1]]
948
+
949
+ # Generate a new synthetic example between the two selected examples
950
+ synthetic_sample = sample1 + (np.array(sample2) - np.array(sample1)) * np.random.rand()
951
+
952
+ x_balanced.append(synthetic_sample.tolist())
953
+ y_balanced.append(y[class_indices[0]]) # The new example has the same class label
954
+
955
+ num_samples += 1
956
+
957
+ return np.array(x_balanced), np.array(y_balanced)
958
+
959
+ def standard_scaler(x_train, x_test):
960
+ info_standard_scaler = """
961
+ Standardizes training and test datasets.
962
+
963
+ Args:
964
+ train_data: numpy.ndarray
965
+ Training data (n_samples, n_features)
966
+ test_data: numpy.ndarray
967
+ Test data (n_samples, n_features)
968
+
969
+ Returns:
970
+ tuple
971
+ Standardized training and test datasets
972
+ """
973
+ try:
974
+ mean = np.mean(x_train, axis=0)
975
+ std = np.std(x_train, axis=0)
976
+
977
+
978
+ train_data_scaled = (x_train - mean) / std
979
+ test_data_scaled = (x_test - mean) / std
980
+
981
+ except:
982
+ print(Fore.RED + "ERROR: x_train and x_test must be numpy array from standard_scaler" + info_standard_scaler)
983
+
984
+ return train_data_scaled, test_data_scaled
985
+
986
+ def get_weights():
987
+
988
+ return 0
989
+
990
+ def get_df():
991
+
992
+ return 2
993
+
994
+ def get_preds():
995
+
996
+ return 1
997
+
998
+ def get_acc():
999
+
1000
+ return 2
1001
+
1002
+ def get_pot():
1003
+
1004
+ return 1