curaitor 0.1.0a1__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.
- curaitor/__init__.py +89 -0
- curaitor/api.py +568 -0
- curaitor/app/__init__.py +47 -0
- curaitor/app/analysis.py +734 -0
- curaitor/app/annotaide_tab.py +244 -0
- curaitor/app/datasets.py +480 -0
- curaitor/app/lifecycle.py +117 -0
- curaitor/app/mcp_server.py +161 -0
- curaitor/app/records.py +283 -0
- curaitor/app/sources/config.yaml +28 -0
- curaitor/app/sources/folder.yaml +29 -0
- curaitor/app/sources/huggingface.yaml +26 -0
- curaitor/app/sources/image_folder.yaml +28 -0
- curaitor/app/static/app.css +210 -0
- curaitor/app/static/app.js +2146 -0
- curaitor/app/static/index.html +130 -0
- curaitor/app/static/map3d.js +271 -0
- curaitor/app/static/vendor/OrbitControls.js +1523 -0
- curaitor/app/static/vendor/three.LICENSE +21 -0
- curaitor/app/static/vendor/three.module.min.js +6 -0
- curaitor/app/views.py +299 -0
- curaitor/app/web.py +762 -0
- curaitor/app/workspace.py +950 -0
- curaitor/app/workspaces/compare/analysis_compare.yaml +37 -0
- curaitor/app/workspaces/compare/candidate.yaml +26 -0
- curaitor/app/workspaces/compare/embedding.yaml +24 -0
- curaitor/app/workspaces/compare/reference.yaml +26 -0
- curaitor/app/workspaces/compare.yaml +19 -0
- curaitor/app/workspaces/image-outliers/analysis_outliers.yaml +34 -0
- curaitor/app/workspaces/image-outliers/embedding.yaml +24 -0
- curaitor/app/workspaces/image-outliers/source.yaml +31 -0
- curaitor/app/workspaces/image-outliers.yaml +18 -0
- curaitor/app/workspaces/images/analysis_overview.yaml +45 -0
- curaitor/app/workspaces/images/analysis_unique.yaml +53 -0
- curaitor/app/workspaces/images/embedding.yaml +24 -0
- curaitor/app/workspaces/images/source.yaml +29 -0
- curaitor/app/workspaces/images.yaml +20 -0
- curaitor/app/workspaces/label-issues/analysis_labels.yaml +36 -0
- curaitor/app/workspaces/label-issues/embedding.yaml +24 -0
- curaitor/app/workspaces/label-issues/source.yaml +28 -0
- curaitor/app/workspaces/label-issues/source@sonair.yaml +28 -0
- curaitor/app/workspaces/label-issues.yaml +20 -0
- curaitor/audio_adapter.py +177 -0
- curaitor/cleanlab_backend.py +96 -0
- curaitor/cli.py +216 -0
- curaitor/evidently_backend.py +164 -0
- curaitor/fiftyone_service.py +80 -0
- curaitor/image_adapter.py +181 -0
- curaitor/networkx_backend.py +62 -0
- curaitor/ops.py +924 -0
- curaitor/plots.py +176 -0
- curaitor/pot_backend.py +182 -0
- curaitor/py.typed +0 -0
- curaitor/pyod_backend.py +136 -0
- curaitor/scipy_backend.py +104 -0
- curaitor/sklearn_backend.py +380 -0
- curaitor/torchmetrics_backend.py +123 -0
- curaitor/umap_backend.py +78 -0
- curaitor-0.1.0a1.data/data/share/curaitor/examples/check_labels.yaml +17 -0
- curaitor-0.1.0a1.data/data/share/curaitor/examples/compare_datasets.yaml +14 -0
- curaitor-0.1.0a1.data/data/share/curaitor/examples/find_outliers.yaml +17 -0
- curaitor-0.1.0a1.data/data/share/curaitor/graphs/image_outliers.yaml +37 -0
- curaitor-0.1.0a1.dist-info/METADATA +397 -0
- curaitor-0.1.0a1.dist-info/RECORD +68 -0
- curaitor-0.1.0a1.dist-info/WHEEL +5 -0
- curaitor-0.1.0a1.dist-info/entry_points.txt +12 -0
- curaitor-0.1.0a1.dist-info/licenses/LICENSE +77 -0
- curaitor-0.1.0a1.dist-info/top_level.txt +1 -0
curaitor/__init__.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Curaitor — adapter for dataset curation & analysis.
|
|
2
|
+
|
|
3
|
+
A thin glue layer that exposes five Confluid-:func:`@configurable` wrappers
|
|
4
|
+
and five dispatch functions over six families of dataset-analysis libraries:
|
|
5
|
+
|
|
6
|
+
- `pyod <https://pyod.readthedocs.io/>`__ — outlier / anomaly detection.
|
|
7
|
+
- `scikit-learn <https://scikit-learn.org/>`__ — lightweight outlier and
|
|
8
|
+
projection defaults (Isolation Forest, LOF, PCA, t-SNE).
|
|
9
|
+
- `POT <https://pythonot.github.io/>`__ — multi-dim optimal-transport
|
|
10
|
+
distances (Wasserstein, Sinkhorn, MMD, energy, Bures).
|
|
11
|
+
- `scipy.stats <https://docs.scipy.org/doc/scipy/reference/stats.html>`__ —
|
|
12
|
+
classical 1-D statistical tests (KS, Anderson, Cramér–von Mises) plus
|
|
13
|
+
``scipy.stats.wasserstein_distance`` / ``energy_distance``.
|
|
14
|
+
- `torchmetrics[image] <https://lightning.ai/docs/torchmetrics/>`__ — FID /
|
|
15
|
+
KID / Inception Score for synthetic-vs-real evaluation.
|
|
16
|
+
- `cleanlab <https://docs.cleanlab.ai/>`__ — confident-learning label-issue
|
|
17
|
+
detection.
|
|
18
|
+
- `evidently <https://docs.evidentlyai.com/>`__ — data-drift reports
|
|
19
|
+
(PSI / JS / column-wise statistical tests).
|
|
20
|
+
- `umap-learn <https://umap-learn.readthedocs.io/>`__ — UMAP projection.
|
|
21
|
+
|
|
22
|
+
Plus two optional modality adapters that turn a RecordStream ``Stream`` of raw
|
|
23
|
+
records into a feature matrix consumable by every dispatcher:
|
|
24
|
+
|
|
25
|
+
- :mod:`curaitor.image_adapter` — ``timm``-based image embeddings (extra
|
|
26
|
+
``[image]``).
|
|
27
|
+
- :mod:`curaitor.audio_adapter` — ``torchaudio`` pretrained-pipeline audio
|
|
28
|
+
embeddings (extra ``[audio]``).
|
|
29
|
+
|
|
30
|
+
Backends are imported lazily, so any subset of the optional extras
|
|
31
|
+
(``[outliers]``, ``[distances]``, ``[generative]``, ``[cleaning]``,
|
|
32
|
+
``[drift]``, ``[viz]``, ``[image]``, ``[audio]``) is enough for the package
|
|
33
|
+
to import.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
37
|
+
|
|
38
|
+
from confluid import register
|
|
39
|
+
|
|
40
|
+
from curaitor.api import (
|
|
41
|
+
ComparisonReport,
|
|
42
|
+
DatasetComparator,
|
|
43
|
+
DistanceMetric,
|
|
44
|
+
LabelChecker,
|
|
45
|
+
LabelIssueResult,
|
|
46
|
+
OutlierDetector,
|
|
47
|
+
OutlierResult,
|
|
48
|
+
ProjectionResult,
|
|
49
|
+
Projector,
|
|
50
|
+
available_methods,
|
|
51
|
+
check_labels,
|
|
52
|
+
compare_datasets,
|
|
53
|
+
compute_distance,
|
|
54
|
+
find_outliers,
|
|
55
|
+
list_methods,
|
|
56
|
+
project,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
# Single source of truth: the installed distribution's metadata, i.e. pyproject.toml's
|
|
61
|
+
# `version` (the distribution is `curaitor`). Never type the number in here as well.
|
|
62
|
+
__version__ = version("curaitor")
|
|
63
|
+
except PackageNotFoundError: # pragma: no cover - uninstalled source checkout
|
|
64
|
+
__version__ = "0.0.0.dev0"
|
|
65
|
+
|
|
66
|
+
register(OutlierDetector)
|
|
67
|
+
register(DistanceMetric)
|
|
68
|
+
register(DatasetComparator)
|
|
69
|
+
register(LabelChecker)
|
|
70
|
+
register(Projector)
|
|
71
|
+
|
|
72
|
+
__all__ = [
|
|
73
|
+
"OutlierDetector",
|
|
74
|
+
"DistanceMetric",
|
|
75
|
+
"DatasetComparator",
|
|
76
|
+
"LabelChecker",
|
|
77
|
+
"Projector",
|
|
78
|
+
"OutlierResult",
|
|
79
|
+
"ComparisonReport",
|
|
80
|
+
"LabelIssueResult",
|
|
81
|
+
"ProjectionResult",
|
|
82
|
+
"find_outliers",
|
|
83
|
+
"compute_distance",
|
|
84
|
+
"compare_datasets",
|
|
85
|
+
"check_labels",
|
|
86
|
+
"project",
|
|
87
|
+
"list_methods",
|
|
88
|
+
"available_methods",
|
|
89
|
+
]
|
curaitor/api.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
"""Unified dataset-curation API.
|
|
2
|
+
|
|
3
|
+
Five concerns, five dispatchers, five Confluid-`@configurable` wrappers:
|
|
4
|
+
|
|
5
|
+
- :func:`find_outliers` / :class:`OutlierDetector` — per-record anomaly scores.
|
|
6
|
+
- :func:`compute_distance` / :class:`DistanceMetric` — one-number distribution
|
|
7
|
+
distance between two feature matrices.
|
|
8
|
+
- :func:`compare_datasets` / :class:`DatasetComparator` — richer comparison
|
|
9
|
+
(FID/KID, drift reports) returning structured metrics.
|
|
10
|
+
- :func:`check_labels` / :class:`LabelChecker` — per-record label-issue scores
|
|
11
|
+
on a labeled feature matrix.
|
|
12
|
+
- :func:`project` / :class:`Projector` — N-D → low-D embedding for inspection.
|
|
13
|
+
|
|
14
|
+
Each backend (``<name>_backend.py``) declares which of the five verbs it
|
|
15
|
+
serves via per-verb method tuples (``OUTLIER_METHODS``, ``DISTANCE_METHODS``,
|
|
16
|
+
``COMPARE_METHODS``, ``LABEL_METHODS``, ``PROJECT_METHODS``) and implements
|
|
17
|
+
only the corresponding callables. Backends are imported at registry-build
|
|
18
|
+
time (cheap — they only import their *upstream* lib lazily inside the verb
|
|
19
|
+
function), so the package works with any subset of the optional extras
|
|
20
|
+
installed.
|
|
21
|
+
|
|
22
|
+
Add a new backend by:
|
|
23
|
+
|
|
24
|
+
1. Dropping a ``<name>_backend.py`` exposing the relevant ``*_METHODS`` tuple
|
|
25
|
+
plus ``is_available()`` and one or more verb functions.
|
|
26
|
+
2. Appending it to :data:`_BACKEND_MODULES` below.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import importlib.util
|
|
32
|
+
import sys
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
from importlib import import_module
|
|
35
|
+
from types import ModuleType
|
|
36
|
+
from typing import Any, Optional
|
|
37
|
+
|
|
38
|
+
import numpy as np
|
|
39
|
+
from confluid import configurable
|
|
40
|
+
from loggair import get_logger
|
|
41
|
+
|
|
42
|
+
logger = get_logger(__name__)
|
|
43
|
+
|
|
44
|
+
#: Backend module names, in registration order. Lightweight backends first so
|
|
45
|
+
#: ``list_methods()`` lists them before heavy ML deps.
|
|
46
|
+
_BACKEND_MODULES: tuple[str, ...] = (
|
|
47
|
+
"curaitor.scipy_backend",
|
|
48
|
+
"curaitor.sklearn_backend",
|
|
49
|
+
"curaitor.pyod_backend",
|
|
50
|
+
"curaitor.pot_backend",
|
|
51
|
+
"curaitor.cleanlab_backend",
|
|
52
|
+
"curaitor.umap_backend",
|
|
53
|
+
"curaitor.evidently_backend",
|
|
54
|
+
"curaitor.torchmetrics_backend",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
#: Per-verb tuple-attribute names declared on each backend module. A backend
|
|
58
|
+
#: only contributes to a registry it has methods for; absent attributes are
|
|
59
|
+
#: treated as empty.
|
|
60
|
+
_VERB_ATTRS: dict[str, str] = {
|
|
61
|
+
"outliers": "OUTLIER_METHODS",
|
|
62
|
+
"distance": "DISTANCE_METHODS",
|
|
63
|
+
"compare": "COMPARE_METHODS",
|
|
64
|
+
"labels": "LABEL_METHODS",
|
|
65
|
+
"project": "PROJECT_METHODS",
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---------------------------------------------------------------------------
|
|
70
|
+
# Result dataclasses (JSON-serializable; round-trip through RecordStream sinks).
|
|
71
|
+
# ---------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class OutlierResult:
|
|
76
|
+
"""Per-record outlier scoring result.
|
|
77
|
+
|
|
78
|
+
Attributes:
|
|
79
|
+
scores: Shape ``(N,)``. Higher = more anomalous (consistent across
|
|
80
|
+
backends — sklearn's ``decision_function`` is sign-flipped before
|
|
81
|
+
storing here).
|
|
82
|
+
flags: Shape ``(N,)`` bool. ``True`` for records above ``threshold``.
|
|
83
|
+
threshold: Score above which records are flagged. Derived from
|
|
84
|
+
``contamination`` (the ``(1 - contamination)``-quantile of
|
|
85
|
+
``scores``).
|
|
86
|
+
method: The dispatcher method name that produced this result.
|
|
87
|
+
extra: Backend-specific extras (e.g. raw model parameters).
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
scores: np.ndarray
|
|
91
|
+
flags: np.ndarray
|
|
92
|
+
threshold: float
|
|
93
|
+
method: str
|
|
94
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class ComparisonReport:
|
|
99
|
+
"""Dataset-vs-dataset comparison result.
|
|
100
|
+
|
|
101
|
+
Attributes:
|
|
102
|
+
distance: Single scalar summary when the metric reduces to one number
|
|
103
|
+
(e.g. FID, KID); ``None`` when the metric is intrinsically
|
|
104
|
+
multi-dimensional (drift reports).
|
|
105
|
+
per_metric: Named sub-metrics — every comparison method populates this
|
|
106
|
+
so callers can serialize uniformly.
|
|
107
|
+
method: The dispatcher method name.
|
|
108
|
+
extra: Backend-specific payload (e.g. evidently's HTML report path).
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
distance: Optional[float]
|
|
112
|
+
per_metric: dict[str, float]
|
|
113
|
+
method: str
|
|
114
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class LabelIssueResult:
|
|
119
|
+
"""Per-record label-quality scoring result.
|
|
120
|
+
|
|
121
|
+
Attributes:
|
|
122
|
+
issue_scores: Shape ``(N,)`` in ``[0, 1]``. Higher = more likely to be
|
|
123
|
+
mislabeled.
|
|
124
|
+
issue_indices: Indices flagged as likely issues, sorted by descending
|
|
125
|
+
``issue_scores`` (i.e. worst first).
|
|
126
|
+
method: Dispatcher method name.
|
|
127
|
+
extra: Backend-specific extras.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
issue_scores: np.ndarray
|
|
131
|
+
issue_indices: np.ndarray
|
|
132
|
+
method: str
|
|
133
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class ProjectionResult:
|
|
138
|
+
"""Low-dimensional projection of a feature matrix.
|
|
139
|
+
|
|
140
|
+
Attributes:
|
|
141
|
+
coords: Shape ``(N, n_components)``.
|
|
142
|
+
n_components: Output dimensionality.
|
|
143
|
+
method: Dispatcher method name (e.g. ``"umap"``, ``"sklearn_pca"``).
|
|
144
|
+
extra: Backend-specific extras (e.g. explained variance for PCA).
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
coords: np.ndarray
|
|
148
|
+
n_components: int
|
|
149
|
+
method: str
|
|
150
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# ---------------------------------------------------------------------------
|
|
154
|
+
# Registry construction.
|
|
155
|
+
# ---------------------------------------------------------------------------
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def installed(*packages: str) -> bool:
|
|
159
|
+
"""Whether every one of ``packages`` is installed, asked WITHOUT importing it.
|
|
160
|
+
|
|
161
|
+
What a backend's ``is_available()`` answers by: importing a package to learn that it is there is slow (umap brings
|
|
162
|
+
in tensorflow), and the methods list asks every backend. A package that is installed but fails to import therefore
|
|
163
|
+
reads as available, and its first use raises the package's own error.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
packages: Import names (``"sklearn"``, ``"scipy.stats"``).
|
|
167
|
+
"""
|
|
168
|
+
for package in packages:
|
|
169
|
+
if package in sys.modules:
|
|
170
|
+
if sys.modules[package] is None:
|
|
171
|
+
return False
|
|
172
|
+
elif importlib.util.find_spec(package) is None:
|
|
173
|
+
return False
|
|
174
|
+
return True
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _load_backend(module_path: str) -> ModuleType:
|
|
178
|
+
return import_module(module_path)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _build_registries() -> dict[str, dict[str, str]]:
|
|
182
|
+
"""Build one method→backend-module-path map per verb.
|
|
183
|
+
|
|
184
|
+
Raises:
|
|
185
|
+
RuntimeError: If two backends register the same method for the same
|
|
186
|
+
verb. Cross-verb collisions are allowed (different verbs have
|
|
187
|
+
disjoint dispatchers).
|
|
188
|
+
"""
|
|
189
|
+
registries: dict[str, dict[str, str]] = {verb: {} for verb in _VERB_ATTRS}
|
|
190
|
+
for module_path in _BACKEND_MODULES:
|
|
191
|
+
backend = _load_backend(module_path)
|
|
192
|
+
for verb, attr in _VERB_ATTRS.items():
|
|
193
|
+
methods = getattr(backend, attr, ())
|
|
194
|
+
for method in methods:
|
|
195
|
+
if method in registries[verb]:
|
|
196
|
+
raise RuntimeError(
|
|
197
|
+
f"Method {method!r} for verb {verb!r} is registered by both "
|
|
198
|
+
f"{registries[verb][method]!r} and {module_path!r}"
|
|
199
|
+
)
|
|
200
|
+
registries[verb][method] = module_path
|
|
201
|
+
return registries
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
_REGISTRIES: dict[str, dict[str, str]] = _build_registries()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def list_methods(only_available: bool = False, verb: Optional[str] = None) -> list[dict[str, Any]]:
|
|
208
|
+
"""Return registered methods with their verb, backend, and availability.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
only_available: If True, omit methods whose upstream package is not
|
|
212
|
+
installed in the current environment.
|
|
213
|
+
verb: If set, restrict to one of ``"outliers" | "distance" | "compare"
|
|
214
|
+
| "labels" | "project"``.
|
|
215
|
+
|
|
216
|
+
Returns:
|
|
217
|
+
A list of ``{"method", "verb", "backend", "available"}`` dicts, sorted
|
|
218
|
+
by ``(verb, method)``.
|
|
219
|
+
"""
|
|
220
|
+
if verb is not None and verb not in _REGISTRIES:
|
|
221
|
+
raise ValueError(f"Unknown verb {verb!r}. Choose from {sorted(_REGISTRIES.keys())}.")
|
|
222
|
+
out: list[dict[str, Any]] = []
|
|
223
|
+
verbs = (verb,) if verb is not None else tuple(_REGISTRIES.keys())
|
|
224
|
+
for v in verbs:
|
|
225
|
+
for method, module_path in sorted(_REGISTRIES[v].items()):
|
|
226
|
+
backend = _load_backend(module_path)
|
|
227
|
+
available = backend.is_available()
|
|
228
|
+
if only_available and not available:
|
|
229
|
+
continue
|
|
230
|
+
out.append(
|
|
231
|
+
{
|
|
232
|
+
"method": method,
|
|
233
|
+
"verb": v,
|
|
234
|
+
"backend": module_path.rsplit(".", 1)[-1].removesuffix("_backend"),
|
|
235
|
+
"available": available,
|
|
236
|
+
}
|
|
237
|
+
)
|
|
238
|
+
return out
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _dispatch(verb: str, method: str, fn_name: str) -> ModuleType:
|
|
242
|
+
"""Resolve ``method`` for ``verb`` to the backend module that serves it."""
|
|
243
|
+
registry = _REGISTRIES[verb]
|
|
244
|
+
if method not in registry:
|
|
245
|
+
raise ValueError(f"Unknown {verb} method {method!r}. Known methods: {sorted(registry.keys())}")
|
|
246
|
+
module_path = registry[method]
|
|
247
|
+
backend = _load_backend(module_path)
|
|
248
|
+
if not backend.is_available():
|
|
249
|
+
raise RuntimeError(
|
|
250
|
+
f"Backend {module_path!r} for {verb} method {method!r} is not available. "
|
|
251
|
+
f"Install the corresponding extra (e.g. `pip install curaitor[outliers]`)."
|
|
252
|
+
)
|
|
253
|
+
if not hasattr(backend, fn_name):
|
|
254
|
+
raise RuntimeError(
|
|
255
|
+
f"Backend {module_path!r} declares method {method!r} for verb {verb!r} but does not "
|
|
256
|
+
f"implement {fn_name!r}. This is a backend bug."
|
|
257
|
+
)
|
|
258
|
+
logger.debug(f"Dispatching verb={verb} method={method} → {module_path}.{fn_name}")
|
|
259
|
+
return backend
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def available_methods(method: Optional[str] = None, verb: Optional[str] = None) -> bool:
|
|
263
|
+
"""Return whether a method (or any method) is available.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
method: Exact method name, or ``None`` to poll any.
|
|
267
|
+
verb: When ``method`` is ``None``, restrict the poll to one verb.
|
|
268
|
+
"""
|
|
269
|
+
if method is None:
|
|
270
|
+
return any(entry["available"] for entry in list_methods(verb=verb))
|
|
271
|
+
for v, registry in _REGISTRIES.items():
|
|
272
|
+
if method in registry:
|
|
273
|
+
return bool(_load_backend(registry[method]).is_available())
|
|
274
|
+
return False
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# ---------------------------------------------------------------------------
|
|
278
|
+
# Verb dispatchers.
|
|
279
|
+
# ---------------------------------------------------------------------------
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def find_outliers(
|
|
283
|
+
features: np.ndarray,
|
|
284
|
+
*,
|
|
285
|
+
method: str = "iforest",
|
|
286
|
+
contamination: float = 0.05,
|
|
287
|
+
**kwargs: Any,
|
|
288
|
+
) -> OutlierResult:
|
|
289
|
+
"""Score every row of ``features`` for how anomalous it is.
|
|
290
|
+
|
|
291
|
+
Args:
|
|
292
|
+
features: 2-D float array, shape ``(N, D)``.
|
|
293
|
+
method: One of the registered outlier methods (see
|
|
294
|
+
:func:`list_methods` with ``verb="outliers"``).
|
|
295
|
+
contamination: Expected fraction of outliers in ``[0, 0.5]`` — used to
|
|
296
|
+
derive the flagging threshold. Default ``0.05``.
|
|
297
|
+
**kwargs: Forwarded to the backend's ``find_outliers``.
|
|
298
|
+
|
|
299
|
+
Returns:
|
|
300
|
+
:class:`OutlierResult` with ``scores`` and ``flags`` of length
|
|
301
|
+
``features.shape[0]``.
|
|
302
|
+
"""
|
|
303
|
+
if features.ndim != 2:
|
|
304
|
+
raise ValueError(f"find_outliers expects a 2-D feature matrix, got shape={features.shape}.")
|
|
305
|
+
if not 0.0 < contamination < 0.5:
|
|
306
|
+
raise ValueError(f"contamination must be in (0, 0.5), got {contamination!r}.")
|
|
307
|
+
backend = _dispatch("outliers", method, "find_outliers")
|
|
308
|
+
return backend.find_outliers( # type: ignore[no-any-return]
|
|
309
|
+
features, method=method, contamination=contamination, **kwargs
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def compute_distance(
|
|
314
|
+
a: np.ndarray,
|
|
315
|
+
b: np.ndarray,
|
|
316
|
+
*,
|
|
317
|
+
method: str = "wasserstein_1d",
|
|
318
|
+
**kwargs: Any,
|
|
319
|
+
) -> float:
|
|
320
|
+
"""Distance between two empirical feature distributions.
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
a: Record matrix from distribution A. 1-D for 1-D-only methods
|
|
324
|
+
(``ks``, ``anderson``, ``wasserstein_1d``, ``energy_1d``,
|
|
325
|
+
``cramer_von_mises``); 2-D ``(N, D)`` for the multi-dim
|
|
326
|
+
optimal-transport methods.
|
|
327
|
+
b: Record matrix from distribution B. Same shape as ``a``.
|
|
328
|
+
method: Registered distance method.
|
|
329
|
+
**kwargs: Forwarded to the backend.
|
|
330
|
+
|
|
331
|
+
Returns:
|
|
332
|
+
A scalar distance (non-negative). For statistical tests like ``ks``
|
|
333
|
+
the returned value is the test statistic, not the p-value.
|
|
334
|
+
"""
|
|
335
|
+
if a.ndim != b.ndim:
|
|
336
|
+
raise ValueError(f"a and b must have the same ndim, got {a.ndim} vs {b.ndim}.")
|
|
337
|
+
if a.ndim == 2 and a.shape[1] != b.shape[1]:
|
|
338
|
+
raise ValueError(f"a and b must have the same feature dim, got {a.shape[1]} vs {b.shape[1]}.")
|
|
339
|
+
backend = _dispatch("distance", method, "compute_distance")
|
|
340
|
+
return float(backend.compute_distance(a, b, method=method, **kwargs))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def compare_datasets(
|
|
344
|
+
a: np.ndarray,
|
|
345
|
+
b: np.ndarray,
|
|
346
|
+
*,
|
|
347
|
+
method: str = "fid",
|
|
348
|
+
**kwargs: Any,
|
|
349
|
+
) -> ComparisonReport:
|
|
350
|
+
"""Multi-metric comparison between two datasets in feature space.
|
|
351
|
+
|
|
352
|
+
Args:
|
|
353
|
+
a: Reference feature matrix, shape ``(N_a, D)``.
|
|
354
|
+
b: Candidate feature matrix, shape ``(N_b, D)``.
|
|
355
|
+
method: Registered comparison method (e.g. ``"fid"``, ``"kid"``,
|
|
356
|
+
``"drift_report"``).
|
|
357
|
+
**kwargs: Forwarded to the backend.
|
|
358
|
+
|
|
359
|
+
Returns:
|
|
360
|
+
:class:`ComparisonReport` with at least one entry in ``per_metric``.
|
|
361
|
+
"""
|
|
362
|
+
if a.ndim != 2 or b.ndim != 2:
|
|
363
|
+
raise ValueError(f"compare_datasets expects 2-D matrices, got shapes={a.shape} and {b.shape}.")
|
|
364
|
+
if a.shape[1] != b.shape[1]:
|
|
365
|
+
raise ValueError(f"a and b must have matching feature dim, got {a.shape[1]} vs {b.shape[1]}.")
|
|
366
|
+
backend = _dispatch("compare", method, "compare_datasets")
|
|
367
|
+
return backend.compare_datasets(a, b, method=method, **kwargs) # type: ignore[no-any-return]
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def check_labels(
|
|
371
|
+
features: np.ndarray,
|
|
372
|
+
labels: np.ndarray,
|
|
373
|
+
*,
|
|
374
|
+
method: str = "cleanlab",
|
|
375
|
+
**kwargs: Any,
|
|
376
|
+
) -> LabelIssueResult:
|
|
377
|
+
"""Score every row of ``features`` for the likelihood that ``labels`` is wrong.
|
|
378
|
+
|
|
379
|
+
Args:
|
|
380
|
+
features: 2-D feature matrix or pre-computed ``pred_probs`` array
|
|
381
|
+
(shape ``(N, K)``); the backend documents which it expects.
|
|
382
|
+
labels: 1-D integer labels, length ``N``.
|
|
383
|
+
method: Registered label-checking method.
|
|
384
|
+
**kwargs: Forwarded to the backend.
|
|
385
|
+
|
|
386
|
+
Returns:
|
|
387
|
+
:class:`LabelIssueResult`.
|
|
388
|
+
"""
|
|
389
|
+
if features.ndim != 2:
|
|
390
|
+
raise ValueError(f"check_labels expects a 2-D feature/probability matrix, got shape={features.shape}.")
|
|
391
|
+
if labels.ndim != 1 or labels.shape[0] != features.shape[0]:
|
|
392
|
+
raise ValueError(
|
|
393
|
+
f"labels must be 1-D with length matching features.shape[0], got {labels.shape} vs {features.shape[0]}."
|
|
394
|
+
)
|
|
395
|
+
backend = _dispatch("labels", method, "check_labels")
|
|
396
|
+
return backend.check_labels(features, labels, method=method, **kwargs) # type: ignore[no-any-return]
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def project(
|
|
400
|
+
features: np.ndarray,
|
|
401
|
+
*,
|
|
402
|
+
method: str = "umap",
|
|
403
|
+
n_components: int = 2,
|
|
404
|
+
**kwargs: Any,
|
|
405
|
+
) -> ProjectionResult:
|
|
406
|
+
"""Project ``features`` to low-D for visualization.
|
|
407
|
+
|
|
408
|
+
Args:
|
|
409
|
+
features: 2-D feature matrix, shape ``(N, D)``.
|
|
410
|
+
method: Registered projection method (``"umap"``, ``"sklearn_pca"``,
|
|
411
|
+
``"sklearn_tsne"``).
|
|
412
|
+
n_components: Output dimensionality (typically 2 or 3).
|
|
413
|
+
**kwargs: Forwarded to the backend (e.g. ``n_neighbors`` for UMAP).
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
:class:`ProjectionResult` with ``coords`` of shape
|
|
417
|
+
``(N, n_components)``.
|
|
418
|
+
"""
|
|
419
|
+
if features.ndim != 2:
|
|
420
|
+
raise ValueError(f"project expects a 2-D feature matrix, got shape={features.shape}.")
|
|
421
|
+
if n_components < 1:
|
|
422
|
+
raise ValueError(f"n_components must be >= 1, got {n_components!r}.")
|
|
423
|
+
backend = _dispatch("project", method, "project")
|
|
424
|
+
return backend.project(features, method=method, n_components=n_components, **kwargs) # type: ignore[no-any-return]
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
# ---------------------------------------------------------------------------
|
|
428
|
+
# Configurable wrappers (for YAML use).
|
|
429
|
+
# ---------------------------------------------------------------------------
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _verb_for_method(method: str) -> str:
|
|
433
|
+
"""Return the verb that ``method`` is registered under, or raise."""
|
|
434
|
+
for verb, registry in _REGISTRIES.items():
|
|
435
|
+
if method in registry:
|
|
436
|
+
return verb
|
|
437
|
+
raise ValueError(f"Method {method!r} is not registered for any verb.")
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _backend_short_name(method: str) -> str:
|
|
441
|
+
return _REGISTRIES[_verb_for_method(method)][method].rsplit(".", 1)[-1].removesuffix("_backend")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
@configurable
|
|
445
|
+
class OutlierDetector:
|
|
446
|
+
"""Confluid-configurable wrapper around :func:`find_outliers`.
|
|
447
|
+
|
|
448
|
+
YAML usage::
|
|
449
|
+
|
|
450
|
+
detector: !class:curaitor.OutlierDetector
|
|
451
|
+
method: iforest
|
|
452
|
+
contamination: 0.02
|
|
453
|
+
"""
|
|
454
|
+
|
|
455
|
+
def __init__(self, method: str = "iforest", contamination: float = 0.05, **kwargs: Any) -> None:
|
|
456
|
+
if method not in _REGISTRIES["outliers"]:
|
|
457
|
+
raise ValueError(
|
|
458
|
+
f"Unknown outlier method {method!r}. Known methods: {sorted(_REGISTRIES['outliers'].keys())}"
|
|
459
|
+
)
|
|
460
|
+
self.method = method
|
|
461
|
+
self.contamination = contamination
|
|
462
|
+
self.kwargs = kwargs
|
|
463
|
+
|
|
464
|
+
@property
|
|
465
|
+
def backend(self) -> str:
|
|
466
|
+
return _backend_short_name(self.method)
|
|
467
|
+
|
|
468
|
+
def apply(self, features: np.ndarray, **overrides: Any) -> OutlierResult:
|
|
469
|
+
merged: dict[str, Any] = {**self.kwargs, **overrides}
|
|
470
|
+
return find_outliers(features, method=self.method, contamination=self.contamination, **merged)
|
|
471
|
+
|
|
472
|
+
def __call__(self, features: np.ndarray, **overrides: Any) -> OutlierResult:
|
|
473
|
+
return self.apply(features, **overrides)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
@configurable
|
|
477
|
+
class DistanceMetric:
|
|
478
|
+
"""Confluid-configurable wrapper around :func:`compute_distance`."""
|
|
479
|
+
|
|
480
|
+
def __init__(self, method: str = "wasserstein_1d", **kwargs: Any) -> None:
|
|
481
|
+
if method not in _REGISTRIES["distance"]:
|
|
482
|
+
raise ValueError(
|
|
483
|
+
f"Unknown distance method {method!r}. Known methods: {sorted(_REGISTRIES['distance'].keys())}"
|
|
484
|
+
)
|
|
485
|
+
self.method = method
|
|
486
|
+
self.kwargs = kwargs
|
|
487
|
+
|
|
488
|
+
@property
|
|
489
|
+
def backend(self) -> str:
|
|
490
|
+
return _backend_short_name(self.method)
|
|
491
|
+
|
|
492
|
+
def apply(self, a: np.ndarray, b: np.ndarray, **overrides: Any) -> float:
|
|
493
|
+
merged: dict[str, Any] = {**self.kwargs, **overrides}
|
|
494
|
+
return compute_distance(a, b, method=self.method, **merged)
|
|
495
|
+
|
|
496
|
+
def __call__(self, a: np.ndarray, b: np.ndarray, **overrides: Any) -> float:
|
|
497
|
+
return self.apply(a, b, **overrides)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@configurable
|
|
501
|
+
class DatasetComparator:
|
|
502
|
+
"""Confluid-configurable wrapper around :func:`compare_datasets`."""
|
|
503
|
+
|
|
504
|
+
def __init__(self, method: str = "fid", **kwargs: Any) -> None:
|
|
505
|
+
if method not in _REGISTRIES["compare"]:
|
|
506
|
+
raise ValueError(
|
|
507
|
+
f"Unknown compare method {method!r}. Known methods: {sorted(_REGISTRIES['compare'].keys())}"
|
|
508
|
+
)
|
|
509
|
+
self.method = method
|
|
510
|
+
self.kwargs = kwargs
|
|
511
|
+
|
|
512
|
+
@property
|
|
513
|
+
def backend(self) -> str:
|
|
514
|
+
return _backend_short_name(self.method)
|
|
515
|
+
|
|
516
|
+
def apply(self, a: np.ndarray, b: np.ndarray, **overrides: Any) -> ComparisonReport:
|
|
517
|
+
merged: dict[str, Any] = {**self.kwargs, **overrides}
|
|
518
|
+
return compare_datasets(a, b, method=self.method, **merged)
|
|
519
|
+
|
|
520
|
+
def __call__(self, a: np.ndarray, b: np.ndarray, **overrides: Any) -> ComparisonReport:
|
|
521
|
+
return self.apply(a, b, **overrides)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
@configurable
|
|
525
|
+
class LabelChecker:
|
|
526
|
+
"""Confluid-configurable wrapper around :func:`check_labels`."""
|
|
527
|
+
|
|
528
|
+
def __init__(self, method: str = "cleanlab", **kwargs: Any) -> None:
|
|
529
|
+
if method not in _REGISTRIES["labels"]:
|
|
530
|
+
raise ValueError(f"Unknown label method {method!r}. Known methods: {sorted(_REGISTRIES['labels'].keys())}")
|
|
531
|
+
self.method = method
|
|
532
|
+
self.kwargs = kwargs
|
|
533
|
+
|
|
534
|
+
@property
|
|
535
|
+
def backend(self) -> str:
|
|
536
|
+
return _backend_short_name(self.method)
|
|
537
|
+
|
|
538
|
+
def apply(self, features: np.ndarray, labels: np.ndarray, **overrides: Any) -> LabelIssueResult:
|
|
539
|
+
merged: dict[str, Any] = {**self.kwargs, **overrides}
|
|
540
|
+
return check_labels(features, labels, method=self.method, **merged)
|
|
541
|
+
|
|
542
|
+
def __call__(self, features: np.ndarray, labels: np.ndarray, **overrides: Any) -> LabelIssueResult:
|
|
543
|
+
return self.apply(features, labels, **overrides)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
@configurable
|
|
547
|
+
class Projector:
|
|
548
|
+
"""Confluid-configurable wrapper around :func:`project`."""
|
|
549
|
+
|
|
550
|
+
def __init__(self, method: str = "umap", n_components: int = 2, **kwargs: Any) -> None:
|
|
551
|
+
if method not in _REGISTRIES["project"]:
|
|
552
|
+
raise ValueError(
|
|
553
|
+
f"Unknown project method {method!r}. Known methods: {sorted(_REGISTRIES['project'].keys())}"
|
|
554
|
+
)
|
|
555
|
+
self.method = method
|
|
556
|
+
self.n_components = n_components
|
|
557
|
+
self.kwargs = kwargs
|
|
558
|
+
|
|
559
|
+
@property
|
|
560
|
+
def backend(self) -> str:
|
|
561
|
+
return _backend_short_name(self.method)
|
|
562
|
+
|
|
563
|
+
def apply(self, features: np.ndarray, **overrides: Any) -> ProjectionResult:
|
|
564
|
+
merged: dict[str, Any] = {**self.kwargs, **overrides}
|
|
565
|
+
return project(features, method=self.method, n_components=self.n_components, **merged)
|
|
566
|
+
|
|
567
|
+
def __call__(self, features: np.ndarray, **overrides: Any) -> ProjectionResult:
|
|
568
|
+
return self.apply(features, **overrides)
|