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