aetherscan 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,100 @@
1
+ """
2
+ Pure Random Forest eval-metric computation for Aetherscan Pipeline.
3
+
4
+ Deliberately TF-free (numpy + sklearn.metrics only; no aetherscan.models import — that
5
+ package's __init__ pulls in TensorFlow via vae.py) so the helper stays unit-testable
6
+ without the GPU stack. train.py calls compute_rf_eval_metrics() at the tail of
7
+ train_random_forest() and persists each returned scalar to training_stats via
8
+ db.write_training_stat(model_name="rf", ...) for the live dashboard's RF tab.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+
15
+ import numpy as np
16
+ from sklearn.metrics import (
17
+ average_precision_score,
18
+ brier_score_loss,
19
+ confusion_matrix,
20
+ roc_auc_score,
21
+ )
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Persisted quantiles of the val P(true) distribution (stat_name val_proba_q{QQ})
26
+ _CONFIDENCE_QUANTILES = (5, 25, 50, 75, 95)
27
+
28
+
29
+ def compute_rf_eval_metrics(
30
+ val_binary_labels: np.ndarray,
31
+ val_subtype_labels: np.ndarray,
32
+ val_probas: np.ndarray,
33
+ val_preds: np.ndarray,
34
+ ) -> dict[str, float]:
35
+ """
36
+ Compute the scalar RF validation metrics persisted to training_stats (model_name='rf').
37
+
38
+ Inputs are the aligned per-cadence arrays already built by train_random_forest():
39
+ binary ground truth (0/1), sub-type ground truth (false_no_signal / false_with_rfi /
40
+ true_only_eti / true_eti_rfi), ensemble P(true), and thresholded predictions (at
41
+ inference.classification_threshold). Returns a flat {stat_name: float} dict:
42
+
43
+ val_accuracy / val_roc_auc / val_average_precision / val_brier_score
44
+ val_accuracy_{subtype} binary correctness within each sub-type
45
+ confusion_{tn,fp,fn,tp} binary 2x2 confusion cell counts
46
+ confusion_{subtype}_pred_{false,true} sub-type x predicted-class cell counts
47
+ val_proba_q{05,...,95} confidence-distribution quantiles
48
+
49
+ The ranking metrics (ROC-AUC / average precision) are threshold-free; accuracy and the
50
+ confusion cells reflect val_preds' operating point (the deployment threshold). On a
51
+ degenerate single-class val split the ranking metrics are undefined, so their two keys
52
+ are omitted (the dashboard renders absent tiles as an em dash) and everything else
53
+ still lands.
54
+ """
55
+ val_binary_labels = np.asarray(val_binary_labels)
56
+ val_subtype_labels = np.asarray(val_subtype_labels)
57
+ val_probas = np.asarray(val_probas, dtype=np.float64)
58
+ val_preds = np.asarray(val_preds)
59
+
60
+ metrics: dict[str, float] = {
61
+ "val_accuracy": float(np.mean(val_preds == val_binary_labels)),
62
+ "val_brier_score": float(brier_score_loss(val_binary_labels, val_probas)),
63
+ }
64
+
65
+ # Ranking metrics are undefined when only one class is present: roc_auc_score raises
66
+ # ValueError and average_precision_score silently degenerates (all-negative labels
67
+ # -> -0.0 with a warning). Omit both keys in that case rather than letting the raise
68
+ # reach the caller's blanket best-effort guard and lose the whole dict.
69
+ if np.unique(val_binary_labels).size > 1:
70
+ metrics["val_roc_auc"] = float(roc_auc_score(val_binary_labels, val_probas))
71
+ metrics["val_average_precision"] = float(
72
+ average_precision_score(val_binary_labels, val_probas)
73
+ )
74
+ else:
75
+ logger.warning(
76
+ "Single-class val split: omitting undefined val_roc_auc / val_average_precision"
77
+ )
78
+
79
+ # Binary 2x2 cells (explicit label order keeps the cell layout stable regardless of
80
+ # which classes appear in the val split)
81
+ tn, fp, fn, tp = confusion_matrix(val_binary_labels, val_preds, labels=[0, 1]).ravel()
82
+ metrics["confusion_tn"] = float(tn)
83
+ metrics["confusion_fp"] = float(fp)
84
+ metrics["confusion_fn"] = float(fn)
85
+ metrics["confusion_tp"] = float(tp)
86
+
87
+ # Per-sub-type binary accuracy + sub-type x predicted-class cell counts
88
+ correct = val_preds == val_binary_labels
89
+ for subtype in np.unique(val_subtype_labels):
90
+ mask = val_subtype_labels == subtype
91
+ metrics[f"val_accuracy_{subtype}"] = float(np.mean(correct[mask]))
92
+ n_pred_true = int(np.sum(val_preds[mask] == 1))
93
+ metrics[f"confusion_{subtype}_pred_true"] = float(n_pred_true)
94
+ metrics[f"confusion_{subtype}_pred_false"] = float(int(np.sum(mask)) - n_pred_true)
95
+
96
+ # Confidence-distribution quantiles of val P(true)
97
+ for q in _CONFIDENCE_QUANTILES:
98
+ metrics[f"val_proba_q{q:02d}"] = float(np.quantile(val_probas, q / 100))
99
+
100
+ return metrics