pyerualjetwork 2.7.1__py3-none-any.whl → 2.7.2__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.
plan/plan.py CHANGED
@@ -1175,1625 +1175,6 @@ def encode_one_hot(y_train, y_test):
1175
1175
  Returns:
1176
1176
  tuple: One-hot encoded y_train ve y_test verileri.
1177
1177
  """
1178
- try:
1179
- classes = np.unique(y_train)
1180
- class_count = len(classes)
1181
-
1182
- class_to_index = {cls: idx for idx, cls in enumerate(classes)}
1183
-
1184
- y_train_encoded = np.zeros((y_train.shape[0], class_count))
1185
- for i, label in enumerate(y_train):
1186
- y_train_encoded[i, class_to_index[label]] = 1
1187
-
1188
- y_test_encoded = np.zeros((y_test.shape[0], class_count))
1189
- for i, label in enumerate(y_test):
1190
- y_test_encoded[i, class_to_index[label]] = 1
1191
- except:
1192
- print(Fore.RED + 'ERROR: y_train and y_test must be numpy array. from: one_hot_encode' + info_one_hot_encode)
1193
-
1194
- return y_train_encoded, y_test_encoded
1195
-
1196
-
1197
- def split(X, y, test_size, random_state):
1198
- """
1199
- Splits the given X (features) and y (labels) data into training and testing subsets.
1200
-
1201
- Args:
1202
- X (numpy.ndarray): Features data.
1203
- y (numpy.ndarray): Labels data.
1204
- test_size (float or int): Proportion or number of samples for the test subset.
1205
- random_state (int or None): Seed for random state.
1206
-
1207
- Returns:
1208
- tuple: x_train, x_test, y_train, y_test as ordered training and testing data subsets.
1209
- """
1210
- num_samples = X.shape[0]
1211
-
1212
- if isinstance(test_size, float):
1213
- test_size = int(test_size * num_samples)
1214
- elif isinstance(test_size, int):
1215
- if test_size > num_samples:
1216
- raise ValueError(
1217
- "test_size cannot be larger than the number of samples.")
1218
- else:
1219
- raise ValueError("test_size should be float or int.")
1220
-
1221
- if random_state is not None:
1222
- np.random.seed(random_state)
1223
-
1224
- indices = np.arange(num_samples)
1225
- np.random.shuffle(indices)
1226
-
1227
- test_indices = indices[:test_size]
1228
- train_indices = indices[test_size:]
1229
-
1230
- x_train, x_test = X[train_indices], X[test_indices]
1231
- y_train, y_test = y[train_indices], y[test_indices]
1232
-
1233
- return x_train, x_test, y_train, y_test
1234
-
1235
-
1236
- def metrics(y_ts, test_preds, average='weighted'):
1237
- """
1238
- Calculates precision, recall and F1 score for a classification task.
1239
-
1240
- Args:
1241
- y_ts (list or numpy.ndarray): True labels.
1242
- test_preds (list or numpy.ndarray): Predicted labels.
1243
- average (str): Type of averaging ('micro', 'macro', 'weighted').
1244
-
1245
- Returns:
1246
- tuple: Precision, recall, F1 score.
1247
- """
1248
- y_test_d = decode_one_hot(y_ts)
1249
- y_test_d = np.array(y_test_d)
1250
- y_pred = np.array(test_preds)
1251
-
1252
- if y_test_d.ndim > 1:
1253
- y_test_d = y_test_d.reshape(-1)
1254
- if y_pred.ndim > 1:
1255
- y_pred = y_pred.reshape(-1)
1256
-
1257
- tp = {}
1258
- fp = {}
1259
- fn = {}
1260
-
1261
- classes = np.unique(np.concatenate((y_test_d, y_pred)))
1262
-
1263
- for c in classes:
1264
- tp[c] = 0
1265
- fp[c] = 0
1266
- fn[c] = 0
1267
-
1268
- for c in classes:
1269
- for true, pred in zip(y_test_d, y_pred):
1270
- if true == c and pred == c:
1271
- tp[c] += 1
1272
- elif true != c and pred == c:
1273
- fp[c] += 1
1274
- elif true == c and pred != c:
1275
- fn[c] += 1
1276
-
1277
- precision = {}
1278
- recall = {}
1279
- f1 = {}
1280
-
1281
- for c in classes:
1282
- precision[c] = tp[c] / (tp[c] + fp[c]) if (tp[c] + fp[c]) > 0 else 0
1283
- recall[c] = tp[c] / (tp[c] + fn[c]) if (tp[c] + fn[c]) > 0 else 0
1284
- f1[c] = 2 * (precision[c] * recall[c]) / (precision[c] + recall[c]) if (precision[c] + recall[c]) > 0 else 0
1285
-
1286
- if average == 'micro':
1287
- precision_val = np.sum(list(tp.values())) / (np.sum(list(tp.values())) + np.sum(list(fp.values()))) if (np.sum(list(tp.values())) + np.sum(list(fp.values()))) > 0 else 0
1288
- recall_val = np.sum(list(tp.values())) / (np.sum(list(tp.values())) + np.sum(list(fn.values()))) if (np.sum(list(tp.values())) + np.sum(list(fn.values()))) > 0 else 0
1289
- f1_val = 2 * (precision_val * recall_val) / (precision_val + recall_val) if (precision_val + recall_val) > 0 else 0
1290
-
1291
- elif average == 'macro':
1292
- precision_val = np.mean(list(precision.values()))
1293
- recall_val = np.mean(list(recall.values()))
1294
- f1_val = np.mean(list(f1.values()))
1295
-
1296
- elif average == 'weighted':
1297
- weights = np.array([np.sum(y_test_d == c) for c in classes])
1298
- weights = weights / np.sum(weights)
1299
- precision_val = np.sum([weights[i] * precision[classes[i]] for i in range(len(classes))])
1300
- recall_val = np.sum([weights[i] * recall[classes[i]] for i in range(len(classes))])
1301
- f1_val = np.sum([weights[i] * f1[classes[i]] for i in range(len(classes))])
1302
-
1303
- else:
1304
- raise ValueError("Invalid value for 'average'. Choose from 'micro', 'macro', 'weighted'.")
1305
-
1306
- return precision_val, recall_val, f1_val
1307
-
1308
-
1309
- def decode_one_hot(encoded_data):
1310
- """
1311
- Decodes one-hot encoded data to original categorical labels.
1312
-
1313
- Args:
1314
- encoded_data (numpy.ndarray): One-hot encoded data with shape (n_samples, n_classes).
1315
-
1316
- Returns:
1317
- numpy.ndarray: Decoded categorical labels with shape (n_samples,).
1318
- """
1319
-
1320
- decoded_labels = np.argmax(encoded_data, axis=1)
1321
-
1322
- return decoded_labels
1323
-
1324
-
1325
- def roc_curve(y_true, y_score):
1326
- """
1327
- Compute Receiver Operating Characteristic (ROC) curve.
1328
-
1329
- Parameters:
1330
- y_true : array, shape = [n_samples]
1331
- True binary labels in range {0, 1} or {-1, 1}.
1332
- y_score : array, shape = [n_samples]
1333
- Target scores, can either be probability estimates of the positive class,
1334
- confidence values, or non-thresholded measure of decisions (as returned
1335
- by decision_function on some classifiers).
1336
-
1337
- Returns:
1338
- fpr : array, shape = [n]
1339
- Increasing false positive rates such that element i is the false positive rate
1340
- of predictions with score >= thresholds[i].
1341
- tpr : array, shape = [n]
1342
- Increasing true positive rates such that element i is the true positive rate
1343
- of predictions with score >= thresholds[i].
1344
- thresholds : array, shape = [n]
1345
- Decreasing thresholds on the decision function used to compute fpr and tpr.
1346
- """
1347
-
1348
- y_true = np.asarray(y_true)
1349
- y_score = np.asarray(y_score)
1350
-
1351
- if len(np.unique(y_true)) != 2:
1352
- raise ValueError("Only binary classification is supported.")
1353
-
1354
-
1355
- desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1]
1356
- y_score = y_score[desc_score_indices]
1357
- y_true = y_true[desc_score_indices]
1358
-
1359
-
1360
- fpr = []
1361
- tpr = []
1362
- thresholds = []
1363
- n_pos = np.sum(y_true)
1364
- n_neg = len(y_true) - n_pos
1365
-
1366
- tp = 0
1367
- fp = 0
1368
- prev_score = None
1369
-
1370
-
1371
- for i, score in enumerate(y_score):
1372
- if score != prev_score:
1373
- fpr.append(fp / n_neg)
1374
- tpr.append(tp / n_pos)
1375
- thresholds.append(score)
1376
- prev_score = score
1377
-
1378
- if y_true[i] == 1:
1379
- tp += 1
1380
- else:
1381
- fp += 1
1382
-
1383
- fpr.append(fp / n_neg)
1384
- tpr.append(tp / n_pos)
1385
- thresholds.append(score)
1386
-
1387
- return np.array(fpr), np.array(tpr), np.array(thresholds)
1388
-
1389
-
1390
- def confusion_matrix(y_true, y_pred, class_count):
1391
- """
1392
- Computes confusion matrix.
1393
-
1394
- Args:
1395
- y_true (numpy.ndarray): True class labels (1D array).
1396
- y_pred (numpy.ndarray): Predicted class labels (1D array).
1397
- num_classes (int): Number of classes.
1398
-
1399
- Returns:
1400
- numpy.ndarray: Confusion matrix of shape (num_classes, num_classes).
1401
- """
1402
- confusion = np.zeros((class_count, class_count), dtype=int)
1403
-
1404
- for i in range(len(y_true)):
1405
- true_label = y_true[i]
1406
- pred_label = y_pred[i]
1407
- confusion[true_label, pred_label] += 1
1408
-
1409
- return confusion
1410
-
1411
-
1412
- def plot_evaluate(y_test, y_preds, acc_list):
1413
-
1414
- acc = acc_list[len(acc_list) - 1]
1415
- y_true = decode_one_hot(y_test)
1416
-
1417
- y_true = np.array(y_true)
1418
- y_preds = np.array(y_preds)
1419
- Class = np.unique(decode_one_hot(y_test))
1420
-
1421
- precision, recall, f1 = metrics(y_test, y_preds)
1422
-
1423
-
1424
- # Confusion matrix
1425
- cm = confusion_matrix(y_true, y_preds, len(Class))
1426
- fig, axs = plt.subplots(2, 2, figsize=(16, 12))
1427
-
1428
- # Confusion Matrix
1429
- sns.heatmap(cm, annot=True, fmt='d', ax=axs[0, 0])
1430
- axs[0, 0].set_title("Confusion Matrix")
1431
- axs[0, 0].set_xlabel("Predicted Class")
1432
- axs[0, 0].set_ylabel("Actual Class")
1433
-
1434
- if len(Class) == 2:
1435
- fpr, tpr, thresholds = roc_curve(y_true, y_preds)
1436
- # ROC Curve
1437
- roc_auc = np.trapz(tpr, fpr)
1438
- axs[1, 0].plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})')
1439
- axs[1, 0].plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
1440
- axs[1, 0].set_xlim([0.0, 1.0])
1441
- axs[1, 0].set_ylim([0.0, 1.05])
1442
- axs[1, 0].set_xlabel('False Positive Rate')
1443
- axs[1, 0].set_ylabel('True Positive Rate')
1444
- axs[1, 0].set_title('Receiver Operating Characteristic (ROC) Curve')
1445
- axs[1, 0].legend(loc="lower right")
1446
- axs[1, 0].legend(loc="lower right")
1447
- else:
1448
-
1449
- for i in range(len(Class)):
1450
-
1451
- y_true_copy = np.copy(y_true)
1452
- y_preds_copy = np.copy(y_preds)
1453
-
1454
- y_true_copy[y_true_copy == i] = 0
1455
- y_true_copy[y_true_copy != 0] = 1
1456
-
1457
- y_preds_copy[y_preds_copy == i] = 0
1458
- y_preds_copy[y_preds_copy != 0] = 1
1459
-
1460
-
1461
- fpr, tpr, thresholds = roc_curve(y_true_copy, y_preds_copy)
1462
-
1463
- roc_auc = np.trapz(tpr, fpr)
1464
- axs[1, 0].plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})')
1465
- axs[1, 0].plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
1466
- axs[1, 0].set_xlim([0.0, 1.0])
1467
- axs[1, 0].set_ylim([0.0, 1.05])
1468
- axs[1, 0].set_xlabel('False Positive Rate')
1469
- axs[1, 0].set_ylabel('True Positive Rate')
1470
- axs[1, 0].set_title('Receiver Operating Characteristic (ROC) Curve')
1471
- axs[1, 0].legend(loc="lower right")
1472
- axs[1, 0].legend(loc="lower right")
1473
-
1474
-
1475
- """
1476
- accuracy_per_class = []
1477
-
1478
- for cls in Class:
1479
- correct = np.sum((y_true == cls) & (y_preds == cls))
1480
- total = np.sum(y_true == cls)
1481
- accuracy_cls = correct / total if total > 0 else 0.0
1482
- accuracy_per_class.append(accuracy_cls)
1483
-
1484
- axs[2, 0].bar(Class, accuracy_per_class, color='b', alpha=0.7)
1485
- axs[2, 0].set_xlabel('Class')
1486
- axs[2, 0].set_ylabel('Accuracy')
1487
- axs[2, 0].set_title('Class-wise Accuracy')
1488
- axs[2, 0].set_xticks(Class)
1489
- axs[2, 0].grid(True)
1490
- """
1491
-
1492
-
1493
-
1494
-
1495
- # Precision, Recall, F1 Score, Accuracy
1496
- metric = ['Precision', 'Recall', 'F1 Score', 'Accuracy']
1497
- values = [precision, recall, f1, acc]
1498
- colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
1499
-
1500
- #
1501
- bars = axs[0, 1].bar(metric, values, color=colors)
1502
-
1503
-
1504
- for bar, value in zip(bars, values):
1505
- axs[0, 1].text(bar.get_x() + bar.get_width() / 2, bar.get_height() - 0.05, f'{value:.2f}',
1506
- ha='center', va='bottom', fontsize=12, color='white', weight='bold')
1507
-
1508
- axs[0, 1].set_ylim(0, 1) # Y eksenini 0 ile 1 arasında sınırla
1509
- axs[0, 1].set_xlabel('Metrics')
1510
- axs[0, 1].set_ylabel('Score')
1511
- axs[0, 1].set_title('Precision, Recall, F1 Score, and Accuracy (Weighted)')
1512
- axs[0, 1].grid(True, axis='y', linestyle='--', alpha=0.7)
1513
-
1514
- # Accuracy
1515
- plt.plot(acc_list, marker='o', linestyle='-',
1516
- color='r', label='Accuracy')
1517
-
1518
-
1519
- plt.axhline(y=1, color='g', linestyle='--', label='Maximum Accuracy')
1520
-
1521
-
1522
- plt.xlabel('Samples')
1523
- plt.ylabel('Accuracy')
1524
- plt.title('Accuracy History')
1525
- plt.legend()
1526
-
1527
-
1528
- plt.tight_layout()
1529
- plt.show()
1530
-
1531
- def manuel_balancer(x_train, y_train, target_samples_per_class):
1532
- """
1533
- Generates synthetic examples to balance classes to the specified number of examples per class.
1534
-
1535
- Arguments:
1536
- x_train -- Input dataset (examples) - NumPy array format
1537
- y_train -- Class labels (one-hot encoded) - NumPy array format
1538
- target_samples_per_class -- Desired number of samples per class
1539
-
1540
- Returns:
1541
- x_balanced -- Balanced input dataset (NumPy array format)
1542
- y_balanced -- Balanced class labels (one-hot encoded, NumPy array format)
1543
- """
1544
- try:
1545
- x_train = np.array(x_train)
1546
- y_train = np.array(y_train)
1547
- except:
1548
- print(Fore.GREEN + "x_tarin and y_train already numpyarray." + Style.RESET_ALL)
1549
- pass
1550
- classes = np.arange(y_train.shape[1])
1551
- class_count = len(classes)
1552
-
1553
- x_balanced = []
1554
- y_balanced = []
1555
-
1556
- for class_label in tqdm(range(class_count),leave=False, desc='Augmenting Data',ncols= 120):
1557
- class_indices = np.where(np.argmax(y_train, axis=1) == class_label)[0]
1558
- num_samples = len(class_indices)
1559
-
1560
- if num_samples > target_samples_per_class:
1561
-
1562
- selected_indices = np.random.choice(class_indices, target_samples_per_class, replace=False)
1563
- x_balanced.append(x_train[selected_indices])
1564
- y_balanced.append(y_train[selected_indices])
1565
-
1566
- else:
1567
-
1568
- x_balanced.append(x_train[class_indices])
1569
- y_balanced.append(y_train[class_indices])
1570
-
1571
- if num_samples < target_samples_per_class:
1572
-
1573
- samples_to_add = target_samples_per_class - num_samples
1574
- additional_samples = np.zeros((samples_to_add, x_train.shape[1]))
1575
- additional_labels = np.zeros((samples_to_add, y_train.shape[1]))
1576
-
1577
- for i in range(samples_to_add):
1578
-
1579
- random_indices = np.random.choice(class_indices, 2, replace=False)
1580
- sample1 = x_train[random_indices[0]]
1581
- sample2 = x_train[random_indices[1]]
1582
-
1583
-
1584
- synthetic_sample = sample1 + (sample2 - sample1) * np.random.rand()
1585
-
1586
- additional_samples[i] = synthetic_sample
1587
- additional_labels[i] = y_train[class_indices[0]]
1588
-
1589
-
1590
- x_balanced.append(additional_samples)
1591
- y_balanced.append(additional_labels)
1592
-
1593
- x_balanced = np.vstack(x_balanced)
1594
- y_balanced = np.vstack(y_balanced)
1595
-
1596
- return x_balanced, y_balanced
1597
-
1598
- def get_weights():
1599
-
1600
- return 0
1601
-
1602
-
1603
- def get_df():
1604
-
1605
- return 2
1606
-
1607
-
1608
- def get_preds():
1609
-
1610
- return 1
1611
-
1612
-
1613
- def get_acc():
1614
-
1615
- return 2
1616
-
1617
- # -*- coding: utf-8 -*-
1618
- """
1619
- Created on Tue Jun 18 23:32:16 2024
1620
-
1621
- @author: hasan
1622
- """
1623
-
1624
- import pandas as pd
1625
- import numpy as np
1626
- import time
1627
- from colorama import Fore, Style
1628
- from typing import List, Union
1629
- import math
1630
- from scipy.special import expit, softmax
1631
- import matplotlib.pyplot as plt
1632
- import seaborn as sns
1633
- from tqdm import tqdm
1634
-
1635
- # BUILD -----
1636
-
1637
-
1638
- def fit(
1639
- x_train: List[Union[int, float]],
1640
- y_train: List[Union[int, float]], # At least two.. and one hot encoded
1641
- val= None,
1642
- val_count = None,
1643
- activation_potentiation=None, # (float): Input activation_potentiation (optional)
1644
- x_val= None,
1645
- y_val= None,
1646
- show_training = None,
1647
- show_count= None
1648
- ) -> str:
1649
-
1650
- infoPLAN = """
1651
- Creates and configures a PLAN model.
1652
-
1653
- Args:
1654
- x_train (list[num]): List of input data.
1655
- y_train (list[num]): List of target labels. (one hot encoded)
1656
- val (None, True or 'final'): validation in training process ? None, True or 'final' Default: None (optional)
1657
- val_count (None, int): After how many examples learned will an accuracy test be performed? Default: 0.1 (%10) (optional)
1658
- activation_potentiation (float): Input activation potentiation (for binary injection) (optional) in range: -1, 1
1659
- x_val (list[num]): List of validation data. (optional) Default: 10% of x_train (auto_balanced)
1660
- y_val (list[num]): (list[num]): List of target labels. (one hot encoded) (optional) Default: 10% of y_train (auto_balanced)
1661
- show_training (bool, str): True, None or'final'
1662
- show_count (None, int): How many learning steps in total will be displayed in a single figure? (Adjust according to your hardware) Default: 10 (optional)
1663
- Returns:
1664
- list([num]): (Weight matrices list, train_predictions list, Train_acc).
1665
- error handled ?: Process status ('e')
1666
- """
1667
-
1668
- if len(x_train) != len(y_train):
1669
-
1670
- print(Fore.RED + "ERROR301: x_train list and y_train list must be same length. from: fit", infoPLAN + Style.RESET_ALL)
1671
- return 'e'
1672
-
1673
- if val == True or val == 'final':
1674
-
1675
- try:
1676
-
1677
- if x_val == None and y_val == None:
1678
-
1679
- x_train, x_val, y_train, y_val = split(x_train, y_train,test_size=0.1,random_state=42)
1680
-
1681
- x_train, y_train = auto_balancer(x_train, y_train)
1682
- x_val, y_val = auto_balancer(x_val, y_val)
1683
-
1684
- y_train, y_val = encode_one_hot(y_train, y_val)
1685
-
1686
- except:
1687
- pass
1688
-
1689
- if val == True:
1690
-
1691
- if val_count == None:
1692
-
1693
- val_count = 0.1
1694
-
1695
- v_iter = 0
1696
-
1697
- if val == 'final':
1698
-
1699
- val_count = 0.99
1700
-
1701
- val_count = int(len(x_train) * val_count)
1702
- val_count_copy = val_count
1703
- val_bar = tqdm(total=1, desc="Validating Accuracy", ncols=120)
1704
- val_list = [] * val_count
1705
-
1706
- if show_count == None:
1707
-
1708
- show_count = 10
1709
-
1710
- if show_training == True or show_training == 'final':
1711
-
1712
- row, col = shape_control(x_train)
1713
-
1714
- class_count = set()
1715
-
1716
- for sublist in y_train:
1717
-
1718
- class_count.add(tuple(sublist))
1719
-
1720
- class_count = list(class_count)
1721
-
1722
- y_train = [tuple(sublist) for sublist in y_train]
1723
-
1724
- neurons = [len(class_count), len(class_count)]
1725
- layers = ['fex']
1726
-
1727
- x_train[0] = np.array(x_train[0])
1728
- x_train[0] = x_train[0].ravel()
1729
- x_train_size = len(x_train[0])
1730
-
1731
- STPW = weight_identification(
1732
- len(layers) - 1, len(class_count), neurons, x_train_size) # STPW = SHORT TIME POTENTIATION WEIGHT
1733
-
1734
- LTPW = [1] * len(STPW) # LTPW = LONG TIME POTENTIATION WEIGHT
1735
-
1736
- y = decode_one_hot(y_train)
1737
-
1738
- train_progress = tqdm(total=len(x_train),leave=False, desc="Training",ncols= 120)
1739
-
1740
- for index, inp in enumerate(x_train):
1741
-
1742
- progress = index / len(x_train) * 100
1743
-
1744
- inp = np.array(inp)
1745
- inp = inp.ravel()
1746
-
1747
- if x_train_size != len(inp):
1748
- print(Fore.RED + "ERROR304: All input matrices or vectors in x_train list, must be same size. from: fit",
1749
- infoPLAN + Style.RESET_ALL)
1750
- return 'e'
1751
-
1752
- neural_layer = inp
1753
-
1754
- for Lindex, Layer in enumerate(layers):
1755
-
1756
- neural_layer = normalization(neural_layer)
1757
-
1758
- if Layer == 'fex':
1759
- STPW[Lindex] = fex(neural_layer, STPW[Lindex], True, y[index], activation_potentiation)
1760
-
1761
- for i, w in enumerate(STPW):
1762
- LTPW[i] = LTPW[i] + w
1763
-
1764
-
1765
- if val == True and index == val_count:
1766
-
1767
-
1768
- val_count += val_count_copy
1769
-
1770
- validation_model = evaluate(x_val, y_val, LTPW, activation_potentiation, None)
1771
-
1772
- val_acc = validation_model[get_acc()]
1773
-
1774
- val_list.append(val_acc)
1775
-
1776
- if v_iter == 0:
1777
-
1778
- val_bar.update(val_acc)
1779
-
1780
-
1781
- if v_iter != 0:
1782
-
1783
- val_acc = val_acc - val_list[v_iter - 1]
1784
- val_bar.update(val_acc)
1785
-
1786
- v_iter += 1
1787
-
1788
- if show_training == True:
1789
-
1790
- if index %show_count == 0:
1791
-
1792
-
1793
- if index != 0:
1794
- plt.close(fig)
1795
-
1796
- if row != 0:
1797
-
1798
- fig, ax = plt.subplots(1, len(class_count), figsize=(18, 14))
1799
-
1800
- else:
1801
-
1802
- fig, ax = plt.subplots(1, 1, figsize=(18, 14))
1803
-
1804
- for j in range(len(class_count)):
1805
-
1806
-
1807
- if row != 0:
1808
-
1809
- mat = LTPW[0][j,:].reshape(row, col)
1810
- suptitle_info = 'Neurons Learning Progress: % '
1811
- title_info = f'{j+1}. Neuron'
1812
-
1813
- mat = LTPW[0][j,:].reshape(row, col)
1814
-
1815
- ax[j].imshow(mat, interpolation='sinc', cmap='viridis')
1816
-
1817
- ax[j].set_aspect('equal')
1818
-
1819
- ax[j].set_xticks([])
1820
- ax[j].set_yticks([])
1821
- ax[j].set_title(title_info)
1822
-
1823
- else:
1824
-
1825
- mat = LTPW[0]
1826
- ax.imshow(mat, interpolation='sinc', cmap='viridis')
1827
- suptitle_info = 'Weight Learning Progress: % '
1828
- title_info = 'Weight Matrix Of Fex Layer'
1829
-
1830
-
1831
-
1832
-
1833
- progress_status = f"{progress:.1f}"
1834
- fig.suptitle(suptitle_info + progress_status)
1835
- plt.draw()
1836
- plt.pause(0.1)
1837
-
1838
-
1839
- STPW = weight_identification(
1840
- len(layers) - 1, len(class_count), neurons, x_train_size)
1841
-
1842
- train_progress.update(1)
1843
-
1844
- if show_training == 'final':
1845
-
1846
- fig, ax = plt.subplots(1, len(class_count), figsize=(18, 14))
1847
-
1848
- for j in range(len(class_count)):
1849
-
1850
- mat = LTPW[0][j,:].reshape(row, col)
1851
-
1852
- ax[j].imshow(mat, interpolation='sinc', cmap='viridis')
1853
- ax[j].set_aspect('equal')
1854
-
1855
- ax[j].set_xticks([])
1856
- ax[j].set_yticks([])
1857
- ax[j].set_title(f'{j+1}. Neuron')
1858
-
1859
- progress_status = f"{progress:.1f}"
1860
- fig.suptitle('Neurons Learning Progress: % ' + progress_status)
1861
- plt.draw()
1862
- plt.pause(0.1)
1863
-
1864
-
1865
- if val == 'final':
1866
-
1867
- validation_model = evaluate(x_val, y_val, None, LTPW, activation_potentiation, None)
1868
-
1869
- val_acc = validation_model[get_acc()]
1870
-
1871
- val_list.append(val_acc)
1872
-
1873
- val_bar.update(val_acc)
1874
-
1875
- return LTPW
1876
-
1877
- # FUNCTIONS -----
1878
-
1879
- def shape_control(x_train):
1880
-
1881
- try:
1882
- row = x_train[1].shape[0]
1883
- col = x_train[1].shape[1]
1884
-
1885
- except:
1886
-
1887
- print(Fore.MAGENTA + 'WARNING: You trying show_training but inputs is raveled. x_train inputs should be reshaped for show_training.' + Style.RESET_ALL)
1888
-
1889
- try:
1890
- row, col = find_numbers(len(x_train[0]))
1891
-
1892
- except:
1893
-
1894
- print(Fore.MAGENTA + 'WARNING: Input length cannot be reshaped. Neurons learning progression cannot be draw, weight learning progress drwaing started.' + Style.RESET_ALL)
1895
- return [0, 0]
1896
-
1897
- return row, col
1898
-
1899
- def find_numbers(n):
1900
- if n <= 1:
1901
- raise ValueError("Parameter 'n' must be greater than 1.")
1902
-
1903
- for i in range(2, int(n**0.5) + 1):
1904
- if n % i == 0:
1905
- factor1 = i
1906
- factor2 = n // i
1907
- if factor1 == factor2:
1908
- return factor1, factor2
1909
-
1910
- return None
1911
-
1912
- def weight_normalization(
1913
- W,
1914
- class_count
1915
- ) -> str:
1916
- """
1917
- Row(Neuron) based normalization. For unbalanced models.
1918
-
1919
- Args:
1920
- W (list(num)): Trained weight matrix list.
1921
- class_count (int): Class count of model.
1922
-
1923
- Returns:
1924
- list([numpy_arrays],[...]): posttrained weight matices of the model. .
1925
- """
1926
-
1927
- for i in range(class_count):
1928
-
1929
- W[0][i,:] = normalization(W[0][i,:])
1930
-
1931
- return W
1932
-
1933
- def weight_identification(
1934
- layer_count, # int: Number of layers in the neural network.
1935
- class_count, # int: Number of classes in the classification task.
1936
- neurons, # list[num]: List of neuron counts for each layer.
1937
- x_train_size # int: Size of the input data.
1938
- ) -> str:
1939
- """
1940
- Identifies the weights for a neural network model.
1941
-
1942
- Args:
1943
- layer_count (int): Number of layers in the neural network.
1944
- class_count (int): Number of classes in the classification task.
1945
- neurons (list[num]): List of neuron counts for each layer.
1946
- x_train_size (int): Size of the input data.
1947
-
1948
- Returns:
1949
- list([numpy_arrays],[...]): pretrained weight matices of the model. .
1950
- """
1951
-
1952
- Wlen = layer_count + 1
1953
- W = [None] * Wlen
1954
- W[0] = np.ones((neurons[0], x_train_size))
1955
- ws = layer_count - 1
1956
- for w in range(ws):
1957
- W[w + 1] = np.ones((neurons[w + 1], neurons[w]))
1958
-
1959
- return W
1960
-
1961
-
1962
- def fex(
1963
- Input, # list[num]: Input data.
1964
- w, # num: Weight matrix of the neural network.
1965
- is_training, # bool: Flag indicating if the function is called during training (True or False).
1966
- Class, # int: Which class is, if training.
1967
- activation_potentiation # float or None: Input activation potentiation (optional)
1968
- ) -> tuple:
1969
- """
1970
- Applies feature extraction process to the input data using synaptic potentiation.
1971
-
1972
- Args:
1973
- Input (num): Input data.
1974
- w (num): Weight matrix of the neural network.
1975
- is_training (bool): Flag indicating if the function is called during training (True or False).
1976
- Class (int): if is during training then which class(label) ? is isnt then put None.
1977
- activation_potentiation (float or None): Threshold value for comparison. (optional)
1978
-
1979
- Returns:
1980
- tuple: A tuple (vector) containing the neural layer result and the updated weight matrix.
1981
- """
1982
-
1983
- if is_training == True and activation_potentiation == None:
1984
-
1985
- w[Class, :] = Input
1986
-
1987
- return w
1988
-
1989
- elif is_training == True and activation_potentiation != None:
1990
-
1991
-
1992
- Input[Input < activation_potentiation] = 0
1993
- Input[Input > activation_potentiation] = 1
1994
-
1995
- w[Class,:] = Input
1996
-
1997
- return w
1998
-
1999
- elif is_training == False and activation_potentiation == None:
2000
-
2001
- neural_layer = np.dot(w, Input)
2002
-
2003
- return neural_layer
2004
-
2005
- elif is_training == False and activation_potentiation != None:
2006
-
2007
- Input[Input < activation_potentiation] = 0
2008
- Input[Input > activation_potentiation] = 1
2009
-
2010
- neural_layer = np.dot(w, Input)
2011
-
2012
- return neural_layer
2013
-
2014
-
2015
-
2016
- def normalization(
2017
- Input # num: Input data to be normalized.
2018
- ):
2019
- """
2020
- Normalizes the input data using maximum absolute scaling.
2021
-
2022
- Args:
2023
- Input (num): Input data to be normalized.
2024
-
2025
- Returns:
2026
- (num) Scaled input data after normalization.
2027
- """
2028
-
2029
- AbsVector = np.abs(Input)
2030
-
2031
- MaxAbs = np.max(AbsVector)
2032
-
2033
- ScaledInput = Input / MaxAbs
2034
-
2035
- return ScaledInput
2036
-
2037
-
2038
- def Softmax(
2039
- x # num: Input data to be transformed using softmax function.
2040
- ):
2041
- """
2042
- Applies the softmax function to the input data.
2043
-
2044
- Args:
2045
- (num): Input data to be transformed using softmax function.
2046
-
2047
- Returns:
2048
- (num): Transformed data after applying softmax function.
2049
- """
2050
-
2051
- return softmax(x)
2052
-
2053
-
2054
- def Sigmoid(
2055
- x # num: Input data to be transformed using sigmoid function.
2056
- ):
2057
- """
2058
- Applies the sigmoid function to the input data.
2059
-
2060
- Args:
2061
- (num): Input data to be transformed using sigmoid function.
2062
-
2063
- Returns:
2064
- (num): Transformed data after applying sigmoid function.
2065
- """
2066
- return expit(x)
2067
-
2068
-
2069
- def Relu(
2070
- x # num: Input data to be transformed using ReLU function.
2071
- ):
2072
- """
2073
- Applies the Rectified Linear Unit (ReLU) function to the input data.
2074
-
2075
- Args:
2076
- (num): Input data to be transformed using ReLU function.
2077
-
2078
- Returns:
2079
- (num): Transformed data after applying ReLU function.
2080
- """
2081
-
2082
- return np.maximum(0, x)
2083
-
2084
-
2085
- def evaluate(
2086
- x_test, # list[num]: Test input data.
2087
- y_test, # list[num]: Test labels.
2088
- W, # list[num]: Weight matrix list of the neural network.
2089
- activation_potentiation=None, # activation_potentiation (float or None): Threshold value for comparison. (optional) Default: None
2090
- acc_bar_status=True, # acc_bar_status (bool): Loading bar for accuracy (True or None) (optional) Default: True
2091
- show_metrices=None # show_metrices (bool): (True or None) (optional) Default: None
2092
- ) -> tuple:
2093
- infoTestModel = """
2094
- Tests the neural network model with the given test data.
2095
-
2096
- Args:
2097
- x_test (list[num]): Test input data.
2098
- y_test (list[num]): Test labels.
2099
- W (list[num]): Weight matrix list of the neural network.
2100
- activation_potentiation (float or None): Threshold value for comparison. (optional) Default: None
2101
- acc_bar_status (bool): Loading bar for accuracy (True or None) (optional) Default: True
2102
- show_metrices (bool): (True or None) (optional) Default: None
2103
-
2104
- Returns:
2105
- tuple: A tuple containing the predicted labels and the accuracy of the model.
2106
- """
2107
-
2108
- layers = ['fex']
2109
-
2110
- try:
2111
- Wc = [0] * len(W) # Wc = Weight copy
2112
- true = 0
2113
- y_preds = [-1] * len(y_test)
2114
- acc_list = []
2115
-
2116
- for i, w in enumerate(W):
2117
- Wc[i] = np.copy(w)
2118
-
2119
-
2120
- if acc_bar_status == True:
2121
-
2122
- test_progress = tqdm(total=len(x_test),leave=False, desc='Testing',ncols=120)
2123
- acc_bar = tqdm(total=1, desc="Test Accuracy", ncols=120)
2124
-
2125
-
2126
- for inpIndex, Input in enumerate(x_test):
2127
- Input = np.array(Input)
2128
- Input = Input.ravel()
2129
- neural_layer = Input
2130
-
2131
- for index, Layer in enumerate(layers):
2132
-
2133
- neural_layer = normalization(neural_layer)
2134
-
2135
- if Layer == 'fex':
2136
- neural_layer = fex(neural_layer, W[index], False, None, activation_potentiation)
2137
-
2138
-
2139
- for i, w in enumerate(Wc):
2140
- W[i] = np.copy(w)
2141
- RealOutput = np.argmax(y_test[inpIndex])
2142
- PredictedOutput = np.argmax(neural_layer)
2143
- if RealOutput == PredictedOutput:
2144
- true += 1
2145
- acc = true / len(y_test)
2146
-
2147
-
2148
- acc_list.append(acc)
2149
- y_preds[inpIndex] = PredictedOutput
2150
-
2151
- if acc_bar_status == True:
2152
- test_progress.update(1)
2153
- if inpIndex == 0:
2154
- acc_bar.update(acc)
2155
-
2156
- else:
2157
- acc = acc - acc_list[inpIndex - 1]
2158
- acc_bar.update(acc)
2159
-
2160
- if show_metrices == True:
2161
- plot_evaluate(y_test, y_preds, acc_list)
2162
-
2163
-
2164
- for i, w in enumerate(Wc):
2165
- W[i] = np.copy(w)
2166
-
2167
- except:
2168
-
2169
- print(Fore.RED + "ERROR: Are you sure weights are loaded ? from: evaluate" +
2170
- infoTestModel + Style.RESET_ALL)
2171
- return 'e'
2172
-
2173
- return W, y_preds, acc
2174
-
2175
-
2176
- def multiple_evaluate(
2177
- x_test, # list[num]: Test input data.
2178
- y_test, # list[num]: Test labels.
2179
- show_metrices, # show_metrices (bool): Visualize test progress ? (True or False)
2180
- MW, # list[list[num]]: Weight matrix of the neural network.
2181
- activation_potentiation=None # (float or None): Threshold value for comparison. (optional)
2182
- ) -> tuple:
2183
- infoTestModel = """
2184
- Tests the neural network model with the given test data.
2185
-
2186
- Args:
2187
- x_test (list[num]): Test input data.
2188
- y_test (list[num]): Test labels.
2189
- show_metrices (bool): (True or False)
2190
- MW (list(list[num])): Multiple Weight matrix list of the neural network. (Multiple model testing)
2191
-
2192
- Returns:
2193
- tuple: A tuple containing the predicted labels and the accuracy of the model.
2194
- """
2195
-
2196
- layers = ['fex', 'cat']
2197
-
2198
- try:
2199
- y_preds = [-1] * len(y_test)
2200
- acc_list = []
2201
- print(Fore.GREEN + "\n\nTest Started with 0 ERROR\n" + Style.RESET_ALL)
2202
- start_time = time.time()
2203
- true = 0
2204
- for inpIndex, Input in enumerate(x_test):
2205
-
2206
- output_layer = 0
2207
-
2208
- for m, Model in enumerate(MW):
2209
-
2210
- W = Model
2211
-
2212
- Wc = [0] * len(W) # Wc = weight copy
2213
-
2214
- y_preds = [None] * len(y_test)
2215
- for i, w in enumerate(W):
2216
- Wc[i] = np.copy(w)
2217
-
2218
- Input = np.array(Input)
2219
- Input = Input.ravel()
2220
- uni_start_time = time.time()
2221
- neural_layer = Input
2222
-
2223
- for index, Layer in enumerate(layers):
2224
-
2225
- neural_layer = normalization(neural_layer)
2226
-
2227
- if Layer == 'fex':
2228
- neural_layer = fex(neural_layer, W[index], False, None, activation_potentiation)
2229
-
2230
- output_layer += neural_layer
2231
-
2232
- for i, w in enumerate(Wc):
2233
- W[i] = np.copy(w)
2234
- for i, w in enumerate(Wc):
2235
- W[i] = np.copy(w)
2236
- RealOutput = np.argmax(y_test[inpIndex])
2237
- PredictedOutput = np.argmax(output_layer)
2238
- if RealOutput == PredictedOutput:
2239
- true += 1
2240
- acc = true / len(y_test)
2241
- if show_metrices == True:
2242
- acc_list.append(acc)
2243
- y_preds[inpIndex] = PredictedOutput
2244
-
2245
-
2246
- uni_end_time = time.time()
2247
-
2248
- calculating_est = round(
2249
- (uni_end_time - uni_start_time) * (len(x_test) - inpIndex), 3)
2250
-
2251
- if calculating_est < 60:
2252
- print('\rest......(sec):', calculating_est, '\n', end="")
2253
- print('\rTest accuracy: ', acc, "\n", end="")
2254
-
2255
- elif calculating_est > 60 and calculating_est < 3600:
2256
- print('\rest......(min):', calculating_est/60, '\n', end="")
2257
- print('\rTest accuracy: ', acc, "\n", end="")
2258
-
2259
- elif calculating_est > 3600:
2260
- print('\rest......(h):', calculating_est/3600, '\n', end="")
2261
- print('\rTest accuracy: ', acc, "\n", end="")
2262
- if show_metrices == True:
2263
- plot_evaluate(y_test, y_preds, acc_list)
2264
-
2265
- EndTime = time.time()
2266
- for i, w in enumerate(Wc):
2267
- W[i] = np.copy(w)
2268
-
2269
- calculating_est = round(EndTime - start_time, 2)
2270
-
2271
- print(Fore.GREEN + "\nTest Finished with 0 ERROR\n")
2272
-
2273
- if calculating_est < 60:
2274
- print('Total testing time(sec): ', calculating_est)
2275
-
2276
- elif calculating_est > 60 and calculating_est < 3600:
2277
- print('Total testing time(min): ', calculating_est/60)
2278
-
2279
- elif calculating_est > 3600:
2280
- print('Total testing time(h): ', calculating_est/3600)
2281
-
2282
- if acc >= 0.8:
2283
- print(Fore.GREEN + '\nTotal Test accuracy: ',
2284
- acc, '\n' + Style.RESET_ALL)
2285
-
2286
- elif acc < 0.8 and acc > 0.6:
2287
- print(Fore.MAGENTA + '\nTotal Test accuracy: ',
2288
- acc, '\n' + Style.RESET_ALL)
2289
-
2290
- elif acc <= 0.6:
2291
- print(Fore.RED + '\nTotal Test accuracy: ',
2292
- acc, '\n' + Style.RESET_ALL)
2293
-
2294
- except:
2295
-
2296
- print(Fore.RED + "ERROR: Testing model parameters like 'activation_potentiation' must be same as trained model. Check parameters. Are you sure weights are loaded ? from: evaluate" + infoTestModel + Style.RESET_ALL)
2297
- return 'e'
2298
-
2299
- return W, y_preds, acc
2300
-
2301
-
2302
- def save_model(model_name,
2303
- model_type,
2304
- class_count,
2305
- test_acc,
2306
- weights_type,
2307
- weights_format,
2308
- model_path,
2309
- scaler_params,
2310
- W,
2311
- activation_potentiation=None
2312
- ):
2313
-
2314
- infosave_model = """
2315
- Function to save a potentiation learning model.
2316
-
2317
- Arguments:
2318
- model_name (str): Name of the model.
2319
- model_type (str): Type of the model.(options: PLAN)
2320
- class_count (int): Number of classes.
2321
- test_acc (float): Test accuracy of the model.
2322
- weights_type (str): Type of weights to save (options: 'txt', 'npy', 'mat').
2323
- WeightFormat (str): Format of the weights (options: 'd', 'f', 'raw').
2324
- model_path (str): Path where the model will be saved. For example: C:/Users/beydili/Desktop/denemePLAN/
2325
- scaler_params (int, float): standard scaler params list: mean,std. If not used standard scaler then be: None.
2326
- W: Weights of the model.
2327
- activation_potentiation (float or None): Threshold value for comparison. (optional)
2328
-
2329
- Returns:
2330
- str: Message indicating if the model was saved successfully or encountered an error.
2331
- """
2332
-
2333
- # Operations to be performed by the function will be written here
2334
- pass
2335
-
2336
- layers = ['fex']
2337
-
2338
- if weights_type != 'txt' and weights_type != 'npy' and weights_type != 'mat':
2339
- print(Fore.RED + "ERROR110: Save Weight type (File Extension) Type must be 'txt' or 'npy' or 'mat' from: save_model" +
2340
- infosave_model + Style.RESET_ALL)
2341
- return 'e'
2342
-
2343
- if weights_format != 'd' and weights_format != 'f' and weights_format != 'raw':
2344
- print(Fore.RED + "ERROR111: Weight Format Type must be 'd' or 'f' or 'raw' from: save_model" +
2345
- infosave_model + Style.RESET_ALL)
2346
- return 'e'
2347
-
2348
- NeuronCount = 0
2349
- SynapseCount = 0
2350
-
2351
- try:
2352
- for w in W:
2353
- NeuronCount += np.shape(w)[0]
2354
- SynapseCount += np.shape(w)[0] * np.shape(w)[1]
2355
- except:
2356
-
2357
- print(Fore.RED + "ERROR: Weight matrices has a problem from: save_model" +
2358
- infosave_model + Style.RESET_ALL)
2359
- return 'e'
2360
- import pandas as pd
2361
- from datetime import datetime
2362
- from scipy import io
2363
-
2364
- data = {'MODEL NAME': model_name,
2365
- 'MODEL TYPE': model_type,
2366
- 'LAYERS': layers,
2367
- 'LAYER COUNT': len(layers),
2368
- 'CLASS COUNT': class_count,
2369
- 'NEURON COUNT': NeuronCount,
2370
- 'SYNAPSE COUNT': SynapseCount,
2371
- 'TEST ACCURACY': test_acc,
2372
- 'SAVE DATE': datetime.now(),
2373
- 'WEIGHTS TYPE': weights_type,
2374
- 'WEIGHTS FORMAT': weights_format,
2375
- 'MODEL PATH': model_path,
2376
- 'STANDARD SCALER': scaler_params,
2377
- 'ACTIVATION POTENTIATION': activation_potentiation
2378
- }
2379
- try:
2380
-
2381
- df = pd.DataFrame(data)
2382
-
2383
- df.to_csv(model_path + model_name + '.txt', sep='\t', index=False)
2384
-
2385
- except:
2386
-
2387
- print(Fore.RED + "ERROR: Model log not saved probably model_path incorrect. Check the log parameters from: save_model" +
2388
- infosave_model + Style.RESET_ALL)
2389
- return 'e'
2390
- try:
2391
-
2392
- if weights_type == 'txt' and weights_format == 'd':
2393
-
2394
- for i, w in enumerate(W):
2395
- np.savetxt(model_path + model_name +
2396
- str(i+1) + 'w.txt', w, fmt='%d')
2397
-
2398
- if weights_type == 'txt' and weights_format == 'f':
2399
-
2400
- for i, w in enumerate(W):
2401
- np.savetxt(model_path + model_name +
2402
- str(i+1) + 'w.txt', w, fmt='%f')
2403
-
2404
- if weights_type == 'txt' and weights_format == 'raw':
2405
-
2406
- for i, w in enumerate(W):
2407
- np.savetxt(model_path + model_name + str(i+1) + 'w.txt', w)
2408
-
2409
- ###
2410
-
2411
- if weights_type == 'npy' and weights_format == 'd':
2412
-
2413
- for i, w in enumerate(W):
2414
- np.save(model_path + model_name +
2415
- str(i+1) + 'w.npy', w.astype(int))
2416
-
2417
- if weights_type == 'npy' and weights_format == 'f':
2418
-
2419
- for i, w in enumerate(W):
2420
- np.save(model_path + model_name + str(i+1) +
2421
- 'w.npy', w, w.astype(float))
2422
-
2423
- if weights_type == 'npy' and weights_format == 'raw':
2424
-
2425
- for i, w in enumerate(W):
2426
- np.save(model_path + model_name + str(i+1) + 'w.npy', w)
2427
-
2428
- ###
2429
-
2430
- if weights_type == 'mat' and weights_format == 'd':
2431
-
2432
- for i, w in enumerate(W):
2433
- w = {'w': w.astype(int)}
2434
- io.savemat(model_path + model_name + str(i+1) + 'w.mat', w)
2435
-
2436
- if weights_type == 'mat' and weights_format == 'f':
2437
-
2438
- for i, w in enumerate(W):
2439
- w = {'w': w.astype(float)}
2440
- io.savemat(model_path + model_name + str(i+1) + 'w.mat', w)
2441
-
2442
- if weights_type == 'mat' and weights_format == 'raw':
2443
-
2444
- for i, w in enumerate(W):
2445
- w = {'w': w}
2446
- io.savemat(model_path + model_name + str(i+1) + 'w.mat', w)
2447
-
2448
- except:
2449
-
2450
- print(Fore.RED + "ERROR: Model Weights not saved. Check the Weight parameters. SaveFilePath expl: 'C:/Users/hasancanbeydili/Desktop/denemePLAN/' from: save_model" + infosave_model + Style.RESET_ALL)
2451
- return 'e'
2452
- print(df)
2453
- message = (
2454
- Fore.GREEN + "Model Saved Successfully\n" +
2455
- Fore.MAGENTA + "Don't forget, if you want to load model: model log file and weight files must be in the same directory." +
2456
- Style.RESET_ALL
2457
- )
2458
-
2459
- return print(message)
2460
-
2461
-
2462
- def load_model(model_name,
2463
- model_path,
2464
- ):
2465
- infoload_model = """
2466
- Function to load a potentiation learning model.
2467
-
2468
- Arguments:
2469
- model_name (str): Name of the model.
2470
- model_path (str): Path where the model is saved.
2471
-
2472
- Returns:
2473
- lists: W(list[num]), activation_potentiation, DataFrame of the model
2474
- """
2475
- pass
2476
-
2477
- import scipy.io as sio
2478
-
2479
- try:
2480
-
2481
- df = pd.read_csv(model_path + model_name + '.' + 'txt', delimiter='\t')
2482
-
2483
- except:
2484
-
2485
- print(Fore.RED + "ERROR: Model Path error. accaptable form: 'C:/Users/hasancanbeydili/Desktop/denemePLAN/' from: load_model" +
2486
- infoload_model + Style.RESET_ALL)
2487
-
2488
- model_name = str(df['MODEL NAME'].iloc[0])
2489
- layer_count = int(df['LAYER COUNT'].iloc[0])
2490
- WeightType = str(df['WEIGHTS TYPE'].iloc[0])
2491
-
2492
- W = [0] * layer_count
2493
-
2494
- if WeightType == 'txt':
2495
- for i in range(layer_count):
2496
- W[i] = np.loadtxt(model_path + model_name + str(i+1) + 'w.txt')
2497
- elif WeightType == 'npy':
2498
- for i in range(layer_count):
2499
- W[i] = np.load(model_path + model_name + str(i+1) + 'w.npy')
2500
- elif WeightType == 'mat':
2501
- for i in range(layer_count):
2502
- W[i] = sio.loadmat(model_path + model_name + str(i+1) + 'w.mat')
2503
- else:
2504
- raise ValueError(
2505
- Fore.RED + "Incorrect weight type value. Value must be 'txt', 'npy' or 'mat' from: load_model." + infoload_model + Style.RESET_ALL)
2506
- print(Fore.GREEN + "Model loaded succesfully" + Style.RESET_ALL)
2507
- return W, df
2508
-
2509
-
2510
- def predict_model_ssd(Input, model_name, model_path):
2511
-
2512
- infopredict_model_ssd = """
2513
- Function to make a prediction using a divided potentiation learning artificial neural network (PLAN).
2514
-
2515
- Arguments:
2516
- Input (list or ndarray): Input data for the model (single vector or single matrix).
2517
- model_name (str): Name of the model.
2518
- Returns:
2519
- ndarray: Output from the model.
2520
- """
2521
- W, df = load_model(model_name, model_path)
2522
-
2523
- activation_potentiation = str(df['ACTIVATION POTENTIATION'].iloc[0])
2524
-
2525
- if activation_potentiation != 'nan':
2526
-
2527
- activation_potentiation = float(activation_potentiation)
2528
-
2529
- else:
2530
-
2531
- activation_potentiation = None
2532
-
2533
- try:
2534
-
2535
- scaler_params = df['STANDARD SCALER'].tolist()
2536
-
2537
-
2538
- scaler_params = [np.fromstring(arr.strip('[]'), sep=' ') for arr in scaler_params]
2539
-
2540
- Input = standard_scaler(None, Input, scaler_params)
2541
-
2542
- except:
2543
-
2544
- pass
2545
-
2546
-
2547
- layers = ['fex']
2548
-
2549
- Wc = [0] * len(W)
2550
- for i, w in enumerate(W):
2551
- Wc[i] = np.copy(w)
2552
- try:
2553
- neural_layer = Input
2554
- neural_layer = np.array(neural_layer)
2555
- neural_layer = neural_layer.ravel()
2556
- for index, Layer in enumerate(layers):
2557
-
2558
- neural_layer = normalization(neural_layer)
2559
-
2560
- if Layer == 'fex':
2561
- neural_layer = fex(neural_layer, W[index], False, None, activation_potentiation)
2562
- elif Layer == 'cat':
2563
- neural_layer = np.dot(W[index], neural_layer)
2564
- except:
2565
- print(Fore.RED + "ERROR: The input was probably entered incorrectly. from: predict_model_ssd" +
2566
- infopredict_model_ssd + Style.RESET_ALL)
2567
- return 'e'
2568
- for i, w in enumerate(Wc):
2569
- W[i] = np.copy(w)
2570
- return neural_layer
2571
-
2572
-
2573
- def predict_model_ram(Input, W, scaler_params=None, activation_potentiation=None):
2574
-
2575
- infopredict_model_ram = """
2576
- Function to make a prediction using a divided potentiation learning artificial neural network (PLAN).
2577
- from weights and parameters stored in memory.
2578
-
2579
- Arguments:
2580
- Input (list or ndarray): Input data for the model (single vector or single matrix).
2581
- W (list of ndarrays): Weights of the model.
2582
- scaler_params (int, float): standard scaler params list: mean,std. (optional) Default: None.
2583
- activation_potentiation (float or None): Threshold value for comparison. (optional) Default: None
2584
-
2585
- Returns:
2586
- ndarray: Output from the model.
2587
- """
2588
- try:
2589
- if scaler_params != None:
2590
-
2591
- Input = standard_scaler(None, Input, scaler_params)
2592
- except:
2593
- Input = standard_scaler(None, Input, scaler_params)
2594
-
2595
- layers = ['fex']
2596
-
2597
- Wc = [0] * len(W)
2598
- for i, w in enumerate(W):
2599
- Wc[i] = np.copy(w)
2600
- try:
2601
- neural_layer = Input
2602
- neural_layer = np.array(neural_layer)
2603
- neural_layer = neural_layer.ravel()
2604
- for index, Layer in enumerate(layers):
2605
-
2606
- neural_layer = normalization(neural_layer)
2607
-
2608
- if Layer == 'fex':
2609
- neural_layer = fex(neural_layer, W[index], False, None, activation_potentiation)
2610
- elif Layer == 'cat':
2611
- neural_layer = np.dot(W[index], neural_layer)
2612
-
2613
- except:
2614
- print(Fore.RED + "ERROR: Unexpected input or wrong model parameters from: predict_model_ram." +
2615
- infopredict_model_ram + Style.RESET_ALL)
2616
- return 'e'
2617
- for i, w in enumerate(Wc):
2618
- W[i] = np.copy(w)
2619
- return neural_layer
2620
-
2621
-
2622
- def auto_balancer(x_train, y_train):
2623
-
2624
- infoauto_balancer = """
2625
- Function to balance the training data across different classes.
2626
-
2627
- Arguments:
2628
- x_train (list): Input data for training.
2629
- y_train (list): Labels corresponding to the input data.
2630
-
2631
- Returns:
2632
- tuple: A tuple containing balanced input data and labels.
2633
- """
2634
- classes = np.arange(y_train.shape[1])
2635
- class_count = len(classes)
2636
-
2637
- try:
2638
- ClassIndices = {i: np.where(np.array(y_train)[:, i] == 1)[
2639
- 0] for i in range(class_count)}
2640
- classes = [len(ClassIndices[i]) for i in range(class_count)]
2641
-
2642
- if len(set(classes)) == 1:
2643
- print(Fore.WHITE + "INFO: All training data have already balanced. from: auto_balancer" + Style.RESET_ALL)
2644
- return x_train, y_train
2645
-
2646
- MinCount = min(classes)
2647
-
2648
- BalancedIndices = []
2649
- for i in tqdm(range(class_count),leave=False,desc='Balancing Data',ncols=120):
2650
- if len(ClassIndices[i]) > MinCount:
2651
- SelectedIndices = np.random.choice(
2652
- ClassIndices[i], MinCount, replace=False)
2653
- else:
2654
- SelectedIndices = ClassIndices[i]
2655
- BalancedIndices.extend(SelectedIndices)
2656
-
2657
- BalancedInputs = [x_train[idx] for idx in BalancedIndices]
2658
- BalancedLabels = [y_train[idx] for idx in BalancedIndices]
2659
-
2660
- print(Fore.GREEN + "All Training Data Succesfully Balanced from: " + str(len(x_train)
2661
- ) + " to: " + str(len(BalancedInputs)) + ". from: auto_balancer " + Style.RESET_ALL)
2662
- except:
2663
- print(Fore.RED + "ERROR: Inputs and labels must be same length check parameters" + infoauto_balancer)
2664
- return 'e'
2665
-
2666
- return np.array(BalancedInputs), np.array(BalancedLabels)
2667
-
2668
-
2669
- def synthetic_augmentation(x_train, y_train):
2670
- """
2671
- Generates synthetic examples to balance classes with fewer examples.
2672
-
2673
- Arguments:
2674
- x -- Input dataset (examples) - list format
2675
- y -- Class labels (one-hot encoded) - list format
2676
-
2677
- Returns:
2678
- x_balanced -- Balanced input dataset (list format)
2679
- y_balanced -- Balanced class labels (one-hot encoded, list format)
2680
- """
2681
- x = x_train
2682
- y = y_train
2683
- classes = np.arange(y_train.shape[1])
2684
- class_count = len(classes)
2685
-
2686
- # Calculate class distribution
2687
- class_distribution = {i: 0 for i in range(class_count)}
2688
- for label in y:
2689
- class_distribution[np.argmax(label)] += 1
2690
-
2691
- max_class_count = max(class_distribution.values())
2692
-
2693
- x_balanced = list(x)
2694
- y_balanced = list(y)
2695
-
2696
- for class_label in tqdm(range(class_count), leave=False, desc='Augmenting Data',ncols= 120):
2697
- class_indices = [i for i, label in enumerate(
2698
- y) if np.argmax(label) == class_label]
2699
- num_samples = len(class_indices)
2700
-
2701
- if num_samples < max_class_count:
2702
- while num_samples < max_class_count:
2703
-
2704
- random_indices = np.random.choice(
2705
- class_indices, 2, replace=False)
2706
- sample1 = x[random_indices[0]]
2707
- sample2 = x[random_indices[1]]
2708
-
2709
- synthetic_sample = sample1 + \
2710
- (np.array(sample2) - np.array(sample1)) * np.random.rand()
2711
-
2712
- x_balanced.append(synthetic_sample.tolist())
2713
- y_balanced.append(y[class_indices[0]])
2714
-
2715
- num_samples += 1
2716
-
2717
- return np.array(x_balanced), np.array(y_balanced)
2718
-
2719
-
2720
- def standard_scaler(x_train, x_test, scaler_params=None):
2721
- info_standard_scaler = """
2722
- Standardizes training and test datasets. x_test may be None.
2723
-
2724
- Args:
2725
- train_data: numpy.ndarray
2726
- Training data
2727
- test_data: numpy.ndarray
2728
- Test data
2729
-
2730
- Returns:
2731
- list:
2732
- Scaler parameters: mean and std
2733
- tuple
2734
- Standardized training and test datasets
2735
- """
2736
- try:
2737
-
2738
- x_train = x_train.tolist()
2739
- x_test = x_test.tolist()
2740
-
2741
- except:
2742
-
2743
- pass
2744
-
2745
- try:
2746
-
2747
- if scaler_params == None and x_test != None:
2748
-
2749
- mean = np.mean(x_train, axis=0)
2750
- std = np.std(x_train, axis=0)
2751
- train_data_scaled = (x_train - mean) / std
2752
- test_data_scaled = (x_test - mean) / std
2753
-
2754
- train_data_scaled = np.nan_to_num(train_data_scaled, nan=0)
2755
- test_data_scaled = np.nan_to_num(test_data_scaled, nan=0)
2756
-
2757
- scaler_params = [mean, std]
2758
-
2759
- return scaler_params, train_data_scaled, test_data_scaled
2760
-
2761
- if scaler_params == None and x_test == None:
2762
-
2763
- mean = np.mean(x_train, axis=0)
2764
- std = np.std(x_train, axis=0)
2765
- train_data_scaled = (x_train - mean) / std
2766
-
2767
- train_data_scaled = np.nan_to_num(train_data_scaled, nan=0)
2768
-
2769
- scaler_params = [mean, std]
2770
-
2771
- return scaler_params, train_data_scaled
2772
-
2773
- if scaler_params != None:
2774
-
2775
- test_data_scaled = (x_test - scaler_params[0]) / scaler_params[1]
2776
- test_data_scaled = np.nan_to_num(test_data_scaled, nan=0)
2777
-
2778
- return test_data_scaled
2779
-
2780
- except:
2781
- print(
2782
- Fore.RED + "ERROR: x_train and x_test must be list[numpyarray] from standard_scaler" + info_standard_scaler)
2783
-
2784
-
2785
- def encode_one_hot(y_train, y_test):
2786
- info_one_hot_encode = """
2787
- Performs one-hot encoding on y_train and y_test data..
2788
-
2789
- Args:
2790
- y_train (numpy.ndarray): Eğitim etiketi verisi.
2791
- y_test (numpy.ndarray): Test etiketi verisi.
2792
-
2793
- Returns:
2794
- tuple: One-hot encoded y_train ve y_test verileri.
2795
- """
2796
-
2797
1178
  classes = np.unique(y_train)
2798
1179
  class_count = len(classes)
2799
1180
 
@@ -2807,7 +1188,6 @@ def encode_one_hot(y_train, y_test):
2807
1188
  for i, label in enumerate(y_test):
2808
1189
  y_test_encoded[i, class_to_index[label]] = 1
2809
1190
 
2810
-
2811
1191
  return y_train_encoded, y_test_encoded
2812
1192
 
2813
1193