tributo-algorithms 0.1.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.
Files changed (110) hide show
  1. tributo_algorithms-0.1.0.dist-info/METADATA +328 -0
  2. tributo_algorithms-0.1.0.dist-info/RECORD +110 -0
  3. tributo_algorithms-0.1.0.dist-info/WHEEL +4 -0
  4. tributo_algorithms-0.1.0.dist-info/entry_points.txt +57 -0
  5. tributo_algorithms-0.1.0.dist-info/licenses/LICENSE +202 -0
  6. tributo_algorithms_boosting/__init__.py +42 -0
  7. tributo_algorithms_boosting/algorithm.py +825 -0
  8. tributo_algorithms_boosting/checkpointing.py +441 -0
  9. tributo_algorithms_boosting/contracts.py +232 -0
  10. tributo_algorithms_boosting/data_config.py +59 -0
  11. tributo_algorithms_boosting/descriptor.py +124 -0
  12. tributo_algorithms_boosting/lightgbm.py +511 -0
  13. tributo_algorithms_boosting/lightgbm_contracts.py +186 -0
  14. tributo_algorithms_boosting/lightgbm_descriptor.py +112 -0
  15. tributo_algorithms_boosting/native.py +557 -0
  16. tributo_algorithms_boosting/stages.py +150 -0
  17. tributo_algorithms_catboost/__init__.py +5 -0
  18. tributo_algorithms_catboost/algorithm.py +379 -0
  19. tributo_algorithms_catboost/contracts.py +145 -0
  20. tributo_algorithms_catboost/descriptor.py +121 -0
  21. tributo_algorithms_catboost/exporter.py +106 -0
  22. tributo_algorithms_catboost/flavor.py +191 -0
  23. tributo_algorithms_causal_core/__init__.py +41 -0
  24. tributo_algorithms_causal_core/algorithm.py +1193 -0
  25. tributo_algorithms_causal_core/contracts.py +136 -0
  26. tributo_algorithms_causal_core/descriptor.py +270 -0
  27. tributo_algorithms_causal_core/exporter.py +52 -0
  28. tributo_algorithms_causal_discovery/__init__.py +23 -0
  29. tributo_algorithms_causal_discovery/algorithm.py +526 -0
  30. tributo_algorithms_causal_discovery/contracts.py +97 -0
  31. tributo_algorithms_causal_discovery/descriptor.py +130 -0
  32. tributo_algorithms_causal_discovery/exporter.py +43 -0
  33. tributo_algorithms_causal_dowhy/__init__.py +38 -0
  34. tributo_algorithms_causal_dowhy/algorithm.py +325 -0
  35. tributo_algorithms_causal_dowhy/contracts.py +209 -0
  36. tributo_algorithms_causal_dowhy/descriptor.py +106 -0
  37. tributo_algorithms_causal_dowhy/exporter.py +43 -0
  38. tributo_algorithms_causal_dowhy/gcm.py +634 -0
  39. tributo_algorithms_causal_dowhy/gcm_descriptor.py +110 -0
  40. tributo_algorithms_causal_dr/__init__.py +22 -0
  41. tributo_algorithms_causal_dr/algorithm.py +446 -0
  42. tributo_algorithms_causal_dr/contracts.py +94 -0
  43. tributo_algorithms_causal_dr/descriptor.py +104 -0
  44. tributo_algorithms_causal_xlearner/__init__.py +29 -0
  45. tributo_algorithms_causal_xlearner/algorithm.py +448 -0
  46. tributo_algorithms_causal_xlearner/contracts.py +97 -0
  47. tributo_algorithms_causal_xlearner/descriptor.py +120 -0
  48. tributo_algorithms_causal_xlearner/exporter.py +432 -0
  49. tributo_algorithms_causal_xlearner/flavor.py +120 -0
  50. tributo_algorithms_causal_xlearner/model.py +116 -0
  51. tributo_algorithms_classical/__init__.py +41 -0
  52. tributo_algorithms_classical/contracts.py +139 -0
  53. tributo_algorithms_classical/descriptors.py +370 -0
  54. tributo_algorithms_classical/exporter.py +166 -0
  55. tributo_algorithms_classical/isolation_forest.py +172 -0
  56. tributo_algorithms_classical/isolation_forest_descriptor.py +122 -0
  57. tributo_algorithms_classical/kmeans.py +315 -0
  58. tributo_algorithms_classical/kmeans_descriptor.py +147 -0
  59. tributo_algorithms_classical/linear_regression.py +206 -0
  60. tributo_algorithms_classical/logistic_regression.py +238 -0
  61. tributo_algorithms_classical/models.py +28 -0
  62. tributo_algorithms_classical/multinomial_nb.py +643 -0
  63. tributo_algorithms_classical/multinomial_nb_descriptor.py +183 -0
  64. tributo_algorithms_classical/pca.py +187 -0
  65. tributo_algorithms_classical/pca_descriptor.py +111 -0
  66. tributo_algorithms_classical/random_forest.py +304 -0
  67. tributo_algorithms_classical/sgd.py +331 -0
  68. tributo_algorithms_classical/sgd_contracts.py +121 -0
  69. tributo_algorithms_classical/sgd_descriptor.py +143 -0
  70. tributo_algorithms_classical/unsupervised_contracts.py +198 -0
  71. tributo_algorithms_classical/unsupervised_exporter.py +427 -0
  72. tributo_algorithms_classical/unsupervised_models.py +90 -0
  73. tributo_algorithms_graph_pyg/__init__.py +37 -0
  74. tributo_algorithms_graph_pyg/algorithm.py +883 -0
  75. tributo_algorithms_graph_pyg/contracts.py +260 -0
  76. tributo_algorithms_graph_pyg/descriptor.py +201 -0
  77. tributo_algorithms_multistage_torch/__init__.py +40 -0
  78. tributo_algorithms_multistage_torch/algorithm.py +532 -0
  79. tributo_algorithms_multistage_torch/contracts.py +220 -0
  80. tributo_algorithms_multistage_torch/descriptor.py +146 -0
  81. tributo_algorithms_multistage_torch/pretrain.py +570 -0
  82. tributo_algorithms_multistage_torch/pretrain_descriptor.py +153 -0
  83. tributo_algorithms_recsys_torch/__init__.py +35 -0
  84. tributo_algorithms_recsys_torch/contracts.py +295 -0
  85. tributo_algorithms_recsys_torch/descriptor.py +136 -0
  86. tributo_algorithms_recsys_torch/jagged.py +707 -0
  87. tributo_algorithms_recsys_torch/jagged_descriptor.py +130 -0
  88. tributo_algorithms_recsys_torch/recipe.py +192 -0
  89. tributo_algorithms_representation/__init__.py +20 -0
  90. tributo_algorithms_representation/contracts.py +117 -0
  91. tributo_algorithms_representation/descriptor.py +137 -0
  92. tributo_algorithms_representation/recipe.py +162 -0
  93. tributo_algorithms_tabular_torch/__init__.py +46 -0
  94. tributo_algorithms_tabular_torch/contracts.py +228 -0
  95. tributo_algorithms_tabular_torch/descriptor.py +223 -0
  96. tributo_algorithms_tabular_torch/priors.py +216 -0
  97. tributo_algorithms_tabular_torch/pu_metrics.py +269 -0
  98. tributo_algorithms_tabular_torch/pu_reducer.py +129 -0
  99. tributo_algorithms_tabular_torch/recipe.py +294 -0
  100. tributo_algorithms_timeseries/__init__.py +36 -0
  101. tributo_algorithms_timeseries/contracts.py +120 -0
  102. tributo_algorithms_timeseries/descriptor.py +137 -0
  103. tributo_algorithms_timeseries/recipe.py +195 -0
  104. tributo_algorithms_timeseries/rnn_contracts.py +170 -0
  105. tributo_algorithms_timeseries/rnn_descriptor.py +167 -0
  106. tributo_algorithms_timeseries/rnn_recipe.py +223 -0
  107. tributo_algorithms_transformers_nlp/__init__.py +20 -0
  108. tributo_algorithms_transformers_nlp/contracts.py +109 -0
  109. tributo_algorithms_transformers_nlp/descriptor.py +137 -0
  110. tributo_algorithms_transformers_nlp/recipe.py +235 -0
@@ -0,0 +1,216 @@
1
+ """Class prior (π_p) estimation module.
2
+
3
+ Used in Positive-Unlabeled Learning scenarios to estimate the proportion of positive examples in unlabeled data.
4
+
5
+ Supports three estimation methods:
6
+ - label_frequency: Naive lower bound estimate (positive count / total)
7
+ - histogram_match: Histogram matching method
8
+ - em: EM iterative refinement (SCAR assumption)
9
+
10
+ References:
11
+ - Bekker & Davis (2020): "Learning from Positive and Unlabeled Data: A Survey"
12
+ - Ramaswamy et al. (2016): "A Statistical Approach to PU Learning"
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ from typing import Literal
19
+
20
+ import numpy as np
21
+ from tributo.util.annotations import PublicAPI
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ PriorMethod = Literal["label_frequency", "histogram_match", "em"]
26
+
27
+
28
+ def label_frequency_prior(positive_count: int, total_count: int) -> float:
29
+ """Naive label frequency estimation.
30
+
31
+ π_p ≥ P(s=1) = positive_count / total. This is a lower bound for the class prior.
32
+
33
+ Args:
34
+ positive_count: Number of positive (labeled) examples.
35
+ total_count: Total number of samples.
36
+
37
+ Returns:
38
+ Estimated class prior value.
39
+
40
+ Raises:
41
+ ValueError: Invalid parameters.
42
+ """
43
+ _validate_counts(positive_count, total_count)
44
+ return positive_count / total_count
45
+
46
+
47
+ def histogram_match_prior(
48
+ positive_scores: np.ndarray,
49
+ unlabeled_scores: np.ndarray,
50
+ n_bins: int = 50,
51
+ ) -> float:
52
+ """Estimate class prior via histogram matching.
53
+
54
+ Compares the histograms of prediction scores between positive and unlabeled samples
55
+ to estimate the proportion of positives.
56
+ Principle: the score distribution of positives in unlabeled data should match that of known positives.
57
+
58
+ Args:
59
+ positive_scores: Prediction probabilities or scores for positives, shape (n_positive,).
60
+ unlabeled_scores: Prediction probabilities or scores for unlabeled samples, shape (n_unlabeled,).
61
+ n_bins: Number of histogram bins.
62
+
63
+ Returns:
64
+ Estimated class prior value.
65
+ """
66
+ if len(positive_scores) == 0:
67
+ raise ValueError("positive_scores must be non-empty")
68
+ if len(unlabeled_scores) == 0:
69
+ raise ValueError("unlabeled_scores must be non-empty")
70
+
71
+ # Unified bin range
72
+ all_scores = np.concatenate([positive_scores, unlabeled_scores])
73
+ bin_edges = np.linspace(all_scores.min(), all_scores.max(), n_bins + 1)
74
+
75
+ pos_hist, _ = np.histogram(positive_scores, bins=bin_edges, density=True)
76
+ unl_hist, _ = np.histogram(unlabeled_scores, bins=bin_edges, density=True)
77
+
78
+ # Normalize
79
+ pos_hist = pos_hist / (pos_hist.sum() + 1e-10)
80
+ unl_hist = unl_hist / (unl_hist.sum() + 1e-10)
81
+
82
+ # Estimate: portion of unlabeled distribution matching positive distribution
83
+ ratio = np.minimum(pos_hist, unl_hist).sum()
84
+ prior = min(max(ratio, 0.0), 1.0)
85
+
86
+ logger.info("Histogram match prior: %.4f (bins=%d)", prior, n_bins)
87
+ return float(prior)
88
+
89
+
90
+ def em_prior(
91
+ positive_scores: np.ndarray,
92
+ unlabeled_scores: np.ndarray,
93
+ max_iter: int = 100,
94
+ tol: float = 1e-6,
95
+ init_prior: float | None = None,
96
+ ) -> float:
97
+ """Estimate class prior via EM algorithm (SCAR assumption).
98
+
99
+ E-step: Estimate the probability of each unlabeled sample belonging to the positive class
100
+ M-step: Update the class prior
101
+
102
+ Args:
103
+ positive_scores: Prediction probabilities for positives, shape (n_positive,).
104
+ unlabeled_scores: Prediction probabilities for unlabeled samples, shape (n_unlabeled,).
105
+ max_iter: Maximum number of iterations.
106
+ tol: Convergence threshold.
107
+ init_prior: Initial prior value; uses label_frequency if None.
108
+
109
+ Returns:
110
+ Estimated class prior value.
111
+ """
112
+ if len(positive_scores) == 0:
113
+ raise ValueError("positive_scores must be non-empty")
114
+ if len(unlabeled_scores) == 0:
115
+ raise ValueError("unlabeled_scores must be non-empty")
116
+
117
+ n_pos = len(positive_scores)
118
+ n_unl = len(unlabeled_scores)
119
+ total = n_pos + n_unl
120
+
121
+ # Initial prior
122
+ if init_prior is not None:
123
+ prior = init_prior
124
+ else:
125
+ prior = n_pos / total
126
+
127
+ for iteration in range(max_iter):
128
+ # E-step: for unlabeled samples, estimate P(y=1|x, s=0)
129
+ # Using Bayes rule: P(y=1|x) = π_p * P(s=1|x,y=1) / P(s=1|x)
130
+ # Simplified: assume P(s=1|x,y=1) ≈ mean of positive scores
131
+ pos_mean = positive_scores.mean()
132
+ unl_mean = unlabeled_scores.mean()
133
+
134
+ # Expected proportion of positives in unlabeled data
135
+ # P(y=1|s=0,x) ≈ π_p * P(x|y=1) / P(x|s=0)
136
+ # Simplified estimate
137
+ expected_pos_in_unl = (
138
+ prior * pos_mean / (prior * pos_mean + (1 - prior) * unl_mean + 1e-10)
139
+ )
140
+ expected_pos_in_unl = np.clip(expected_pos_in_unl, 0, 1)
141
+
142
+ # M-step: update prior
143
+ new_prior = (n_pos + n_unl * expected_pos_in_unl) / total
144
+
145
+ if abs(new_prior - prior) < tol:
146
+ logger.info(
147
+ "EM converged at iteration %d: prior=%.4f", iteration + 1, new_prior
148
+ )
149
+ return float(min(max(new_prior, 0.0), 1.0))
150
+
151
+ prior = new_prior
152
+
153
+ logger.warning(
154
+ "EM did not converge after %d iterations, prior=%.4f", max_iter, prior
155
+ )
156
+ return float(min(max(prior, 0.0), 1.0))
157
+
158
+
159
+ @PublicAPI(stability="beta")
160
+ def estimate_class_prior(
161
+ positive_count: int,
162
+ total_count: int,
163
+ method: PriorMethod = "label_frequency",
164
+ positive_scores: np.ndarray | None = None,
165
+ unlabeled_scores: np.ndarray | None = None,
166
+ **kwargs: float,
167
+ ) -> float:
168
+ """Unified entry point for class prior estimation.
169
+
170
+ Args:
171
+ positive_count: Number of positive examples.
172
+ total_count: Total number of samples.
173
+ method: Estimation method.
174
+ positive_scores: Prediction probabilities for positives (required for histogram_match and em).
175
+ unlabeled_scores: Prediction probabilities for unlabeled samples (required for histogram_match and em).
176
+ **kwargs: Method-specific parameters (n_bins, max_iter, tol, etc.).
177
+
178
+ Returns:
179
+ Estimated class prior value.
180
+ """
181
+ if method == "label_frequency":
182
+ return label_frequency_prior(positive_count, total_count)
183
+ elif method == "histogram_match":
184
+ if positive_scores is None or unlabeled_scores is None:
185
+ raise ValueError(
186
+ "histogram_match requires positive_scores and unlabeled_scores"
187
+ )
188
+ return histogram_match_prior(
189
+ positive_scores,
190
+ unlabeled_scores,
191
+ n_bins=int(kwargs.get("n_bins", 50)),
192
+ )
193
+ elif method == "em":
194
+ if positive_scores is None or unlabeled_scores is None:
195
+ raise ValueError("em requires positive_scores and unlabeled_scores")
196
+ return em_prior(
197
+ positive_scores,
198
+ unlabeled_scores,
199
+ max_iter=int(kwargs.get("max_iter", 100)),
200
+ tol=float(kwargs.get("tol", 1e-6)),
201
+ init_prior=kwargs.get("init_prior"),
202
+ )
203
+ else:
204
+ raise ValueError(f"Unknown method: {method}")
205
+
206
+
207
+ def _validate_counts(positive_count: int, total_count: int) -> None:
208
+ """Validate count parameters."""
209
+ if positive_count < 0:
210
+ raise ValueError(f"positive_count must be non-negative, got {positive_count}")
211
+ if total_count <= 0:
212
+ raise ValueError(f"total_count must be positive, got {total_count}")
213
+ if positive_count > total_count:
214
+ raise ValueError(
215
+ f"positive_count ({positive_count}) cannot exceed total_count ({total_count})"
216
+ )
@@ -0,0 +1,269 @@
1
+ """PU Learning specific evaluation metrics.
2
+
3
+ Standard classification metrics (precision, recall, F1) are biased in PU scenarios,
4
+ because unlabeled samples may contain true positives. This module provides PU-corrected metrics.
5
+
6
+ References:
7
+ - Bekker & Davis (2020): "Learning from Positive and Unlabeled Data: A Survey"
8
+ - pulearn.metrics: https://github.com/pulearn/pulearn
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ from typing import Any
15
+
16
+ import numpy as np
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def pu_precision_score(
22
+ y_true: np.ndarray,
23
+ y_pred_proba: np.ndarray,
24
+ class_prior: float,
25
+ threshold: float = 0.5,
26
+ ) -> float:
27
+ """PU-corrected Precision.
28
+
29
+ Standard precision is overestimated in PU scenarios (because unlabeled true positives are counted as FP).
30
+ PU correction formula:
31
+ pu_precision = TP / (TP + FP * (1 - π_p))
32
+
33
+ Args:
34
+ y_true: Ground truth labels (1=positive, 0=unlabeled).
35
+ y_pred_proba: Prediction probabilities.
36
+ class_prior: Proportion of positives in unlabeled data (π_p).
37
+ threshold: Classification threshold.
38
+
39
+ Returns:
40
+ PU-corrected precision value.
41
+ """
42
+ y_pred = (y_pred_proba >= threshold).astype(int)
43
+ tp: int = int(np.sum((y_pred == 1) & (y_true == 1)))
44
+ fp: int = int(np.sum((y_pred == 1) & (y_true == 0)))
45
+
46
+ # PU correction: part of FP are actually true positives
47
+ corrected_fp = fp * (1 - class_prior)
48
+ denominator = tp + corrected_fp
49
+
50
+ if denominator == 0:
51
+ return 0.0
52
+ return float(tp / denominator)
53
+
54
+
55
+ def pu_f1_score(
56
+ y_true: np.ndarray,
57
+ y_pred_proba: np.ndarray,
58
+ class_prior: float,
59
+ threshold: float = 0.5,
60
+ ) -> float:
61
+ """PU-corrected F1 Score.
62
+
63
+ F1 = 2 * pu_precision * pu_recall / (pu_precision + pu_recall)
64
+
65
+ where pu_recall uses standard recall (positive labels are certain).
66
+
67
+ Args:
68
+ y_true: Ground truth labels (1=positive, 0=unlabeled).
69
+ y_pred_proba: Prediction probabilities.
70
+ class_prior: Class prior (π_p).
71
+ threshold: Classification threshold.
72
+
73
+ Returns:
74
+ PU-corrected F1 value.
75
+ """
76
+ precision = pu_precision_score(y_true, y_pred_proba, class_prior, threshold)
77
+ recall = _standard_recall(y_true, y_pred_proba, threshold)
78
+
79
+ if precision + recall == 0:
80
+ return 0.0
81
+ return float(2 * precision * recall / (precision + recall))
82
+
83
+
84
+ def pu_auc_score(
85
+ y_true: np.ndarray,
86
+ y_pred_proba: np.ndarray,
87
+ class_prior: float,
88
+ ) -> float:
89
+ """PU-corrected AUC.
90
+
91
+ Computes AUC using PU-corrected ROC curve.
92
+ Correction: discounts false positives in unlabeled samples by class_prior.
93
+
94
+ Args:
95
+ y_true: Ground truth labels (1=positive, 0=unlabeled).
96
+ y_pred_proba: Prediction probabilities.
97
+ class_prior: Class prior (π_p).
98
+
99
+ Returns:
100
+ PU-corrected AUC value.
101
+ """
102
+ # Weight unlabeled contributions by (1 - class_prior)
103
+ # Only (1 - π_p) of unlabeled samples are true negatives
104
+ thresholds = np.sort(np.unique(y_pred_proba))
105
+ if len(thresholds) > 200:
106
+ # Downsample for performance
107
+ indices = np.linspace(0, len(thresholds) - 1, 200, dtype=int)
108
+ thresholds = thresholds[indices]
109
+
110
+ tpr_list = []
111
+ fpr_list = []
112
+
113
+ for thresh in thresholds:
114
+ y_pred = (y_pred_proba >= thresh).astype(int)
115
+
116
+ # TPR: recall on positive samples (labeled positives are certain)
117
+ tp: int = int(np.sum((y_pred == 1) & (y_true == 1)))
118
+ fn: int = int(np.sum((y_pred == 0) & (y_true == 1)))
119
+ tpr = tp / (tp + fn) if (tp + fn) > 0 else 0.0
120
+
121
+ # FPR: false positive rate in unlabeled samples (corrected by class_prior)
122
+ fp: int = int(np.sum((y_pred == 1) & (y_true == 0)))
123
+ tn: int = int(np.sum((y_pred == 0) & (y_true == 0)))
124
+ # True negatives count in unlabeled ≈ n_unlabeled * (1 - π_p)
125
+ # But we use weighting directly: FP contribution multiplied by (1 - π_p)
126
+ total_unlabeled = fp + tn
127
+ if total_unlabeled > 0:
128
+ # Standard FPR
129
+ fpr = fp / total_unlabeled
130
+ # PU correction: some FP in unlabeled are actually true positives
131
+ fpr = fpr * (1 - class_prior)
132
+ else:
133
+ fpr = 0.0
134
+
135
+ tpr_list.append(tpr)
136
+ fpr_list.append(fpr)
137
+
138
+ # Sort and compute AUC
139
+ fpr_arr = np.array(fpr_list)
140
+ tpr_arr = np.array(tpr_list)
141
+ sorted_indices = np.argsort(fpr_arr)
142
+ fpr_arr = fpr_arr[sorted_indices]
143
+ tpr_arr = tpr_arr[sorted_indices]
144
+
145
+ auc = float(np.trapezoid(tpr_arr, fpr_arr))
146
+ return max(0.0, min(1.0, auc))
147
+
148
+
149
+ def pu_calibration(
150
+ y_true: np.ndarray,
151
+ y_pred_proba: np.ndarray,
152
+ class_prior: float,
153
+ n_bins: int = 10,
154
+ ) -> dict[str, Any]:
155
+ """PU calibration analysis.
156
+
157
+ Checks the consistency between predicted probabilities and actual positive rates.
158
+ In PU scenarios, the expected positive rate needs to be corrected by class_prior.
159
+
160
+ Args:
161
+ y_true: Ground truth labels (1=positive, 0=unlabeled).
162
+ y_pred_proba: Prediction probabilities.
163
+ class_prior: Class prior (π_p).
164
+ n_bins: Number of bins.
165
+
166
+ Returns:
167
+ Dictionary containing calibration statistics:
168
+ - bin_centers: Center probability of each bin
169
+ - bin_positive_rates: Actual positive rate per bin
170
+ - bin_expected_rates: Expected positive rate per bin (PU-corrected)
171
+ - calibration_error: Calibration error
172
+ """
173
+ bin_edges = np.linspace(0, 1, n_bins + 1)
174
+ bin_centers = []
175
+ bin_positive_rates = []
176
+ bin_expected_rates = []
177
+
178
+ for i in range(n_bins):
179
+ mask = (y_pred_proba >= bin_edges[i]) & (y_pred_proba < bin_edges[i + 1])
180
+ if mask.sum() == 0:
181
+ continue
182
+
183
+ center = (bin_edges[i] + bin_edges[i + 1]) / 2
184
+ positive_rate = y_true[mask].mean()
185
+
186
+ # Expected positive rate = standard expectation + contribution of true positives in unlabeled
187
+ # Samples labeled 0 in unlabeled data have probability π_p of being true positives
188
+ n_pos_in_bin = y_true[mask].sum()
189
+ n_unl_in_bin = mask.sum() - n_pos_in_bin
190
+ expected_rate = (n_pos_in_bin + n_unl_in_bin * class_prior) / mask.sum()
191
+
192
+ bin_centers.append(center)
193
+ bin_positive_rates.append(positive_rate)
194
+ bin_expected_rates.append(expected_rate)
195
+
196
+ if len(bin_centers) == 0:
197
+ return {
198
+ "bin_centers": [],
199
+ "bin_positive_rates": [],
200
+ "bin_expected_rates": [],
201
+ "calibration_error": 0.0,
202
+ }
203
+
204
+ center_values = np.asarray(bin_centers, dtype=np.float64)
205
+ positive_rate_values = np.asarray(bin_positive_rates, dtype=np.float64)
206
+ expected_rate_values = np.asarray(bin_expected_rates, dtype=np.float64)
207
+
208
+ # Calibration error: difference between actual and expected positive rates
209
+ calibration_error = float(
210
+ np.mean(np.abs(positive_rate_values - expected_rate_values))
211
+ )
212
+
213
+ return {
214
+ "bin_centers": center_values.tolist(),
215
+ "bin_positive_rates": positive_rate_values.tolist(),
216
+ "bin_expected_rates": expected_rate_values.tolist(),
217
+ "calibration_error": calibration_error,
218
+ }
219
+
220
+
221
+ def compute_pu_metrics(
222
+ y_true: np.ndarray,
223
+ y_pred_proba: np.ndarray,
224
+ class_prior: float,
225
+ threshold: float = 0.5,
226
+ ) -> dict[str, float]:
227
+ """Compute all PU metrics in one call.
228
+
229
+ Args:
230
+ y_true: Ground truth labels (1=positive, 0=unlabeled).
231
+ y_pred_proba: Prediction probabilities.
232
+ class_prior: Class prior (π_p).
233
+ threshold: Classification threshold.
234
+
235
+ Returns:
236
+ Dictionary containing all PU metrics.
237
+ """
238
+ return {
239
+ "pu_precision": pu_precision_score(
240
+ y_true, y_pred_proba, class_prior, threshold
241
+ ),
242
+ "pu_recall": _standard_recall(y_true, y_pred_proba, threshold),
243
+ "pu_f1": pu_f1_score(y_true, y_pred_proba, class_prior, threshold),
244
+ "pu_auc": pu_auc_score(y_true, y_pred_proba, class_prior),
245
+ }
246
+
247
+
248
+ def _standard_recall(
249
+ y_true: np.ndarray,
250
+ y_pred_proba: np.ndarray,
251
+ threshold: float = 0.5,
252
+ ) -> float:
253
+ """Standard Recall (positive labels are certain, no PU correction needed).
254
+
255
+ Args:
256
+ y_true: Ground truth labels.
257
+ y_pred_proba: Prediction probabilities.
258
+ threshold: Classification threshold.
259
+
260
+ Returns:
261
+ Recall value.
262
+ """
263
+ y_pred = (y_pred_proba >= threshold).astype(int)
264
+ tp: int = int(np.sum((y_pred == 1) & (y_true == 1)))
265
+ fn: int = int(np.sum((y_pred == 0) & (y_true == 1)))
266
+
267
+ if tp + fn == 0:
268
+ return 0.0
269
+ return float(tp / (tp + fn))
@@ -0,0 +1,129 @@
1
+ """Wheel-owned global nnPU/uPU loss reduction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from tributo.algorithms.api.torch_runtime import (
12
+ TorchCompositeGlobalState,
13
+ TorchGlobalLossContext,
14
+ TorchGlobalLossReduction,
15
+ TorchMetricContribution,
16
+ )
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class PURiskReducerPlan:
21
+ """Immutable PU risk parameters shared by the Recipe and reducer."""
22
+
23
+ mode: str = "nnpu"
24
+ class_prior: float = 0.5
25
+ beta: float = 0.0
26
+ gamma: float = 1.0
27
+
28
+ def __post_init__(self) -> None:
29
+ if self.mode not in {"nnpu", "upu"}:
30
+ raise ValueError("PU risk mode must be nnpu or upu")
31
+ if not 0.0 < self.class_prior < 1.0 or not math.isfinite(self.class_prior):
32
+ raise ValueError("PU class_prior must be finite and in (0, 1)")
33
+ if self.beta < 0.0 or not math.isfinite(self.beta):
34
+ raise ValueError("PU beta must be finite and non-negative")
35
+ if not 0.0 <= self.gamma <= 1.0 or not math.isfinite(self.gamma):
36
+ raise ValueError("PU gamma must be finite and in [0, 1]")
37
+
38
+
39
+ class PUGlobalLossReducer:
40
+ """Reduce PU components without performing collectives or I/O."""
41
+
42
+ api_version = 1
43
+ reducer_id = "tributo.official.tabular_torch.pu-risk"
44
+ component_schema_id = "tributo.official.tabular_torch.pu-risk-components.v1"
45
+ code_digest = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
46
+
47
+ def reduce(
48
+ self,
49
+ config: Mapping[str, object],
50
+ global_state: TorchCompositeGlobalState,
51
+ context: TorchGlobalLossContext,
52
+ ) -> TorchGlobalLossReduction:
53
+ del context
54
+ loss_config = config.get("loss", {})
55
+ if not isinstance(loss_config, Mapping):
56
+ return TorchGlobalLossReduction(
57
+ "rejected", failure_code="pu.invalid_config"
58
+ )
59
+ try:
60
+ prior = float(loss_config["class_prior"])
61
+ beta = float(loss_config.get("beta", 0.0))
62
+ gamma = float(loss_config.get("gamma", 1.0))
63
+ mode = str(loss_config.get("type", "nnpu"))
64
+ positive_count = float(global_state.normalizers["positive_count"])
65
+ unlabeled_count = float(global_state.normalizers["unlabeled_count"])
66
+ positive_loss = float(global_state.components["positive_loss_sum"])
67
+ positive_as_negative = float(
68
+ global_state.components["positive_as_negative_sum"]
69
+ )
70
+ unlabeled_negative = float(
71
+ global_state.components["unlabeled_negative_sum"]
72
+ )
73
+ except (KeyError, TypeError, ValueError):
74
+ return TorchGlobalLossReduction(
75
+ "rejected", failure_code="pu.invalid_components"
76
+ )
77
+ try:
78
+ risk_plan = PURiskReducerPlan(
79
+ mode=mode,
80
+ class_prior=prior,
81
+ beta=beta,
82
+ gamma=gamma,
83
+ )
84
+ except ValueError:
85
+ return TorchGlobalLossReduction(
86
+ "rejected", failure_code="pu.invalid_config"
87
+ )
88
+ if positive_count <= 0 or unlabeled_count <= 0:
89
+ return TorchGlobalLossReduction("rejected", failure_code="pu.empty_group")
90
+ negative_risk = (
91
+ unlabeled_negative / unlabeled_count
92
+ - prior * positive_as_negative / positive_count
93
+ )
94
+ correction = risk_plan.mode == "nnpu" and negative_risk < -risk_plan.beta
95
+ if correction:
96
+ coefficients = {
97
+ "positive_loss_sum": 0.0,
98
+ "positive_as_negative_sum": risk_plan.gamma
99
+ * risk_plan.class_prior
100
+ / positive_count,
101
+ "unlabeled_negative_sum": -risk_plan.gamma / unlabeled_count,
102
+ }
103
+ branch = "nnpu_correction"
104
+ risk = -risk_plan.gamma * negative_risk
105
+ else:
106
+ coefficients = {
107
+ "positive_loss_sum": risk_plan.class_prior / positive_count,
108
+ "positive_as_negative_sum": -risk_plan.class_prior / positive_count,
109
+ "unlabeled_negative_sum": 1.0 / unlabeled_count,
110
+ }
111
+ branch = "upu" if mode == "upu" else "nnpu_normal"
112
+ risk = (
113
+ risk_plan.class_prior * positive_loss / positive_count + negative_risk
114
+ )
115
+ return TorchGlobalLossReduction(
116
+ "accepted",
117
+ coefficients=coefficients,
118
+ branch=branch,
119
+ evidence={
120
+ "mode": mode,
121
+ "class_prior": risk_plan.class_prior,
122
+ "beta": risk_plan.beta,
123
+ "gamma": risk_plan.gamma,
124
+ },
125
+ metrics={"train_loss": TorchMetricContribution(risk, 1.0)},
126
+ )
127
+
128
+
129
+ __all__ = ["PUGlobalLossReducer", "PURiskReducerPlan"]