pyerualjetwork 5.1__py3-none-any.whl → 5.5__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.
Files changed (29) hide show
  1. pyerualjetwork/__init__.py +15 -14
  2. pyerualjetwork/cpu/__init__.py +24 -0
  3. pyerualjetwork/{activation_functions_cpu.py → cpu/activation_functions.py} +40 -4
  4. pyerualjetwork/{data_operations_cpu.py → cpu/data_ops.py} +17 -19
  5. pyerualjetwork/{metrics_cpu.py → cpu/metrics.py} +3 -1
  6. pyerualjetwork/{visualizations_cpu.py → cpu/visualizations.py} +96 -139
  7. pyerualjetwork/cuda/__init__.py +24 -0
  8. pyerualjetwork/{activation_functions_cuda.py → cuda/activation_functions.py} +54 -5
  9. pyerualjetwork/{data_operations_cuda.py → cuda/data_ops.py} +16 -16
  10. pyerualjetwork/{metrics_cuda.py → cuda/metrics.py} +1 -1
  11. pyerualjetwork/{visualizations_cuda.py → cuda/visualizations.py} +8 -244
  12. pyerualjetwork/{ene_cpu.py → ene.py} +29 -95
  13. pyerualjetwork/fitness_functions.py +0 -1
  14. pyerualjetwork/help.py +5 -5
  15. pyerualjetwork/issue_solver.py +39 -11
  16. pyerualjetwork/{memory_operations.py → memory_ops.py} +1 -1
  17. pyerualjetwork/model_ops.py +734 -0
  18. pyerualjetwork/{neu_cpu.py → nn.py} +199 -91
  19. pyerualjetwork/{model_operations_cpu.py → old_cpu_model_ops.py} +62 -59
  20. pyerualjetwork/{model_operations_cuda.py → old_cuda_model_ops.py} +99 -86
  21. {pyerualjetwork-5.1.dist-info → pyerualjetwork-5.5.dist-info}/METADATA +16 -18
  22. pyerualjetwork-5.5.dist-info/RECORD +27 -0
  23. pyerualjetwork/ene_cuda.py +0 -962
  24. pyerualjetwork/neu_cuda.py +0 -588
  25. pyerualjetwork-5.1.dist-info/RECORD +0 -26
  26. /pyerualjetwork/{loss_functions_cpu.py → cpu/loss_functions.py} +0 -0
  27. /pyerualjetwork/{loss_functions_cuda.py → cuda/loss_functions.py} +0 -0
  28. {pyerualjetwork-5.1.dist-info → pyerualjetwork-5.5.dist-info}/WHEEL +0 -0
  29. {pyerualjetwork-5.1.dist-info → pyerualjetwork-5.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,734 @@
1
+ """
2
+
3
+
4
+ Model Operations
5
+ =======================
6
+ This module hosts functions for handling all operational processes related to models, including:
7
+
8
+ - Saving and loading models
9
+ - Making predictions from memory
10
+ - Making predictions from storage
11
+ - Retrieving model weights
12
+ - Retrieving model activation functions
13
+ - Retrieving model accuracy
14
+ - Running the model in reverse (applicable to PLAN models)
15
+
16
+ Module functions:
17
+ -----------------
18
+ - get_model_template()
19
+ - build_model()
20
+ - save_model()
21
+ - load_model()
22
+ - predict_from_storage()
23
+ - predict_from_memory()
24
+ - reverse_predict_from_storage()
25
+ - reverse_predict_from_memory()
26
+
27
+ Examples: https://github.com/HCB06/PyerualJetwork/tree/main/Welcome_to_PyerualJetwork/ExampleCodes
28
+
29
+ PyerualJetwork document: https://github.com/HCB06/PyerualJetwork/blob/main/Welcome_to_PyerualJetwork/PYERUALJETWORK_USER_MANUEL_AND_LEGAL_INFORMATION(EN).pdf
30
+
31
+ - Creator: Hasan Can Beydili
32
+ - YouTube: https://www.youtube.com/@HasanCanBeydili
33
+ - Linkedin: https://www.linkedin.com/in/hasan-can-beydili-77a1b9270/
34
+ - Instagram: https://www.instagram.com/canbeydilj
35
+ - Contact: tchasancan@gmail.com
36
+ """
37
+
38
+ import numpy as np
39
+ import cupy as cp
40
+ from colorama import Fore, Style
41
+ from datetime import datetime
42
+ import pickle
43
+ from scipy import io
44
+ import scipy.io as sio
45
+ import pandas as pd
46
+ from collections import namedtuple
47
+
48
+ def get_model_template():
49
+ """
50
+ Creates and returns a named tuple template for a model structure.
51
+
52
+ This function defines a `Model` named tuple with standard fields used
53
+ to represent various components of a machine learning model.
54
+ All fields are initialized to `None`.
55
+
56
+ Returns:
57
+ Model: A named tuple with the following fields initialized to None:
58
+ -> weights: Model weights.
59
+ -> predictions: Raw class predictions.
60
+ -> accuracy: Model evaluation metric (e.g., accuracy).
61
+ -> activations: Activation functions used in the model.
62
+ -> scaler_params: Parameters used for feature scaling.
63
+ -> softmax_predictions: Output probabilities after softmax.
64
+ -> model_type: A string indicating the type of model.
65
+ -> weights_type: The format or data type of the weights.
66
+ -> weights_format: Structural format of the weights.
67
+ -> model_version: A string or identifier for versioning.
68
+ -> model_df: DataFrame holding model-related data.
69
+ -> activation_potentiation: Only for PTNN models.
70
+ """
71
+ Model = namedtuple("Model", [
72
+ "weights",
73
+ "predictions",
74
+ "accuracy",
75
+ "activations",
76
+ "scaler_params",
77
+ "softmax_predictions",
78
+ "model_type",
79
+ "weights_type",
80
+ "weights_format",
81
+ "model_version",
82
+ "model_df",
83
+ "activation_potentiation"
84
+ ])
85
+
86
+ template_model = Model(None, None, None, None, None, None, None, None, None, None, None, None)
87
+
88
+ return template_model
89
+
90
+
91
+ def build_model(W, activations, model_type, activation_potentiation=None):
92
+ """
93
+ Builds a model using the template and specified components.
94
+
95
+ Args:
96
+ W (any): The weight parameters of the model.
97
+ activations (any): The activation functions to be used.
98
+ model_type (str): A string specifying the model architecture (PLAN, MLP or PTNN).
99
+ activation_potentiation (optional): An optional parameter only for PTNN models.
100
+
101
+ Returns:
102
+ Model: A named tuple representing the constructed model, with relevant fields filled in.
103
+ """
104
+ template_model = get_model_template()
105
+ model = template_model._replace(
106
+ weights=W,
107
+ activations=activations,
108
+ model_type=model_type,
109
+ activation_potentiation=activation_potentiation
110
+ )
111
+
112
+ return model
113
+
114
+
115
+ def save_model(model,
116
+ model_name,
117
+ model_path='',
118
+ weights_type='npy',
119
+ weights_format='raw',
120
+ show_architecture=False,
121
+ show_info=True
122
+ ):
123
+
124
+ """
125
+ Function to save a potentiation learning artificial neural network model.
126
+ Args:
127
+
128
+ model (tuple): Trained model.
129
+
130
+ model_name: (str): Name of the model.
131
+
132
+ model_path: (str): Path where the model will be saved. For example: C:/Users/beydili/Desktop/denemePLAN/ default: ''
133
+
134
+ weights_type: (str): Type of weights to save (options: 'txt', 'pkl', 'npy', 'mat'). default: 'npy'
135
+
136
+ weights_format: (str): Format of the weights (options: 'f', 'raw'). default: 'raw'
137
+
138
+ show_architecture: (bool): It draws model architecture. True or False. Default: False. NOTE! draw architecture only works for PLAN models. Not MLP models for now, but it will be.
139
+
140
+ show_info: (bool): Prints model details into console. default: True
141
+
142
+ Returns:
143
+ No return.
144
+ """
145
+
146
+ from .cpu.visualizations import draw_model_architecture
147
+ from . import __version__
148
+
149
+ model_type = model.model_type
150
+ activations = model.activations
151
+ activation_potentiation = model.activation_potentiation
152
+ scaler_params = model.scaler_params
153
+ W = model.weights
154
+ acc = model.accuracy
155
+
156
+ if model_type != 'PLAN' and model_type != 'MLP' and model_type != 'PTNN':
157
+ raise ValueError("model_type parameter must be 'PLAN', 'MLP' or 'PTNN'.")
158
+
159
+ if model_type == 'PTNN' and activation_potentiation == []:
160
+ raise ValueError('PTNN models need extra activation_potentiation parameter.')
161
+
162
+ if isinstance(activations, str):
163
+ activations = [activations]
164
+ else:
165
+ activations = [item if isinstance(item, list) else [item] for item in activations]
166
+
167
+ activations = activations.copy()
168
+
169
+ if model_type == 'PTNN':
170
+ if isinstance(activation_potentiation, str):
171
+ activation_potentiation = [activation_potentiation]
172
+ else:
173
+ activation_potentiation = [item if isinstance(item, list) else [item] for item in activation_potentiation]
174
+
175
+ activation_potentiation = activation_potentiation.copy()
176
+
177
+ if acc != None:
178
+ acc= float(acc)
179
+
180
+ if weights_type != 'txt' and weights_type != 'npy' and weights_type != 'mat' and weights_type != 'pkl':
181
+ raise ValueError(Fore.RED + "ERROR: Save Weight type (File Extension) Type must be 'txt' or 'npy' or 'mat' or 'pkl' from: save_model" + Style.RESET_ALL)
182
+
183
+ if weights_format != 'd' and weights_format != 'f' and weights_format != 'raw':
184
+ raise ValueError(Fore.RED + "ERROR: Weight Format Type must be 'd' or 'f' or 'raw' from: save_model" + Style.RESET_ALL)
185
+
186
+ NeuronCount = []
187
+ SynapseCount = []
188
+
189
+ if model_type == 'PLAN':
190
+ class_count = W.shape[0]
191
+
192
+ try:
193
+ NeuronCount.append(np.shape(W)[1])
194
+ NeuronCount.append(np.shape(W)[0])
195
+ SynapseCount.append(np.shape(W)[0] * np.shape(W)[1])
196
+ except AttributeError as e:
197
+ raise AttributeError(Fore.RED + "ERROR: W does not have a shape attribute. Check if W is a valid matrix." + Style.RESET_ALL) from e
198
+ except IndexError as e:
199
+ raise IndexError(Fore.RED + "ERROR: W has an unexpected shape format. Ensure it has two dimensions." + Style.RESET_ALL) from e
200
+ except (TypeError, ValueError) as e:
201
+ raise TypeError(Fore.RED + "ERROR: W is not a valid numeric matrix." + Style.RESET_ALL) from e
202
+ except Exception as e:
203
+ raise RuntimeError(Fore.RED + f"ERROR: An unexpected error occurred in save_model: {e}" + Style.RESET_ALL) from e
204
+
205
+ elif model_type == 'MLP' or model_type == 'PTNN':
206
+
207
+ class_count = W[-1].shape[0]
208
+
209
+ NeuronCount.append(np.shape(W[0])[1])
210
+
211
+ for i in range(len(W)):
212
+ try:
213
+ NeuronCount.append(np.shape(W[i])[0])
214
+ SynapseCount.append(np.shape(W[i])[0] * np.shape(W[i])[1])
215
+ except AttributeError as e:
216
+ raise AttributeError(Fore.RED + "ERROR: W does not have a shape attribute. Check if W is a valid matrix." + Style.RESET_ALL) from e
217
+ except IndexError as e:
218
+ raise IndexError(Fore.RED + "ERROR: W has an unexpected shape format. Ensure it has two dimensions." + Style.RESET_ALL) from e
219
+ except (TypeError, ValueError) as e:
220
+ raise TypeError(Fore.RED + "ERROR: W is not a valid numeric matrix." + Style.RESET_ALL) from e
221
+ except Exception as e:
222
+ raise RuntimeError(Fore.RED + f"ERROR: An unexpected error occurred in save_model: {e}" + Style.RESET_ALL) from e
223
+
224
+
225
+ SynapseCount.append(' ')
226
+
227
+ activations.append('')
228
+ activations.insert(0, '')
229
+
230
+ if len(activations) == 1 and model_type == 'PLAN':
231
+ activations = [activations]
232
+ activations.append('')
233
+
234
+ if model_type == 'PTNN':
235
+ if len(activations) > len(activation_potentiation):
236
+ for i in range(len(activations) - len(activation_potentiation)):
237
+ activation_potentiation.append('')
238
+
239
+ if len(activation_potentiation) > len(activations):
240
+ for i in range(len(activation_potentiation) - len(activations)):
241
+ activations.append('')
242
+
243
+ if len(activations) > len(NeuronCount):
244
+ for i in range(len(activations) - len(NeuronCount)):
245
+ NeuronCount.append('')
246
+
247
+ if len(activations) > len(SynapseCount):
248
+ for i in range(len(activations) - len(SynapseCount)):
249
+ SynapseCount.append('')
250
+
251
+ if scaler_params != None:
252
+
253
+ if len(scaler_params) > len(activations):
254
+
255
+ activations += ['']
256
+
257
+ elif len(activations) > len(scaler_params):
258
+
259
+ for i in range(len(activations) - len(scaler_params)):
260
+
261
+ scaler_params.append(' ')
262
+
263
+ data = {'MODEL NAME': model_name,
264
+ 'MODEL TYPE': model_type,
265
+ 'CLASS COUNT': class_count,
266
+ 'NEURON COUNT': NeuronCount,
267
+ 'SYNAPSE COUNT': SynapseCount,
268
+ 'VERSION': __version__,
269
+ 'ACCURACY': acc,
270
+ 'SAVE DATE': datetime.now(),
271
+ 'WEIGHTS TYPE': weights_type,
272
+ 'WEIGHTS FORMAT': weights_format,
273
+ 'STANDARD SCALER': scaler_params,
274
+ 'ACTIVATION FUNCTIONS': activations,
275
+ 'ACTIVATION POTENTIATION': activation_potentiation
276
+ }
277
+
278
+ df = pd.DataFrame(data)
279
+ df.to_pickle(model_path + model_name + '.pkl')
280
+
281
+ try:
282
+
283
+ if weights_type == 'txt' and weights_format == 'f':
284
+
285
+ np.savetxt(model_path + model_name + f'_weights.txt', W, fmt='%f')
286
+
287
+ if weights_type == 'txt' and weights_format == 'raw':
288
+
289
+ np.savetxt(model_path + model_name + f'_weights.txt', W)
290
+
291
+ ###
292
+
293
+
294
+ if weights_type == 'pkl' and weights_format == 'f':
295
+
296
+ with open(model_path + model_name + f'_weights.pkl', 'wb') as f:
297
+ pickle.dump(W.astype(float), f)
298
+
299
+ if weights_type == 'pkl' and weights_format =='raw':
300
+
301
+ with open(model_path + model_name + f'_weights.pkl', 'wb') as f:
302
+ pickle.dump(W, f)
303
+
304
+ ###
305
+
306
+ if weights_type == 'npy' and weights_format == 'f':
307
+
308
+ np.save(model_path + model_name + f'_weights.npy', W, W.astype(float))
309
+
310
+ if weights_type == 'npy' and weights_format == 'raw':
311
+
312
+ np.save(model_path + model_name + f'_weights.npy', W)
313
+
314
+ ###
315
+
316
+ if weights_type == 'mat' and weights_format == 'f':
317
+
318
+ w = {'w': W.astype(float)}
319
+ io.savemat(model_path + model_name + f'_weights.mat', w)
320
+
321
+ if weights_type == 'mat' and weights_format == 'raw':
322
+
323
+ w = {'w': W}
324
+ io.savemat(model_path + model_name + f'_weights.mat', w)
325
+
326
+
327
+ except OSError as e:
328
+ raise OSError(Fore.RED + f"ERROR: An OSError error occurred in save_model at saving weights. Maybe model name or path or administration issue: {e}" + Style.RESET_ALL) from e
329
+
330
+ if show_info:
331
+ print(df)
332
+
333
+ message = (
334
+ Fore.GREEN + "Model Saved Successfully\n" +
335
+ Fore.MAGENTA + "Don't forget, if you want to load model: model log file and weight files must be in the same directory." +
336
+ Style.RESET_ALL
337
+ )
338
+
339
+ print(message)
340
+
341
+ if show_architecture:
342
+ draw_model_architecture(model_name=model_name, model_path=model_path)
343
+
344
+
345
+
346
+ def load_model(model_name,
347
+ model_path,
348
+ ):
349
+ """
350
+ Function to load a potentiation learning model.
351
+
352
+ Args:
353
+ model_name (str): Name of the model.
354
+
355
+ model_path (str): Path where the model is saved.
356
+
357
+ Returns:
358
+ tuple(model): Weights, None, accuracy, activations, scaler_params, None, model_type, weight_type, weight_format, device_version, (list[df_elements])=Pandas DataFrame of the model, activation_potentiation
359
+ """
360
+
361
+ from . import __version__
362
+
363
+ try:
364
+
365
+ df = pd.read_pickle(model_path + model_name + '.pkl')
366
+
367
+ except OSError as e:
368
+ raise OSError(Fore.RED + f"ERROR: An OSError error occurred in load_model at loading model params. Maybe model name or path or administration issue: {e}" + Style.RESET_ALL) from e
369
+
370
+
371
+
372
+ scaler_params = df['STANDARD SCALER'].tolist()
373
+
374
+ try:
375
+ if scaler_params[0] == None:
376
+ scaler_params = scaler_params[0]
377
+
378
+ except:
379
+ scaler_params = [item for item in scaler_params if isinstance(item, np.ndarray)]
380
+
381
+
382
+ model_name = str(df['MODEL NAME'].iloc[0])
383
+ model_type = str(df['MODEL TYPE'].iloc[0])
384
+ WeightType = str(df['WEIGHTS TYPE'].iloc[0])
385
+ WeightFormat = str(df['WEIGHTS FORMAT'].iloc[0])
386
+ acc = str(df['ACCURACY'].iloc[0])
387
+
388
+ activations = list(df['ACTIVATION FUNCTIONS'])
389
+ activations = [x for x in activations if not (isinstance(x, float) and np.isnan(x))]
390
+ activations = [item for item in activations if item != '']
391
+
392
+ activation_potentiation = list(df['ACTIVATION POTENTIATION'])
393
+ activation_potentiation = [x for x in activation_potentiation if not (isinstance(x, float) and np.isnan(x))]
394
+ activation_potentiation = [item for item in activation_potentiation if item != '']
395
+
396
+ device_version = __version__
397
+
398
+ try:
399
+ model_version = str(df['VERSION'].iloc[0])
400
+ if model_version != device_version:
401
+ message = (
402
+ Fore.MAGENTA + f"WARNING: Your PyerualJetwork version({device_version}) is different from this model's version({model_version}).\nIf you have a performance issue, please install this model version. Use this: pip install pyerualjetwork=={model_version} or look issue_solver module." +
403
+ Style.RESET_ALL
404
+ )
405
+ print(message)
406
+
407
+ except:
408
+ pass # Version check only in >= 5.0.2
409
+
410
+ if model_type == 'MLP' or model_type == 'PTNN': allow_pickle = True
411
+ else: allow_pickle = False
412
+
413
+ try:
414
+ if WeightType == 'txt':
415
+ W = (np.loadtxt(model_path + model_name + f'_weights.txt'))
416
+ elif WeightType == 'npy':
417
+ W = (np.load(model_path + model_name + f'_weights.npy', allow_pickle=allow_pickle))
418
+ elif WeightType == 'mat':
419
+ W = (sio.loadmat(model_path + model_name + f'_weights.mat'))
420
+ elif WeightType == 'pkl':
421
+ with open(model_path + model_name + f'_weights.pkl', 'rb') as f:
422
+ W = pickle.load(f)
423
+ else:
424
+
425
+ raise ValueError(
426
+ Fore.RED + "Incorrect weight type value. Value must be 'txt', 'npy', 'pkl' or 'mat' from: load_model." + Style.RESET_ALL)
427
+
428
+ except OSError as e:
429
+ raise OSError(Fore.RED + f"ERROR: An OSError error occurred in load_model at loading weights. Maybe model name or path or administration issue: {e}" + Style.RESET_ALL) from e
430
+
431
+
432
+ if WeightType == 'mat':
433
+ W = W['w']
434
+
435
+ template_model = get_model_template()
436
+
437
+ model = template_model._replace(weights=W,
438
+ accuracy=acc,
439
+ activations=activations,
440
+ scaler_params=scaler_params,
441
+ weights_type=WeightType,
442
+ weights_format=WeightFormat,
443
+ model_version=device_version,
444
+ model_df=df,
445
+ model_type=model_type,
446
+ activation_potentiation=activation_potentiation)
447
+
448
+ return model
449
+
450
+
451
+
452
+ def predict_from_storage(Input, model_name, cuda=False, model_path=''):
453
+
454
+ """
455
+ Function to make a prediction
456
+ from storage
457
+
458
+ Args:
459
+ Input (list or ndarray): Input data for the model.
460
+
461
+ model_name (str): Name of the model.
462
+
463
+ cuda (bool, optional): CUDA GPU acceleration ? Default = False.
464
+
465
+ model_path (str): Path of the model. Default: ''
466
+
467
+ Returns:
468
+ ndarray: Output from the model.
469
+ """
470
+
471
+ if cuda:
472
+ if not isinstance(Input, cp.ndarray): Input = cp.array(Input)
473
+ from .cuda.activation_functions import apply_activation
474
+ from .cuda.data_ops import standard_scaler
475
+
476
+ else:
477
+ from .cpu.activation_functions import apply_activation
478
+ from .cpu.data_ops import standard_scaler
479
+
480
+ try:
481
+
482
+ model = load_model(model_name, model_path)
483
+
484
+ model_type = model.model_type
485
+ activations = model.activations
486
+ activation_potentiation = model.activation_potentiation
487
+ scaler_params = model.scaler_params
488
+ W = model.weights
489
+
490
+ if cuda and scaler_params is not None:
491
+ if not isinstance(scaler_params[0], cp.ndarray): scaler_params[0] = cp.array(scaler_params[0])
492
+ if not isinstance(scaler_params[1], cp.ndarray): scaler_params[1] = cp.array(scaler_params[1])
493
+
494
+ Input = standard_scaler(None, Input, scaler_params)
495
+
496
+ if isinstance(activations, str):
497
+ activations = [activations]
498
+ elif isinstance(activations, list):
499
+ activations = [item if isinstance(item, list) or isinstance(item, str) else [item] for item in activations]
500
+
501
+ if model_type == 'MLP':
502
+
503
+ layer = Input @ cp.array(W[0]).T if cuda else Input @ W[0].T
504
+ for i in range(1, len(W)):
505
+ layer = apply_activation(layer, activations[i-1])
506
+ layer = layer @ cp.array(W[i]).T if cuda else layer @ W[i].T
507
+
508
+ result = layer
509
+
510
+ if model_type == 'PLAN':
511
+
512
+ Input = apply_activation(Input, activations)
513
+ result = Input @ cp.array(W).T if cuda else Input @ W.T
514
+
515
+ if model_type == 'PTNN':
516
+
517
+ if isinstance(activation_potentiation, str):
518
+ activation_potentiation = [activation_potentiation]
519
+ elif isinstance(activation_potentiation, list):
520
+ activation_potentiation = [item if isinstance(item, list) or isinstance(item, str) else [item] for item in activation_potentiation]
521
+
522
+ Input = apply_activation(Input, activation_potentiation)
523
+ layer = Input @ cp.array(W[0]).T if cuda else Input @ W[0].T
524
+
525
+ for i in range(1, len(W)):
526
+ layer = apply_activation(layer, activations[i-1])
527
+ layer = layer @ cp.array(W[i]).T if cuda else layer @ W[i].T
528
+
529
+ result = layer
530
+
531
+ return result
532
+
533
+ except Exception as e:
534
+ raise RuntimeError(Fore.RED + f"ERROR: An error occurred in predict_from_storage {e}" + Style.RESET_ALL) from e
535
+
536
+
537
+ def reverse_predict_from_storage(output, model_name, cuda=False, model_path=''):
538
+
539
+ """
540
+ reverse prediction function from storage
541
+ Args:
542
+
543
+ output (list or ndarray): output layer for the model .
544
+
545
+ model_name (str): Name of the model.
546
+
547
+ cuda (bool, optional): CUDA GPU acceleration ? Default = False.
548
+
549
+ model_path (str): Path of the model. Default: ''
550
+
551
+ Returns:
552
+ ndarray: Input from the model.
553
+ """
554
+
555
+ if cuda:
556
+ if not isinstance(output, cp.ndarray): output = cp.array(output)
557
+
558
+ model = load_model(model_name, model_path)
559
+
560
+ W = model.weights if not cuda else cp.array(model.weights)
561
+
562
+ try:
563
+ Input = W.T @ output
564
+ return Input
565
+ except Exception as e:
566
+ raise RuntimeError(Fore.RED + f"ERROR: An error occurred {e}" + Style.RESET_ALL) from e
567
+
568
+
569
+
570
+ def predict_from_memory(Input, model, cuda=False):
571
+
572
+ """
573
+ Function to make a prediction.
574
+ from memory.
575
+
576
+ Args:
577
+ Input (list or ndarray): Input data for the model.
578
+
579
+ model (tuple): Trained model.
580
+
581
+ cuda (bool, optional): CUDA GPU acceleration ? Default = False.
582
+
583
+ Returns:
584
+ ndarray: Output from the model.
585
+ """
586
+
587
+ model_type = model.model_type
588
+ activations = model.activations
589
+ activation_potentiation = model.activation_potentiation
590
+ scaler_params = model.scaler_params
591
+ W = model.weights
592
+
593
+ if not cuda:
594
+ from .cpu.data_ops import standard_scaler
595
+ from .cpu.activation_functions import apply_activation
596
+ else:
597
+ if scaler_params is not None:
598
+ if not isinstance(scaler_params[0], cp.ndarray): scaler_params[0] = cp.array(scaler_params[0])
599
+ if not isinstance(scaler_params[1], cp.ndarray): scaler_params[1] = cp.array(scaler_params[1])
600
+
601
+ if not isinstance(Input, cp.ndarray): Input = cp.array(Input)
602
+ from .cuda.data_ops import standard_scaler
603
+ from .cuda.activation_functions import apply_activation
604
+
605
+ if model_type != 'PLAN' and model_type != 'MLP' and model_type != 'PTNN': raise ValueError("model_type parameter must be 'PLAN', 'MLP' or 'PTNN'.")
606
+
607
+ try:
608
+
609
+ Input = standard_scaler(None, Input, scaler_params)
610
+
611
+ if isinstance(activations, str):
612
+ activations = [activations]
613
+ elif isinstance(activations, list):
614
+ activations = [item if isinstance(item, list) or isinstance(item, str) else [item] for item in activations]
615
+
616
+ if model_type == 'MLP':
617
+
618
+ layer = Input @ cp.array(W[0]).T if cuda else Input @ W[0].T
619
+ for i in range(1, len(W)):
620
+ layer = apply_activation(layer, activations[i-1])
621
+ layer = layer @ cp.array(W[i]).T if cuda else layer @ W[i].T
622
+
623
+ result = layer
624
+
625
+ if model_type == 'PLAN':
626
+
627
+ Input = apply_activation(Input, activations)
628
+ result = Input @ cp.array(W).T if cuda else Input @ W.T
629
+
630
+ if model_type == 'PTNN':
631
+
632
+ if isinstance(activation_potentiation, str):
633
+ activation_potentiation = [activation_potentiation]
634
+ elif isinstance(activation_potentiation, list):
635
+ activation_potentiation = [item if isinstance(item, list) or isinstance(item, str) else [item] for item in activation_potentiation]
636
+
637
+ Input = apply_activation(Input, activation_potentiation)
638
+ layer = Input @ cp.array(W[0]).T if cuda else Input @ W[0].T
639
+
640
+ for i in range(1, len(W)):
641
+ layer = apply_activation(layer, activations[i-1])
642
+ layer = layer @ cp.array(W[i]).T if cuda else layer @ W[i].T
643
+
644
+ result = layer
645
+
646
+ return result
647
+
648
+ except Exception as e:
649
+ raise RuntimeError(Fore.RED + f"ERROR: An error occurred in predict_from_memory {e}" + Style.RESET_ALL) from e
650
+
651
+ def reverse_predict_from_memory(output, W, cuda=False):
652
+
653
+ """
654
+ reverse prediction function from memory
655
+
656
+ Args:
657
+
658
+ output (list or ndarray): output layer for the model.
659
+
660
+ W (ndarray): Weights of the model.
661
+
662
+ cuda (bool, optional): CUDA GPU acceleration ? Default = False.
663
+
664
+ Returns:
665
+ ndarray: Input from the model.
666
+ """
667
+
668
+ try:
669
+ if cuda: W = cp.array(W)
670
+ Input = W.T @ output
671
+ return Input
672
+
673
+ except Exception as e:
674
+ raise RuntimeError(Fore.RED + f"ERROR: An error occurred {e}" + Style.RESET_ALL) from e
675
+
676
+
677
+ def get_weights():
678
+
679
+ return 0
680
+
681
+
682
+ def get_preds():
683
+
684
+ return 1
685
+
686
+
687
+ def get_acc():
688
+
689
+ return 2
690
+
691
+
692
+ def get_act():
693
+
694
+ return 3
695
+
696
+
697
+ def get_scaler():
698
+
699
+ return 4
700
+
701
+
702
+ def get_preds_softmax():
703
+
704
+ return 5
705
+
706
+
707
+ def get_model_type():
708
+
709
+ return 6
710
+
711
+
712
+ def get_weights_type():
713
+
714
+ return 7
715
+
716
+
717
+ def get_weights_format():
718
+
719
+ return 8
720
+
721
+
722
+ def get_model_version():
723
+
724
+ return 9
725
+
726
+
727
+ def get_model_df():
728
+
729
+ return 10
730
+
731
+
732
+ def get_act_pot():
733
+
734
+ return 11