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,238 @@
1
+ """Binary L2 logistic regression mathematical Hook implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pickle
6
+ from collections.abc import Iterable, Mapping
7
+ from typing import Any, cast
8
+
9
+ import numpy as np
10
+ from tributo.algorithms import IterativeOptimizationAlgorithm
11
+ from tributo.algorithms.spi import (
12
+ AlgorithmExecutionContext,
13
+ MaterializedTabularInputView,
14
+ TabularBatchInputView,
15
+ )
16
+
17
+ from tributo_algorithms_classical.models import SklearnModel
18
+
19
+
20
+ class PickleCheckpointCodec:
21
+ """Serialize complete iterative optimizer state."""
22
+
23
+ def dumps(self, value: object) -> bytes:
24
+ return pickle.dumps(value, protocol=5)
25
+
26
+ def loads(self, payload: bytes) -> object:
27
+ return pickle.loads(payload)
28
+
29
+
30
+ class BinaryL2LogisticRegression(
31
+ IterativeOptimizationAlgorithm[
32
+ Mapping[str, object],
33
+ Mapping[str, object],
34
+ Mapping[str, object],
35
+ SklearnModel,
36
+ ]
37
+ ):
38
+ """Synchronous full-gradient binary logistic regression."""
39
+
40
+ def initialize_state(
41
+ self,
42
+ config: Mapping[str, Any],
43
+ input_descriptor: object,
44
+ ) -> Mapping[str, object]:
45
+ del input_descriptor
46
+ feature_count = int(config.get("feature_count", 2))
47
+ feature_names = tuple(
48
+ str(name)
49
+ for name in config.get(
50
+ "_tributo_feature_names",
51
+ tuple(f"feature_{index}" for index in range(feature_count)),
52
+ )
53
+ )
54
+ if len(feature_names) != feature_count:
55
+ raise ValueError("feature_count does not match input feature names")
56
+ c_value = float(config.get("C", 1.0))
57
+ if not np.isfinite(c_value) or c_value <= 0:
58
+ raise ValueError("C must be a positive finite value")
59
+ return {
60
+ "coef": np.zeros(feature_count, dtype=np.float64),
61
+ "intercept": np.zeros(1, dtype=np.float64),
62
+ "round": np.zeros(1, dtype=np.int64),
63
+ "feature_count": np.asarray([feature_count], dtype=np.int64),
64
+ "learning_rate": np.asarray(
65
+ [float(config.get("learning_rate", 0.25))], dtype=np.float64
66
+ ),
67
+ "tolerance": np.asarray(
68
+ [float(config.get("tolerance", 1e-6))], dtype=np.float64
69
+ ),
70
+ "regularization": np.asarray([1.0 / c_value], dtype=np.float64),
71
+ "feature_names": feature_names,
72
+ }
73
+
74
+ def compute_partition_update(
75
+ self,
76
+ batches: Iterable[Mapping[str, object]],
77
+ state: Mapping[str, object],
78
+ round_index: int,
79
+ context: AlgorithmExecutionContext,
80
+ ) -> Mapping[str, object]:
81
+ del round_index
82
+ view = context.inputs["train"]
83
+ if not isinstance(view, (TabularBatchInputView, MaterializedTabularInputView)):
84
+ raise ValueError("Logistic Regression requires tabular batch input")
85
+ feature_names = tuple(str(name) for name in view.feature_names)
86
+ label_name = view.label_name
87
+ if not isinstance(label_name, str):
88
+ raise ValueError("Logistic Regression requires a label")
89
+ coef = np.asarray(state["coef"], dtype=np.float64)
90
+ intercept = float(np.asarray(state["intercept"])[0])
91
+ gradient = np.zeros_like(coef)
92
+ hessian = np.zeros((len(coef) + 1, len(coef) + 1), dtype=np.float64)
93
+ intercept_gradient = 0.0
94
+ loss_sum = 0.0
95
+ rows = 0
96
+ for batch in batches:
97
+ features = np.column_stack(
98
+ [np.asarray(batch[name], dtype=np.float64) for name in feature_names]
99
+ )
100
+ labels = np.asarray(batch[label_name], dtype=np.float64)
101
+ if not np.isin(labels, (0.0, 1.0)).all():
102
+ raise ValueError("binary Logistic Regression labels must be 0 or 1")
103
+ logits = features @ coef + intercept
104
+ probability = 1.0 / (1.0 + np.exp(-np.clip(logits, -30.0, 30.0)))
105
+ error = probability - labels
106
+ gradient += features.T @ error
107
+ intercept_gradient += float(np.sum(error))
108
+ design = np.column_stack((features, np.ones(len(labels))))
109
+ weights = probability * (1.0 - probability)
110
+ hessian += design.T @ (weights[:, None] * design)
111
+ loss_sum += float(np.sum(np.logaddexp(0.0, logits) - labels * logits))
112
+ rows += len(labels)
113
+ return {
114
+ "gradient_sum": gradient,
115
+ "intercept_gradient_sum": np.asarray([intercept_gradient]),
116
+ "hessian_sum": hessian,
117
+ "loss_sum": np.asarray([loss_sum]),
118
+ "row_count": np.asarray([rows], dtype=np.int64),
119
+ }
120
+
121
+ def merge_updates(
122
+ self,
123
+ left: Mapping[str, object],
124
+ right: Mapping[str, object],
125
+ ) -> Mapping[str, object]:
126
+ return {name: np.asarray(left[name]) + np.asarray(right[name]) for name in left}
127
+
128
+ def apply_update(
129
+ self,
130
+ state: Mapping[str, object],
131
+ update: Mapping[str, object],
132
+ round_index: int,
133
+ ) -> Mapping[str, object]:
134
+ rows = int(np.asarray(update["row_count"])[0])
135
+ if rows < 1:
136
+ raise ValueError("Logistic Regression cannot update from zero rows")
137
+ learning_rate = float(np.asarray(state["learning_rate"])[0])
138
+ regularization = float(np.asarray(state["regularization"])[0]) / rows
139
+ coef = np.asarray(state["coef"], dtype=np.float64)
140
+ intercept = float(np.asarray(state["intercept"])[0])
141
+ gradient = (
142
+ np.concatenate(
143
+ (
144
+ np.asarray(update["gradient_sum"], dtype=np.float64),
145
+ np.asarray(update["intercept_gradient_sum"], dtype=np.float64),
146
+ )
147
+ )
148
+ / rows
149
+ )
150
+ gradient[: len(coef)] += regularization * coef
151
+ hessian = np.asarray(update["hessian_sum"], dtype=np.float64) / rows
152
+ hessian[: len(coef), : len(coef)] += np.eye(len(coef)) * regularization
153
+ try:
154
+ step = np.linalg.solve(hessian, gradient)
155
+ except np.linalg.LinAlgError:
156
+ step = np.linalg.lstsq(hessian, gradient, rcond=None)[0]
157
+ return {
158
+ **state,
159
+ "coef": coef - learning_rate * step[:-1],
160
+ "intercept": np.asarray([intercept - learning_rate * step[-1]]),
161
+ "round": np.asarray([round_index + 1], dtype=np.int64),
162
+ }
163
+
164
+ def evaluate_round(
165
+ self,
166
+ state: Mapping[str, object],
167
+ update: Mapping[str, object],
168
+ round_index: int,
169
+ ) -> Mapping[str, int | float]:
170
+ del round_index
171
+ rows = int(np.asarray(update["row_count"])[0])
172
+ gradient = np.asarray(update["gradient_sum"], dtype=np.float64) / rows
173
+ gradient += (
174
+ float(np.asarray(state["regularization"])[0])
175
+ / rows
176
+ * np.asarray(state["coef"], dtype=np.float64)
177
+ )
178
+ return {
179
+ "loss": float(np.asarray(update["loss_sum"])[0] / rows),
180
+ "gradient_norm": float(np.linalg.norm(gradient)),
181
+ "row_count": rows,
182
+ }
183
+
184
+ def should_stop(
185
+ self,
186
+ state: Mapping[str, object],
187
+ metrics: Mapping[str, int | float],
188
+ round_index: int,
189
+ ) -> bool:
190
+ del round_index
191
+ tolerance = float(np.asarray(state["tolerance"])[0])
192
+ return float(metrics["gradient_norm"]) < tolerance
193
+
194
+ def finalize_model(self, state: Mapping[str, object]) -> SklearnModel:
195
+ from sklearn.linear_model import LogisticRegression
196
+
197
+ estimator = LogisticRegression()
198
+ estimator.classes_ = np.asarray([0, 1], dtype=np.int64)
199
+ estimator.coef_ = np.asarray(state["coef"], dtype=np.float64)[None, :]
200
+ estimator.intercept_ = np.asarray(state["intercept"], dtype=np.float64)
201
+ estimator.n_iter_ = np.asarray(state["round"], dtype=np.int32)
202
+ estimator.n_features_in_ = int(np.asarray(state["feature_count"])[0])
203
+ feature_names = tuple(
204
+ str(name) for name in cast(Iterable[object], state["feature_names"])
205
+ )
206
+ estimator.C = 1.0 / float(np.asarray(state["regularization"])[0])
207
+ return SklearnModel(estimator, feature_names, "classification")
208
+
209
+ def state_schema(self) -> Mapping[str, object]:
210
+ return {
211
+ "coef": "float64[*]",
212
+ "intercept": "float64[1]",
213
+ "round": "int64[1]",
214
+ "feature_count": "int64[1]",
215
+ "learning_rate": "float64[1]",
216
+ "tolerance": "float64[1]",
217
+ "regularization": "float64[1]",
218
+ "feature_names": "tuple[str]",
219
+ }
220
+
221
+ def update_schema(self) -> Mapping[str, object]:
222
+ return {
223
+ "gradient_sum": "float64[*]",
224
+ "intercept_gradient_sum": "float64[1]",
225
+ "hessian_sum": "float64[*,*]",
226
+ "loss_sum": "float64[1]",
227
+ "row_count": "int64[1]",
228
+ }
229
+
230
+ def checkpoint_codec(self) -> object:
231
+ return PickleCheckpointCodec()
232
+
233
+ @property
234
+ def retry_safe(self) -> bool:
235
+ return True
236
+
237
+
238
+ __all__ = ["BinaryL2LogisticRegression", "PickleCheckpointCodec"]
@@ -0,0 +1,28 @@
1
+ """Model containers shared by classical training and export."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class SklearnModel:
10
+ """A fitted estimator plus its stable ordered feature signature."""
11
+
12
+ estimator: object
13
+ feature_names: tuple[str, ...]
14
+ task: str
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class TreeUnitModel:
19
+ """One independently trained tree and final-forest metadata."""
20
+
21
+ estimator: object
22
+ feature_names: tuple[str, ...]
23
+ task: str
24
+ classes: tuple[object, ...]
25
+ n_outputs: int
26
+
27
+
28
+ __all__ = ["SklearnModel", "TreeUnitModel"]