pyerualjetwork 2.7.8__py3-none-any.whl → 4.1.9__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,403 @@
1
+ from tqdm import tqdm
2
+ import numpy as np
3
+ from colorama import Fore, Style
4
+ import sys
5
+ import math
6
+
7
+ def encode_one_hot(y_train, y_test=None, summary=False):
8
+ """
9
+ Performs one-hot encoding on y_train and y_test data.
10
+
11
+ Args:
12
+ y_train (numpy.ndarray): Train label data.
13
+ y_test (numpy.ndarray): Test label data one-hot encoded. (optional).
14
+ summary (bool, optional): If True, prints the class-to-index mapping. Default: False
15
+
16
+ Returns:
17
+ tuple: One-hot encoded y_train and (if given) y_test.
18
+ """
19
+ from .memory_operations import optimize_labels
20
+
21
+ y_train = optimize_labels(y_train, one_hot_encoded=False, cuda=False)
22
+ y_test = optimize_labels(y_test, one_hot_encoded=False, cuda=False)
23
+
24
+ classes = np.unique(y_train)
25
+ class_count = len(classes)
26
+
27
+ class_to_index = {cls: idx for idx, cls in enumerate(classes)}
28
+
29
+ if summary:
30
+ print("Class-to-index mapping:")
31
+ for cls, idx in class_to_index.items():
32
+ print(f" {idx}: {cls}")
33
+
34
+ y_train_encoded = np.zeros((y_train.shape[0], class_count), dtype=y_train.dtype)
35
+ for i, label in enumerate(y_train):
36
+ y_train_encoded[i, class_to_index[label]] = 1
37
+
38
+ if y_test is not None:
39
+ y_test_encoded = np.zeros((y_test.shape[0], class_count), dtype=y_test.dtype)
40
+ for i, label in enumerate(y_test):
41
+ y_test_encoded[i, class_to_index[label]] = 1
42
+ return y_train_encoded, y_test_encoded
43
+
44
+ return y_train_encoded
45
+
46
+
47
+ def decode_one_hot(encoded_data):
48
+ """
49
+ Decodes one-hot encoded data to original categorical labels.
50
+
51
+ Args:
52
+ encoded_data (numpy.ndarray): One-hot encoded data with shape (n_samples, n_classes).
53
+
54
+ Returns:
55
+ numpy.ndarray: Decoded categorical labels with shape (n_samples,).
56
+ """
57
+
58
+ decoded_labels = np.argmax(encoded_data, axis=1)
59
+
60
+ return decoded_labels
61
+
62
+
63
+ def split(X, y, test_size, random_state=42, dtype=np.float32):
64
+ """
65
+ Splits the given X (features) and y (labels) data into training and testing subsets.
66
+
67
+ Args:
68
+ X (numpy.ndarray): Features data.
69
+ y (numpy.ndarray): Labels data.
70
+ test_size (float or int): Proportion or number of samples for the test subset.
71
+ random_state (int or None): Seed for random state. Default: 42.
72
+ dtype (numpy.dtype): Data type for the arrays. np.float32 by default. Example: np.float64 or np.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!]
73
+
74
+ Returns:
75
+ tuple: x_train, x_test, y_train, y_test as ordered training and testing data subsets.
76
+ """
77
+ from .memory_operations import transfer_to_cpu, optimize_labels
78
+
79
+ X = transfer_to_cpu(X, dtype=dtype)
80
+ y = optimize_labels(y, one_hot_encoded=False, cuda=False)
81
+
82
+ num_samples = X.shape[0]
83
+
84
+ if isinstance(test_size, float):
85
+ test_size = int(test_size * num_samples)
86
+ elif isinstance(test_size, int):
87
+ if test_size > num_samples:
88
+ raise ValueError(
89
+ "test_size cannot be larger than the number of samples.")
90
+ else:
91
+ raise ValueError("test_size should be float or int.")
92
+
93
+ if random_state is not None:
94
+ np.random.seed(random_state)
95
+
96
+ indices = np.arange(num_samples)
97
+ np.random.shuffle(indices)
98
+
99
+ test_indices = indices[:test_size]
100
+ train_indices = indices[test_size:]
101
+
102
+ x_train, x_test = X[train_indices], X[test_indices]
103
+ y_train, y_test = y[train_indices], y[test_indices]
104
+
105
+ del X, y
106
+
107
+ return x_train, x_test, y_train, y_test
108
+
109
+
110
+ def manuel_balancer(x_train, y_train, target_samples_per_class, dtype=np.float32):
111
+ """
112
+ Generates synthetic examples to balance classes to the specified number of examples per class.
113
+
114
+ Arguments:
115
+ x_train -- Input dataset (examples) - NumPy array format
116
+ y_train -- Class labels (one-hot encoded) - NumPy array format
117
+ target_samples_per_class -- Desired number of samples per class
118
+ dtype (numpy.dtype): Data type for the arrays. np.float32 by default. Example: np.float64 or np.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!]
119
+
120
+ Returns:
121
+ x_balanced -- Balanced input dataset (NumPy array format)
122
+ y_balanced -- Balanced class labels (one-hot encoded, NumPy array format)
123
+ """
124
+ from .ui import loading_bars
125
+ from .memory_operations import transfer_to_cpu
126
+
127
+ x_train = transfer_to_cpu(x_train, dtype=dtype)
128
+
129
+ bar_format = loading_bars()[0]
130
+ classes = np.arange(y_train.shape[1])
131
+ class_count = len(classes)
132
+
133
+ x_balanced = []
134
+ y_balanced = []
135
+
136
+ for class_label in tqdm(range(class_count),leave=False, ascii="▱▰",
137
+ bar_format=bar_format,desc='Augmenting Data',ncols= 52):
138
+ class_indices = np.where(np.argmax(y_train, axis=1) == class_label)[0]
139
+ num_samples = len(class_indices)
140
+
141
+ if num_samples > target_samples_per_class:
142
+
143
+ selected_indices = np.random.choice(class_indices, target_samples_per_class, replace=False)
144
+ x_balanced.append(x_train[selected_indices])
145
+ y_balanced.append(y_train[selected_indices])
146
+
147
+ else:
148
+
149
+ x_balanced.append(x_train[class_indices])
150
+ y_balanced.append(y_train[class_indices])
151
+
152
+ if num_samples < target_samples_per_class:
153
+
154
+ samples_to_add = target_samples_per_class - num_samples
155
+ additional_samples = np.zeros((samples_to_add, x_train.shape[1]), dtype=x_train.dtype)
156
+ additional_labels = np.zeros((samples_to_add, y_train.shape[1]), dtype=y_train.dtype)
157
+
158
+ for i in range(samples_to_add):
159
+
160
+ random_indices = np.random.choice(class_indices, 2, replace=False)
161
+ sample1 = x_train[random_indices[0]]
162
+ sample2 = x_train[random_indices[1]]
163
+
164
+
165
+ synthetic_sample = sample1 + (sample2 - sample1) * np.random.rand()
166
+
167
+ additional_samples[i] = synthetic_sample
168
+ additional_labels[i] = y_train[class_indices[0]]
169
+
170
+
171
+ x_balanced.append(additional_samples)
172
+ y_balanced.append(additional_labels)
173
+
174
+ x_balanced = np.vstack(x_balanced, dtype=x_train.dtype)
175
+ y_balanced = np.vstack(y_balanced, dtype=y_train.dtype)
176
+
177
+ del x_train, y_train
178
+
179
+ return x_balanced, y_balanced
180
+
181
+
182
+ def auto_balancer(x_train, y_train, dtype=np.float32):
183
+
184
+ """
185
+ Function to balance the training data across different classes.
186
+
187
+ Arguments:
188
+ x_train (list): Input data for training.
189
+ y_train (list): Labels corresponding to the input data. one-hot encoded.
190
+ dtype (numpy.dtype): Data type for the arrays. np.float32 by default. Example: np.float64 or np.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!]
191
+
192
+ Returns:
193
+ tuple: A tuple containing balanced input data and labels.
194
+ """
195
+ from .ui import loading_bars
196
+ from .memory_operations import transfer_to_cpu
197
+
198
+ x_train = transfer_to_cpu(x_train, dtype=dtype)
199
+
200
+ bar_format = loading_bars()[0]
201
+ classes = np.arange(y_train.shape[1])
202
+ class_count = len(classes)
203
+
204
+ try:
205
+ ClassIndices = {i: np.where(y_train[:, i] == 1)[
206
+ 0] for i in range(class_count)}
207
+ classes = [len(ClassIndices[i]) for i in range(class_count)]
208
+
209
+ if len(set(classes)) == 1:
210
+ print(Fore.WHITE + "INFO: Data have already balanced. from: auto_balancer" + Style.RESET_ALL)
211
+ return x_train, y_train
212
+
213
+ MinCount = min(classes)
214
+
215
+ BalancedIndices = []
216
+ for i in tqdm(range(class_count),leave=False, ascii="▱▰",
217
+ bar_format= bar_format, desc='Balancing Data',ncols=70):
218
+ if len(ClassIndices[i]) > MinCount:
219
+ SelectedIndices = np.random.choice(
220
+ ClassIndices[i], MinCount, replace=False)
221
+ else:
222
+ SelectedIndices = ClassIndices[i]
223
+ BalancedIndices.extend(SelectedIndices)
224
+
225
+ BalancedInputs = [x_train[idx] for idx in BalancedIndices]
226
+ BalancedLabels = [y_train[idx] for idx in BalancedIndices]
227
+
228
+ permutation = np.random.permutation(len(BalancedInputs))
229
+ BalancedInputs = np.array(BalancedInputs)[permutation]
230
+ BalancedLabels = np.array(BalancedLabels)[permutation]
231
+
232
+ print(Fore.GREEN + "Data Succesfully Balanced from: " + str(len(x_train)
233
+ ) + " to: " + str(len(BalancedInputs)) + ". from: auto_balancer " + Style.RESET_ALL)
234
+ except:
235
+ print(Fore.RED + "ERROR: Inputs and labels must be same length check parameters")
236
+ sys.exit()
237
+
238
+ BalancedInputs = BalancedInputs.astype(dtype, copy=False)
239
+ BalancedLabels = BalancedLabels.astype(dtype=y_train.dtype, copy=False)
240
+
241
+ del x_train, y_train
242
+
243
+ return BalancedInputs, BalancedLabels
244
+
245
+
246
+ def synthetic_augmentation(x, y, dtype=np.float32):
247
+ """
248
+ Generates synthetic examples to balance classes with fewer examples.
249
+
250
+ Arguments:
251
+ x -- Input dataset (examples) - array format
252
+ y -- Class labels (one-hot encoded) - array format
253
+ dtype (numpy.dtype): Data type for the arrays. np.float32 by default. Example: np.float64 or np.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!]
254
+
255
+ Returns:
256
+ x_balanced -- Balanced input dataset (array format)
257
+ y_balanced -- Balanced class labels (one-hot encoded, array format)
258
+ """
259
+ from .ui import loading_bars
260
+ from .memory_operations import transfer_to_cpu
261
+
262
+ x = transfer_to_cpu(x, dtype=dtype)
263
+
264
+ bar_format = loading_bars()[0]
265
+ classes = np.arange(y.shape[1])
266
+ class_count = len(classes)
267
+
268
+ class_distribution = {i: 0 for i in range(class_count)}
269
+ for label in y:
270
+ class_distribution[np.argmax(label)] += 1
271
+
272
+ max_class_count = max(class_distribution.values())
273
+
274
+ x_balanced = list(x)
275
+ y_balanced = list(y)
276
+
277
+
278
+ for class_label in tqdm(range(class_count), leave=False, ascii="▱▰",
279
+ bar_format=bar_format,desc='Augmenting Data',ncols= 52):
280
+ class_indices = [i for i, label in enumerate(
281
+ y) if np.argmax(label) == class_label]
282
+ num_samples = len(class_indices)
283
+
284
+ if num_samples < max_class_count:
285
+ while num_samples < max_class_count:
286
+
287
+ random_indices = np.random.choice(
288
+ class_indices, 2, replace=False)
289
+ sample1 = x[random_indices[0]]
290
+ sample2 = x[random_indices[1]]
291
+
292
+ synthetic_sample = sample1 + \
293
+ (np.array(sample2) - np.array(sample1)) * np.random.rand()
294
+
295
+ x_balanced.append(synthetic_sample.tolist())
296
+ y_balanced.append(y[class_indices[0]])
297
+
298
+ num_samples += 1
299
+
300
+ x_balanced = np.array(x_balanced).astype(dtype, copy=False)
301
+ y_balanced = np.array(y_balanced).astype(dtype=y.dtype, copy=False)
302
+
303
+ del x, y
304
+
305
+ return x_balanced, y_balanced
306
+
307
+
308
+ def standard_scaler(x_train=None, x_test=None, scaler_params=None, dtype=np.float32):
309
+ """
310
+ Standardizes training and test datasets. x_test may be None.
311
+
312
+ Args:
313
+ x_train: numpy.ndarray
314
+
315
+ x_test: numpy.ndarray (optional)
316
+
317
+ scaler_params (optional for using model)
318
+
319
+ dtype (numpy.dtype): Data type for the arrays. np.float32 by default. Example: np.float64 or np.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!]
320
+
321
+ Returns:
322
+ list:
323
+ Scaler parameters: mean and std
324
+ tuple
325
+ Standardized training and test datasets
326
+ """
327
+ if x_train is not None and scaler_params is None and x_test is not None:
328
+ x_train = x_train.astype(dtype, copy=False)
329
+ x_test = x_test.astype(dtype, copy=False)
330
+
331
+ mean = np.mean(x_train, axis=0)
332
+ std = np.std(x_train, axis=0)
333
+
334
+ train_data_scaled = (x_train - mean) / std
335
+ test_data_scaled = (x_test - mean) / std
336
+
337
+ train_data_scaled = np.nan_to_num(train_data_scaled, nan=0)
338
+ test_data_scaled = np.nan_to_num(test_data_scaled, nan=0)
339
+
340
+ scaler_params = [mean, std]
341
+
342
+ return scaler_params, train_data_scaled, test_data_scaled
343
+
344
+ if scaler_params is None and x_train is None and x_test is not None:
345
+ return x_test.astype(dtype, copy=False) # sample data not scaled
346
+
347
+ if scaler_params is not None:
348
+ x_test = x_test.astype(dtype, copy=False)
349
+ scaled_data = (x_test - scaler_params[0]) / scaler_params[1]
350
+ scaled_data = np.nan_to_num(scaled_data, nan=0)
351
+
352
+ return scaled_data # sample data scaled
353
+
354
+
355
+ def normalization(
356
+ Input, # num: Input data to be normalized.
357
+ dtype=np.float32):
358
+ """
359
+ Normalizes the input data using maximum absolute scaling.
360
+
361
+ Args:
362
+ Input (num): Input data to be normalized.
363
+ dtype (numpy.dtype): Data type for the arrays. np.float32 by default. Example: np.float64 or np.float16. [fp32 for balanced devices, fp64 for strong devices, fp16 for weak devices: not reccomended!]
364
+
365
+ Returns:
366
+ (num) Scaled input data after normalization.
367
+ """
368
+
369
+ MaxAbs = np.max(np.abs(Input.astype(dtype, copy=False)))
370
+ return (Input / MaxAbs)
371
+
372
+
373
+ def find_closest_factors(a):
374
+
375
+ root = int(math.sqrt(a))
376
+
377
+ for i in range(root, 0, -1):
378
+ if a % i == 0:
379
+ j = a // i
380
+ return i, j
381
+
382
+
383
+ def batcher(x_test, y_test, batch_size=1):
384
+
385
+ if batch_size == 1:
386
+ return x_test, y_test
387
+
388
+ y_labels = np.argmax(y_test, axis=1)
389
+
390
+ sampled_x, sampled_y = [], []
391
+
392
+ for class_label in np.unique(y_labels):
393
+
394
+ class_indices = np.where(y_labels == class_label)[0]
395
+
396
+ num_samples = int(len(class_indices) * batch_size)
397
+
398
+ sampled_indices = np.random.choice(class_indices, num_samples, replace=False)
399
+
400
+ sampled_x.append(x_test[sampled_indices])
401
+ sampled_y.append(y_test[sampled_indices])
402
+
403
+ return np.concatenate(sampled_x), np.concatenate(sampled_y)