pyerualjetwork 3.3.3__py3-none-any.whl → 4.0.0__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,350 @@
1
+ import numpy as np
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 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 += np.shape(W)[0] + np.shape(W)[1]
76
+ SynapseCount += np.shape(W)[0] * np.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
+ np.savetxt(model_path + model_name + '_weights.txt', W, fmt='%f')
117
+
118
+ if weights_type == 'txt' and weights_format == 'raw':
119
+
120
+ np.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
+ np.save(model_path + model_name + '_weights.npy', W, W.astype(float))
140
+
141
+ if weights_type == 'npy' and weights_format == 'raw':
142
+
143
+ np.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
+ np.set_printoptions(threshold=np.Infinity)
194
+
195
+ try:
196
+
197
+ df = pd.read_pickle(model_path + model_name + '.pkl')
198
+
199
+ except:
200
+
201
+ print(Fore.RED + "ERROR: Model Path error. acceptable form: 'C:/Users/hasancanbeydili/Desktop/denemePLAN/' from: load_model" + Style.RESET_ALL)
202
+
203
+ sys.exit()
204
+
205
+ activation_potentiation = list(df['ACTIVATION POTENTIATION'])
206
+ activation_potentiation = [x for x in activation_potentiation if not (isinstance(x, float) and np.isnan(x))]
207
+ activation_potentiation = [item for item in activation_potentiation if item != '']
208
+
209
+ scaler_params = df['STANDARD SCALER'].tolist()
210
+
211
+ try:
212
+ if scaler_params[0] == None:
213
+ scaler_params = scaler_params[0]
214
+
215
+ except:
216
+ scaler_params = [item for item in scaler_params if isinstance(item, np.ndarray)]
217
+
218
+
219
+ model_name = str(df['MODEL NAME'].iloc[0])
220
+ WeightType = str(df['WEIGHTS TYPE'].iloc[0])
221
+
222
+ if WeightType == 'txt':
223
+ W = np.loadtxt(model_path + model_name + '_weights.txt')
224
+ elif WeightType == 'npy':
225
+ W = np.load(model_path + model_name + '_weights.npy')
226
+ elif WeightType == 'mat':
227
+ W = sio.loadmat(model_path + model_name + '_weights.mat')
228
+ elif WeightType == 'pkl':
229
+ with open(model_path + model_name + '_weights.pkl', 'rb') as f:
230
+ W = pickle.load(f)
231
+ else:
232
+
233
+ raise ValueError(
234
+ Fore.RED + "Incorrect weight type value. Value must be 'txt', 'npy', 'pkl' or 'mat' from: load_model." + Style.RESET_ALL)
235
+
236
+ if WeightType == 'mat':
237
+ W = W['w']
238
+
239
+ return W, None, None, activation_potentiation, scaler_params
240
+
241
+
242
+ def predict_model_ssd(Input, model_name, model_path):
243
+
244
+ """
245
+ Function to make a prediction using a divided potentiation learning artificial neural network (PLAN).
246
+
247
+ Arguments:
248
+
249
+ Input (list or ndarray): Input data for the model (single vector or single matrix).
250
+
251
+ model_name (str): Name of the model.
252
+
253
+ Returns:
254
+ ndarray: Output from the model.
255
+ """
256
+
257
+ from .plan import feed_forward
258
+ from .data_operations import standard_scaler
259
+
260
+ model = load_model(model_name, model_path)
261
+
262
+ activation_potentiation = model[get_act_pot()]
263
+ scaler_params = model[get_scaler()]
264
+ W = model[get_weights()]
265
+
266
+ Input = standard_scaler(None, Input, scaler_params)
267
+
268
+ Wc = np.copy(W)
269
+
270
+ neural_layer = Input
271
+ neural_layer = np.array(neural_layer)
272
+ neural_layer = neural_layer.ravel()
273
+
274
+
275
+ neural_layer = feed_forward(neural_layer, W, is_training=False, Class='?', activation_potentiation=activation_potentiation)
276
+
277
+ W = np.copy(Wc)
278
+ return neural_layer
279
+
280
+
281
+ def predict_model_ram(Input, W, scaler_params=None, activation_potentiation=['linear']):
282
+
283
+ """
284
+ Function to make a prediction using a divided potentiation learning artificial neural network (PLAN).
285
+ from weights and parameters stored in memory.
286
+
287
+ Arguments:
288
+
289
+ Input (list or ndarray): Input data for the model (single vector or single matrix).
290
+
291
+ W (list of ndarrays): Weights of the model.
292
+
293
+ scaler_params (list): standard scaler params list: mean,std. (optional) Default: None.
294
+
295
+ activation_potentiation (list): ac list for deep PLAN. default: [None] ('linear') (optional)
296
+
297
+ Returns:
298
+ ndarray: Output from the model.
299
+ """
300
+
301
+ from .data_operations import standard_scaler
302
+ from .plan import feed_forward
303
+
304
+ Input = standard_scaler(None, Input, scaler_params)
305
+
306
+ Wc = np.copy(W)
307
+
308
+ try:
309
+
310
+ neural_layer = Input
311
+ neural_layer = np.array(neural_layer)
312
+ neural_layer = neural_layer.ravel()
313
+
314
+ neural_layer = feed_forward(neural_layer, W, is_training=False, Class='?', activation_potentiation=activation_potentiation)
315
+
316
+ W = np.copy(Wc)
317
+ return neural_layer
318
+
319
+ except:
320
+ print(Fore.RED + "ERROR: Unexpected input or wrong model parameters from: predict_model_ram." + Style.RESET_ALL)
321
+ sys.exit()
322
+
323
+
324
+ def get_weights():
325
+
326
+ return 0
327
+
328
+
329
+ def get_preds():
330
+
331
+ return 1
332
+
333
+
334
+ def get_acc():
335
+
336
+ return 2
337
+
338
+
339
+ def get_act_pot():
340
+
341
+ return 3
342
+
343
+
344
+ def get_scaler():
345
+
346
+ return 4
347
+
348
+ def get_preds_softmax():
349
+
350
+ return 5