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.
- tributo_algorithms-0.1.0.dist-info/METADATA +328 -0
- tributo_algorithms-0.1.0.dist-info/RECORD +110 -0
- tributo_algorithms-0.1.0.dist-info/WHEEL +4 -0
- tributo_algorithms-0.1.0.dist-info/entry_points.txt +57 -0
- tributo_algorithms-0.1.0.dist-info/licenses/LICENSE +202 -0
- tributo_algorithms_boosting/__init__.py +42 -0
- tributo_algorithms_boosting/algorithm.py +825 -0
- tributo_algorithms_boosting/checkpointing.py +441 -0
- tributo_algorithms_boosting/contracts.py +232 -0
- tributo_algorithms_boosting/data_config.py +59 -0
- tributo_algorithms_boosting/descriptor.py +124 -0
- tributo_algorithms_boosting/lightgbm.py +511 -0
- tributo_algorithms_boosting/lightgbm_contracts.py +186 -0
- tributo_algorithms_boosting/lightgbm_descriptor.py +112 -0
- tributo_algorithms_boosting/native.py +557 -0
- tributo_algorithms_boosting/stages.py +150 -0
- tributo_algorithms_catboost/__init__.py +5 -0
- tributo_algorithms_catboost/algorithm.py +379 -0
- tributo_algorithms_catboost/contracts.py +145 -0
- tributo_algorithms_catboost/descriptor.py +121 -0
- tributo_algorithms_catboost/exporter.py +106 -0
- tributo_algorithms_catboost/flavor.py +191 -0
- tributo_algorithms_causal_core/__init__.py +41 -0
- tributo_algorithms_causal_core/algorithm.py +1193 -0
- tributo_algorithms_causal_core/contracts.py +136 -0
- tributo_algorithms_causal_core/descriptor.py +270 -0
- tributo_algorithms_causal_core/exporter.py +52 -0
- tributo_algorithms_causal_discovery/__init__.py +23 -0
- tributo_algorithms_causal_discovery/algorithm.py +526 -0
- tributo_algorithms_causal_discovery/contracts.py +97 -0
- tributo_algorithms_causal_discovery/descriptor.py +130 -0
- tributo_algorithms_causal_discovery/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/__init__.py +38 -0
- tributo_algorithms_causal_dowhy/algorithm.py +325 -0
- tributo_algorithms_causal_dowhy/contracts.py +209 -0
- tributo_algorithms_causal_dowhy/descriptor.py +106 -0
- tributo_algorithms_causal_dowhy/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/gcm.py +634 -0
- tributo_algorithms_causal_dowhy/gcm_descriptor.py +110 -0
- tributo_algorithms_causal_dr/__init__.py +22 -0
- tributo_algorithms_causal_dr/algorithm.py +446 -0
- tributo_algorithms_causal_dr/contracts.py +94 -0
- tributo_algorithms_causal_dr/descriptor.py +104 -0
- tributo_algorithms_causal_xlearner/__init__.py +29 -0
- tributo_algorithms_causal_xlearner/algorithm.py +448 -0
- tributo_algorithms_causal_xlearner/contracts.py +97 -0
- tributo_algorithms_causal_xlearner/descriptor.py +120 -0
- tributo_algorithms_causal_xlearner/exporter.py +432 -0
- tributo_algorithms_causal_xlearner/flavor.py +120 -0
- tributo_algorithms_causal_xlearner/model.py +116 -0
- tributo_algorithms_classical/__init__.py +41 -0
- tributo_algorithms_classical/contracts.py +139 -0
- tributo_algorithms_classical/descriptors.py +370 -0
- tributo_algorithms_classical/exporter.py +166 -0
- tributo_algorithms_classical/isolation_forest.py +172 -0
- tributo_algorithms_classical/isolation_forest_descriptor.py +122 -0
- tributo_algorithms_classical/kmeans.py +315 -0
- tributo_algorithms_classical/kmeans_descriptor.py +147 -0
- tributo_algorithms_classical/linear_regression.py +206 -0
- tributo_algorithms_classical/logistic_regression.py +238 -0
- tributo_algorithms_classical/models.py +28 -0
- tributo_algorithms_classical/multinomial_nb.py +643 -0
- tributo_algorithms_classical/multinomial_nb_descriptor.py +183 -0
- tributo_algorithms_classical/pca.py +187 -0
- tributo_algorithms_classical/pca_descriptor.py +111 -0
- tributo_algorithms_classical/random_forest.py +304 -0
- tributo_algorithms_classical/sgd.py +331 -0
- tributo_algorithms_classical/sgd_contracts.py +121 -0
- tributo_algorithms_classical/sgd_descriptor.py +143 -0
- tributo_algorithms_classical/unsupervised_contracts.py +198 -0
- tributo_algorithms_classical/unsupervised_exporter.py +427 -0
- tributo_algorithms_classical/unsupervised_models.py +90 -0
- tributo_algorithms_graph_pyg/__init__.py +37 -0
- tributo_algorithms_graph_pyg/algorithm.py +883 -0
- tributo_algorithms_graph_pyg/contracts.py +260 -0
- tributo_algorithms_graph_pyg/descriptor.py +201 -0
- tributo_algorithms_multistage_torch/__init__.py +40 -0
- tributo_algorithms_multistage_torch/algorithm.py +532 -0
- tributo_algorithms_multistage_torch/contracts.py +220 -0
- tributo_algorithms_multistage_torch/descriptor.py +146 -0
- tributo_algorithms_multistage_torch/pretrain.py +570 -0
- tributo_algorithms_multistage_torch/pretrain_descriptor.py +153 -0
- tributo_algorithms_recsys_torch/__init__.py +35 -0
- tributo_algorithms_recsys_torch/contracts.py +295 -0
- tributo_algorithms_recsys_torch/descriptor.py +136 -0
- tributo_algorithms_recsys_torch/jagged.py +707 -0
- tributo_algorithms_recsys_torch/jagged_descriptor.py +130 -0
- tributo_algorithms_recsys_torch/recipe.py +192 -0
- tributo_algorithms_representation/__init__.py +20 -0
- tributo_algorithms_representation/contracts.py +117 -0
- tributo_algorithms_representation/descriptor.py +137 -0
- tributo_algorithms_representation/recipe.py +162 -0
- tributo_algorithms_tabular_torch/__init__.py +46 -0
- tributo_algorithms_tabular_torch/contracts.py +228 -0
- tributo_algorithms_tabular_torch/descriptor.py +223 -0
- tributo_algorithms_tabular_torch/priors.py +216 -0
- tributo_algorithms_tabular_torch/pu_metrics.py +269 -0
- tributo_algorithms_tabular_torch/pu_reducer.py +129 -0
- tributo_algorithms_tabular_torch/recipe.py +294 -0
- tributo_algorithms_timeseries/__init__.py +36 -0
- tributo_algorithms_timeseries/contracts.py +120 -0
- tributo_algorithms_timeseries/descriptor.py +137 -0
- tributo_algorithms_timeseries/recipe.py +195 -0
- tributo_algorithms_timeseries/rnn_contracts.py +170 -0
- tributo_algorithms_timeseries/rnn_descriptor.py +167 -0
- tributo_algorithms_timeseries/rnn_recipe.py +223 -0
- tributo_algorithms_transformers_nlp/__init__.py +20 -0
- tributo_algorithms_transformers_nlp/contracts.py +109 -0
- tributo_algorithms_transformers_nlp/descriptor.py +137 -0
- tributo_algorithms_transformers_nlp/recipe.py +235 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Descriptor for the official conditional CatBoost ensemble."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from tributo.algorithms import AlgorithmBuilder
|
|
6
|
+
from tributo.algorithms.api import (
|
|
7
|
+
ContractBinding,
|
|
8
|
+
ContractBindingSet,
|
|
9
|
+
DistributedExactness,
|
|
10
|
+
DistributionStrategy,
|
|
11
|
+
EnvironmentSpec,
|
|
12
|
+
ExecutionMode,
|
|
13
|
+
ExecutionProfile,
|
|
14
|
+
ParallelEnsemblePolicy,
|
|
15
|
+
QualifiedReference,
|
|
16
|
+
WorkerRange,
|
|
17
|
+
WorkerResources,
|
|
18
|
+
)
|
|
19
|
+
from tributo.training.algorithm_spec import (
|
|
20
|
+
AlgorithmSpec,
|
|
21
|
+
Capability,
|
|
22
|
+
DataLoadingMode,
|
|
23
|
+
ProblemType,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_PACKAGE = "tributo-algorithms"
|
|
27
|
+
_VERSION = "0.1.0"
|
|
28
|
+
_INPUT = "tributo.official.tabular.labeled.v1"
|
|
29
|
+
_OUTPUT = "tributo.official.catboost.native.v1"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _binding(contract_id: str, digest: str, validator: str) -> ContractBinding:
|
|
33
|
+
return ContractBinding(
|
|
34
|
+
contract_id=contract_id,
|
|
35
|
+
schema_version=1,
|
|
36
|
+
schema_digest=digest * 64,
|
|
37
|
+
validator_ref=QualifiedReference.parse(
|
|
38
|
+
f"tributo_algorithms_catboost.contracts:{validator}"
|
|
39
|
+
),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_SPEC = AlgorithmSpec(
|
|
44
|
+
name="catboost",
|
|
45
|
+
trainer_cls=None,
|
|
46
|
+
version="1.0.0",
|
|
47
|
+
default_config={"task": "classification"},
|
|
48
|
+
supported_tasks=("fit",),
|
|
49
|
+
operations=("fit",),
|
|
50
|
+
data_loading=DataLoadingMode.CANONICAL_DRIVER,
|
|
51
|
+
problem_types=(
|
|
52
|
+
ProblemType.BINARY_CLASSIFICATION,
|
|
53
|
+
ProblemType.MULTI_CLASS_CLASSIFICATION,
|
|
54
|
+
ProblemType.REGRESSION,
|
|
55
|
+
),
|
|
56
|
+
capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE),
|
|
57
|
+
learning_paradigm="supervised",
|
|
58
|
+
model_family="categorical_gradient_boosted_trees",
|
|
59
|
+
data_modalities=("tabular",),
|
|
60
|
+
lifecycle_kind="batch_fit",
|
|
61
|
+
allowed_execution_modes=(ExecutionMode.PARALLEL_ENSEMBLE.value,),
|
|
62
|
+
config_contract_ref="tributo.official.catboost.config.v1",
|
|
63
|
+
input_contract_ref=_INPUT,
|
|
64
|
+
output_contract_ref=_OUTPUT,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
CATBOOST_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
|
|
68
|
+
spec=_SPEC,
|
|
69
|
+
implementation_id="tributo.official.catboost.parallel_ensemble",
|
|
70
|
+
implementation_version="1.0.0",
|
|
71
|
+
implementation="tributo_algorithms_catboost.algorithm:CatBoostEnsemble",
|
|
72
|
+
executable_factory="tributo_algorithms_catboost.algorithm:create_algorithm",
|
|
73
|
+
distribution=_PACKAGE,
|
|
74
|
+
framework="catboost",
|
|
75
|
+
environment=EnvironmentSpec(
|
|
76
|
+
environment_id="tributo.official.catboost.v1",
|
|
77
|
+
dependencies=(
|
|
78
|
+
"catboost>=1.2,<2",
|
|
79
|
+
"onnxruntime>=1.20",
|
|
80
|
+
"tributo>=1.1",
|
|
81
|
+
f"tributo-algorithms[catboost]=={_VERSION}",
|
|
82
|
+
),
|
|
83
|
+
),
|
|
84
|
+
allowed_config_keys=(
|
|
85
|
+
"model",
|
|
86
|
+
"n_estimators",
|
|
87
|
+
"output",
|
|
88
|
+
"runtime",
|
|
89
|
+
"seed",
|
|
90
|
+
"task",
|
|
91
|
+
"unit_count",
|
|
92
|
+
),
|
|
93
|
+
strategy=DistributionStrategy.RAY_PARALLEL_ENSEMBLE,
|
|
94
|
+
supported_worker_range=WorkerRange(2, 256),
|
|
95
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
96
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
97
|
+
package_name=_PACKAGE,
|
|
98
|
+
package_version=_VERSION,
|
|
99
|
+
tributo_version_spec=">=1.1",
|
|
100
|
+
policy=ParallelEnsemblePolicy(
|
|
101
|
+
max_units=256,
|
|
102
|
+
max_retries=1,
|
|
103
|
+
exactness=DistributedExactness.CONDITIONAL,
|
|
104
|
+
),
|
|
105
|
+
exporter="tributo_algorithms_catboost.algorithm:export_result",
|
|
106
|
+
flavor_id="catboost-native-v1",
|
|
107
|
+
contract_bindings=ContractBindingSet(
|
|
108
|
+
config=_binding(
|
|
109
|
+
_SPEC.config_contract_ref or "", "5", "CatBoostConfigValidator"
|
|
110
|
+
),
|
|
111
|
+
input=_binding(_INPUT, "6", "CatBoostInputValidator"),
|
|
112
|
+
output=_binding(_OUTPUT, "7", "CatBoostOutputValidator"),
|
|
113
|
+
coverage=_binding(
|
|
114
|
+
"tributo.official.catboost.coverage.v1", "8", "CatBoostCoverageValidator"
|
|
115
|
+
),
|
|
116
|
+
),
|
|
117
|
+
descriptor_api_version=2,
|
|
118
|
+
is_default=True,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
__all__ = ["CATBOOST_DESCRIPTOR"]
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""CatBoost native model exporter plugin."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Any, ClassVar, cast
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, ConfigDict
|
|
10
|
+
from tributo.exporting.models import (
|
|
11
|
+
ArtifactDraft,
|
|
12
|
+
DraftFile,
|
|
13
|
+
ExportContext,
|
|
14
|
+
ExportSource,
|
|
15
|
+
PlannedTarget,
|
|
16
|
+
ProducerInfo,
|
|
17
|
+
ResolvedArtifact,
|
|
18
|
+
SupportRequest,
|
|
19
|
+
SupportResult,
|
|
20
|
+
ValidatorBinding,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from tributo_algorithms_catboost.algorithm import CatBoostModel
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CatBoostExportOptions(BaseModel):
|
|
27
|
+
"""No optional fields are exposed until native parity is validated."""
|
|
28
|
+
|
|
29
|
+
model_config = ConfigDict(extra="forbid")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CatBoostNativeExporter:
|
|
33
|
+
"""Write the CatBoost binary model and its typed metadata."""
|
|
34
|
+
|
|
35
|
+
api_version: ClassVar[int] = 2
|
|
36
|
+
exporter_id: ClassVar[str] = "catboost-native-v1"
|
|
37
|
+
priority: ClassVar[int] = 100
|
|
38
|
+
output_format: ClassVar[str] = "catboost"
|
|
39
|
+
output_flavor_id: ClassVar[str] = "catboost-native-v1"
|
|
40
|
+
source_kinds: ClassVar[tuple[str, ...]] = ("catboost_result",)
|
|
41
|
+
options_model: ClassVar[type[BaseModel]] = CatBoostExportOptions
|
|
42
|
+
validator_bindings: ClassVar[tuple[ValidatorBinding, ...]] = ()
|
|
43
|
+
mutates_source: ClassVar[bool] = False
|
|
44
|
+
upstream_requirements: ClassVar[tuple[Any, ...]] = ()
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def supports(cls, request: SupportRequest) -> SupportResult:
|
|
48
|
+
if request.source_kind != "catboost_result":
|
|
49
|
+
return SupportResult(
|
|
50
|
+
supported=False,
|
|
51
|
+
code="UNSUPPORTED_SOURCE_KIND",
|
|
52
|
+
reason="CatBoost exporter requires source_kind='catboost_result'",
|
|
53
|
+
)
|
|
54
|
+
return SupportResult(supported=True, code="OK")
|
|
55
|
+
|
|
56
|
+
def export(
|
|
57
|
+
self,
|
|
58
|
+
context: ExportContext,
|
|
59
|
+
source: ExportSource,
|
|
60
|
+
upstream: Mapping[str, ResolvedArtifact],
|
|
61
|
+
target: PlannedTarget,
|
|
62
|
+
) -> ArtifactDraft:
|
|
63
|
+
del upstream
|
|
64
|
+
import catboost
|
|
65
|
+
|
|
66
|
+
model = source.model_object
|
|
67
|
+
if not isinstance(model, CatBoostModel):
|
|
68
|
+
raise TypeError("CatBoost native exporter requires CatBoostModel")
|
|
69
|
+
model_path = context.artifact_dir / "model.cbm"
|
|
70
|
+
config_path = context.artifact_dir / "config.json"
|
|
71
|
+
cast(Any, model.model).save_model(str(model_path), format="cbm")
|
|
72
|
+
raw_classes = getattr(model.model, "classes_", ())
|
|
73
|
+
classes = model.classes or tuple(
|
|
74
|
+
raw_classes.tolist() if hasattr(raw_classes, "tolist") else raw_classes
|
|
75
|
+
)
|
|
76
|
+
class_count = len(classes) or 2
|
|
77
|
+
config_path.write_text(
|
|
78
|
+
json.dumps(
|
|
79
|
+
{
|
|
80
|
+
"cat_features": list(model.cat_features),
|
|
81
|
+
"classes": list(classes),
|
|
82
|
+
"feature_names": list(model.feature_names),
|
|
83
|
+
"task": model.task,
|
|
84
|
+
"class_count": class_count,
|
|
85
|
+
},
|
|
86
|
+
sort_keys=True,
|
|
87
|
+
),
|
|
88
|
+
encoding="utf-8",
|
|
89
|
+
)
|
|
90
|
+
return ArtifactDraft(
|
|
91
|
+
name=target.target.name,
|
|
92
|
+
format=self.output_format,
|
|
93
|
+
flavor_id=self.output_flavor_id,
|
|
94
|
+
files=(
|
|
95
|
+
DraftFile(relative_path="model.cbm", role="model"),
|
|
96
|
+
DraftFile(relative_path="config.json", role="config"),
|
|
97
|
+
),
|
|
98
|
+
entrypoint="model.cbm",
|
|
99
|
+
producer=ProducerInfo(
|
|
100
|
+
exporter_id=self.exporter_id,
|
|
101
|
+
framework_versions={"catboost": catboost.__version__},
|
|
102
|
+
),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
__all__ = ["CatBoostNativeExporter"]
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Safe CatBoost native Bundle model flavor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, ClassVar
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from tributo.exceptions import ModelLoadError
|
|
10
|
+
from tributo.exporting.models import ResolvedArtifact
|
|
11
|
+
from tributo.exporting.runtime import SECURITY_MODE_SAFE, BundleModel
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CatBoostNativeFlavor:
|
|
15
|
+
"""Load a CatBoost binary model without pickle or remote code."""
|
|
16
|
+
|
|
17
|
+
api_version: ClassVar[int] = 1
|
|
18
|
+
flavor_id: ClassVar[str] = "catboost-native-v1"
|
|
19
|
+
supported_formats: ClassVar[tuple[str, ...]] = ("catboost",)
|
|
20
|
+
batch_supported: ClassVar[bool] = True
|
|
21
|
+
serveable: ClassVar[bool] = True
|
|
22
|
+
security_mode: ClassVar[str] = SECURITY_MODE_SAFE
|
|
23
|
+
signature_required: ClassVar[bool] = True
|
|
24
|
+
required_dependencies: ClassVar[tuple[str, ...]] = ("catboost",)
|
|
25
|
+
operations: ClassVar[tuple[str, ...]] = ("prediction.batch", "prediction.online")
|
|
26
|
+
conditional_operations: ClassVar[tuple[str, ...]] = ()
|
|
27
|
+
|
|
28
|
+
def load(
|
|
29
|
+
self,
|
|
30
|
+
artifact: ResolvedArtifact,
|
|
31
|
+
*,
|
|
32
|
+
role: str,
|
|
33
|
+
unsafe: bool = False,
|
|
34
|
+
architecture_id: str | None = None,
|
|
35
|
+
) -> BundleModel:
|
|
36
|
+
del role, unsafe, architecture_id
|
|
37
|
+
try:
|
|
38
|
+
from catboost import CatBoost
|
|
39
|
+
except ImportError as exc:
|
|
40
|
+
raise ModelLoadError("catboost is required for catboost-native-v1") from exc
|
|
41
|
+
try:
|
|
42
|
+
raw_metadata = json.loads(
|
|
43
|
+
artifact.path_for("config.json").read_text(encoding="utf-8")
|
|
44
|
+
)
|
|
45
|
+
if not isinstance(raw_metadata, dict):
|
|
46
|
+
raise ValueError("CatBoost native metadata is not an object")
|
|
47
|
+
raw_feature_names = raw_metadata.get("feature_names")
|
|
48
|
+
raw_cat_features = raw_metadata.get("cat_features", [])
|
|
49
|
+
raw_classes = raw_metadata.get("classes", [])
|
|
50
|
+
raw_task = raw_metadata.get("task")
|
|
51
|
+
raw_class_count = raw_metadata.get("class_count", 2)
|
|
52
|
+
if not isinstance(raw_feature_names, list) or not all(
|
|
53
|
+
isinstance(name, str) and name for name in raw_feature_names
|
|
54
|
+
):
|
|
55
|
+
raise ValueError("CatBoost native feature metadata is invalid")
|
|
56
|
+
if not isinstance(raw_cat_features, list) or any(
|
|
57
|
+
not isinstance(index, int) or isinstance(index, bool)
|
|
58
|
+
for index in raw_cat_features
|
|
59
|
+
):
|
|
60
|
+
raise ValueError("CatBoost native categorical metadata is invalid")
|
|
61
|
+
if not isinstance(raw_classes, list):
|
|
62
|
+
raise ValueError("CatBoost native class metadata is invalid")
|
|
63
|
+
if (
|
|
64
|
+
not isinstance(raw_task, str)
|
|
65
|
+
or not isinstance(raw_class_count, int)
|
|
66
|
+
or isinstance(raw_class_count, bool)
|
|
67
|
+
):
|
|
68
|
+
raise ValueError("CatBoost native task metadata is invalid")
|
|
69
|
+
model = CatBoost()
|
|
70
|
+
model.load_model(str(artifact.entrypoint_path))
|
|
71
|
+
except Exception as exc:
|
|
72
|
+
raise ModelLoadError(
|
|
73
|
+
"CatBoost native artifact could not be loaded"
|
|
74
|
+
) from exc
|
|
75
|
+
return _CatBoostRuntimeModel(
|
|
76
|
+
model,
|
|
77
|
+
tuple(str(name) for name in raw_feature_names),
|
|
78
|
+
raw_task,
|
|
79
|
+
raw_class_count,
|
|
80
|
+
tuple(raw_cat_features),
|
|
81
|
+
tuple(raw_classes),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _CatBoostRuntimeModel:
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
model: Any,
|
|
89
|
+
feature_names: tuple[str, ...],
|
|
90
|
+
task: str,
|
|
91
|
+
class_count: int,
|
|
92
|
+
cat_features: tuple[int, ...],
|
|
93
|
+
classes: tuple[object, ...],
|
|
94
|
+
) -> None:
|
|
95
|
+
if not feature_names or task not in {"classification", "regression"}:
|
|
96
|
+
raise ModelLoadError("CatBoost native metadata is incomplete")
|
|
97
|
+
if any(index < 0 or index >= len(feature_names) for index in cat_features):
|
|
98
|
+
raise ModelLoadError("CatBoost native categorical metadata is invalid")
|
|
99
|
+
if len(set(cat_features)) != len(cat_features):
|
|
100
|
+
raise ModelLoadError("CatBoost native categorical metadata is duplicated")
|
|
101
|
+
if task == "classification" and class_count < 2:
|
|
102
|
+
raise ModelLoadError("CatBoost native class metadata is invalid")
|
|
103
|
+
if task == "classification" and len(classes) != class_count:
|
|
104
|
+
raise ModelLoadError("CatBoost native class metadata is incomplete")
|
|
105
|
+
try:
|
|
106
|
+
if len(set(classes)) != len(classes):
|
|
107
|
+
raise ModelLoadError("CatBoost native class metadata is duplicated")
|
|
108
|
+
except TypeError as exc:
|
|
109
|
+
raise ModelLoadError(
|
|
110
|
+
"CatBoost native class metadata is not scalar"
|
|
111
|
+
) from exc
|
|
112
|
+
self._model = model
|
|
113
|
+
self._feature_names = feature_names
|
|
114
|
+
self._task = task
|
|
115
|
+
self._class_count = class_count
|
|
116
|
+
self._cat_features = cat_features
|
|
117
|
+
self._classes = classes
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def input_names(self) -> tuple[str, ...]:
|
|
121
|
+
return ("float_input",)
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def output_names(self) -> tuple[str, ...]:
|
|
125
|
+
return (
|
|
126
|
+
("label", "probabilities")
|
|
127
|
+
if self._task == "classification"
|
|
128
|
+
else ("variable",)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def input_dtypes(self) -> tuple[str, ...]:
|
|
133
|
+
return ("object" if self._cat_features else "float32",)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def output_dtypes(self) -> tuple[str, ...]:
|
|
137
|
+
return ("int64", "float32") if self._task == "classification" else ("float32",)
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def input_shapes(self) -> tuple[tuple[int | None, ...], ...]:
|
|
141
|
+
return ((None, len(self._feature_names)),)
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def output_shapes(self) -> tuple[tuple[int | None, ...], ...]:
|
|
145
|
+
return (
|
|
146
|
+
((None,), (None, self._class_count))
|
|
147
|
+
if self._task == "classification"
|
|
148
|
+
else ((None, 1),)
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
def predict(self, inputs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
|
|
152
|
+
if set(inputs) != {"float_input"}:
|
|
153
|
+
raise ModelLoadError("CatBoost model requires exactly float_input")
|
|
154
|
+
values = np.asarray(inputs["float_input"])
|
|
155
|
+
if values.ndim != 2 or values.shape[1] != len(self._feature_names):
|
|
156
|
+
raise ModelLoadError("CatBoost input shape does not match feature metadata")
|
|
157
|
+
if self._task == "classification":
|
|
158
|
+
raw_labels = np.asarray(
|
|
159
|
+
self._model.predict(values, prediction_type="Class")
|
|
160
|
+
).reshape(-1)
|
|
161
|
+
class_indices = {value: index for index, value in enumerate(self._classes)}
|
|
162
|
+
try:
|
|
163
|
+
labels = np.asarray(
|
|
164
|
+
[
|
|
165
|
+
class_indices[
|
|
166
|
+
value.item() if isinstance(value, np.generic) else value
|
|
167
|
+
]
|
|
168
|
+
for value in raw_labels
|
|
169
|
+
],
|
|
170
|
+
dtype=np.int64,
|
|
171
|
+
)
|
|
172
|
+
except (KeyError, TypeError) as exc:
|
|
173
|
+
raise ModelLoadError(
|
|
174
|
+
"CatBoost prediction contains an unknown class"
|
|
175
|
+
) from exc
|
|
176
|
+
return {
|
|
177
|
+
"label": labels,
|
|
178
|
+
"probabilities": np.asarray(
|
|
179
|
+
self._model.predict(values, prediction_type="Probability"),
|
|
180
|
+
dtype=np.float32,
|
|
181
|
+
),
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
"variable": np.asarray(
|
|
185
|
+
self._model.predict(values, prediction_type="RawFormulaVal"),
|
|
186
|
+
dtype=np.float32,
|
|
187
|
+
).reshape(-1, 1)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
__all__ = ["CatBoostNativeFlavor"]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Official distributed causal algorithms with lazy runtime exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from tributo_algorithms_causal_core.descriptor import (
|
|
8
|
+
ATE_DESCRIPTOR,
|
|
9
|
+
LINEAR_DML_DESCRIPTOR,
|
|
10
|
+
LINEAR_IV_DESCRIPTOR,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
_LAZY_EXPORTS = {
|
|
14
|
+
"DifferenceInMeansATE": (
|
|
15
|
+
"tributo_algorithms_causal_core.algorithm",
|
|
16
|
+
"DifferenceInMeansATE",
|
|
17
|
+
),
|
|
18
|
+
"LinearDMLATE": ("tributo_algorithms_causal_core.algorithm", "LinearDMLATE"),
|
|
19
|
+
"LinearIVATE": ("tributo_algorithms_causal_core.algorithm", "LinearIVATE"),
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def __getattr__(name: str) -> Any:
|
|
24
|
+
target = _LAZY_EXPORTS.get(name)
|
|
25
|
+
if target is None:
|
|
26
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
27
|
+
import importlib
|
|
28
|
+
|
|
29
|
+
value = getattr(importlib.import_module(target[0]), target[1])
|
|
30
|
+
globals()[name] = value
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"ATE_DESCRIPTOR",
|
|
36
|
+
"LINEAR_DML_DESCRIPTOR",
|
|
37
|
+
"LINEAR_IV_DESCRIPTOR",
|
|
38
|
+
"DifferenceInMeansATE",
|
|
39
|
+
"LinearDMLATE",
|
|
40
|
+
"LinearIVATE",
|
|
41
|
+
]
|