rhscope.metrics

Metric primitives used throughout rhscope.

These implementations depend only on numpy and are correctness-matched against scikit-learn in the test suite. Scikit-learn is an optional dependency, so we cannot rely on it in core modules - but train_probe and the benchmark runner both need AUROC, so a lightweight implementation lives here.

rhscope.metrics.auroc(scores, labels)[source]

Compute AUROC via the Mann-Whitney U statistic.

Parameters:
Returns:

AUROC in [0, 1]. Returns 0.5 when every example has the same label (undefined case).

Raises:

ValueError – If inputs are not 1-D or labels are not binary.

Return type:

float

rhscope.metrics.accuracy_at_threshold(scores, labels, threshold)[source]

Classification accuracy using score >= threshold as the decision rule.

The >= convention matches the ROC-sweep operating point returned by youden_j_threshold, which picks a threshold at a specific sorted score value - examples at that value should classify as positive, not negative.

Parameters:
Return type:

float

class rhscope.metrics.ThresholdFit(threshold, accuracy, tpr, fpr)[source]

Bases: object

Result of selecting a decision threshold via Youden’s J statistic.

Variables:
  • threshold (float) – Score threshold at which J = TPR - FPR is maximized.

  • accuracy (float) – Classification accuracy at that threshold.

  • tpr (float) – True-positive rate at that threshold.

  • fpr (float) – False-positive rate at that threshold.

Parameters:
threshold: float
accuracy: float
tpr: float
fpr: float
rhscope.metrics.youden_j_threshold(scores, labels)[source]

Find the threshold maximizing Youden’s J statistic (TPR - FPR).

Parameters:
Returns:

ThresholdFit with the chosen threshold and its operating-point metrics. If either class is empty, returns threshold at the data median with zero TPR/FPR; callers should check auroc is well-defined separately.

Return type:

ThresholdFit

class rhscope.metrics.ConfusionMatrix(tp, fp, tn, fn)[source]

Bases: object

Confusion matrix at a given decision threshold.

Variables:
  • tp (int) – True positives.

  • fp (int) – False positives.

  • tn (int) – True negatives.

  • fn (int) – False negatives.

Parameters:
tp: int
fp: int
tn: int
fn: int
property positive: int

Ground-truth positives (tp + fn).

property negative: int

Ground-truth negatives (tn + fp).

property total: int

Total number of examples.

property precision: float

tp / (tp + fp). Returns 0.0 when no positive predictions.

property recall: float

tp / (tp + fn). Returns 0.0 when no positive labels.

property f1: float

Harmonic mean of precision and recall; 0.0 if both are 0.

property accuracy: float

Classification accuracy; 0.0 on an empty input.

to_dict()[source]

Return a flat dict of every derived metric for structured logging.

Return type:

dict[str, float]

rhscope.metrics.confusion_matrix(scores, labels, threshold)[source]

Build a ConfusionMatrix from scores + labels at a given threshold.

The decision rule is score >= threshold to match accuracy_at_threshold() and youden_j_threshold().

Parameters:
Return type:

ConfusionMatrix

rhscope.metrics.precision_recall_curve(scores, labels)[source]

Compute the precision-recall curve.

Matches scikit-learn’s precision_recall_curve conventions:

  • Thresholds are returned in ascending order.

  • precision and recall are aligned with the thresholds; recall consequently decreases from ~1 (lowest threshold) to the smallest attainable value.

  • A sentinel (precision=1, recall=0) is appended at the end so the curve closes cleanly at the “nothing is predicted positive” corner.

Parameters:
Returns:

(precision, recall, thresholds). precision and recall have length len(thresholds) + 1.

Raises:

ValueError – If inputs are not 1-D or labels are non-binary.

Return type:

tuple[ndarray, ndarray, ndarray]

rhscope.metrics.average_precision(scores, labels)[source]

Average precision (PR-AUC) via the step-function sum.

Matches scikit-learn’s average_precision_score: AP = sum_k (R_{k-1} - R_k) * P_k where R is ordered such that R_{k-1} > R_k (i.e. moving along the curve from high recall toward low recall). Equivalent to -sum(diff(recall) * precision[1:]) on the ascending-threshold ordering returned by precision_recall_curve().

Parameters:
Returns:

Average precision in [0, 1]. Returns 0.0 when there are no positive labels (AP is undefined in that case).

Return type:

float

rhscope.metrics.expected_calibration_error(probabilities, labels, *, n_bins=10)[source]

Expected Calibration Error with equal-width bins.

Parameters:
Returns:

ECE in [0, 1]. Lower is better.

Raises:

ValueError – If probabilities are outside [0, 1] or inputs mismatch.

Return type:

float

rhscope.metrics.brier_score(probabilities, labels)[source]

Brier score: mean squared error between predicted probabilities and labels.

Parameters:
Returns:

Brier score in [0, 1]. Lower is better.

Return type:

float

rhscope.metrics.sigmoid(scores)[source]

Numerically stable sigmoid, returning a numpy array.

Useful for converting un-normalized probe scores (DoM dot products, logistic logits) into calibrated-ish probabilities for ECE and Brier computation. Evaluates each branch only on the appropriate half of the input to avoid overflow encountered in exp warnings on large inputs.

Parameters:

scores (ndarray | Tensor | list[float] | list[int] | list[bool])

Return type:

ndarray