pyerualjetwork 4.0.2__py3-none-any.whl → 4.0.3b0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,405 @@
1
+ import cupy as cp
2
+ from colorama import Fore, Style
3
+ import sys
4
+ from datetime import datetime
5
+ import pickle
6
+ from scipy import io
7
+ import scipy.io as sio
8
+ import pandas as pd
9
+
10
+
11
+ def save_model(model_name,
12
+ W,
13
+ scaler_params=None,
14
+ model_type='PLAN',
15
+ test_acc=None,
16
+ model_path='',
17
+ activation_potentiation=['linear'],
18
+ weights_type='npy',
19
+ weights_format='raw',
20
+ show_architecture=None,
21
+ show_info=True
22
+ ):
23
+
24
+ """
25
+ Function to save a potentiation learning artificial neural network model.
26
+
27
+ Arguments:
28
+
29
+ model_name (str): Name of the model.
30
+
31
+ model_type (str): Type of the model. default: 'PLAN'
32
+
33
+ test_acc (float): Test accuracy of the model. default: None
34
+
35
+ weights_type (str): Type of weights to save (options: 'txt', 'pkl', 'npy', 'mat'). default: 'npy'
36
+
37
+ WeightFormat (str): Format of the weights (options: 'f', 'raw'). default: 'raw'
38
+
39
+ model_path (str): Path where the model will be saved. For example: C:/Users/beydili/Desktop/denemePLAN/ default: ''
40
+
41
+ scaler_params (list[num, num]): standard scaler params list: mean,std. If not used standard scaler then be: None.
42
+
43
+ W: Weights of the model. (cparray)
44
+
45
+ activation_potentiation (list): For deeper PLAN networks, activation function parameters. For more information please run this code: plan.activations_list() default: ['linear']
46
+
47
+ show_architecture (str): It draws model architecture. Takes 2 value='basic' or 'detailed'. Default: None(not drawing)
48
+
49
+ show_info (bool): Prints model details into console. default: True
50
+
51
+ Returns:
52
+ No return.
53
+ """
54
+
55
+ from .visualizations_cuda import draw_model_architecture
56
+
57
+ class_count = W.shape[0]
58
+
59
+ if test_acc != None:
60
+ test_acc= float(test_acc)
61
+
62
+ if weights_type != 'txt' and weights_type != 'npy' and weights_type != 'mat' and weights_type != 'pkl':
63
+ print(Fore.RED + "ERROR110: Save Weight type (File Extension) Type must be 'txt' or 'npy' or 'mat' or 'pkl' from: save_model" + Style.RESET_ALL)
64
+ sys.exit()
65
+
66
+ if weights_format != 'd' and weights_format != 'f' and weights_format != 'raw':
67
+ print(Fore.RED + "ERROR111: Weight Format Type must be 'd' or 'f' or 'raw' from: save_model" + Style.RESET_ALL)
68
+ sys.exit()
69
+
70
+ NeuronCount = 0
71
+ SynapseCount = 0
72
+
73
+
74
+ try:
75
+ NeuronCount += cp.shape(W)[0] + cp.shape(W)[1]
76
+ SynapseCount += cp.shape(W)[0] * cp.shape(W)[1]
77
+ except:
78
+
79
+ print(Fore.RED + "ERROR: Weight matrices has a problem from: save_model" + Style.RESET_ALL)
80
+ sys.exit()
81
+
82
+ if scaler_params != None:
83
+
84
+ if len(scaler_params) > len(activation_potentiation):
85
+
86
+ activation_potentiation += ['']
87
+
88
+ elif len(activation_potentiation) > len(scaler_params):
89
+
90
+ for i in range(len(activation_potentiation) - len(scaler_params)):
91
+
92
+ scaler_params.append(' ')
93
+
94
+ data = {'MODEL NAME': model_name,
95
+ 'MODEL TYPE': model_type,
96
+ 'CLASS COUNT': class_count,
97
+ 'NEURON COUNT': NeuronCount,
98
+ 'SYNAPSE COUNT': SynapseCount,
99
+ 'TEST ACCURACY': test_acc,
100
+ 'SAVE DATE': datetime.now(),
101
+ 'WEIGHTS TYPE': weights_type,
102
+ 'WEIGHTS FORMAT': weights_format,
103
+ 'MODEL PATH': model_path,
104
+ 'STANDARD SCALER': scaler_params,
105
+ 'ACTIVATION POTENTIATION': activation_potentiation
106
+ }
107
+
108
+ df = pd.DataFrame(data)
109
+ df.to_pickle(model_path + model_name + '.pkl')
110
+
111
+
112
+ try:
113
+
114
+ if weights_type == 'txt' and weights_format == 'f':
115
+
116
+ cp.savetxt(model_path + model_name + '_weights.txt', W, fmt='%f')
117
+
118
+ if weights_type == 'txt' and weights_format == 'raw':
119
+
120
+ cp.savetxt(model_path + model_name + '_weights.txt', W)
121
+
122
+ ###
123
+
124
+
125
+ if weights_type == 'pkl' and weights_format == 'f':
126
+
127
+ with open(model_path + model_name + '_weights.pkl', 'wb') as f:
128
+ pickle.dump(W.astype(float), f)
129
+
130
+ if weights_type == 'pkl' and weights_format =='raw':
131
+
132
+ with open(model_path + model_name + '_weights.pkl', 'wb') as f:
133
+ pickle.dump(W, f)
134
+
135
+ ###
136
+
137
+ if weights_type == 'npy' and weights_format == 'f':
138
+
139
+ cp.save(model_path + model_name + '_weights.npy', W, W.astype(float))
140
+
141
+ if weights_type == 'npy' and weights_format == 'raw':
142
+
143
+ cp.save(model_path + model_name + '_weights.npy', W)
144
+
145
+ ###
146
+
147
+ if weights_type == 'mat' and weights_format == 'f':
148
+
149
+ w = {'w': W.astype(float)}
150
+ io.savemat(model_path + model_name + '_weights.mat', w)
151
+
152
+ if weights_type == 'mat' and weights_format == 'raw':
153
+
154
+ w = {'w': W}
155
+ io.savemat(model_path + model_name + '_weights.mat', w)
156
+
157
+ except:
158
+
159
+ print(Fore.RED + "ERROR: Model Weights not saved. Check the Weight parameters. SaveFilePath expl: 'C:/Users/hasancanbeydili/Desktop/denemePLAN/' from: save_model" + Style.RESET_ALL)
160
+ sys.exit()
161
+
162
+ if show_info:
163
+ print(df)
164
+
165
+ message = (
166
+ Fore.GREEN + "Model Saved Successfully\n" +
167
+ Fore.MAGENTA + "Don't forget, if you want to load model: model log file and weight files must be in the same directory." +
168
+ Style.RESET_ALL
169
+ )
170
+
171
+ print(message)
172
+
173
+ if show_architecture is not None:
174
+ draw_model_architecture(model_name=model_name, model_path=model_path, style=show_architecture)
175
+
176
+
177
+
178
+ def load_model(model_name,
179
+ model_path,
180
+ ):
181
+ """
182
+ Function to load a potentiation learning model.
183
+
184
+ Arguments:
185
+
186
+ model_name (str): Name of the model.
187
+
188
+ model_path (str): Path where the model is saved.
189
+
190
+ Returns:
191
+ lists: W(list[num]), activation_potentiation, DataFrame of the model
192
+ """
193
+ try:
194
+
195
+ df = pd.read_pickle(model_path + model_name + '.pkl')
196
+
197
+ except:
198
+
199
+ print(Fore.RED + "ERROR: Model Path error. acceptable form: 'C:/Users/hasancanbeydili/Desktop/denemePLAN/' from: load_model" + Style.RESET_ALL)
200
+
201
+ sys.exit()
202
+
203
+ activation_potentiation = list(df['ACTIVATION POTENTIATION'])
204
+ activation_potentiation = [x for x in activation_potentiation if not (isinstance(x, float) and cp.isnan(x))]
205
+ activation_potentiation = [item for item in activation_potentiation if item != '']
206
+
207
+ scaler_params = df['STANDARD SCALER'].tolist()
208
+
209
+ try:
210
+ if scaler_params[0] == None:
211
+ scaler_params = scaler_params[0]
212
+
213
+ except:
214
+ scaler_params = [item for item in scaler_params if isinstance(item, cp.ndarray)]
215
+
216
+
217
+ model_name = str(df['MODEL NAME'].iloc[0])
218
+ WeightType = str(df['WEIGHTS TYPE'].iloc[0])
219
+
220
+ if WeightType == 'txt':
221
+ W = cp.loadtxt(model_path + model_name + '_weights.txt')
222
+ elif WeightType == 'npy':
223
+ W = cp.load(model_path + model_name + '_weights.npy')
224
+ elif WeightType == 'mat':
225
+ W = sio.loadmat(model_path + model_name + '_weights.mat')
226
+ elif WeightType == 'pkl':
227
+ with open(model_path + model_name + '_weights.pkl', 'rb') as f:
228
+ W = pickle.load(f)
229
+ else:
230
+
231
+ raise ValueError(
232
+ Fore.RED + "Incorrect weight type value. Value must be 'txt', 'npy', 'pkl' or 'mat' from: load_model." + Style.RESET_ALL)
233
+
234
+ if WeightType == 'mat':
235
+ W = W['w']
236
+
237
+ return W, None, None, activation_potentiation, scaler_params
238
+
239
+
240
+ def predict_model_ssd(Input, model_name, model_path=''):
241
+
242
+ """
243
+ Function to make a prediction using a potentiation learning artificial neural network (PLAN).
244
+ from storage
245
+
246
+ Arguments:
247
+
248
+ Input (list or cparray): Input data for the model (single vector or single matrix).
249
+
250
+ model_name (str): Name of the model.
251
+
252
+ model_path (str): Path of the model. Default: ''
253
+
254
+ Returns:
255
+ cparray: Output from the model.
256
+ """
257
+
258
+ Input = cp.array(Input, copy=False)
259
+
260
+ from .plan_cuda import feed_forward
261
+ from .data_operations_cuda import standard_scaler
262
+
263
+ model = load_model(model_name, model_path)
264
+
265
+ activation_potentiation = model[get_act_pot()]
266
+ scaler_params = model[get_scaler()]
267
+ W = model[get_weights()]
268
+
269
+ Input = standard_scaler(None, Input, scaler_params)
270
+
271
+ neural_layer = Input
272
+ neural_layer = cp.array(neural_layer)
273
+ neural_layer = neural_layer.ravel()
274
+
275
+ try:
276
+ neural_layer = feed_forward(neural_layer, cp.copy(W), is_training=False, Class='?', activation_potentiation=activation_potentiation)
277
+ return neural_layer
278
+ except:
279
+ print(Fore.RED + "ERROR: Unexpected Output or wrong model parameters from: predict_model_ssd." + Style.RESET_ALL)
280
+ sys.exit()
281
+
282
+
283
+ def reverse_predict_model_ssd(output, model_name, model_path=''):
284
+
285
+ """
286
+ reverse prediction function from storage
287
+ Arguments:
288
+
289
+ output (list or cparray): output layer for the model (single probability vector, output layer of trained model).
290
+
291
+ model_name (str): Name of the model.
292
+
293
+ model_path (str): Path of the model. Default: ''
294
+
295
+ Returns:
296
+ cparray: Input from the model.
297
+ """
298
+
299
+ Input = cp.array(Input, copy=False)
300
+
301
+ model = load_model(model_name, model_path)
302
+
303
+ W = model[get_weights()]
304
+
305
+ try:
306
+ Input = cp.dot(output, cp.copy(W))
307
+ return Input
308
+ except:
309
+ print(Fore.RED + "ERROR: Unexpected Output or wrong model parameters from: reverse_predict_model_ssd." + Style.RESET_ALL)
310
+ sys.exit()
311
+
312
+
313
+
314
+ def predict_model_ram(Input, W, scaler_params=None, activation_potentiation=['linear']):
315
+
316
+ """
317
+ Function to make a prediction using a potentiation learning artificial neural network (PLAN).
318
+ from memory.
319
+
320
+ Arguments:
321
+
322
+ Input (list or cparray): Input data for the model (single vector or single matrix).
323
+
324
+ W (list of cparray): Weights of the model.
325
+
326
+ scaler_params (list): standard scaler params list: mean,std. (optional) Default: None.
327
+
328
+ activation_potentiation (list): ac list for deep PLAN. default: [None] ('linear') (optional)
329
+
330
+ Returns:
331
+ cparray: Output from the model.
332
+ """
333
+
334
+ from .data_operations_cuda import standard_scaler
335
+ from .plan_cuda import feed_forward
336
+
337
+ Input = cp.array(Input, copy=False)
338
+ Input = standard_scaler(None, Input, scaler_params)
339
+
340
+ try:
341
+
342
+ neural_layer = Input
343
+ neural_layer = cp.array(neural_layer)
344
+ neural_layer = neural_layer.ravel()
345
+
346
+ neural_layer = feed_forward(neural_layer, cp.copy(W), is_training=False, Class='?', activation_potentiation=activation_potentiation)
347
+
348
+ return neural_layer
349
+
350
+ except:
351
+ print(Fore.RED + "ERROR: Unexpected input or wrong model parameters from: predict_model_ram." + Style.RESET_ALL)
352
+ sys.exit()
353
+
354
+ def reverse_predict_model_ram(output, W):
355
+
356
+ """
357
+ reverse prediction function from memory
358
+
359
+ Arguments:
360
+
361
+ output (list or cparray): output layer for the model (single probability vector, output layer of trained model).
362
+
363
+ W (list of cparray): Weights of the model.
364
+
365
+ Returns:
366
+ cparray: Input from the model.
367
+ """
368
+ Input = cp.array(Input, copy=False)
369
+
370
+ try:
371
+ Input = cp.dot(output, cp.copy(W))
372
+ return Input
373
+
374
+ except:
375
+ print(Fore.RED + "ERROR: Unexpected Output or wrong model parameters from: reverse_predict_model_ram." + Style.RESET_ALL)
376
+ sys.exit()
377
+
378
+
379
+ def get_weights():
380
+
381
+ return 0
382
+
383
+
384
+ def get_preds():
385
+
386
+ return 1
387
+
388
+
389
+ def get_acc():
390
+
391
+ return 2
392
+
393
+
394
+ def get_act_pot():
395
+
396
+ return 3
397
+
398
+
399
+ def get_scaler():
400
+
401
+ return 4
402
+
403
+ def get_preds_softmax():
404
+
405
+ return 5
pyerualjetwork/plan.py CHANGED
@@ -14,17 +14,16 @@ ANAPLAN document: https://github.com/HCB06/Anaplan/blob/main/Welcome_to_Anaplan/
14
14
  """
15
15
 
16
16
  import numpy as np
17
- from colorama import Fore, Style
18
- import sys
17
+ from colorama import Fore
19
18
 
20
19
  ### LIBRARY IMPORTS ###
21
- from .ui import loading_bars, initialize_loading_bar
22
- from .data_operations import normalization, decode_one_hot, batcher
23
- from .loss_functions import binary_crossentropy, categorical_crossentropy
24
- from .activation_functions import apply_activation, Softmax, all_activations
25
- from .metrics import metrics
26
- from.model_operations import get_acc, get_preds, get_preds_softmax
27
- from .visualizations import (
20
+ from ui import loading_bars, initialize_loading_bar
21
+ from data_operations import normalization, decode_one_hot, batcher
22
+ from loss_functions import binary_crossentropy, categorical_crossentropy
23
+ from activation_functions import apply_activation, Softmax, all_activations
24
+ from metrics import metrics
25
+ from model_operations import get_acc, get_preds, get_preds_softmax
26
+ from visualizations import (
28
27
  draw_neural_web,
29
28
  plot_evaluate,
30
29
  neuron_history,
@@ -547,89 +546,73 @@ def feed_forward(
547
546
 
548
547
 
549
548
  def evaluate(
550
- x_test, # list[num]: Test input data.
551
- y_test, # list[num]: Test labels.
552
- W, # list[num]: Weight matrix list of the neural network.
553
- activation_potentiation=['linear'], # (list): Activation potentiation list for deep PLAN. (optional)
554
- loading_bar_status=True, # bar_status (bool): Loading bar for accuracy (True or None) (optional) Default: True
555
- show_metrics=None, # show_metrices (bool): (True or None) (optional) Default: None
549
+ x_test, # NumPy array: Test input data.
550
+ y_test, # NumPy array: Test labels.
551
+ W, # List of NumPy arrays: Neural network weight matrices.
552
+ activation_potentiation=['linear'], # List of activation functions.
553
+ loading_bar_status=True, # Optionally show loading bar.
554
+ show_metrics=None, # Optionally show metrics.
556
555
  ) -> tuple:
557
556
  """
558
- Tests the neural network model with the given test data.
557
+ Evaluates the neural network model using the given test data.
559
558
 
560
559
  Args:
561
-
562
- x_test (list[num]): Test input data.
563
-
564
- y_test (list[num]): Test labels.
565
-
566
- W (list[num]): Weight matrix list of the neural network.
567
-
568
- activation_potentiation (list): For deeper PLAN networks, activation function parameters. For more information please run this code: plan.activations_list() default: [None]
569
-
570
- loading_bar_status: Evaluate progress have a loading bar ? (True or False) Default: True.
571
-
572
- show_metrics (bool): (True or None) (optional) Default: None
560
+ x_test (np.ndarray): Test input data.
561
+ y_test (np.ndarray): Test labels.
562
+ W (list[np.ndarray]): List of neural network weight matrices.
563
+ activation_potentiation (list): List of activation functions.
564
+ loading_bar_status (bool): Option to show a loading bar (optional).
565
+ show_metrics (bool): Option to show metrics (optional).
573
566
 
574
567
  Returns:
575
- tuple: A tuple containing the predicted labels and the accuracy of the model.
568
+ tuple: Predicted labels, model accuracy, and other evaluation metrics.
576
569
  """
577
- predict_probabilitys = []
578
- real_classes = []
579
- predict_classes = []
580
-
581
- try:
570
+ # Initialize arrays to store probabilities, real and predicted classes, and accuracy
571
+ predict_probabilitys = np.empty((len(x_test), W.shape[0]), dtype=np.float32)
572
+ real_classes = np.empty(len(x_test), dtype=np.int32) # Real classes
573
+ predict_classes = np.empty(len(x_test), dtype=np.int32) # Predicted classes
582
574
 
583
- true_predict = 0
584
- y_preds = []
585
- y_preds_raw = []
586
- acc_list = []
575
+ true_predict = 0
576
+ acc_list = np.empty(len(x_test), dtype=np.float32) # Accuracy list
587
577
 
588
-
589
- if loading_bar_status == True:
590
-
591
- loading_bar = initialize_loading_bar(total=len(x_test), ncols=64, desc='Testing', bar_format=bar_format_normal)
578
+ if loading_bar_status:
579
+ loading_bar = initialize_loading_bar(total=len(x_test), ncols=64, desc='Testing', bar_format=bar_format_normal)
592
580
 
593
- for inpIndex, Input in enumerate(x_test):
594
- Input = np.array(Input)
595
- Input = Input.ravel()
596
- neural_layer = Input
597
-
598
-
599
- neural_layer = feed_forward(neural_layer, W, is_training=False, Class='?', activation_potentiation=activation_potentiation)
600
- neural_layer = Softmax(neural_layer)
581
+ for inpIndex in range(len(x_test)):
582
+ # Flatten the input data for processing
583
+ Input = x_test[inpIndex].ravel() # Flatten the input
601
584
 
602
- max_value = max(neural_layer)
585
+ neural_layer = Input
603
586
 
604
- predict_probabilitys.append(max_value)
605
-
606
- RealOutput = np.argmax(y_test[inpIndex])
607
- real_classes.append(RealOutput)
608
- PredictedOutput = np.argmax(neural_layer)
609
- predict_classes.append(PredictedOutput)
587
+ # Perform feedforward operation
588
+ neural_layer = feed_forward(neural_layer, np.copy(W), is_training=False, Class='?', activation_potentiation=activation_potentiation)
610
589
 
611
- if RealOutput == PredictedOutput:
612
- true_predict += 1
613
- acc = true_predict / len(y_test)
590
+ # Calculate probabilities and predictions
591
+ predict_probabilitys[inpIndex] = Softmax(neural_layer)
614
592
 
593
+ # Find the actual class and predicted class
594
+ RealOutput = np.argmax(y_test[inpIndex])
595
+ real_classes[inpIndex] = RealOutput
596
+ PredictedOutput = np.argmax(neural_layer)
597
+ predict_classes[inpIndex] = PredictedOutput
615
598
 
616
- acc_list.append(acc)
617
- y_preds.append(PredictedOutput)
618
- y_preds_raw.append(Softmax(neural_layer))
619
-
620
- if loading_bar_status == True:
621
- loading_bar.update(1)
622
-
623
- if inpIndex > 0 and loading_bar_status == True:
624
- loading_bar.set_postfix({"Test Accuracy": acc})
599
+ # Check if the prediction is correct
600
+ if RealOutput == PredictedOutput:
601
+ true_predict += 1
602
+
603
+ # Dynamically calculate accuracy
604
+ acc = true_predict / (inpIndex + 1)
605
+ acc_list[inpIndex] = acc
625
606
 
626
- if show_metrics == True:
627
-
628
- loading_bar.close()
629
- plot_evaluate(x_test, y_test, y_preds, acc_list, W=np.copy(W), activation_potentiation=activation_potentiation)
607
+ if loading_bar_status:
608
+ loading_bar.update(1)
609
+ loading_bar.set_postfix({"Test Accuracy": acc})
630
610
 
631
- except Exception as e:
611
+ if loading_bar_status:
612
+ loading_bar.close()
632
613
 
633
- raise(e)
614
+ if show_metrics:
615
+ # Plot the evaluation metrics
616
+ plot_evaluate(x_test, y_test, predict_classes, acc_list, W=np.copy(W), activation_potentiation=activation_potentiation)
634
617
 
635
- return W, y_preds, acc, None, None, y_preds_raw
618
+ return W, predict_classes, acc_list[-1], None, None, predict_probabilitys