pyerualjetwork 4.1.4__py3-none-any.whl → 4.1.6__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.
@@ -15,6 +15,7 @@ ANAPLAN document: https://github.com/HCB06/Anaplan/blob/main/Welcome_to_Anaplan/
15
15
 
16
16
  import cupy as cp
17
17
  from colorama import Fore
18
+ import math
18
19
 
19
20
  ### LIBRARY IMPORTS ###
20
21
  from .ui import loading_bars, initialize_loading_bar
@@ -25,8 +26,9 @@ from .metrics_cuda import metrics
25
26
  from .model_operations_cuda import get_acc, get_preds, get_preds_softmax
26
27
  from .visualizations_cuda import (
27
28
  draw_neural_web,
29
+ update_neural_web_for_fit,
28
30
  plot_evaluate,
29
- neuron_history,
31
+ update_neuron_history,
30
32
  initialize_visualization_for_fit,
31
33
  update_weight_visualization_for_fit,
32
34
  update_decision_boundary_for_fit,
@@ -34,7 +36,9 @@ from .visualizations_cuda import (
34
36
  display_visualization_for_fit,
35
37
  display_visualizations_for_learner,
36
38
  update_history_plots_for_learner,
37
- initialize_visualization_for_learner
39
+ initialize_visualization_for_learner,
40
+ update_neuron_history_for_learner,
41
+ show
38
42
  )
39
43
 
40
44
  ### GLOBAL VARIABLES ###
@@ -58,7 +62,8 @@ def fit(
58
62
  train_bar=True,
59
63
  auto_normalization=True,
60
64
  neurons_history=False,
61
- dtype=cp.float32
65
+ dtype=cp.float32,
66
+ memory='gpu'
62
67
  ):
63
68
  """
64
69
  Creates a model to fitting data.
@@ -95,23 +100,15 @@ def fit(
95
100
 
96
101
  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)
97
102
 
103
+ memory (str): The memory parameter determines whether the dataset to be processed on the GPU will be stored in the CPU's RAM or the GPU's RAM. Options: 'gpu', 'cpu'. Default: 'gpu'.
104
+
98
105
  Returns:
99
106
  numpyarray([num]): (Weight matrix).
100
107
  """
101
108
  # Pre-checks
102
109
 
103
- x_train = cp.array(x_train, copy=False).astype(dtype, copy=False)
104
-
105
- if len(y_train[0]) < 256:
106
- if y_train.dtype != cp.uint8:
107
- y_train = cp.array(y_train, copy=False).astype(cp.uint8, copy=False)
108
- elif len(y_train[0]) <= 32767:
109
- if y_train.dtype != cp.uint16:
110
- y_train = cp.array(y_train, copy=False).astype(cp.uint16, copy=False)
111
- else:
112
- if y_train.dtype != cp.uint32:
113
- y_train = cp.array(y_train, copy=False).astype(cp.uint32, copy=False)
114
-
110
+ from memory_operations import transfer_to_gpu, transfer_to_cpu
111
+
115
112
  if train_bar and val:
116
113
  train_progress = initialize_loading_bar(total=len(x_train), ncols=71, desc='Fitting', bar_format=bar_format_normal)
117
114
  elif train_bar and val == False:
@@ -123,6 +120,25 @@ def fit(
123
120
  if val and (x_val is None or y_val is None):
124
121
  x_val, y_val = x_train, y_train
125
122
 
123
+ if memory == 'gpu':
124
+ x_train = transfer_to_gpu(x_train, dtype=dtype)
125
+ y_train = transfer_to_gpu(y_train, dtype=y_train.dtype)
126
+
127
+ if val:
128
+ x_val = transfer_to_gpu(x_val, dtype=dtype)
129
+ y_val = transfer_to_gpu(y_val, dtype=y_train.dtype)
130
+
131
+ elif memory == 'cpu':
132
+ x_train = transfer_to_cpu(x_train, dtype=dtype)
133
+ y_train = transfer_to_cpu(y_train, dtype=y_train.dtype)
134
+
135
+ if val:
136
+ x_val = transfer_to_cpu(x_val, dtype=dtype)
137
+ y_val = transfer_to_cpu(y_val, dtype=y_train.dtype)
138
+
139
+ else:
140
+ raise ValueError("memory parameter must be 'cpu' or 'gpu'.")
141
+
126
142
  val_list = [] if val else None
127
143
  val_count = val_count or 10
128
144
  # Defining weights
@@ -130,29 +146,44 @@ def fit(
130
146
  LTPW = cp.zeros((len(y_train[0]), len(x_train[0].ravel()))).astype(dtype, copy=False) # LTPW = LONG TERM POTENTIATION WEIGHT
131
147
  # Initialize visualization
132
148
  vis_objects = initialize_visualization_for_fit(val, show_training, neurons_history, x_train, y_train)
133
-
149
+
134
150
  # Training process
135
151
  for index, inp in enumerate(x_train):
136
- inp = cp.array(inp, copy=False).ravel()
137
- y_decoded = decode_one_hot(y_train)
152
+ inp = transfer_to_gpu(inp, dtype=dtype).ravel()
153
+ y_decoded = decode_one_hot(cp.array(y_train[index], copy=False, dtype=y_train.dtype))
138
154
  # Weight updates
139
- STPW = feed_forward(inp, STPW, is_training=True, Class=y_decoded[index], activation_potentiation=activation_potentiation, LTD=LTD)
155
+ STPW = feed_forward(inp, STPW, is_training=True, Class=y_decoded, activation_potentiation=activation_potentiation, LTD=LTD)
140
156
  LTPW += normalization(STPW, dtype=dtype) if auto_normalization else STPW
141
157
 
142
- # Visualization updates
143
- if show_training:
144
- update_weight_visualization_for_fit(vis_objects['ax'][0, 0], LTPW, vis_objects['artist2'])
145
- if decision_boundary_status:
146
- update_decision_boundary_for_fit(vis_objects['ax'][0, 1], x_val, y_val, activation_potentiation, LTPW, vis_objects['artist1'])
147
- update_validation_history_for_fit(vis_objects['ax'][1, 1], val_list, vis_objects['artist3'])
158
+ if val and index != 0:
159
+ if index % math.ceil((val_count / len(x_train)) * 100) == 0:
160
+ val_acc = evaluate(x_val, y_val, loading_bar_status=False, activation_potentiation=activation_potentiation, W=LTPW, memory=memory)[get_acc()]
161
+ val_list.append(val_acc)
162
+
163
+ # Visualization updates
164
+ if show_training:
165
+ update_weight_visualization_for_fit(vis_objects['ax'][0, 0], LTPW, vis_objects['artist2'])
166
+ if decision_boundary_status:
167
+ update_decision_boundary_for_fit(vis_objects['ax'][0, 1], x_val, y_val, activation_potentiation, LTPW, vis_objects['artist1'])
168
+ update_validation_history_for_fit(vis_objects['ax'][1, 1], val_list, vis_objects['artist3'])
169
+ update_neural_web_for_fit(W=LTPW, G=vis_objects['G'], ax=vis_objects['ax'][1, 0], artist=vis_objects['artist4'])
170
+ if neurons_history:
171
+ update_neuron_history(LTPW, row=vis_objects['row'], col=vis_objects['col'], class_count=len(y_train[0]), fig1=vis_objects['fig1'], ax1=vis_objects['ax1'], artist5=vis_objects['artist5'], acc=val_acc)
148
172
  if train_bar:
149
173
  train_progress.update(1)
150
174
 
151
175
  STPW = cp.ones((len(y_train[0]), len(x_train[0].ravel()))).astype(dtype, copy=False)
152
176
 
153
- # Finalize visualization
154
177
  if show_training:
155
- display_visualization_for_fit(vis_objects['fig'], vis_objects['artist1'], interval)
178
+ ani1 = display_visualization_for_fit(vis_objects['fig'], vis_objects['artist1'], interval)
179
+ ani2 = display_visualization_for_fit(vis_objects['fig'], vis_objects['artist2'], interval)
180
+ ani3 = display_visualization_for_fit(vis_objects['fig'], vis_objects['artist3'], interval)
181
+ ani4 = display_visualization_for_fit(vis_objects['fig'], vis_objects['artist4'], interval)
182
+ show()
183
+
184
+ if neurons_history:
185
+ ani5 = display_visualization_for_fit(vis_objects['fig1'], vis_objects['artist5'], interval)
186
+ show()
156
187
 
157
188
  return normalization(LTPW, dtype=dtype)
158
189
 
@@ -162,7 +193,7 @@ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', bat
162
193
  neurons_history=False, patience=None, depth=None, early_shifting=False,
163
194
  early_stop=False, loss='categorical_crossentropy', show_history=False,
164
195
  interval=33.33, target_acc=None, target_loss=None, except_this=None,
165
- only_this=None, start_this=None, dtype=cp.float32):
196
+ only_this=None, start_this=None, dtype=cp.float32, memory='gpu'):
166
197
  """
167
198
  Optimizes the activation functions for a neural network by leveraging train data to find
168
199
  the most accurate combination of activation potentiation for the given dataset.
@@ -215,11 +246,15 @@ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', bat
215
246
 
216
247
  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)
217
248
 
249
+ memory (str): The memory parameter determines whether the dataset to be processed on the GPU will be stored in the CPU's RAM or the GPU's RAM. Options: 'gpu', 'cpu'. Default: 'gpu'.
250
+
218
251
  Returns:
219
252
  tuple: A list for model parameters: [Weight matrix, Preds, Accuracy, [Activations functions]]. You can acces this parameters in model_operations module. For example: model_operations.get_weights() for Weight matrix.
220
253
 
221
254
  """
222
- print(Fore.WHITE + "\nRemember, optimization on large datasets can be very time-consuming and computationally expensive. Therefore, if you are working with such a dataset, our recommendation is to include activation function: ['circular', 'spiral'] in the 'except_this' parameter unless absolutely necessary, as they can significantly prolong the process. from: learner\n" + Fore.RESET)
255
+ from memory_operations import transfer_to_gpu, transfer_to_cpu
256
+
257
+ print(Fore.WHITE + "\nRemember, optimization on large datasets can be very time-consuming and computationally expensive. Therefore, if you are working with such a dataset, our recommendation is to include activation function: ['circular'] in the 'except_this' parameter unless absolutely necessary, as they can significantly prolong the process. from: learner\n" + Fore.RESET)
223
258
 
224
259
  activation_potentiation = all_activations()
225
260
 
@@ -230,29 +265,27 @@ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', bat
230
265
  else:
231
266
  data = 'Test'
232
267
 
233
- x_train = cp.array(x_train, copy=False)
234
-
235
- if len(y_train[0]) < 256:
236
- if y_train.dtype != cp.uint8:
237
- y_train = cp.array(y_train, copy=False).astype(cp.uint8, copy=False)
238
- elif len(y_train[0]) <= 32767:
239
- if y_train.dtype != cp.uint16:
240
- y_train = cp.array(y_train, copy=False).astype(cp.uint16, copy=False)
241
- else:
242
- if y_train.dtype != cp.uint32:
243
- y_train = cp.array(y_train, copy=False).astype(cp.uint32, copy=False)
268
+ if memory == 'gpu':
269
+ x_train = transfer_to_gpu(x_train, dtype=dtype)
270
+ y_train = transfer_to_gpu(y_train, dtype=y_train.dtype)
271
+
272
+ x_test = transfer_to_gpu(x_test, dtype=dtype)
273
+ y_test = transfer_to_gpu(y_test, dtype=y_train.dtype)
274
+
275
+ from data_operations_cuda import batcher
276
+
277
+ elif memory == 'cpu':
278
+ x_train = transfer_to_cpu(x_train, dtype=dtype)
279
+ y_train = transfer_to_cpu(y_train, dtype=y_train.dtype)
244
280
 
245
- x_test = cp.array(x_test, copy=False)
281
+ x_test = transfer_to_cpu(x_test, dtype=dtype)
282
+ y_test = transfer_to_cpu(y_test, dtype=y_train.dtype)
283
+
284
+ from data_operations import batcher
246
285
 
247
- if len(y_test[0]) < 256:
248
- if y_test.dtype != cp.uint8:
249
- y_test = cp.array(y_test, copy=False).astype(cp.uint8, copy=False)
250
- elif len(y_test[0]) <= 32767:
251
- if y_test.dtype != cp.uint16:
252
- y_test = cp.array(y_test, copy=False).astype(cp.uint16, copy=False)
253
286
  else:
254
- if y_test.dtype != cp.uint32:
255
- y_test = cp.array(y_test, copy=False).astype(cp.uint32, copy=False)
287
+ raise ValueError("memory parameter must be 'cpu' or 'gpu'.")
288
+
256
289
 
257
290
  if early_shifting != False:
258
291
  shift_patience = early_shifting
@@ -297,13 +330,13 @@ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', bat
297
330
  else:
298
331
  best_activations = start_this
299
332
  x_test_batch, y_test_batch = batcher(x_test, y_test, batch_size=batch_size)
300
- W = fit(x_train, y_train, activation_potentiation=best_activations, train_bar=False, auto_normalization=auto_normalization, dtype=dtype)
301
- model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations, dtype=dtype)
302
-
333
+ W = fit(x_train, y_train, activation_potentiation=best_activations, train_bar=False, auto_normalization=auto_normalization, dtype=dtype, memory=memory)
334
+ model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations, dtype=dtype, memory=memory)
335
+
303
336
  if loss == 'categorical_crossentropy':
304
- test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
337
+ test_loss = categorical_crossentropy(y_true_batch=transfer_to_gpu(y_test_batch, dtype=y_test_batch.dtype), y_pred_batch=model[get_preds_softmax()])
305
338
  else:
306
- test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
339
+ test_loss = binary_crossentropy(y_true_batch=transfer_to_gpu(y_test_batch, dtype=y_test_batch.dtype), y_pred_batch=model[get_preds_softmax()])
307
340
 
308
341
  best_acc = model[get_acc()]
309
342
  best_loss = test_loss
@@ -327,22 +360,22 @@ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', bat
327
360
  activations.append(activation_potentiation[j])
328
361
 
329
362
  x_test_batch, y_test_batch = batcher(x_test, y_test, batch_size=batch_size)
330
- W = fit(x_train, y_train, activation_potentiation=activations, train_bar=False, auto_normalization=auto_normalization, dtype=dtype)
331
- model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations, dtype=dtype)
363
+ W = fit(x_train, y_train, activation_potentiation=activations, train_bar=False, auto_normalization=auto_normalization, dtype=dtype, memory=memory)
364
+ model = evaluate(x_test_batch, y_test_batch, W=W, loading_bar_status=False, activation_potentiation=activations, dtype=dtype, memory=memory)
332
365
 
333
366
  acc = model[get_acc()]
334
367
 
335
368
  if strategy == 'loss' or strategy == 'all':
336
369
  if loss == 'categorical_crossentropy':
337
- test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
370
+ test_loss = categorical_crossentropy(y_true_batch=transfer_to_gpu(y_test_batch, dtype=y_test_batch.dtype), y_pred_batch=model[get_preds_softmax()])
338
371
  else:
339
- test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
372
+ test_loss = binary_crossentropy(y_true_batch=transfer_to_gpu(y_test_batch, dtype=y_test_batch.dtype), y_pred_batch=model[get_preds_softmax()])
340
373
 
341
374
  if i == 0 and j == 0 and start_this is None:
342
375
  best_loss = test_loss
343
376
 
344
377
  if strategy == 'f1' or strategy == 'precision' or strategy == 'recall' or strategy == 'all':
345
- precision_score, recall_score, f1_score = metrics(y_test_batch, model[get_preds()])
378
+ precision_score, recall_score, f1_score = metrics(transfer_to_gpu(y_test_batch, dtype=y_test_batch.dtype), model[get_preds()])
346
379
 
347
380
  if strategy == 'precision' or strategy == 'all':
348
381
  if i == 0 and j == 0:
@@ -391,9 +424,9 @@ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', bat
391
424
 
392
425
  if strategy != 'loss':
393
426
  if loss == 'categorical_crossentropy':
394
- test_loss = categorical_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
427
+ test_loss = categorical_crossentropy(y_true_batch=transfer_to_gpu(y_test_batch, dtype=y_test_batch.dtype), y_pred_batch=model[get_preds_softmax()])
395
428
  else:
396
- test_loss = binary_crossentropy(y_true_batch=y_test_batch, y_pred_batch=model[get_preds_softmax()])
429
+ test_loss = binary_crossentropy(y_true_batch=transfer_to_gpu(y_test_batch, dtype=y_test_batch.dtype), y_pred_batch=model[get_preds_softmax()])
397
430
 
398
431
  if batch_size == 1:
399
432
  postfix_dict[f"{data} Loss"] = test_loss
@@ -411,7 +444,7 @@ def learner(x_train, y_train, x_test=None, y_test=None, strategy='accuracy', bat
411
444
 
412
445
  if neurons_history:
413
446
  viz_objects['neurons']['artists'] = (
414
- neuron_history(cp.copy(best_weights), viz_objects['neurons']['ax'],
447
+ update_neuron_history_for_learner(cp.copy(best_weights), viz_objects['neurons']['ax'],
415
448
  viz_objects['neurons']['row'], viz_objects['neurons']['col'],
416
449
  y_train[0], viz_objects['neurons']['artists'],
417
450
  data=data, fig1=viz_objects['neurons']['fig'],
@@ -593,7 +626,8 @@ def evaluate(
593
626
  activation_potentiation=['linear'],
594
627
  loading_bar_status=True,
595
628
  show_metrics=False,
596
- dtype=cp.float32
629
+ dtype=cp.float32,
630
+ memory='gpu'
597
631
  ) -> tuple:
598
632
  """
599
633
  Evaluates the neural network model using the given test data.
@@ -613,45 +647,43 @@ def evaluate(
613
647
 
614
648
  dtype (cupy.dtype): Data type for the arrays. cp.float32 by default. Example: cp.float64 or cp.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!] (optional)
615
649
 
650
+ memory (str): The memory parameter determines whether the dataset to be processed on the GPU will be stored in the CPU's RAM or the GPU's RAM. Options: 'gpu', 'cpu'. Default: 'gpu'.
651
+
616
652
  Returns:
617
653
  tuple: Model (list).
618
654
  """
655
+ from memory_operations import transfer_to_cpu, transfer_to_gpu
619
656
 
620
- x_test = cp.array(x_test, copy=False).astype(dtype, copy=False)
657
+ if memory == 'gpu':
658
+ x_test = transfer_to_gpu(x_test, dtype=dtype)
659
+ y_test = transfer_to_gpu(y_test, dtype=y_test.dtype)
621
660
 
622
- if len(y_test[0]) < 256:
623
- y_type = cp.uint8
624
- if y_test.dtype != cp.uint8:
625
- y_test = cp.array(y_test, copy=False).astype(cp.uint8, copy=False)
626
- elif len(y_test[0]) <= 32767:
627
- y_type = cp.uint16
628
- if y_test.dtype != cp.uint16:
629
- y_test = cp.array(y_test, copy=False).astype(cp.uint16, copy=False)
630
- else:
631
- y_type = cp.uint32
632
- if y_test.dtype != cp.uint32:
633
- y_test = cp.array(y_test, copy=False).astype(cp.uint32, copy=False)
661
+ elif memory == 'cpu':
662
+ x_test = transfer_to_cpu(x_test, dtype=dtype)
663
+ y_test = transfer_to_cpu(y_test, dtype=y_test.dtype)
634
664
 
665
+ else:
666
+ raise ValueError("memory parameter must be 'cpu' or 'gpu'.")
635
667
 
636
668
  predict_probabilitys = cp.empty((len(x_test), W.shape[0]), dtype=dtype)
637
- real_classes = cp.empty(len(x_test), dtype=y_type)
638
- predict_classes = cp.empty(len(x_test), dtype=y_type)
669
+ real_classes = cp.empty(len(x_test), dtype=y_test.dtype)
670
+ predict_classes = cp.empty(len(x_test), dtype=y_test.dtype)
639
671
 
640
672
  true_predict = 0
641
- acc_list = cp.empty(len(x_test), dtype=dtype)
673
+ acc_list = cp.empty(len(x_test), dtype=dtype)
642
674
 
643
675
  if loading_bar_status:
644
676
  loading_bar = initialize_loading_bar(total=len(x_test), ncols=64, desc='Testing', bar_format=bar_format_normal)
645
677
 
646
678
  for inpIndex in range(len(x_test)):
647
- Input = x_test[inpIndex].ravel()
679
+ Input = transfer_to_gpu(x_test[inpIndex], dtype=dtype).ravel()
648
680
  neural_layer = Input
649
681
 
650
682
  neural_layer = feed_forward(neural_layer, cp.copy(W), is_training=False, Class='?', activation_potentiation=activation_potentiation)
651
683
 
652
684
  predict_probabilitys[inpIndex] = Softmax(neural_layer)
653
685
 
654
- RealOutput = cp.argmax(y_test[inpIndex])
686
+ RealOutput = decode_one_hot(transfer_to_gpu(y_test[inpIndex], dtype=y_test[inpIndex].dtype))
655
687
  real_classes[inpIndex] = RealOutput
656
688
  PredictedOutput = cp.argmax(neural_layer)
657
689
  predict_classes[inpIndex] = PredictedOutput