pyerualjetwork 4.0.5__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,414 @@
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.
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='', dtype=cp.float32):
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 ndarray): 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
+ dtype (cupy.dtype): Data type for the arrays. np.float32 by default. Example: cp.float64 or cp.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!] (optional)
255
+
256
+ Returns:
257
+ ndarray: Output from the model.
258
+ """
259
+
260
+ Input = cp.array(Input, dtype=dtype, copy=False)
261
+
262
+ from .plan_cuda import feed_forward
263
+ from .data_operations_cuda import standard_scaler
264
+
265
+ model = load_model(model_name, model_path)
266
+
267
+ activation_potentiation = model[get_act_pot()]
268
+ scaler_params = model[get_scaler()]
269
+ W = model[get_weights()]
270
+
271
+ Input = standard_scaler(None, Input, scaler_params)
272
+
273
+ neural_layer = Input
274
+ neural_layer = cp.array(neural_layer)
275
+ neural_layer = neural_layer.ravel()
276
+
277
+ try:
278
+ neural_layer = feed_forward(neural_layer, cp.copy(W), is_training=False, Class='?', activation_potentiation=activation_potentiation)
279
+ return neural_layer
280
+ except:
281
+ print(Fore.RED + "ERROR: Unexpected Output or wrong model parameters from: predict_model_ssd." + Style.RESET_ALL)
282
+ sys.exit()
283
+
284
+
285
+ def reverse_predict_model_ssd(output, model_name, model_path='', dtype=cp.float32):
286
+
287
+ """
288
+ reverse prediction function from storage
289
+ Arguments:
290
+
291
+ output (list or ndarray): output layer for the model (single probability vector, output layer of trained model).
292
+
293
+ model_name (str): Name of the model.
294
+
295
+ model_path (str): Path of the model. Default: ''
296
+
297
+ dtype (cupy.dtype): Data type for the arrays. np.float32 by default. Example: cp.float64 or cp.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!] (optional)
298
+
299
+ Returns:
300
+ ndarray: Input from the model.
301
+ """
302
+
303
+ output = cp.array(output, dtype=dtype, copy=False)
304
+
305
+ model = load_model(model_name, model_path)
306
+
307
+ W = model[get_weights()]
308
+
309
+ try:
310
+ Input = cp.dot(output, cp.copy(W))
311
+ return Input
312
+ except:
313
+ print(Fore.RED + "ERROR: Unexpected Output or wrong model parameters from: reverse_predict_model_ssd." + Style.RESET_ALL)
314
+ sys.exit()
315
+
316
+
317
+ def predict_model_ram(Input, W, scaler_params=None, activation_potentiation=['linear'], dtype=cp.float32):
318
+
319
+ """
320
+ Function to make a prediction using a potentiation learning artificial neural network (PLAN).
321
+ from memory.
322
+
323
+ Arguments:
324
+
325
+ Input (list or ndarray): Input data for the model (single vector or single matrix).
326
+
327
+ W (list of ndarrays): Weights of the model.
328
+
329
+ scaler_params (list): standard scaler params list: mean,std. (optional) Default: None.
330
+
331
+ activation_potentiation (list): ac list for deep PLAN. default: [None] ('linear') (optional)
332
+
333
+ dtype (cupy.dtype): Data type for the arrays. np.float32 by default. Example: cp.float64 or cp.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!] (optional)
334
+
335
+ Returns:
336
+ ndarray: Output from the model.
337
+ """
338
+
339
+ from .data_operations_cuda import standard_scaler
340
+ from .plan_cuda import feed_forward
341
+
342
+ Input = cp.array(Input, dtype=dtype, copy=False)
343
+
344
+ Input = standard_scaler(None, Input, scaler_params)
345
+
346
+ try:
347
+
348
+ neural_layer = Input
349
+ neural_layer = cp.array(neural_layer)
350
+ neural_layer = neural_layer.ravel()
351
+
352
+ neural_layer = feed_forward(neural_layer, cp.copy(W), is_training=False, Class='?', activation_potentiation=activation_potentiation)
353
+
354
+ return neural_layer
355
+
356
+ except:
357
+ print(Fore.RED + "ERROR: Unexpected input or wrong model parameters from: predict_model_ram." + Style.RESET_ALL)
358
+ sys.exit()
359
+
360
+ def reverse_predict_model_ram(output, W, dtype=cp.float32):
361
+
362
+ """
363
+ reverse prediction function from memory
364
+
365
+ Arguments:
366
+
367
+ output (list or ndarray): output layer for the model (single probability vector, output layer of trained model).
368
+
369
+ W (list of ndarrays): Weights of the model.
370
+
371
+ dtype (cupy.dtype): Data type for the arrays. np.float32 by default. Example: cp.float64 or cp.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!] (optional)
372
+
373
+ Returns:
374
+ ndarray: Input from the model.
375
+ """
376
+
377
+ output = cp.array(output, dtype=dtype, copy=False)
378
+
379
+ try:
380
+ Input = cp.dot(output, cp.copy(W))
381
+ return Input
382
+
383
+ except:
384
+ print(Fore.RED + "ERROR: Unexpected Output or wrong model parameters from: reverse_predict_model_ram." + Style.RESET_ALL)
385
+ sys.exit()
386
+
387
+
388
+ def get_weights():
389
+
390
+ return 0
391
+
392
+
393
+ def get_preds():
394
+
395
+ return 1
396
+
397
+
398
+ def get_acc():
399
+
400
+ return 2
401
+
402
+
403
+ def get_act_pot():
404
+
405
+ return 3
406
+
407
+
408
+ def get_scaler():
409
+
410
+ return 4
411
+
412
+ def get_preds_softmax():
413
+
414
+ return 5