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,427 @@
1
+ """Typed ONNX Bundle exporters for PCA and KMeans."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import Any, cast
8
+
9
+ from tributo.algorithms.api import (
10
+ AlgorithmConfigurationError,
11
+ AlgorithmExecutionError,
12
+ AlgorithmExecutionResult,
13
+ ArtifactDraft,
14
+ ResolvedAlgorithmPlan,
15
+ )
16
+
17
+ from tributo_algorithms_classical.unsupervised_models import (
18
+ IsolationForestModel,
19
+ KMeansModel,
20
+ PCAModel,
21
+ )
22
+
23
+
24
+ def _onnx_metadata(
25
+ model: Any,
26
+ plan: ResolvedAlgorithmPlan,
27
+ graph_name: str,
28
+ ) -> bytes:
29
+ import numpy as np
30
+ import onnx
31
+ from onnx import TensorProto, helper, numpy_helper
32
+
33
+ feature_count = len(model.feature_names)
34
+ input_info = helper.make_tensor_value_info(
35
+ "float_input", TensorProto.FLOAT, [None, feature_count]
36
+ )
37
+ initializers = [
38
+ numpy_helper.from_array(
39
+ np.asarray(model.mean, dtype=np.float32),
40
+ name="mean",
41
+ ),
42
+ ]
43
+ nodes = [
44
+ helper.make_node("Sub", ["float_input", "mean"], ["centered"]),
45
+ helper.make_node(
46
+ "MatMul",
47
+ ["centered", "components"],
48
+ ["variable"],
49
+ ),
50
+ ]
51
+ initializers.append(
52
+ numpy_helper.from_array(
53
+ np.asarray(model.components, dtype=np.float32).T,
54
+ name="components",
55
+ )
56
+ )
57
+ output_info = helper.make_tensor_value_info(
58
+ "variable",
59
+ TensorProto.FLOAT,
60
+ [None, int(model.components.shape[0])],
61
+ )
62
+ graph = helper.make_graph(
63
+ nodes,
64
+ graph_name,
65
+ [input_info],
66
+ [output_info],
67
+ initializer=initializers,
68
+ )
69
+ model_proto = helper.make_model_gen_version(
70
+ graph,
71
+ producer_name="tributo-algorithms",
72
+ opset_imports=[helper.make_operatorsetid("", 18)],
73
+ )
74
+ model_proto.metadata_props.add(
75
+ key="feature_names", value=json.dumps(model.feature_names)
76
+ )
77
+ model_proto.metadata_props.add(
78
+ key="distribution_spec_digest",
79
+ value=plan.runtime.distribution_digest or "",
80
+ )
81
+ model_proto.doc_string = ""
82
+ for node in model_proto.graph.node:
83
+ node.doc_string = ""
84
+ onnx.checker.check_model(model_proto)
85
+ return bytes(model_proto.SerializeToString())
86
+
87
+
88
+ def _kmeans_onnx(model: KMeansModel, plan: ResolvedAlgorithmPlan) -> bytes:
89
+ import numpy as np
90
+ import onnx
91
+ from onnx import TensorProto, helper, numpy_helper
92
+
93
+ feature_count = len(model.feature_names)
94
+ input_info = helper.make_tensor_value_info(
95
+ "float_input", TensorProto.FLOAT, [None, feature_count]
96
+ )
97
+ labels = helper.make_tensor_value_info("label", TensorProto.INT64, [None])
98
+ distance = helper.make_tensor_value_info("distance", TensorProto.FLOAT, [None])
99
+ axes_batch = numpy_helper.from_array(
100
+ np.asarray([1], dtype=np.int64), name="axes_batch"
101
+ )
102
+ axes_feature = numpy_helper.from_array(
103
+ np.asarray([2], dtype=np.int64), name="axes_feature"
104
+ )
105
+ centers = numpy_helper.from_array(
106
+ np.asarray(model.centers, dtype=np.float32), name="centers"
107
+ )
108
+ nodes = [
109
+ helper.make_node("Unsqueeze", ["float_input", "axes_batch"], ["input_3d"]),
110
+ helper.make_node("Unsqueeze", ["centers", "axes_zero"], ["centers_3d"]),
111
+ helper.make_node("Sub", ["input_3d", "centers_3d"], ["delta"]),
112
+ helper.make_node("Mul", ["delta", "delta"], ["squared"]),
113
+ helper.make_node(
114
+ "ReduceSum", ["squared", "axes_feature"], ["distances"], keepdims=0
115
+ ),
116
+ helper.make_node("ArgMin", ["distances"], ["label"], axis=1, keepdims=0),
117
+ helper.make_node(
118
+ "ReduceMin", ["distances", "axes_cluster"], ["distance"], keepdims=0
119
+ ),
120
+ ]
121
+ initializers = [
122
+ centers,
123
+ axes_batch,
124
+ axes_feature,
125
+ numpy_helper.from_array(np.asarray([0], dtype=np.int64), name="axes_zero"),
126
+ numpy_helper.from_array(np.asarray([1], dtype=np.int64), name="axes_cluster"),
127
+ ]
128
+ graph = helper.make_graph(
129
+ nodes,
130
+ "tributo-kmeans",
131
+ [input_info],
132
+ [labels, distance],
133
+ initializer=initializers,
134
+ )
135
+ model_proto = helper.make_model_gen_version(
136
+ graph,
137
+ producer_name="tributo-algorithms",
138
+ opset_imports=[helper.make_operatorsetid("", 18)],
139
+ )
140
+ model_proto.metadata_props.add(
141
+ key="feature_names", value=json.dumps(model.feature_names)
142
+ )
143
+ model_proto.metadata_props.add(
144
+ key="distribution_spec_digest",
145
+ value=plan.runtime.distribution_digest or "",
146
+ )
147
+ model_proto.metadata_props.add(key="variant", value=model.variant)
148
+ onnx.checker.check_model(model_proto)
149
+ return bytes(model_proto.SerializeToString())
150
+
151
+
152
+ def _bundle_result(
153
+ *,
154
+ artifact: ArtifactDraft,
155
+ model: Any,
156
+ plan: ResolvedAlgorithmPlan,
157
+ run_id: str | None,
158
+ payload: bytes,
159
+ task_type: str,
160
+ output_schema: Sequence[Any],
161
+ output_values: Mapping[str, object],
162
+ ) -> AlgorithmExecutionResult:
163
+ output = plan.algorithm_config.get("output")
164
+ if not isinstance(output, Mapping):
165
+ raise AlgorithmConfigurationError("unsupervised fit requires output config")
166
+ bundle_uri = output.get("bundle_uri")
167
+ if not isinstance(bundle_uri, str) or not bundle_uri:
168
+ raise AlgorithmConfigurationError("output.bundle_uri must be non-empty")
169
+ from tributo.exporting.models import (
170
+ BundleOutputConfig,
171
+ CheckpointField,
172
+ ExportCheckpointV1,
173
+ ExportSource,
174
+ ExportTarget,
175
+ )
176
+ from tributo.exporting.service import BundleExportService
177
+
178
+ source = ExportSource(
179
+ source_kind="prebuilt_onnx",
180
+ model_object=payload,
181
+ feature_schema={"feature_names": list(model.feature_names)},
182
+ metadata={
183
+ "framework": "onnx",
184
+ "framework_versions": {"onnx": "18"},
185
+ "task_type": task_type,
186
+ "producer_distribution": "tributo-algorithms",
187
+ },
188
+ source_fingerprint=artifact.sha256,
189
+ checkpoint_contract=ExportCheckpointV1(
190
+ trainer_type=task_type,
191
+ architecture_id=plan.resolution.algorithm,
192
+ input_schema=(
193
+ CheckpointField(
194
+ name="float_input",
195
+ dtype="float32",
196
+ shape=("batch", len(model.feature_names)),
197
+ ),
198
+ ),
199
+ output_schema=tuple(output_schema),
200
+ preprocessing={"type": "none"},
201
+ task_type=task_type,
202
+ framework="onnx",
203
+ framework_version="18",
204
+ ),
205
+ )
206
+ bundle = BundleExportService().export_bundle(
207
+ source,
208
+ BundleOutputConfig(
209
+ bundle_uri=bundle_uri,
210
+ request_id=run_id,
211
+ run_id=run_id,
212
+ targets=[
213
+ ExportTarget(
214
+ name="onnx-model",
215
+ format="onnx",
216
+ exporter_id="prebuilt-onnx-v1",
217
+ )
218
+ ],
219
+ roles={"inference": "onnx-model"},
220
+ ),
221
+ )
222
+ return AlgorithmExecutionResult(
223
+ status="succeeded",
224
+ outputs={
225
+ **dict(output_values),
226
+ "bundle_id": bundle.bundle_id,
227
+ "bundle_uri": bundle.canonical_uri,
228
+ "execution_id": bundle.execution_id,
229
+ "manifest_sha256": bundle.manifest_sha256,
230
+ },
231
+ artifacts=(artifact,),
232
+ )
233
+
234
+
235
+ def export_pca_model(
236
+ *,
237
+ model: PCAModel,
238
+ plan: ResolvedAlgorithmPlan,
239
+ run_id: str | None = None,
240
+ ) -> AlgorithmExecutionResult:
241
+ """Export PCA as a typed ONNX transform Bundle."""
242
+ if not isinstance(model, PCAModel):
243
+ raise AlgorithmExecutionError("PCA exporter received an invalid model")
244
+ payload = _onnx_metadata(model, plan, "tributo-pca")
245
+ artifact = ArtifactDraft.from_payload(
246
+ name="model",
247
+ kind="model",
248
+ format="application/onnx",
249
+ payload=payload,
250
+ )
251
+ from tributo.exporting.models import CheckpointField
252
+
253
+ return _bundle_result(
254
+ artifact=artifact,
255
+ model=model,
256
+ plan=plan,
257
+ run_id=run_id,
258
+ payload=payload,
259
+ task_type="feature_transform",
260
+ output_schema=(
261
+ CheckpointField(
262
+ name="variable",
263
+ dtype="float32",
264
+ shape=("batch", int(model.components.shape[0])),
265
+ ),
266
+ ),
267
+ output_values={
268
+ "n_components": int(model.components.shape[0]),
269
+ "explained_variance": model.explained_variance.tolist(),
270
+ "explained_variance_ratio": model.explained_variance_ratio.tolist(),
271
+ },
272
+ )
273
+
274
+
275
+ def export_kmeans_model(
276
+ *,
277
+ model: KMeansModel,
278
+ plan: ResolvedAlgorithmPlan,
279
+ run_id: str | None = None,
280
+ ) -> AlgorithmExecutionResult:
281
+ """Export KMeans labels and distances as a typed ONNX Bundle."""
282
+ if not isinstance(model, KMeansModel):
283
+ raise AlgorithmExecutionError("KMeans exporter received an invalid model")
284
+ payload = _kmeans_onnx(model, plan)
285
+ artifact = ArtifactDraft.from_payload(
286
+ name="model",
287
+ kind="model",
288
+ format="application/onnx",
289
+ payload=payload,
290
+ )
291
+ from tributo.exporting.models import CheckpointField
292
+
293
+ return _bundle_result(
294
+ artifact=artifact,
295
+ model=model,
296
+ plan=plan,
297
+ run_id=run_id,
298
+ payload=payload,
299
+ task_type="clustering",
300
+ output_schema=(
301
+ CheckpointField(name="label", dtype="int64", shape=("batch",)),
302
+ CheckpointField(name="distance", dtype="float32", shape=("batch",)),
303
+ ),
304
+ output_values={
305
+ "n_clusters": int(model.centers.shape[0]),
306
+ "variant": model.variant,
307
+ },
308
+ )
309
+
310
+
311
+ def export_isolation_forest_model(
312
+ *,
313
+ model: IsolationForestModel,
314
+ plan: ResolvedAlgorithmPlan,
315
+ run_id: str | None = None,
316
+ ) -> AlgorithmExecutionResult:
317
+ """Export Isolation Forest raw scores and the explicit score threshold."""
318
+ if not isinstance(model, IsolationForestModel):
319
+ raise AlgorithmExecutionError(
320
+ "Isolation Forest exporter received an invalid model"
321
+ )
322
+ from skl2onnx import convert_sklearn
323
+ from skl2onnx.common.data_types import FloatTensorType
324
+ from tributo.exporting.models import CheckpointField
325
+
326
+ try:
327
+ converted = convert_sklearn(
328
+ model.estimator,
329
+ initial_types=[
330
+ ("float_input", FloatTensorType([None, len(model.feature_names)]))
331
+ ],
332
+ target_opset={"": 18, "ai.onnx.ml": 3},
333
+ )
334
+ import numpy as np
335
+ from onnx import TensorProto, helper, numpy_helper
336
+
337
+ score_output = next(
338
+ output for output in converted.graph.output if output.name == "scores"
339
+ )
340
+ del converted.graph.output[:]
341
+ threshold_output = helper.make_tensor_value_info(
342
+ "threshold", TensorProto.FLOAT, [None, 1]
343
+ )
344
+ converted.graph.output.extend([score_output, threshold_output])
345
+ converted.graph.initializer.extend(
346
+ [
347
+ numpy_helper.from_array(
348
+ np.asarray(0, dtype=np.int64), name="threshold_batch_index"
349
+ ),
350
+ numpy_helper.from_array(
351
+ np.asarray([0], dtype=np.int64), name="threshold_axes_zero"
352
+ ),
353
+ numpy_helper.from_array(
354
+ np.asarray([1], dtype=np.int64), name="threshold_one"
355
+ ),
356
+ numpy_helper.from_array(
357
+ np.asarray(
358
+ [[float(cast(Any, model.estimator).offset_)]],
359
+ dtype=np.float32,
360
+ ),
361
+ name="threshold_value",
362
+ ),
363
+ ]
364
+ )
365
+ converted.graph.node.extend(
366
+ [
367
+ helper.make_node("Shape", ["float_input"], ["threshold_input_shape"]),
368
+ helper.make_node(
369
+ "Gather",
370
+ ["threshold_input_shape", "threshold_batch_index"],
371
+ ["threshold_batch_size"],
372
+ axis=0,
373
+ ),
374
+ helper.make_node(
375
+ "Unsqueeze",
376
+ ["threshold_batch_size", "threshold_axes_zero"],
377
+ ["threshold_batch_dim"],
378
+ ),
379
+ helper.make_node(
380
+ "Concat",
381
+ ["threshold_batch_dim", "threshold_one"],
382
+ ["threshold_shape"],
383
+ axis=0,
384
+ ),
385
+ helper.make_node(
386
+ "Expand", ["threshold_value", "threshold_shape"], ["threshold"]
387
+ ),
388
+ ]
389
+ )
390
+ converted.graph.name = "tributo-isolation-forest"
391
+ converted.doc_string = ""
392
+ for node in converted.graph.node:
393
+ node.doc_string = ""
394
+ payload = converted.SerializeToString()
395
+ except Exception as exc:
396
+ raise AlgorithmExecutionError(
397
+ f"Isolation Forest ONNX export failed: {type(exc).__name__}"
398
+ ) from exc
399
+ artifact = ArtifactDraft.from_payload(
400
+ name="model",
401
+ kind="model",
402
+ format="application/onnx",
403
+ payload=payload,
404
+ )
405
+ return _bundle_result(
406
+ artifact=artifact,
407
+ model=model,
408
+ plan=plan,
409
+ run_id=run_id,
410
+ payload=payload,
411
+ task_type="anomaly_detection",
412
+ output_schema=(
413
+ CheckpointField(name="scores", dtype="float32", shape=("batch", 1)),
414
+ CheckpointField(name="threshold", dtype="float32", shape=("batch", 1)),
415
+ ),
416
+ output_values={
417
+ "n_estimators": len(cast(Any, model.estimator).estimators_),
418
+ "threshold": float(cast(Any, model.estimator).offset_),
419
+ },
420
+ )
421
+
422
+
423
+ __all__ = [
424
+ "export_isolation_forest_model",
425
+ "export_kmeans_model",
426
+ "export_pca_model",
427
+ ]
@@ -0,0 +1,90 @@
1
+ """Typed model metadata for official unsupervised algorithms."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ import numpy as np
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class PCAModel:
12
+ """Principal-component transform state produced by distributed fitting."""
13
+
14
+ components: np.ndarray
15
+ mean: np.ndarray
16
+ explained_variance: np.ndarray
17
+ explained_variance_ratio: np.ndarray
18
+ feature_names: tuple[str, ...]
19
+ n_samples: int
20
+
21
+ def __post_init__(self) -> None:
22
+ components = np.asarray(self.components, dtype=np.float64)
23
+ mean = np.asarray(self.mean, dtype=np.float64)
24
+ explained_variance = np.asarray(self.explained_variance, dtype=np.float64)
25
+ explained_variance_ratio = np.asarray(
26
+ self.explained_variance_ratio, dtype=np.float64
27
+ )
28
+ if components.ndim != 2 or mean.ndim != 1:
29
+ raise ValueError("PCA state must contain a matrix and a vector")
30
+ if components.shape[1] != mean.shape[0]:
31
+ raise ValueError("PCA components and mean dimensions disagree")
32
+ if explained_variance.shape != (components.shape[0],):
33
+ raise ValueError("PCA explained variance dimensions disagree")
34
+ if explained_variance_ratio.shape != explained_variance.shape:
35
+ raise ValueError("PCA explained variance ratio dimensions disagree")
36
+ if len(self.feature_names) != mean.shape[0] or self.n_samples < 2:
37
+ raise ValueError("PCA metadata is inconsistent")
38
+ object.__setattr__(self, "components", components)
39
+ object.__setattr__(self, "mean", mean)
40
+ object.__setattr__(self, "explained_variance", explained_variance)
41
+ object.__setattr__(self, "explained_variance_ratio", explained_variance_ratio)
42
+ object.__setattr__(self, "feature_names", tuple(self.feature_names))
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class KMeansModel:
47
+ """Cluster-center state produced by distributed KMeans fitting."""
48
+
49
+ centers: np.ndarray
50
+ feature_names: tuple[str, ...]
51
+ n_iter: int
52
+ variant: str
53
+
54
+ def __post_init__(self) -> None:
55
+ centers = np.asarray(self.centers, dtype=np.float64)
56
+ if centers.ndim != 2 or not centers.shape[0] or not centers.shape[1]:
57
+ raise ValueError("KMeans centers must be a non-empty matrix")
58
+ if len(self.feature_names) != centers.shape[1]:
59
+ raise ValueError("KMeans centers and feature names disagree")
60
+ if self.n_iter < 1 or self.variant not in {"kmeans", "minibatch"}:
61
+ raise ValueError("KMeans metadata is invalid")
62
+ object.__setattr__(self, "centers", centers)
63
+ object.__setattr__(self, "feature_names", tuple(self.feature_names))
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class IsolationForestModel:
68
+ """Isolation Forest model and ordered feature metadata."""
69
+
70
+ estimator: object
71
+ feature_names: tuple[str, ...]
72
+ training_values: np.ndarray | None = None
73
+
74
+ def __post_init__(self) -> None:
75
+ if not self.feature_names:
76
+ raise ValueError("Isolation Forest requires feature names")
77
+ if self.training_values is not None:
78
+ values = np.asarray(self.training_values, dtype=np.float64)
79
+ if (
80
+ values.ndim != 2
81
+ or not values.shape[0]
82
+ or values.shape[1] != len(self.feature_names)
83
+ or not np.isfinite(values).all()
84
+ ):
85
+ raise ValueError("Isolation Forest training values are inconsistent")
86
+ object.__setattr__(self, "training_values", values)
87
+ object.__setattr__(self, "feature_names", tuple(self.feature_names))
88
+
89
+
90
+ __all__ = ["IsolationForestModel", "KMeansModel", "PCAModel"]
@@ -0,0 +1,37 @@
1
+ """Official PyG graph algorithms with lazy runtime exports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from tributo_algorithms_graph_pyg.descriptor import (
8
+ GRAPHSAGE_DESCRIPTOR,
9
+ RGCN_DESCRIPTOR,
10
+ )
11
+
12
+ _LAZY_EXPORTS = {
13
+ "DistributedGraphSAGE": (
14
+ "tributo_algorithms_graph_pyg.algorithm",
15
+ "DistributedGraphSAGE",
16
+ ),
17
+ "DistributedRGCN": ("tributo_algorithms_graph_pyg.algorithm", "DistributedRGCN"),
18
+ }
19
+
20
+
21
+ def __getattr__(name: str) -> Any:
22
+ target = _LAZY_EXPORTS.get(name)
23
+ if target is None:
24
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
25
+ import importlib
26
+
27
+ value = getattr(importlib.import_module(target[0]), target[1])
28
+ globals()[name] = value
29
+ return value
30
+
31
+
32
+ __all__ = [
33
+ "DistributedGraphSAGE",
34
+ "DistributedRGCN",
35
+ "GRAPHSAGE_DESCRIPTOR",
36
+ "RGCN_DESCRIPTOR",
37
+ ]