AbstractIntegratedModule 1.2.3__tar.gz → 1.2.4__tar.gz
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.
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractIntegratedModule.egg-info/PKG-INFO +1 -1
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractIntegratedModule.py +187 -168
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractOptimizedModules.c +200 -200
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/PKG-INFO +1 -1
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/README.md +8 -4
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/pyproject.toml +1 -1
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/setup.py +2 -2
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractIntegratedModule.egg-info/SOURCES.txt +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractIntegratedModule.egg-info/dependency_links.txt +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractIntegratedModule.egg-info/requires.txt +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractIntegratedModule.egg-info/top_level.txt +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractOptimizedModules.pyx +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/MANIFEST.in +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/Cargo.toml +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/pyproject.toml +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/src/lib.rs +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/target/debug/build/libsqlite3-sys-ed07b882cd2aa5e2/out/bindgen.rs +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/target/debug/build/serde_core-ebc15f2e9cad7f5f/out/private.rs +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/target/debug/build/target-lexicon-08527f45de28143d/out/host.rs +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/target/release/build/libsqlite3-sys-bf0400df4523274c/out/bindgen.rs +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/target/release/build/serde_core-5cdb76131825e4af/out/private.rs +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/abstract_model_storage/target/release/build/target-lexicon-43eb95a0588bf457/out/host.rs +0 -0
- {abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/setup.cfg +0 -0
{abstractintegratedmodule-1.2.3 → abstractintegratedmodule-1.2.4}/AbstractIntegratedModule.py
RENAMED
|
@@ -3796,7 +3796,9 @@ class MLP:
|
|
|
3796
3796
|
return y_pred, y_true
|
|
3797
3797
|
|
|
3798
3798
|
|
|
3799
|
-
def train(self, X, y, epochs=1000, lr=0.01, verbose=True, max_samples_for_focused_fit=500):
|
|
3799
|
+
def train(self, X, y, X_val=None, y_val=None, epochs=1000, lr=0.01, verbose=True, max_samples_for_focused_fit=500):
|
|
3800
|
+
y_val_pred = None
|
|
3801
|
+
y_val_true = None
|
|
3800
3802
|
X = self._sanitize_string_chars(X)
|
|
3801
3803
|
y = self._sanitize_string_chars(y)
|
|
3802
3804
|
parameters = sum(w.size for w in self.layers[0].W) + sum(b.size for b in self.layers[0].b)
|
|
@@ -3814,6 +3816,10 @@ class MLP:
|
|
|
3814
3816
|
else:
|
|
3815
3817
|
print(f'[+] MLP Training started with: {parameters} Parameters.')
|
|
3816
3818
|
for epoch in range(epochs):
|
|
3819
|
+
if X_val is not None and y_val is not None:
|
|
3820
|
+
y_val_pred = self.forward(X_val, y=y_val, AME=AME, anisotropy=anisotropy, condition='training')
|
|
3821
|
+
y_val_pred, y_val_true = self.adapt_predict_shape(y_val_pred, y_val)
|
|
3822
|
+
|
|
3817
3823
|
y_pred = self.forward(X, y=y, AME=AME, anisotropy=anisotropy, condition='training')
|
|
3818
3824
|
y_pred, y_true = self.adapt_predict_shape(y_pred, y)
|
|
3819
3825
|
|
|
@@ -3823,16 +3829,16 @@ class MLP:
|
|
|
3823
3829
|
try:
|
|
3824
3830
|
params = self.layers[0].opt.step(self.layers[0].params, key_grads, clip_norm=5.0)
|
|
3825
3831
|
except Exception as e:
|
|
3826
|
-
print(f'[>] AdamOptimizer
|
|
3832
|
+
print(f'[>] AdamOptimizer error occured: {e}')
|
|
3827
3833
|
continue
|
|
3828
3834
|
|
|
3829
|
-
if np.isnan(loss) or np.isinf(loss):
|
|
3830
|
-
if focused_fit_condition:
|
|
3831
|
-
focused_fit_condition = False
|
|
3832
|
-
|
|
3833
3835
|
if verbose and epoch % 100 == 0:
|
|
3834
3836
|
acc = np.mean(np.argmax(y_pred, axis=1) == np.argmax(y_true, axis=1))
|
|
3835
|
-
|
|
3837
|
+
if y_val_pred is not None and y_val_true is not None:
|
|
3838
|
+
val_acc = np.mean(np.argmax(y_val_pred, axis=1) == np.argmax(y_val_true, axis=1))
|
|
3839
|
+
print(f"[=] Epoch {epoch} | Loss: {loss:.4f} | Acc: {acc:.2f} | Validation Acc: {val_acc:.2f}")
|
|
3840
|
+
else:
|
|
3841
|
+
print(f"[=] Epoch {epoch} | Loss: {loss:.4f} | Acc: {acc:.2f}")
|
|
3836
3842
|
|
|
3837
3843
|
# ─────────────────────────────────────────────
|
|
3838
3844
|
# LSTM Cell
|
|
@@ -15422,7 +15428,7 @@ class IntegratedPipeline:
|
|
|
15422
15428
|
return True, (f'n={n_samples}, T={T}, anisotropy={anisotropy:.4f} — '
|
|
15423
15429
|
f'sufficient structure and data to justify Transformer training')
|
|
15424
15430
|
|
|
15425
|
-
def transformer_utilities(self, X_provided= None, X_raw=None, y_true=None, rules=None,
|
|
15431
|
+
def transformer_utilities(self, X_val=None, y_val=None, X_provided= None, X_raw=None, y_true=None, rules=None,
|
|
15426
15432
|
datasets=None, label_map=None, batch_size=2, min_signal=1e-3,
|
|
15427
15433
|
max_samples_for_focused_fit=500, max_ram_used=80):
|
|
15428
15434
|
unsuitable = False
|
|
@@ -15618,7 +15624,7 @@ class IntegratedPipeline:
|
|
|
15618
15624
|
self.initialize_model_(X, input_dim, n_classes)
|
|
15619
15625
|
|
|
15620
15626
|
if not unsuitable:
|
|
15621
|
-
self.model3.train(X, y, epochs=self.mlp_training_epochs, lr=self.mlp_lr, max_samples_for_focused_fit=max_samples_for_focused_fit)
|
|
15627
|
+
self.model3.train(X, y, X_val=X_val, y_val=y_val, epochs=self.mlp_training_epochs, lr=self.mlp_lr, max_samples_for_focused_fit=max_samples_for_focused_fit)
|
|
15622
15628
|
else:
|
|
15623
15629
|
print('[->] MLP Training skipped due to unproper Y samples.')
|
|
15624
15630
|
|
|
@@ -15861,8 +15867,8 @@ class AccurateAnswerCache:
|
|
|
15861
15867
|
if min_len > 0:
|
|
15862
15868
|
seq_sim = float(np.mean(ids_a[:min_len] == ids_b[:min_len]))
|
|
15863
15869
|
|
|
15864
|
-
combined_env_sim = ((mlp_sim + seq_sim) / 2
|
|
15865
|
-
deterministic_modelling_sim = ((mlp_sim + seq_sim) / 2
|
|
15870
|
+
combined_env_sim = ((mlp_sim + seq_sim) / 2 * anisotropy)
|
|
15871
|
+
deterministic_modelling_sim = ((mlp_sim + seq_sim) / 2 * AME)
|
|
15866
15872
|
|
|
15867
15873
|
combinatorial_absolute_factor = (
|
|
15868
15874
|
deterministic_modelling_sim > best_combined_sim and
|
|
@@ -18805,21 +18811,26 @@ def mc_confidence(net, encoder, x, n_samples=20, temperature=1.0,
|
|
|
18805
18811
|
# Printing
|
|
18806
18812
|
# ----------------------------------------------------------------------
|
|
18807
18813
|
|
|
18808
|
-
def print_confidence_report(results, top_k=3):
|
|
18809
|
-
"""
|
|
18814
|
+
def print_confidence_report(results, top_k=3, max_print_threshold=50):
|
|
18815
|
+
"""readable printout for a list of dicts from
|
|
18810
18816
|
predict_with_confidence() or mc_confidence()."""
|
|
18817
|
+
pred_cache = []
|
|
18811
18818
|
for i, r in enumerate(results):
|
|
18812
18819
|
order = np.argsort(-r["probs"])[:top_k]
|
|
18813
18820
|
top_str = ", ".join(f"{cls}:{r['probs'][cls]*100:.1f}%" for cls in order)
|
|
18814
18821
|
std_str = f" (±{r['confidence_std']*100:.1f}%)" if "confidence_std" in r else ""
|
|
18815
|
-
|
|
18816
|
-
|
|
18817
|
-
|
|
18818
|
-
|
|
18822
|
+
pred_cache.append(r['pred_name'])
|
|
18823
|
+
if i <= max_print_threshold:
|
|
18824
|
+
print(f"[>] Sample {i:3d} -> predicted={r['pred_name']} "
|
|
18825
|
+
f"|| Confidence={r['confidence']*100:.1f}%{std_str} "
|
|
18826
|
+
f"|| Entropy={r['entropy_frac']*100:.0f}% "
|
|
18827
|
+
f"|| Top-{top_k}: [{top_str}]")
|
|
18828
|
+
return pred_cache
|
|
18819
18829
|
|
|
18820
18830
|
|
|
18821
18831
|
|
|
18822
|
-
def train_snn_network(X=None, y=None,
|
|
18832
|
+
def train_snn_network(X=None, y=None, net=None, hidden_layer=None,
|
|
18833
|
+
epochs=50, batch_size=32, n_steps=20,
|
|
18823
18834
|
n_hidden=64, lr=2e-3, seed=0, pretrain_steps=200, unsupervised_stdp=False,
|
|
18824
18835
|
random_state=42):
|
|
18825
18836
|
tracker = DiagnosticsTracker()
|
|
@@ -18830,8 +18841,9 @@ def train_snn_network(X=None, y=None, epochs=50, batch_size=32, n_steps=20,
|
|
|
18830
18841
|
X_train, X_test, y_train, y_test, _, _ = _prepare_train_val_split(X=X, y=y, random_state=random_state)
|
|
18831
18842
|
n_in = X_train.shape[1]
|
|
18832
18843
|
n_classes = int(y_train.max() + 1)
|
|
18844
|
+
if net is None and hidden_layer is None:
|
|
18845
|
+
net, hidden_layer = build_snn_network(n_in, n_hidden, n_classes, rng)
|
|
18833
18846
|
|
|
18834
|
-
net, hidden_layer = build_snn_network(n_in, n_hidden, n_classes, rng)
|
|
18835
18847
|
encoder = PoissonEncoder(n_steps=n_steps, max_rate=1.0, rng=rng)
|
|
18836
18848
|
optimizer = Adam(lr=lr, weight_decay=1e-5)
|
|
18837
18849
|
homeostasis = ThresholdHomeostasis(target_rate=0.15, adjust_rate=0.05)
|
|
@@ -18887,7 +18899,7 @@ def train_snn_network(X=None, y=None, epochs=50, batch_size=32, n_steps=20,
|
|
|
18887
18899
|
return encoder, net, report, warnings
|
|
18888
18900
|
|
|
18889
18901
|
|
|
18890
|
-
def snn_predict(X=None, y=None, label_map=None, encoder=None, net=None, random_state=42):
|
|
18902
|
+
def snn_predict(X=None, y=None, label_map=None, encoder=None, net=None, random_state=42, max_print_threshold=50):
|
|
18891
18903
|
utility = SNNUtility()
|
|
18892
18904
|
reverse_map = None
|
|
18893
18905
|
|
|
@@ -18925,9 +18937,10 @@ def snn_predict(X=None, y=None, label_map=None, encoder=None, net=None, random_s
|
|
|
18925
18937
|
test_spikes = encoder.encode(X)
|
|
18926
18938
|
preds, logits = net.predict(test_spikes)
|
|
18927
18939
|
if reverse_map is not None:
|
|
18928
|
-
#
|
|
18940
|
+
# SNN-specific: uncertainty from the encoder's own stochasticity
|
|
18929
18941
|
mc_results = mc_confidence(net, encoder, X, n_samples=20, class_names=reverse_map)
|
|
18930
|
-
|
|
18942
|
+
print(f'[>] Displaying {max_print_threshold} predictions over {len(X)} samples...')
|
|
18943
|
+
_ = print_confidence_report(mc_results, max_print_threshold=max_print_threshold)
|
|
18931
18944
|
else:
|
|
18932
18945
|
print('[>] Label map is Missing during SNN prediction, returning SNN Logits as is without any label mapping...')
|
|
18933
18946
|
except Exception as e:
|
|
@@ -20100,7 +20113,7 @@ class PipelinePredictionManager:
|
|
|
20100
20113
|
# max: catches localized single-class failure
|
|
20101
20114
|
# that a flat average would dilute away
|
|
20102
20115
|
worst_class_idx = int(np.argmax(error_counts))
|
|
20103
|
-
max_error =
|
|
20116
|
+
max_error = error_counts[worst_class_idx]
|
|
20104
20117
|
if max_error > error_threshold:
|
|
20105
20118
|
signals.append(f'error_rate(class={worst_class_idx}, '
|
|
20106
20119
|
f'value={max_error:.2f})')
|
|
@@ -20158,6 +20171,35 @@ class PipelinePredictionManager:
|
|
|
20158
20171
|
print(f'[+] Transformer Prediction allowed: {propriate_single_transformer}')
|
|
20159
20172
|
return propriate_single_transformer
|
|
20160
20173
|
|
|
20174
|
+
def _get_voted_results(self, probs, reverse_map, n_samples):
|
|
20175
|
+
pred_cache = []
|
|
20176
|
+
_cache = {}
|
|
20177
|
+
cache = []
|
|
20178
|
+
for i in range(n_samples):
|
|
20179
|
+
try:
|
|
20180
|
+
each_idx = probs[i].argmax()
|
|
20181
|
+
except:
|
|
20182
|
+
each_idx = np.argmax(probs[:len(reverse_map)-1])
|
|
20183
|
+
try:
|
|
20184
|
+
confidence = float(probs[each_idx])
|
|
20185
|
+
except:
|
|
20186
|
+
confidence = float(probs[i][len(reverse_map)-1]) if isinstance(probs[i], (float, int)) else 0.0
|
|
20187
|
+
|
|
20188
|
+
pred_cache.append(each_idx)
|
|
20189
|
+
_cache[i] = (each_idx, confidence)
|
|
20190
|
+
|
|
20191
|
+
voted_chosen_label = max(set(pred_cache), key=pred_cache.count)
|
|
20192
|
+
conf_cache = []
|
|
20193
|
+
for i in range(len(_cache)):
|
|
20194
|
+
if _cache[i][0] == voted_chosen_label:
|
|
20195
|
+
confidence = _cache[i][1]
|
|
20196
|
+
conf_cache.append(confidence)
|
|
20197
|
+
|
|
20198
|
+
float_counts = Counter(conf_cache)
|
|
20199
|
+
voted_confidence, _ = float_counts.most_common(1)[0]
|
|
20200
|
+
|
|
20201
|
+
return voted_chosen_label, voted_confidence
|
|
20202
|
+
|
|
20161
20203
|
|
|
20162
20204
|
def advanced_prediction_method(self, titles=None, label_map=None, rules=None,
|
|
20163
20205
|
X=None, y=None,
|
|
@@ -20207,7 +20249,6 @@ class PipelinePredictionManager:
|
|
|
20207
20249
|
self.pipeline.titles = titles
|
|
20208
20250
|
self.pipeline.labels = label_map
|
|
20209
20251
|
|
|
20210
|
-
|
|
20211
20252
|
if X is not None and y is not None:
|
|
20212
20253
|
print(f"[🔍] Processing X and y samples for prediction and Training...")
|
|
20213
20254
|
if isinstance(X, (str, np.str_)):
|
|
@@ -20230,7 +20271,6 @@ class PipelinePredictionManager:
|
|
|
20230
20271
|
(x for x in clean_str.split() if x != "..."), dtype=float
|
|
20231
20272
|
)
|
|
20232
20273
|
|
|
20233
|
-
|
|
20234
20274
|
if len(X) < 5:
|
|
20235
20275
|
print(f"[⚠️] Warning: Only {len(X)} samples provided. Consider providing more samples for better prediction accuracy!")
|
|
20236
20276
|
|
|
@@ -20733,9 +20773,41 @@ class PipelinePredictionManager:
|
|
|
20733
20773
|
if float(results[0]['confidence']) < self.pipeline.confidence_threshold:
|
|
20734
20774
|
verbose = True
|
|
20735
20775
|
|
|
20736
|
-
|
|
20737
|
-
|
|
20738
|
-
|
|
20776
|
+
prediction_cache = []
|
|
20777
|
+
confidence_cache = {}
|
|
20778
|
+
agreement_cache = {}
|
|
20779
|
+
_cache = []
|
|
20780
|
+
|
|
20781
|
+
for i in range(len(results)):
|
|
20782
|
+
each_label = results[i].get('predicted') if results else 'Unknown'
|
|
20783
|
+
each_confidence = results[i].get('confidence') if results else 0.0
|
|
20784
|
+
each_agreement = results[i].get('models_agree') if results else False
|
|
20785
|
+
|
|
20786
|
+
prediction_cache.append(each_label)
|
|
20787
|
+
confidence_cache[i] = (each_label, each_confidence)
|
|
20788
|
+
agreement_cache[i] = (each_label, each_agreement)
|
|
20789
|
+
|
|
20790
|
+
voted_chosen_label = max(set(prediction_cache), key=prediction_cache.count)
|
|
20791
|
+
conf_cache = []
|
|
20792
|
+
for i in range(len(confidence_cache)):
|
|
20793
|
+
if confidence_cache[i][0] == voted_chosen_label:
|
|
20794
|
+
confidence = confidence_cache[i][1]
|
|
20795
|
+
conf_cache.append(confidence)
|
|
20796
|
+
|
|
20797
|
+
float_counts = Counter(conf_cache)
|
|
20798
|
+
voted_confidence, _ = float_counts.most_common(1)[0]
|
|
20799
|
+
|
|
20800
|
+
voted_agreement = []
|
|
20801
|
+
for i in range(len(agreement_cache)):
|
|
20802
|
+
if agreement_cache[i][0] == voted_chosen_label:
|
|
20803
|
+
get_agreement = agreement_cache[i][1]
|
|
20804
|
+
voted_agreement.append(get_agreement)
|
|
20805
|
+
|
|
20806
|
+
counts = Counter(voted_agreement)
|
|
20807
|
+
agreement_counts = counts[True]
|
|
20808
|
+
models_agreement = agreement_counts > counts[False]
|
|
20809
|
+
|
|
20810
|
+
if not isinstance(voted_chosen_label, str):
|
|
20739
20811
|
for i in range(num_classes):
|
|
20740
20812
|
mlp_class_idx = int(mlp_pred_indices[i])
|
|
20741
20813
|
is_valid_index = 0 <= mlp_class_idx < num_classes
|
|
@@ -20760,26 +20832,27 @@ class PipelinePredictionManager:
|
|
|
20760
20832
|
'is_valid' : True,
|
|
20761
20833
|
})
|
|
20762
20834
|
|
|
20763
|
-
|
|
20764
|
-
|
|
20835
|
+
voted_chosen_label = results[0].get('predicted') if results else None
|
|
20836
|
+
voted_confidence = results[0].get('confidence') if results else 0.0
|
|
20765
20837
|
|
|
20766
|
-
if isinstance(
|
|
20767
|
-
|
|
20838
|
+
if isinstance(voted_chosen_label, int) or isinstance(voted_chosen_label, np.integer):
|
|
20839
|
+
voted_chosen_label = str(voted_chosen_label)
|
|
20768
20840
|
|
|
20769
|
-
if isinstance(
|
|
20770
|
-
|
|
20841
|
+
if isinstance(voted_confidence, (np.ndarray, list)):
|
|
20842
|
+
voted_confidence = np.mean(voted_confidence)
|
|
20771
20843
|
|
|
20772
|
-
|
|
20773
|
-
|
|
20774
|
-
not need_ensemble_method
|
|
20775
|
-
|
|
20776
|
-
)
|
|
20777
|
-
if return_single_condition:
|
|
20778
|
-
print('[=] Displaying Results....')
|
|
20844
|
+
if not need_ensemble_method:
|
|
20845
|
+
print('[=] Getting Results...')
|
|
20779
20846
|
if not results[0].get('models_agree', True) and self.pipeline.use_transformer:
|
|
20780
|
-
|
|
20781
|
-
|
|
20782
|
-
|
|
20847
|
+
trans_conf_cache = []
|
|
20848
|
+
for i in range(len(results)):
|
|
20849
|
+
trans_confidence = results[i].get('trans_confidence', 1e-8)
|
|
20850
|
+
trans_conf_cache.append(trans_confidence)
|
|
20851
|
+
|
|
20852
|
+
trans_counts = Counter(trans_conf_cache)
|
|
20853
|
+
trans_confidence, _ = trans_counts.most_common(1)[0]
|
|
20854
|
+
confidence = (voted_confidence + trans_confidence / 2) + 1e-5
|
|
20855
|
+
print(f'[=] Calibrating confidence around frequent Transformer confidence distributions: {confidence:.1%}')
|
|
20783
20856
|
|
|
20784
20857
|
payload = {
|
|
20785
20858
|
'X_samples': X,
|
|
@@ -20789,46 +20862,40 @@ class PipelinePredictionManager:
|
|
|
20789
20862
|
if titles is not None and len(titles) > 0:
|
|
20790
20863
|
correct, sec_correct = self.display_hybrid_results(payload, final_class_idx, results, top_k, verbose=True)
|
|
20791
20864
|
|
|
20792
|
-
if isinstance(
|
|
20793
|
-
if
|
|
20794
|
-
|
|
20795
|
-
|
|
20796
|
-
print(f"\n[⚠️]
|
|
20865
|
+
if isinstance(voted_chosen_label, str) and voted_chosen_label.startswith("unknown") or float(voted_confidence) < self.pipeline.confidence_threshold:
|
|
20866
|
+
if voted_chosen_label is None or voted_chosen_label.startswith('unknown'):
|
|
20867
|
+
voted_chosen_label = 'Unknown'
|
|
20868
|
+
voted_confidence = 1.0 - voted_confidence #Invert confidence for unknown class
|
|
20869
|
+
print(f"\n[⚠️] Frequent predicted label is {voted_chosen_label} with uncertain confidence: {voted_confidence:.1%}. Consider more consistent data for the model to learn from.")
|
|
20797
20870
|
else:
|
|
20798
|
-
print(f"\n[🎯] Predicted label: {
|
|
20871
|
+
print(f"\n[🎯] Frequent Predicted label: {voted_chosen_label} || With Certain Confidence: {voted_confidence:.1%}")
|
|
20799
20872
|
|
|
20800
|
-
return results,
|
|
20873
|
+
return results, voted_chosen_label, voted_confidence
|
|
20801
20874
|
|
|
20802
20875
|
else:
|
|
20803
|
-
if
|
|
20804
|
-
print(f
|
|
20805
|
-
|
|
20876
|
+
if models_agreement and voted_confidence > self.pipeline.confidence_threshold and not voted_chosen_label.startswith("Unknown"):
|
|
20877
|
+
print(f'[>] Agreement count: {agreement_counts}, Both models agree frequently on predicted label: {voted_chosen_label}')
|
|
20878
|
+
print(f"\n[🎯] Proper Confidence of Final chosen label for input: {voted_chosen_label} || Confidence: {voted_confidence:.1%}")
|
|
20879
|
+
return results, voted_chosen_label, voted_confidence
|
|
20806
20880
|
|
|
20807
20881
|
# Only recalibrate if models disagreed
|
|
20808
|
-
elif results and not
|
|
20882
|
+
elif results and not models_agreement or not self.pipeline.agreement and self.pipeline.use_transformer:
|
|
20809
20883
|
|
|
20810
|
-
need_peer_condition = not
|
|
20884
|
+
need_peer_condition = not models_agreement and self.pipeline.peer_assistance_threshold > 0.3 and self.pipeline.use_transformer
|
|
20811
20885
|
print("\n[⚠️] Disagreement detected between MLP and Transformer predictions. Usig calibrated probabilities for final decision.")
|
|
20812
|
-
if
|
|
20886
|
+
if voted_confidence < self.pipeline.confidence_threshold and need_peer_condition:
|
|
20813
20887
|
print('|| Uncertain advanced prediction, requesting peer assistance if allowed...')
|
|
20814
20888
|
final_probs = self.pipeline._handle_distributed_connections(final_probs, attn_weights, input_ids, agreement)
|
|
20815
20889
|
|
|
20816
|
-
final_idx =
|
|
20890
|
+
final_idx, voted_confidence = self._get_voted_results(final_probs, reverse_map, len(X))
|
|
20817
20891
|
original_idx = final_idx
|
|
20818
20892
|
|
|
20819
20893
|
if final_idx > len(reverse_map):
|
|
20820
20894
|
final_idx = int(np.argmax(final_probs[:len(reverse_map)-1]))
|
|
20821
|
-
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20822
|
-
final_idx = int(final_idx)
|
|
20823
|
-
|
|
20824
|
-
chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20825
|
-
if chosen_label.startswith('unknown'):
|
|
20826
|
-
final_idx = int(np.argmax(final_probs[:len(reverse_map)-1]))
|
|
20895
|
+
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20827
20896
|
|
|
20828
|
-
|
|
20829
|
-
|
|
20830
|
-
except:
|
|
20831
|
-
confidence = float(final_probs[0][len(reverse_map)-1]) if isinstance(final_probs[0], (float, int)) else 0.0
|
|
20897
|
+
final_idx = int(final_idx)
|
|
20898
|
+
voted_chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20832
20899
|
|
|
20833
20900
|
elif self.pipeline.autonomous and need_peer_condition and attn_weights is not None:
|
|
20834
20901
|
if agreement is None:
|
|
@@ -20837,27 +20904,22 @@ class PipelinePredictionManager:
|
|
|
20837
20904
|
print('[||] Iniating local peer output search in database for best output...')
|
|
20838
20905
|
final_probs = self.pipeline.distribution._handle_peer_agent_request(final_probs, attn_weights, input_ids, type='DevicePeer', agreement=agreement)
|
|
20839
20906
|
|
|
20840
|
-
final_idx =
|
|
20907
|
+
final_idx, voted_confidence = self._get_voted_results(final_probs, reverse_map, len(X))
|
|
20841
20908
|
original_idx = final_idx
|
|
20842
20909
|
|
|
20843
20910
|
if final_idx > len(reverse_map):
|
|
20844
20911
|
final_idx = int(np.argmax(final_probs[:len(reverse_map)-1]))
|
|
20845
|
-
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20846
|
-
final_idx = int(final_idx)
|
|
20847
|
-
|
|
20848
|
-
chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20849
|
-
try:
|
|
20850
|
-
confidence = float(final_probs[final_idx])
|
|
20851
|
-
except:
|
|
20852
|
-
confidence = float(final_probs[0][len(reverse_map)-1]) if isinstance(final_probs[0], (float, int)) else 0.0
|
|
20912
|
+
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20853
20913
|
|
|
20914
|
+
final_idx = int(final_idx)
|
|
20915
|
+
voted_chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20854
20916
|
|
|
20855
|
-
elif not
|
|
20917
|
+
elif not models_agreement and voted_confidence > self.pipeline.confidence_threshold:
|
|
20856
20918
|
if final_confidence is not None and confidence < self.pipeline.confidence_threshold:
|
|
20857
20919
|
print("\n[⚠️] Low confidence detected, but both models don't agree. Using calibrated probabilities for final decision to ensure robustness.")
|
|
20858
20920
|
final_probs = self.pipeline.hybrid_prediction(rules, input_ids, dataset, X=X, y=y, use_embedded=use_embedded)
|
|
20859
20921
|
|
|
20860
|
-
final_idx =
|
|
20922
|
+
final_idx, voted_confidence = self._get_voted_results(final_probs, reverse_map, len(X))
|
|
20861
20923
|
original_idx = final_idx
|
|
20862
20924
|
|
|
20863
20925
|
if final_idx > len(reverse_map):
|
|
@@ -20868,68 +20930,51 @@ class PipelinePredictionManager:
|
|
|
20868
20930
|
print('[🎯] Stable confidence established, But both Models doesnt Agree, Re-evaluating...')
|
|
20869
20931
|
final_probs = self.pipeline.hybrid_prediction(rules, input_ids, dataset, X=X, y=y, use_embedded=use_embedded)
|
|
20870
20932
|
|
|
20871
|
-
final_idx =
|
|
20933
|
+
final_idx, voted_confidence = self._get_voted_results(final_probs, reverse_map, len(X))
|
|
20872
20934
|
original_idx = final_idx
|
|
20873
20935
|
if final_idx > len(reverse_map):
|
|
20874
20936
|
final_idx = int(np.argmax(final_probs[:len(reverse_map)-1]))
|
|
20875
20937
|
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20876
20938
|
final_idx = int(final_idx)
|
|
20877
20939
|
|
|
20878
|
-
chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20879
|
-
try:
|
|
20880
|
-
confidence = float(final_probs[0][final_idx])
|
|
20881
|
-
except:
|
|
20882
|
-
confidence = float(final_probs[0][len(reverse_map)-1]) if isinstance(final_probs[0], (float, int)) else 0.0
|
|
20883
20940
|
else:
|
|
20884
20941
|
if self.pipeline.use_transformer and need_ensemble_method:
|
|
20885
20942
|
print("\n[⚠️] Uncertain confidence and disagreement detected. Using ensemble method for final decision.")
|
|
20886
20943
|
input_forward = sequence_ids if sequence_ids is not None else input_ids
|
|
20887
20944
|
final_probs, details = self.pipeline.ensemble.predict_ensemble(input_forward, X, y, method='dynamic', embedded=use_embedded)
|
|
20888
20945
|
|
|
20889
|
-
final_idx =
|
|
20946
|
+
final_idx, voted_confidence = self._get_voted_results(final_probs, reverse_map, len(X))
|
|
20890
20947
|
original_idx = final_idx
|
|
20891
20948
|
|
|
20892
20949
|
if final_idx > len(reverse_map):
|
|
20893
20950
|
final_idx = int(np.argmax(final_probs[:len(reverse_map)-1]))
|
|
20894
|
-
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20895
|
-
final_idx = int(final_idx)
|
|
20951
|
+
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20896
20952
|
|
|
20897
|
-
|
|
20898
|
-
|
|
20899
|
-
confidence = float(final_probs[0][final_idx])
|
|
20900
|
-
except:
|
|
20901
|
-
confidence = float(final_probs[0][len(reverse_map)-1]) if isinstance(final_probs[0], (float, int)) else 0.0
|
|
20953
|
+
final_idx = int(final_idx)
|
|
20954
|
+
voted_chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20902
20955
|
else:
|
|
20903
20956
|
if final_probs is None:
|
|
20904
20957
|
final_probs = mlp_probs
|
|
20905
20958
|
|
|
20906
|
-
|
|
20959
|
+
target_cache = []
|
|
20960
|
+
for i in range(len(target_pred_indices)):
|
|
20961
|
+
target_cache.append(target_pred_indices[i])
|
|
20962
|
+
|
|
20963
|
+
counter = Counter(target_cache)
|
|
20964
|
+
predicted_idx, _ = counter.most_common(1)[0]
|
|
20907
20965
|
|
|
20908
|
-
|
|
20909
|
-
|
|
20966
|
+
final_probs = self.calibration_penalized_check(target_probs, predicted_idx)
|
|
20967
|
+
final_idx, voted_confidence = self._get_voted_results(target_probs, reverse_map, len(X))
|
|
20910
20968
|
original_idx = final_idx
|
|
20911
20969
|
|
|
20912
20970
|
if final_idx > len(reverse_map):
|
|
20913
|
-
final_idx = int(np.argmax(
|
|
20914
|
-
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20915
|
-
final_idx = int(final_idx)
|
|
20971
|
+
final_idx = int(np.argmax(target_probs[:len(reverse_map)-1]))
|
|
20972
|
+
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20916
20973
|
|
|
20917
|
-
|
|
20918
|
-
|
|
20919
|
-
final_probs = target_probs.copy()
|
|
20974
|
+
final_idx = int(final_idx)
|
|
20975
|
+
voted_chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20920
20976
|
|
|
20921
|
-
|
|
20922
|
-
try:
|
|
20923
|
-
confidence = float(final_probs[0][final_idx])
|
|
20924
|
-
except:
|
|
20925
|
-
confidence = float(final_probs[0][len(reverse_map)-1]) if isinstance(final_probs[0], (float, int)) else 0.0
|
|
20926
|
-
except:
|
|
20927
|
-
try:
|
|
20928
|
-
confidence = float(final_probs[final_idx])
|
|
20929
|
-
except:
|
|
20930
|
-
confidence = self.pipeline.confidence_threshold
|
|
20931
|
-
|
|
20932
|
-
elif confidence < self.pipeline.confidence_threshold and not self.pipeline.agreement and not results[0].get('models_agree', True):
|
|
20977
|
+
elif voted_confidence < self.pipeline.confidence_threshold and not self.pipeline.agreement and not results[0].get('models_agree', True):
|
|
20933
20978
|
if trans_probs is not None:
|
|
20934
20979
|
prob_entropy = self.calculate_entropy(final_probs)
|
|
20935
20980
|
normalized_entropy = prob_entropy / np.log(prob_entropy.shape[-1]) if prob_entropy.shape[-1] > 1 else 0
|
|
@@ -20946,8 +20991,8 @@ class PipelinePredictionManager:
|
|
|
20946
20991
|
use_simple_prediction = (
|
|
20947
20992
|
anisotropy < 0.3 or
|
|
20948
20993
|
mean_entropy < 0.5 or # High uncertainty
|
|
20949
|
-
|
|
20950
|
-
not
|
|
20994
|
+
voted_confidence < 0.4 or # Low confidence
|
|
20995
|
+
not models_agreement or # Disagreement
|
|
20951
20996
|
attn_quality < 0.4
|
|
20952
20997
|
)
|
|
20953
20998
|
|
|
@@ -20959,73 +21004,47 @@ class PipelinePredictionManager:
|
|
|
20959
21004
|
return _, predicted_label, confidence
|
|
20960
21005
|
|
|
20961
21006
|
else:
|
|
20962
|
-
final_idx =
|
|
21007
|
+
final_idx, confidence =self._get_voted_results(final_probs, reverse_map, len(X))
|
|
20963
21008
|
original_idx = final_idx
|
|
20964
21009
|
|
|
20965
21010
|
if final_idx > len(reverse_map):
|
|
20966
21011
|
final_idx = int(np.argmax(final_probs[:len(reverse_map)-1]))
|
|
20967
21012
|
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20968
21013
|
final_idx = int(final_idx)
|
|
20969
|
-
|
|
20970
|
-
chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20971
|
-
if final_probs is not None:
|
|
20972
|
-
try:
|
|
20973
|
-
confidence = float(final_probs[0][final_idx])
|
|
20974
|
-
except:
|
|
20975
|
-
confidence = float(final_probs[0][len(reverse_map)-1]) if isinstance(final_probs[0], (float, int)) else 0.0
|
|
20976
|
-
|
|
20977
|
-
else:
|
|
20978
|
-
final_probs = target_probs.copy()
|
|
21014
|
+
voted_chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20979
21015
|
|
|
20980
21016
|
else:
|
|
20981
21017
|
print("\n[🎯] Using initial Regular final prediction as final decision.")
|
|
20982
|
-
final_idx =
|
|
21018
|
+
final_idx, voted_confidence = self._get_voted_results(final_probs, reverse_map, len(X))
|
|
20983
21019
|
|
|
20984
21020
|
if final_idx > len(reverse_map):
|
|
20985
21021
|
final_idx = int(np.argmax(final_probs[:len(reverse_map)-1]))
|
|
20986
21022
|
print(f"[⚠️] Clamping {final_idx} → {final_idx}")
|
|
20987
21023
|
final_idx = int(final_idx)
|
|
21024
|
+
voted_chosen_label = reverse_map.get(final_idx, f"unknown_{final_idx}")
|
|
20988
21025
|
|
|
20989
|
-
|
|
20990
|
-
|
|
20991
|
-
try:
|
|
20992
|
-
confidence = float(final_probs[0][final_idx])
|
|
20993
|
-
except:
|
|
20994
|
-
confidence = float(final_probs[0][len(reverse_map)-1]) if isinstance(final_probs[0], (float, int)) else 0.0
|
|
20995
|
-
|
|
20996
|
-
if confidence > 0.8:
|
|
20997
|
-
confidence = (confidence + performance_score) / 2
|
|
21026
|
+
if voted_confidence > 0.8:
|
|
21027
|
+
voted_confidence = (voted_confidence + performance_score) / 2
|
|
20998
21028
|
print(f'[⚡] Confidence calibrated to be around: {confidence}')
|
|
20999
21029
|
|
|
21000
|
-
if isinstance(
|
|
21001
|
-
if
|
|
21002
|
-
|
|
21003
|
-
|
|
21030
|
+
if isinstance(voted_chosen_label, str) and voted_chosen_label.startswith("unknown") or float(voted_confidence) < self.pipeline.confidence_threshold:
|
|
21031
|
+
if voted_chosen_label.startswith("unknown"):
|
|
21032
|
+
voted_chosen_label = 'Unknown'
|
|
21033
|
+
voted_confidence = 1.0 - voted_confidence #Invert confidence for unknown class
|
|
21004
21034
|
|
|
21005
|
-
print(f"\n[⚠️] Final prediction is {
|
|
21035
|
+
print(f"\n[⚠️] Final prediction is {voted_chosen_label} with uncertain confidence: {voted_confidence:.1%}. Consider more consistent data for the model to learn from.")
|
|
21006
21036
|
else:
|
|
21007
|
-
print(f"\n[🎯] Final chosen label for input: {
|
|
21037
|
+
print(f"\n[🎯] Final chosen label for input: {voted_chosen_label} || Confidence: {voted_confidence:.1%}")
|
|
21008
21038
|
|
|
21009
21039
|
try:
|
|
21010
21040
|
consecutive_probs = self.pipeline.distribution._handle_peer_agent_request(target_probs, attn_weights, input_ids, type='DevicePeer', agreement=agreement)
|
|
21011
|
-
sec_final_idx =
|
|
21041
|
+
sec_final_idx, sec_confidence = self._get_voted_results(consecutive_probs, reverse_map, len(X))
|
|
21012
21042
|
|
|
21013
21043
|
if sec_final_idx > len(reverse_map):
|
|
21014
21044
|
sec_final_idx = int(np.argmax(consecutive_probs[:len(reverse_map)-1]))
|
|
21015
|
-
print(f"[⚠️] Clamping {sec_final_idx} → {sec_final_idx}")
|
|
21016
|
-
sec_final_idx = int(sec_final_idx)
|
|
21045
|
+
print(f"[⚠️] Clamping {sec_final_idx} → {sec_final_idx}")
|
|
21017
21046
|
|
|
21018
|
-
|
|
21019
|
-
try:
|
|
21020
|
-
sec_confidence = float(consecutive_probs[0][sec_final_idx])
|
|
21021
|
-
except:
|
|
21022
|
-
sec_confidence = float(consecutive_probs[0][len(reverse_map)-1]) if isinstance(consecutive_probs[0], (float, int)) else self.pipeline.confidence_threshold
|
|
21023
|
-
|
|
21024
|
-
if isinstance(confidence, (np.ndarray, list)):
|
|
21025
|
-
confidence = np.mean(confidence)
|
|
21026
|
-
if isinstance(sec_confidence, (np.ndarray, list)):
|
|
21027
|
-
sec_confidence = np.mean(sec_confidence)
|
|
21028
|
-
|
|
21047
|
+
sec_final_idx = int(sec_final_idx)
|
|
21029
21048
|
if sec_confidence > 0.8:
|
|
21030
21049
|
sec_confidence = (sec_confidence + performance_score) + eps / 2
|
|
21031
21050
|
|
|
@@ -21039,8 +21058,8 @@ class PipelinePredictionManager:
|
|
|
21039
21058
|
results[0]['sec_index'] = sec_final_idx
|
|
21040
21059
|
|
|
21041
21060
|
if confidence > results[0]['confidence']:
|
|
21042
|
-
results[0]['predicted'] =
|
|
21043
|
-
results[0]['confidence'] =
|
|
21061
|
+
results[0]['predicted'] = voted_chosen_label
|
|
21062
|
+
results[0]['confidence'] = voted_confidence
|
|
21044
21063
|
results[0]['predicted_idx'] = final_idx
|
|
21045
21064
|
else:
|
|
21046
21065
|
print('[!] No prediction in results cache are found!')
|
|
@@ -21048,8 +21067,8 @@ class PipelinePredictionManager:
|
|
|
21048
21067
|
except Exception as e:
|
|
21049
21068
|
print(f'[!] Error initiating second prediction in Advanced prediction method: {e} ')
|
|
21050
21069
|
|
|
21051
|
-
results[0]['sec_predicted'] =
|
|
21052
|
-
results[0]['sec_confidence'] =
|
|
21070
|
+
results[0]['sec_predicted'] = voted_chosen_label
|
|
21071
|
+
results[0]['sec_confidence'] = voted_confidence
|
|
21053
21072
|
results[0]['sec_index'] = final_idx
|
|
21054
21073
|
|
|
21055
21074
|
|
|
@@ -21058,12 +21077,12 @@ class PipelinePredictionManager:
|
|
|
21058
21077
|
traceback.print_exc()
|
|
21059
21078
|
try:
|
|
21060
21079
|
results = self.regular_prediction_method(titles=titles, label_map=label_map, rules=rules, X=X, y=y, show_proba=False, top_k=3, batch_size=2, use_transformer=self.pipeline.use_transformer)
|
|
21061
|
-
|
|
21062
|
-
|
|
21080
|
+
voted_chosen_label = results[0]['predicted']
|
|
21081
|
+
voted_confidence = results[0]['confidence']
|
|
21063
21082
|
except Exception as error:
|
|
21064
21083
|
print(f'[= ! =] Error in all prediction method: {error}')
|
|
21065
21084
|
traceback.print_exc()
|
|
21066
|
-
results,
|
|
21085
|
+
results, voted_chosen_label, voted_confidence = None, None, 0.0
|
|
21067
21086
|
|
|
21068
21087
|
print('[=] Displaying Results....')
|
|
21069
21088
|
payload = {
|
|
@@ -21078,17 +21097,17 @@ class PipelinePredictionManager:
|
|
|
21078
21097
|
chosen_label = sec_chosen_label # overrides previous chosen label if accuracy is higher
|
|
21079
21098
|
elif self.pipeline.autonomous and sec_confidence > self.pipeline.confidence_threshold:
|
|
21080
21099
|
print(f'[⚡] Autonomous Prediction used second predicted label: {sec_chosen_label}')
|
|
21081
|
-
|
|
21100
|
+
voted_chosen_label = sec_chosen_label
|
|
21082
21101
|
else:
|
|
21083
|
-
print(f'[⚡] Final Prediction: {
|
|
21084
|
-
|
|
21102
|
+
print(f'[⚡] Final Prediction: {voted_chosen_label} with confidence: {voted_confidence:.2%}')
|
|
21103
|
+
voted_chosen_label = voted_chosen_label
|
|
21085
21104
|
|
|
21086
21105
|
self.pipeline.evaluate_mlp_performance(X, y, self.label_map)
|
|
21087
21106
|
# delete pipelines cache
|
|
21088
21107
|
print('[🔍] Pipelines Cache Cleaned!')
|
|
21089
21108
|
self.pipeline.cache.clear()
|
|
21090
21109
|
|
|
21091
|
-
return results,
|
|
21110
|
+
return results, voted_chosen_label, voted_confidence
|
|
21092
21111
|
|
|
21093
21112
|
|
|
21094
21113
|
def calibration_penalized_check(self, final_probs, predicted_index):
|