driftcheck-gui 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.
- driftcheck/__init__.py +7 -0
- driftcheck/__main__.py +11 -0
- driftcheck/core/__init__.py +1 -0
- driftcheck/core/analysis.py +138 -0
- driftcheck/core/detectors.py +128 -0
- driftcheck/core/settings.py +31 -0
- driftcheck/gui/__init__.py +0 -0
- driftcheck/gui/app.py +222 -0
- driftcheck/io/__init__.py +1 -0
- driftcheck/io/files.py +78 -0
- driftcheck_gui-0.1.0.dist-info/METADATA +95 -0
- driftcheck_gui-0.1.0.dist-info/RECORD +16 -0
- driftcheck_gui-0.1.0.dist-info/WHEEL +5 -0
- driftcheck_gui-0.1.0.dist-info/entry_points.txt +2 -0
- driftcheck_gui-0.1.0.dist-info/licenses/LICENSE +21 -0
- driftcheck_gui-0.1.0.dist-info/top_level.txt +1 -0
driftcheck/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""driftcheck: detect dataset shift between a reference dataset and new data."""
|
|
2
|
+
|
|
3
|
+
from driftcheck.core.analysis import DriftReport, run_analysis
|
|
4
|
+
from driftcheck.core.settings import Settings
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
__all__ = ["DriftReport", "Settings", "run_analysis", "__version__"]
|
driftcheck/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Analysis logic. Nothing in this package may import tkinter or the gui package."""
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Run every drift test on two datasets and collect the results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Callable
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from driftcheck.core import detectors
|
|
12
|
+
from driftcheck.core.settings import Settings
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class FeatureResult:
|
|
17
|
+
"""Per-feature drift results."""
|
|
18
|
+
|
|
19
|
+
name: str
|
|
20
|
+
kind: str # "numeric" or "categorical"
|
|
21
|
+
test_name: str # "KS" or "Chi2"
|
|
22
|
+
statistic: float
|
|
23
|
+
p_value: float
|
|
24
|
+
psi: float
|
|
25
|
+
importance: float
|
|
26
|
+
drift: bool
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class DriftReport:
|
|
31
|
+
"""Everything one analysis produced."""
|
|
32
|
+
|
|
33
|
+
settings: Settings
|
|
34
|
+
n_reference: int
|
|
35
|
+
n_current: int
|
|
36
|
+
features: list[FeatureResult] = field(default_factory=list)
|
|
37
|
+
mmd_statistic: float = 0.0
|
|
38
|
+
mmd_p_value: float = 1.0
|
|
39
|
+
mmd_drift: bool = False
|
|
40
|
+
classifier_auc: float = 0.5
|
|
41
|
+
classifier_drift: bool = False
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def drifted_features(self) -> list[str]:
|
|
45
|
+
"""Names of features flagged by the per-feature test or by PSI."""
|
|
46
|
+
return [f.name for f in self.features if f.drift]
|
|
47
|
+
|
|
48
|
+
def to_frame(self) -> pd.DataFrame:
|
|
49
|
+
"""Per-feature results as a table, most drifted first."""
|
|
50
|
+
df = pd.DataFrame([f.__dict__ for f in self.features])
|
|
51
|
+
return df.sort_values("psi", ascending=False).reset_index(drop=True)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def align_columns(ref: pd.DataFrame, cur: pd.DataFrame) -> list[str]:
|
|
55
|
+
"""Columns present in both datasets, in reference order."""
|
|
56
|
+
common = [c for c in ref.columns if c in cur.columns]
|
|
57
|
+
if not common:
|
|
58
|
+
raise ValueError("The two datasets have no columns in common")
|
|
59
|
+
return common
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _encode(ref: pd.DataFrame, cur: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
|
|
63
|
+
"""Numeric matrix for the multivariate tests: one-hot categoricals, median-fill, standardise."""
|
|
64
|
+
both = pd.concat([ref, cur], keys=["r", "c"])
|
|
65
|
+
both = pd.get_dummies(both, dummy_na=False).astype(float)
|
|
66
|
+
both = both.fillna(both.median())
|
|
67
|
+
std = both.std().replace(0, 1)
|
|
68
|
+
both = (both - both.mean()) / std
|
|
69
|
+
return both.loc["r"].to_numpy(), both.loc["c"].to_numpy()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def run_analysis(
|
|
73
|
+
reference: pd.DataFrame,
|
|
74
|
+
current: pd.DataFrame,
|
|
75
|
+
settings: Settings | None = None,
|
|
76
|
+
columns: list[str] | None = None,
|
|
77
|
+
progress: Callable[[float, str], None] | None = None,
|
|
78
|
+
) -> DriftReport:
|
|
79
|
+
"""Compare two datasets and return a DriftReport.
|
|
80
|
+
|
|
81
|
+
progress, if given, is called with (fraction_done, message).
|
|
82
|
+
"""
|
|
83
|
+
s = settings or Settings()
|
|
84
|
+
np.random.seed(s.seed)
|
|
85
|
+
cols = columns or align_columns(reference, current)
|
|
86
|
+
ref, cur = reference[cols], current[cols]
|
|
87
|
+
say = progress or (lambda frac, msg: None)
|
|
88
|
+
|
|
89
|
+
# Bonferroni correction across per-feature tests
|
|
90
|
+
alpha_feature = s.alpha / len(cols)
|
|
91
|
+
|
|
92
|
+
say(0.1, "Encoding data")
|
|
93
|
+
xr, xc = _encode(ref, cur)
|
|
94
|
+
|
|
95
|
+
say(0.2, "Training domain classifier")
|
|
96
|
+
clf, importances = detectors.domain_classifier_test(
|
|
97
|
+
xr, xc, s.classifier_folds, s.auc_threshold, s.seed
|
|
98
|
+
)
|
|
99
|
+
encoded_names = pd.get_dummies(pd.concat([ref, cur]), dummy_na=False).columns
|
|
100
|
+
imp_by_col = {c: 0.0 for c in cols}
|
|
101
|
+
for name, value in zip(encoded_names, importances):
|
|
102
|
+
base = next((c for c in cols if name == c or name.startswith(f"{c}_")), None)
|
|
103
|
+
if base is not None:
|
|
104
|
+
imp_by_col[base] += float(value)
|
|
105
|
+
|
|
106
|
+
say(0.5, "Running MMD test")
|
|
107
|
+
mmd = detectors.mmd_test(xr, xc, s.mmd_permutations, s.mmd_max_rows, s.alpha, s.seed)
|
|
108
|
+
|
|
109
|
+
report = DriftReport(
|
|
110
|
+
settings=s,
|
|
111
|
+
n_reference=len(ref),
|
|
112
|
+
n_current=len(cur),
|
|
113
|
+
mmd_statistic=mmd.statistic,
|
|
114
|
+
mmd_p_value=float(mmd.p_value),
|
|
115
|
+
mmd_drift=mmd.drift,
|
|
116
|
+
classifier_auc=clf.statistic,
|
|
117
|
+
classifier_drift=clf.drift,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
for i, c in enumerate(cols):
|
|
121
|
+
say(0.8 + 0.2 * i / len(cols), f"Testing {c}")
|
|
122
|
+
numeric = detectors.is_numeric(ref[c])
|
|
123
|
+
test = (detectors.ks_test if numeric else detectors.chi2_test)(ref[c], cur[c], alpha_feature)
|
|
124
|
+
p = detectors.psi(ref[c], cur[c], s.psi_bins, s.psi_threshold)
|
|
125
|
+
report.features.append(
|
|
126
|
+
FeatureResult(
|
|
127
|
+
name=c,
|
|
128
|
+
kind="numeric" if numeric else "categorical",
|
|
129
|
+
test_name="KS" if numeric else "Chi2",
|
|
130
|
+
statistic=test.statistic,
|
|
131
|
+
p_value=float(test.p_value),
|
|
132
|
+
psi=p.statistic,
|
|
133
|
+
importance=imp_by_col[c],
|
|
134
|
+
drift=test.drift or p.drift,
|
|
135
|
+
)
|
|
136
|
+
)
|
|
137
|
+
say(1.0, "Done")
|
|
138
|
+
return report
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Drift tests: KS, chi-square, PSI, MMD and a domain classifier."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from scipy import stats
|
|
10
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
11
|
+
from sklearn.metrics import roc_auc_score
|
|
12
|
+
from sklearn.model_selection import StratifiedKFold, cross_val_predict
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class TestResult:
|
|
17
|
+
"""Outcome of a two-sample test on one feature or on the whole dataset."""
|
|
18
|
+
|
|
19
|
+
statistic: float
|
|
20
|
+
p_value: float | None
|
|
21
|
+
drift: bool
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def is_numeric(series: pd.Series) -> bool:
|
|
25
|
+
"""True if the column should be treated as numeric."""
|
|
26
|
+
return pd.api.types.is_numeric_dtype(series) and not pd.api.types.is_bool_dtype(series)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def ks_test(ref: pd.Series, cur: pd.Series, alpha: float = 0.05) -> TestResult:
|
|
30
|
+
"""Two-sample Kolmogorov-Smirnov test for a numeric feature."""
|
|
31
|
+
a, b = ref.dropna().to_numpy(float), cur.dropna().to_numpy(float)
|
|
32
|
+
if len(a) == 0 or len(b) == 0:
|
|
33
|
+
raise ValueError("KS test needs at least one non-missing value in each sample")
|
|
34
|
+
stat, p = stats.ks_2samp(a, b)
|
|
35
|
+
return TestResult(float(stat), float(p), bool(p < alpha))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def chi2_test(ref: pd.Series, cur: pd.Series, alpha: float = 0.05) -> TestResult:
|
|
39
|
+
"""Chi-square test of homogeneity for a categorical feature."""
|
|
40
|
+
a, b = ref.dropna().astype(str), cur.dropna().astype(str)
|
|
41
|
+
cats = sorted(set(a) | set(b))
|
|
42
|
+
table = np.array([[(a == c).sum() for c in cats], [(b == c).sum() for c in cats]])
|
|
43
|
+
if len(cats) < 2:
|
|
44
|
+
return TestResult(0.0, 1.0, False)
|
|
45
|
+
stat, p, _, _ = stats.chi2_contingency(table)
|
|
46
|
+
return TestResult(float(stat), float(p), bool(p < alpha))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def psi(ref: pd.Series, cur: pd.Series, bins: int = 10, threshold: float = 0.2) -> TestResult:
|
|
50
|
+
"""Population Stability Index. Numeric features use quantile bins of the reference."""
|
|
51
|
+
eps = 1e-6
|
|
52
|
+
a, b = ref.dropna(), cur.dropna()
|
|
53
|
+
if is_numeric(a):
|
|
54
|
+
edges = np.unique(np.quantile(a.to_numpy(float), np.linspace(0, 1, bins + 1)))
|
|
55
|
+
if len(edges) < 2:
|
|
56
|
+
edges = np.array([a.min(), a.max()])
|
|
57
|
+
edges[0], edges[-1] = -np.inf, np.inf
|
|
58
|
+
p = np.histogram(a, edges)[0] / len(a)
|
|
59
|
+
q = np.histogram(b, edges)[0] / len(b)
|
|
60
|
+
else:
|
|
61
|
+
cats = sorted(set(a.astype(str)) | set(b.astype(str)))
|
|
62
|
+
p = np.array([(a.astype(str) == c).mean() for c in cats])
|
|
63
|
+
q = np.array([(b.astype(str) == c).mean() for c in cats])
|
|
64
|
+
p, q = np.clip(p, eps, None), np.clip(q, eps, None)
|
|
65
|
+
value = float(np.sum((q - p) * np.log(q / p)))
|
|
66
|
+
return TestResult(value, None, bool(value > threshold))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _rbf_kernel(x: np.ndarray, y: np.ndarray, gamma: float) -> np.ndarray:
|
|
70
|
+
d = np.sum(x**2, 1)[:, None] + np.sum(y**2, 1)[None, :] - 2 * x @ y.T
|
|
71
|
+
return np.exp(-gamma * np.maximum(d, 0))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _mmd2(k: np.ndarray, n: int) -> float:
|
|
75
|
+
kxx, kyy, kxy = k[:n, :n], k[n:, n:], k[:n, n:]
|
|
76
|
+
return float(kxx.mean() + kyy.mean() - 2 * kxy.mean())
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def mmd_test(
|
|
80
|
+
ref: np.ndarray,
|
|
81
|
+
cur: np.ndarray,
|
|
82
|
+
permutations: int = 200,
|
|
83
|
+
max_rows: int = 1000,
|
|
84
|
+
alpha: float = 0.05,
|
|
85
|
+
seed: int = 42,
|
|
86
|
+
) -> TestResult:
|
|
87
|
+
"""Multivariate MMD permutation test with an RBF kernel (median heuristic)."""
|
|
88
|
+
rng = np.random.default_rng(seed)
|
|
89
|
+
if len(ref) > max_rows:
|
|
90
|
+
ref = ref[rng.choice(len(ref), max_rows, replace=False)]
|
|
91
|
+
if len(cur) > max_rows:
|
|
92
|
+
cur = cur[rng.choice(len(cur), max_rows, replace=False)]
|
|
93
|
+
z = np.vstack([ref, cur])
|
|
94
|
+
n = len(ref)
|
|
95
|
+
norms = np.sum(z**2, 1)
|
|
96
|
+
sq = np.maximum(norms[:, None] + norms[None, :] - 2 * z @ z.T, 0)
|
|
97
|
+
median = np.median(sq[sq > 0]) if np.any(sq > 0) else 1.0
|
|
98
|
+
k = _rbf_kernel(z, z, 1.0 / median)
|
|
99
|
+
observed = _mmd2(k, n)
|
|
100
|
+
count = 0
|
|
101
|
+
for _ in range(permutations):
|
|
102
|
+
idx = rng.permutation(len(z))
|
|
103
|
+
if _mmd2(k[np.ix_(idx, idx)], n) >= observed:
|
|
104
|
+
count += 1
|
|
105
|
+
p = (count + 1) / (permutations + 1)
|
|
106
|
+
return TestResult(observed, float(p), bool(p < alpha))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def domain_classifier_test(
|
|
110
|
+
ref: np.ndarray,
|
|
111
|
+
cur: np.ndarray,
|
|
112
|
+
folds: int = 5,
|
|
113
|
+
auc_threshold: float = 0.6,
|
|
114
|
+
seed: int = 42,
|
|
115
|
+
) -> tuple[TestResult, np.ndarray]:
|
|
116
|
+
"""Train a classifier to tell reference rows from new rows.
|
|
117
|
+
|
|
118
|
+
Returns the cross-validated ROC AUC (0.5 means no drift) and the
|
|
119
|
+
feature importances of a model fitted on all rows.
|
|
120
|
+
"""
|
|
121
|
+
x = np.vstack([ref, cur])
|
|
122
|
+
y = np.r_[np.zeros(len(ref)), np.ones(len(cur))]
|
|
123
|
+
model = RandomForestClassifier(n_estimators=100, random_state=seed, n_jobs=1)
|
|
124
|
+
cv = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed)
|
|
125
|
+
proba = cross_val_predict(model, x, y, cv=cv, method="predict_proba")[:, 1]
|
|
126
|
+
auc = float(roc_auc_score(y, proba))
|
|
127
|
+
model.fit(x, y)
|
|
128
|
+
return TestResult(auc, None, bool(auc > auc_threshold)), model.feature_importances_
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""User settings, including the single global random seed."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Settings:
|
|
12
|
+
"""All options that affect results. Saved with every session."""
|
|
13
|
+
|
|
14
|
+
seed: int = 42
|
|
15
|
+
alpha: float = 0.05
|
|
16
|
+
psi_bins: int = 10
|
|
17
|
+
psi_threshold: float = 0.2
|
|
18
|
+
mmd_permutations: int = 200
|
|
19
|
+
mmd_max_rows: int = 1000
|
|
20
|
+
classifier_folds: int = 5
|
|
21
|
+
auc_threshold: float = 0.6
|
|
22
|
+
|
|
23
|
+
def save(self, path: str | Path) -> None:
|
|
24
|
+
"""Write the settings to a JSON file."""
|
|
25
|
+
Path(path).write_text(json.dumps(asdict(self), indent=2), encoding="utf-8")
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def load(cls, path: str | Path) -> "Settings":
|
|
29
|
+
"""Read settings from a JSON file written by save()."""
|
|
30
|
+
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
31
|
+
return cls(**data)
|
|
File without changes
|
driftcheck/gui/app.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Tkinter interface. It only calls driftcheck.core and driftcheck.io."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import queue
|
|
6
|
+
import threading
|
|
7
|
+
import tkinter as tk
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from tkinter import filedialog, messagebox, ttk
|
|
10
|
+
|
|
11
|
+
import matplotlib
|
|
12
|
+
|
|
13
|
+
matplotlib.use("TkAgg")
|
|
14
|
+
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # noqa: E402
|
|
15
|
+
from matplotlib.figure import Figure # noqa: E402
|
|
16
|
+
|
|
17
|
+
from driftcheck.core.analysis import DriftReport, run_analysis # noqa: E402
|
|
18
|
+
from driftcheck.core.detectors import is_numeric # noqa: E402
|
|
19
|
+
from driftcheck.core.settings import Settings # noqa: E402
|
|
20
|
+
from driftcheck.io.files import export_json, export_script, load_table # noqa: E402
|
|
21
|
+
|
|
22
|
+
SETTINGS_FILE = Path.home() / ".driftcheck_settings.json"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DriftApp(tk.Tk):
|
|
26
|
+
"""Main window: load two files, run the analysis, inspect and export results."""
|
|
27
|
+
|
|
28
|
+
def __init__(self) -> None:
|
|
29
|
+
super().__init__()
|
|
30
|
+
self.title("driftcheck")
|
|
31
|
+
self.geometry("1000x650")
|
|
32
|
+
self.settings = Settings.load(SETTINGS_FILE) if SETTINGS_FILE.exists() else Settings()
|
|
33
|
+
self.ref_path: str = ""
|
|
34
|
+
self.cur_path: str = ""
|
|
35
|
+
self.reference = None
|
|
36
|
+
self.current = None
|
|
37
|
+
self.report: DriftReport | None = None
|
|
38
|
+
self.messages: queue.Queue = queue.Queue()
|
|
39
|
+
self._build()
|
|
40
|
+
|
|
41
|
+
# ---------- layout ----------
|
|
42
|
+
def _build(self) -> None:
|
|
43
|
+
top = ttk.Frame(self, padding=8)
|
|
44
|
+
top.pack(fill="x")
|
|
45
|
+
ttk.Button(top, text="Load reference data", command=self._load_ref).pack(side="left")
|
|
46
|
+
self.ref_label = ttk.Label(top, text="none", width=25)
|
|
47
|
+
self.ref_label.pack(side="left", padx=6)
|
|
48
|
+
ttk.Button(top, text="Load new data", command=self._load_cur).pack(side="left")
|
|
49
|
+
self.cur_label = ttk.Label(top, text="none", width=25)
|
|
50
|
+
self.cur_label.pack(side="left", padx=6)
|
|
51
|
+
|
|
52
|
+
ttk.Label(top, text="Seed").pack(side="left")
|
|
53
|
+
self.seed_var = tk.IntVar(value=self.settings.seed)
|
|
54
|
+
ttk.Entry(top, textvariable=self.seed_var, width=6).pack(side="left", padx=4)
|
|
55
|
+
self.run_btn = ttk.Button(top, text="Run analysis", command=self._run)
|
|
56
|
+
self.run_btn.pack(side="left", padx=6)
|
|
57
|
+
|
|
58
|
+
bar = ttk.Frame(self, padding=(8, 0))
|
|
59
|
+
bar.pack(fill="x")
|
|
60
|
+
self.progress = ttk.Progressbar(bar, maximum=1.0)
|
|
61
|
+
self.progress.pack(side="left", fill="x", expand=True)
|
|
62
|
+
self.status = ttk.Label(bar, text="Load two datasets to start", width=40)
|
|
63
|
+
self.status.pack(side="left", padx=6)
|
|
64
|
+
|
|
65
|
+
self.summary = ttk.Label(self, text="", padding=8, font=("TkDefaultFont", 10, "bold"))
|
|
66
|
+
self.summary.pack(fill="x")
|
|
67
|
+
|
|
68
|
+
body = ttk.PanedWindow(self, orient="horizontal")
|
|
69
|
+
body.pack(fill="both", expand=True, padx=8, pady=4)
|
|
70
|
+
|
|
71
|
+
cols = ("feature", "test", "p_value", "psi", "importance", "drift")
|
|
72
|
+
self.table = ttk.Treeview(body, columns=cols, show="headings", height=20)
|
|
73
|
+
for c in cols:
|
|
74
|
+
self.table.heading(c, text=c)
|
|
75
|
+
self.table.column(c, width=90, anchor="center")
|
|
76
|
+
self.table.bind("<<TreeviewSelect>>", self._on_select)
|
|
77
|
+
body.add(self.table, weight=1)
|
|
78
|
+
|
|
79
|
+
self.figure = Figure(figsize=(5, 4), dpi=100)
|
|
80
|
+
self.canvas = FigureCanvasTkAgg(self.figure, master=body)
|
|
81
|
+
body.add(self.canvas.get_tk_widget(), weight=1)
|
|
82
|
+
|
|
83
|
+
bottom = ttk.Frame(self, padding=8)
|
|
84
|
+
bottom.pack(fill="x")
|
|
85
|
+
ttk.Button(bottom, text="Export JSON report", command=self._export_json).pack(side="left")
|
|
86
|
+
ttk.Button(bottom, text="Export Python script", command=self._export_script).pack(side="left", padx=6)
|
|
87
|
+
|
|
88
|
+
# ---------- loading ----------
|
|
89
|
+
def _pick(self) -> str:
|
|
90
|
+
return filedialog.askopenfilename(filetypes=[("Data", "*.csv *.xlsx *.xls"), ("All", "*.*")])
|
|
91
|
+
|
|
92
|
+
def _load_ref(self) -> None:
|
|
93
|
+
path = self._pick()
|
|
94
|
+
if path:
|
|
95
|
+
try:
|
|
96
|
+
self.reference = load_table(path)
|
|
97
|
+
except Exception as exc: # shown to the user, not swallowed
|
|
98
|
+
messagebox.showerror("Could not load file", str(exc))
|
|
99
|
+
return
|
|
100
|
+
self.ref_path = path
|
|
101
|
+
self.ref_label.config(text=f"{Path(path).name} ({len(self.reference)} rows)")
|
|
102
|
+
|
|
103
|
+
def _load_cur(self) -> None:
|
|
104
|
+
path = self._pick()
|
|
105
|
+
if path:
|
|
106
|
+
try:
|
|
107
|
+
self.current = load_table(path)
|
|
108
|
+
except Exception as exc:
|
|
109
|
+
messagebox.showerror("Could not load file", str(exc))
|
|
110
|
+
return
|
|
111
|
+
self.cur_path = path
|
|
112
|
+
self.cur_label.config(text=f"{Path(path).name} ({len(self.current)} rows)")
|
|
113
|
+
|
|
114
|
+
# ---------- running in a worker thread ----------
|
|
115
|
+
def _run(self) -> None:
|
|
116
|
+
if self.reference is None or self.current is None:
|
|
117
|
+
messagebox.showwarning("Missing data", "Load both the reference and the new dataset first.")
|
|
118
|
+
return
|
|
119
|
+
try:
|
|
120
|
+
self.settings.seed = int(self.seed_var.get())
|
|
121
|
+
except (tk.TclError, ValueError):
|
|
122
|
+
messagebox.showerror("Invalid seed", "The seed must be a whole number.")
|
|
123
|
+
return
|
|
124
|
+
self.settings.save(SETTINGS_FILE)
|
|
125
|
+
self.run_btn.state(["disabled"])
|
|
126
|
+
threading.Thread(target=self._worker, daemon=True).start()
|
|
127
|
+
self.after(100, self._poll)
|
|
128
|
+
|
|
129
|
+
def _worker(self) -> None:
|
|
130
|
+
try:
|
|
131
|
+
report = run_analysis(
|
|
132
|
+
self.reference,
|
|
133
|
+
self.current,
|
|
134
|
+
self.settings,
|
|
135
|
+
progress=lambda f, m: self.messages.put(("progress", f, m)),
|
|
136
|
+
)
|
|
137
|
+
self.messages.put(("done", report, None))
|
|
138
|
+
except Exception as exc:
|
|
139
|
+
self.messages.put(("error", exc, None))
|
|
140
|
+
|
|
141
|
+
def _poll(self) -> None:
|
|
142
|
+
try:
|
|
143
|
+
while True:
|
|
144
|
+
kind, a, b = self.messages.get_nowait()
|
|
145
|
+
if kind == "progress":
|
|
146
|
+
self.progress["value"] = a
|
|
147
|
+
self.status.config(text=b)
|
|
148
|
+
elif kind == "done":
|
|
149
|
+
self._show(a)
|
|
150
|
+
self.run_btn.state(["!disabled"])
|
|
151
|
+
return
|
|
152
|
+
elif kind == "error":
|
|
153
|
+
self.run_btn.state(["!disabled"])
|
|
154
|
+
self.status.config(text="Failed")
|
|
155
|
+
messagebox.showerror("Analysis failed", str(a))
|
|
156
|
+
return
|
|
157
|
+
except queue.Empty:
|
|
158
|
+
pass
|
|
159
|
+
self.after(100, self._poll)
|
|
160
|
+
|
|
161
|
+
# ---------- results ----------
|
|
162
|
+
def _show(self, report: DriftReport) -> None:
|
|
163
|
+
self.report = report
|
|
164
|
+
self.table.delete(*self.table.get_children())
|
|
165
|
+
for _, r in report.to_frame().iterrows():
|
|
166
|
+
self.table.insert(
|
|
167
|
+
"",
|
|
168
|
+
"end",
|
|
169
|
+
values=(r["name"], r["test_name"], f"{r['p_value']:.4f}", f"{r['psi']:.3f}",
|
|
170
|
+
f"{r['importance']:.3f}", "YES" if r["drift"] else "no"),
|
|
171
|
+
)
|
|
172
|
+
self.summary.config(
|
|
173
|
+
text=(
|
|
174
|
+
f"{len(report.drifted_features)} of {len(report.features)} features drifted | "
|
|
175
|
+
f"MMD p = {report.mmd_p_value:.4f} ({'drift' if report.mmd_drift else 'no drift'}) | "
|
|
176
|
+
f"Domain classifier AUC = {report.classifier_auc:.3f} "
|
|
177
|
+
f"({'drift' if report.classifier_drift else 'no drift'})"
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def _on_select(self, _event=None) -> None:
|
|
182
|
+
sel = self.table.selection()
|
|
183
|
+
if not sel or self.reference is None:
|
|
184
|
+
return
|
|
185
|
+
name = self.table.item(sel[0], "values")[0]
|
|
186
|
+
ref, cur = self.reference[name].dropna(), self.current[name].dropna()
|
|
187
|
+
self.figure.clear()
|
|
188
|
+
ax = self.figure.add_subplot(111)
|
|
189
|
+
if is_numeric(ref):
|
|
190
|
+
ax.hist(ref, bins=30, alpha=0.5, density=True, label="reference")
|
|
191
|
+
ax.hist(cur, bins=30, alpha=0.5, density=True, label="new")
|
|
192
|
+
else:
|
|
193
|
+
a = ref.astype(str).value_counts(normalize=True)
|
|
194
|
+
b = cur.astype(str).value_counts(normalize=True)
|
|
195
|
+
both = a.to_frame("reference").join(b.to_frame("new"), how="outer").fillna(0)
|
|
196
|
+
both.plot.bar(ax=ax)
|
|
197
|
+
ax.set_title(name)
|
|
198
|
+
ax.legend()
|
|
199
|
+
self.figure.tight_layout()
|
|
200
|
+
self.canvas.draw()
|
|
201
|
+
|
|
202
|
+
# ---------- export ----------
|
|
203
|
+
def _export_json(self) -> None:
|
|
204
|
+
if self.report is None:
|
|
205
|
+
messagebox.showinfo("Nothing to export", "Run an analysis first.")
|
|
206
|
+
return
|
|
207
|
+
path = filedialog.asksaveasfilename(defaultextension=".json")
|
|
208
|
+
if path:
|
|
209
|
+
export_json(self.report, path, self.ref_path, self.cur_path)
|
|
210
|
+
|
|
211
|
+
def _export_script(self) -> None:
|
|
212
|
+
if self.report is None:
|
|
213
|
+
messagebox.showinfo("Nothing to export", "Run an analysis first.")
|
|
214
|
+
return
|
|
215
|
+
path = filedialog.asksaveasfilename(defaultextension=".py")
|
|
216
|
+
if path:
|
|
217
|
+
export_script(self.report, path, self.ref_path, self.cur_path)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def launch() -> None:
|
|
221
|
+
"""Open the main window."""
|
|
222
|
+
DriftApp().mainloop()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""File loading and report export."""
|
driftcheck/io/files.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Load datasets and export reports, reproducible scripts and environment info."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import platform
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import asdict
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from importlib import metadata
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
from driftcheck.core.analysis import DriftReport
|
|
16
|
+
|
|
17
|
+
PACKAGES = ["driftcheck-gui", "numpy", "pandas", "scipy", "scikit-learn", "matplotlib"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def load_table(path: str | Path) -> pd.DataFrame:
|
|
21
|
+
"""Read a CSV or Excel file into a DataFrame."""
|
|
22
|
+
path = Path(path)
|
|
23
|
+
suffix = path.suffix.lower()
|
|
24
|
+
if suffix == ".csv":
|
|
25
|
+
return pd.read_csv(path)
|
|
26
|
+
if suffix in {".xlsx", ".xls"}:
|
|
27
|
+
return pd.read_excel(path)
|
|
28
|
+
raise ValueError(f"Unsupported file type: {suffix}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def environment() -> dict:
|
|
32
|
+
"""Python, OS and package versions, for reproducibility."""
|
|
33
|
+
versions = {}
|
|
34
|
+
for name in PACKAGES:
|
|
35
|
+
try:
|
|
36
|
+
versions[name] = metadata.version(name)
|
|
37
|
+
except metadata.PackageNotFoundError:
|
|
38
|
+
versions[name] = "not installed"
|
|
39
|
+
return {"python": sys.version.split()[0], "platform": platform.platform(), "packages": versions}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def export_json(report: DriftReport, path: str | Path, ref_path: str = "", cur_path: str = "") -> None:
|
|
43
|
+
"""Write the full report, settings and environment to JSON."""
|
|
44
|
+
data = {
|
|
45
|
+
"created": datetime.now(timezone.utc).isoformat(),
|
|
46
|
+
"reference_file": str(ref_path),
|
|
47
|
+
"current_file": str(cur_path),
|
|
48
|
+
"settings": asdict(report.settings),
|
|
49
|
+
"environment": environment(),
|
|
50
|
+
"n_reference": report.n_reference,
|
|
51
|
+
"n_current": report.n_current,
|
|
52
|
+
"mmd": {"statistic": report.mmd_statistic, "p_value": report.mmd_p_value, "drift": report.mmd_drift},
|
|
53
|
+
"domain_classifier": {"auc": report.classifier_auc, "drift": report.classifier_drift},
|
|
54
|
+
"features": [asdict(f) for f in report.features],
|
|
55
|
+
}
|
|
56
|
+
Path(path).write_text(json.dumps(data, indent=2), encoding="utf-8")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def export_script(report: DriftReport, path: str | Path, ref_path: str, cur_path: str) -> None:
|
|
60
|
+
"""Write a Python script that reproduces this analysis without the GUI."""
|
|
61
|
+
s = asdict(report.settings)
|
|
62
|
+
args = ", ".join(f"{k}={v!r}" for k, v in s.items())
|
|
63
|
+
cols = [f.name for f in report.features]
|
|
64
|
+
script = f'''"""Reproduces a driftcheck session. Generated {datetime.now(timezone.utc):%Y-%m-%d %H:%M} UTC."""
|
|
65
|
+
import pandas as pd
|
|
66
|
+
from driftcheck import Settings, run_analysis
|
|
67
|
+
|
|
68
|
+
reference = pd.read_csv({str(ref_path)!r})
|
|
69
|
+
current = pd.read_csv({str(cur_path)!r})
|
|
70
|
+
settings = Settings({args})
|
|
71
|
+
columns = {cols!r}
|
|
72
|
+
|
|
73
|
+
report = run_analysis(reference, current, settings, columns)
|
|
74
|
+
print(report.to_frame().to_string())
|
|
75
|
+
print(f"MMD p-value: {{report.mmd_p_value:.4f}} drift={{report.mmd_drift}}")
|
|
76
|
+
print(f"Domain classifier AUC: {{report.classifier_auc:.3f}} drift={{report.classifier_drift}}")
|
|
77
|
+
'''
|
|
78
|
+
Path(path).write_text(script, encoding="utf-8")
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: driftcheck-gui
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Offline desktop tool for detecting dataset shift between training and new data
|
|
5
|
+
Author: McZane
|
|
6
|
+
License: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Topic :: Scientific/Engineering
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: numpy>=1.24
|
|
15
|
+
Requires-Dist: pandas>=2.0
|
|
16
|
+
Requires-Dist: scipy>=1.10
|
|
17
|
+
Requires-Dist: scikit-learn>=1.3
|
|
18
|
+
Requires-Dist: matplotlib>=3.7
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-cov>=4; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# driftcheck
|
|
25
|
+
|
|
26
|
+
driftcheck tells you whether new data has drifted away from the data a model was trained on. Load two CSV or Excel files, press Run, and it shows which columns changed and how much. It runs offline, so sensitive data never leaves your computer.
|
|
27
|
+
|
|
28
|
+
Tests it runs:
|
|
29
|
+
|
|
30
|
+
| Test | Level | What it measures |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| Kolmogorov–Smirnov | per numeric column | difference between the two distributions |
|
|
33
|
+
| Chi-square | per categorical column | difference in category frequencies |
|
|
34
|
+
| Population Stability Index | per column | size of the shift (above 0.2 counts as drift) |
|
|
35
|
+
| MMD permutation test | whole dataset | whether the joint distribution changed |
|
|
36
|
+
| Domain classifier | whole dataset | AUC of a model that tries to tell old rows from new (0.5 = no drift) |
|
|
37
|
+
|
|
38
|
+
Per-column p-values use a Bonferroni correction.
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
Python 3.10 or later.
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
pip install driftcheck-gui
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
From source:
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
git clone https://github.com/McZane-05/driftcheck
|
|
52
|
+
cd driftcheck
|
|
53
|
+
pip install -e ".[dev]"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Quick start
|
|
57
|
+
|
|
58
|
+
Open the app:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
driftcheck
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
or `python -m driftcheck`. Then load the reference data, load the new data, and click **Run analysis**. Click a row in the table to see that column's distribution plot.
|
|
65
|
+
|
|
66
|
+
From Python:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
import pandas as pd
|
|
70
|
+
from driftcheck import Settings, run_analysis
|
|
71
|
+
|
|
72
|
+
report = run_analysis(pd.read_csv("reference.csv"), pd.read_csv("current.csv"), Settings(seed=42))
|
|
73
|
+
print(report.to_frame())
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Example data: `python examples/make_example_data.py`, then `python examples/quickstart.py`.
|
|
77
|
+
|
|
78
|
+
## Screenshots
|
|
79
|
+
|
|
80
|
+
_Add screenshots of the main window to `docs/` and link them here._
|
|
81
|
+
|
|
82
|
+
## Reproducibility
|
|
83
|
+
|
|
84
|
+
Every random step uses one seed, set in the window or in `Settings(seed=...)`. Settings are saved to `~/.driftcheck_settings.json`. **Export JSON report** saves results, settings and package versions. **Export Python script** writes a script that reruns the same analysis without the GUI.
|
|
85
|
+
|
|
86
|
+
## Running the tests
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
python -m coverage run --source=src/driftcheck -m pytest
|
|
90
|
+
python -m coverage report --omit="*/gui/*,*__main__*"
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT. See `LICENSE`. To cite this software, see `CITATION.cff`.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
driftcheck/__init__.py,sha256=UDXtyKZafav-jm5CEJEMn6-9uSGYhzhc1FPp2copJ5w,283
|
|
2
|
+
driftcheck/__main__.py,sha256=FDQ83O-aBgxiHBC3Sx6aN_x-btBPeMBBYVDuBZJIQ7E,179
|
|
3
|
+
driftcheck/core/__init__.py,sha256=-bAbzMub3EXzWRsiDaVg1RkqPn3CQZf0OgUZTSCai7Y,85
|
|
4
|
+
driftcheck/core/analysis.py,sha256=tV2T9rT2l9BhPIJ7VfKfQk2q475xDfV6eG0FPQJosRY,4550
|
|
5
|
+
driftcheck/core/detectors.py,sha256=Q6a_RMlVc1aBxw15Tz57VciBgliV7GOsDGme8QFTckY,4846
|
|
6
|
+
driftcheck/core/settings.py,sha256=iFvcbRZBGVDYnYzRIJcTbpxzRa5HrCS2VBjJaKxqGrg,902
|
|
7
|
+
driftcheck/gui/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
driftcheck/gui/app.py,sha256=_lOlav6M3tP9nXIg1H9fSb4wKnD1a3yMIJD2znQv1vM,8993
|
|
9
|
+
driftcheck/io/__init__.py,sha256=c_XTlUcXjsGbVmXw1YmI6izq79HxQn99rDz9okY9p4s,38
|
|
10
|
+
driftcheck/io/files.py,sha256=tx527_1KXjS-npocNHyEb2vtZKnJsxDhQ6K7Hg5XDro,2972
|
|
11
|
+
driftcheck_gui-0.1.0.dist-info/licenses/LICENSE,sha256=QySw1_8InFG3QlucqXo-UXNunmYbBU3niwjPqEI7L4o,1063
|
|
12
|
+
driftcheck_gui-0.1.0.dist-info/METADATA,sha256=wzyVIYGgG2DBeFAR__5sId8gDdASDfnIu3VVxBEkGac,2883
|
|
13
|
+
driftcheck_gui-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
14
|
+
driftcheck_gui-0.1.0.dist-info/entry_points.txt,sha256=L1KHZzlJpywCGW2vrw81D7xk4_Okwn0JL5cByw9WYzU,56
|
|
15
|
+
driftcheck_gui-0.1.0.dist-info/top_level.txt,sha256=eFLPSy6B3bEZn1aKTj0Nb84NzE5gtL53F7CMJXlB8Rw,11
|
|
16
|
+
driftcheck_gui-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 McZane
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
driftcheck
|