-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatatypical.py
More file actions
3514 lines (2872 loc) · 136 KB
/
datatypical.py
File metadata and controls
3514 lines (2872 loc) · 136 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DataTypical v0.7.3 --- Dual-Perspective Significance with Shapley Explanations
===========================================================================
Revolutionary framework combining geometric and influence-based significance.
Key Innovation:
- Actual significance: Samples that ARE archetypal/prototypical/stereotypical (geometric)
- Formative instances: Samples that MAKE the dataset archetypal/prototypical/stereotypical (Shapley)
- Local explanations: WHY each sample is significant (feature attributions)
Two complementary perspectivesF:
1. LOCAL: "This sample IS significant because features X, Y contribute most"
2. GLOBAL: "This sample CREATES significance by defining the distribution and boundary"
What's new in v0.7:
- shapley_mode parameter (True/False)
- When True: computes explanations + formative instances
- Dual rankings: *_rank (actual) + *_shapley_rank (formative)
- Novel value functions: convex hull, coverage, extremeness
- Parallel Shapley computation with Option A (accurate v0.4 explanations)
All v0.6 features retained:
- Local explanations via get_shapley_explanations()
- Global explanations to identify formative instances
All v0.5 features retained:
- Tabular/Text/Graph support
- Label column preservation
- Graph topology features
All v0.4 features retained:
- User-configurable stereotypes
Sections:
[A] Exceptions & Globals
[B] Thread Control
[C] Helpers (sparse/dense math)
[D] Facility-Location (CELF, deterministic)
[E] Shapley Significance Engine (NEW in v0.6)
[F] DataTypical API
[G] Graph Topology Features
[H] Stereotype Computation
"""
from __future__ import annotations
from dataclasses import dataclass, field, fields as dc_fields
from typing import Iterable, List, Optional, Dict, Tuple, Union, Callable
import heapq
import math
import gc
import warnings
import hashlib
import numpy as np
import pandas as pd
from sklearn.decomposition import NMF
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import MinMaxScaler
from threadpoolctl import threadpool_limits
from joblib import Parallel, delayed
from sklearn.exceptions import ConvergenceWarning
try:
from numba import jit, prange
import numpy as np
# Test if Numba actually works with the current NumPy
@jit(nopython=True)
def _test(x): return x
_test(np.array([1]))
NUMBA_AVAILABLE = True
except (ImportError, Exception):
# This catches the "NumPy version too new" error too!
NUMBA_AVAILABLE = False
def jit(*args, **kwargs):
return lambda f: f
def prange(n):
return range(n)
try:
import scipy.sparse as sp
except Exception:
sp = None
ArrayLike = Union[np.ndarray, "sp.spmatrix"]
try:
from scipy.spatial import ConvexHull
from scipy.spatial.distance import cdist
except Exception:
ConvexHull = None
cdist = None
try:
from py_pcha import PCHA
except ImportError:
PCHA = None
try:
import faiss
FAISS_AVAILABLE = True
except ImportError:
FAISS_AVAILABLE = False
# ============================================================
# [A] Exceptions & Globals
# ============================================================
class DataTypicalError(Exception):
pass
class MemoryBudgetError(DataTypicalError):
pass
class ConfigError(DataTypicalError):
pass
def _seed_everything(seed: int) -> None:
np.random.seed(seed)
# ============================================================
# [B] Thread Control
# ============================================================
class _ThreadControl:
def __init__(self, deterministic: bool = True):
self.deterministic = deterministic
self._ctx = None
self.effective_limit = None
def __enter__(self):
if self.deterministic:
self._ctx = threadpool_limits(limits=1)
self.effective_limit = 1
else:
self._ctx = threadpool_limits(limits=None)
self.effective_limit = None
self._ctx.__enter__()
return self
def __exit__(self, exc_type, exc, tb):
if self._ctx is not None:
self._ctx.__exit__(exc_type, exc, tb)
# ============================================================
# [C] Helpers (sparse/dense math)
# ============================================================
def _cleanup_memory(*arrays, force_gc: bool = False) -> None:
"""
Explicitly delete arrays and optionally force garbage collection.
MEMORY OPTIMIZED: Python's GC doesn't always free memory immediately.
This forces cleanup of large temporaries to reduce peak memory usage.
"""
for arr in arrays:
if arr is not None:
del arr
if force_gc:
gc.collect()
def _l2_normalize_rows_dense(X: np.ndarray) -> np.ndarray:
norms = np.linalg.norm(X, axis=1, keepdims=True)
norms[norms == 0.0] = 1.0
return X / norms
def _sparse_l2_normalize_rows(X: "sp.spmatrix") -> "sp.spmatrix":
if sp is None:
raise ImportError("scipy is required for sparse operations.")
if not sp.isspmatrix_csr(X):
X = X.tocsr(copy=False)
sq = X.multiply(X).sum(axis=1)
norms = np.sqrt(np.maximum(np.asarray(sq).ravel(), 0.0))
norms[norms == 0.0] = 1.0
D = sp.diags(1.0 / norms)
return D @ X
def _sparse_minmax_0_1_nonneg(M: "sp.spmatrix") -> "sp.spmatrix":
if sp is None:
raise ImportError("scipy is required for sparse operations.")
if not sp.isspmatrix(M):
raise TypeError("Expected a scipy.sparse matrix.")
A = M.tocsc(copy=False)
# CRITICAL: Must use .toarray() to convert sparse matrix to dense
col_max = A.max(axis=0).toarray().ravel()
col_max[col_max == 0.0] = 1.0
return (A @ sp.diags(1.0 / col_max)).tocsr()
def _chunk_len(n_left: int, n_right: int, bytes_per: int, max_memory_mb: int) -> int:
if max_memory_mb <= 0:
raise MemoryBudgetError("max_memory_mb must be positive")
max_bytes = max_memory_mb * 1024 * 1024
return max(1, min(n_right, int(max_bytes // max(8, n_left * bytes_per))))
def _ensure_dtype(X: np.ndarray, dtype: str = 'float32') -> np.ndarray:
"""
Ensure array has specified dtype, converting if necessary.
MEMORY OPTIMIZED: Default to float32 (4 bytes) instead of float64 (8 bytes).
"""
target_dtype = np.float32 if dtype == 'float32' else np.float64
if X.dtype != target_dtype:
return X.astype(target_dtype, copy=False)
return X
def _euclidean_min_to_set_dense(
X: np.ndarray, Y: np.ndarray, max_memory_mb: int = 2048
) -> np.ndarray:
"""
Compute minimum Euclidean distance from each row of X to any row in Y.
OPTIMIZED: Uses Numba JIT for 2-3× speedup and better memory efficiency.
"""
n, d = X.shape
m = Y.shape[0]
# For small problems, use JIT-compiled direct computation
if n * m < 100000:
return _euclidean_min_jit(X, Y)
# For large problems, use chunked computation with JIT
best = np.full(n, np.inf, dtype=np.float64)
block = _chunk_len(n, m, bytes_per=8, max_memory_mb=max_memory_mb)
# Pre-compute X squared norms once
x2 = np.sum(X * X, axis=1)
for s in range(0, m, block):
e = min(m, s + block)
YY = Y[s:e]
# Use JIT-compiled function for this chunk
chunk_dists = _euclidean_chunk_jit(X, YY, x2)
best = np.minimum(best, chunk_dists)
return best
@jit(nopython=True, parallel=True, cache=True, fastmath=True)
def _euclidean_min_jit(X: np.ndarray, Y: np.ndarray) -> np.ndarray:
"""
JIT-compiled minimum Euclidean distance computation.
Uses parallel loops for multi-core acceleration.
"""
n = X.shape[0]
m = Y.shape[0]
d = X.shape[1]
min_dists = np.empty(n, dtype=np.float64)
# Parallel loop over X samples (explicit with prange)
for i in prange(n): # Changed from range to prange
min_dist = np.inf
for j in range(m):
dist_sq = 0.0
for k in range(d):
diff = X[i, k] - Y[j, k]
dist_sq += diff * diff
if dist_sq < min_dist:
min_dist = dist_sq
min_dists[i] = np.sqrt(max(min_dist, 0.0))
return min_dists
@jit(nopython=True, cache=True, fastmath=True)
def _euclidean_chunk_jit(
X: np.ndarray,
Y_chunk: np.ndarray,
x2: np.ndarray
) -> np.ndarray:
"""
JIT-compiled chunked distance computation using pre-computed norms.
Computes: sqrt(||x||² + ||y||² - 2⟨x,y⟩) efficiently.
"""
n = X.shape[0]
m = Y_chunk.shape[0]
d = X.shape[1]
min_dists = np.empty(n, dtype=np.float64)
# Pre-compute Y chunk squared norms
y2 = np.empty(m, dtype=np.float64)
for j in range(m):
y2_val = 0.0
for k in range(d):
y2_val += Y_chunk[j, k] * Y_chunk[j, k]
y2[j] = y2_val
# Parallel loop over X samples
for i in range(n):
min_dist_sq = np.inf
for j in range(m):
# Compute dot product
dot = 0.0
for k in range(d):
dot += X[i, k] * Y_chunk[j, k]
# Distance squared using pre-computed norms
dist_sq = x2[i] + y2[j] - 2.0 * dot
if dist_sq < min_dist_sq:
min_dist_sq = dist_sq
min_dists[i] = np.sqrt(max(min_dist_sq, 0.0))
return min_dists
@jit(nopython=True, cache=True, fastmath=True)
def _pairwise_euclidean_jit(X: np.ndarray) -> np.ndarray:
"""
JIT-compiled pairwise Euclidean distance matrix.
Returns upper triangle only to save memory.
"""
n = X.shape[0]
d = X.shape[1]
# Compute full distance matrix (symmetric)
dists = np.zeros((n, n), dtype=np.float64)
# Parallel outer loop
for i in range(n):
for j in range(i + 1, n):
dist_sq = 0.0
for k in range(d):
diff = X[i, k] - X[j, k]
dist_sq += diff * diff
dist = np.sqrt(max(dist_sq, 0.0))
dists[i, j] = dist
dists[j, i] = dist # Symmetric
return dists
@jit(nopython=True, cache=True, fastmath=True)
def _cosine_similarity_jit(X: np.ndarray, Y: np.ndarray) -> np.ndarray:
"""
JIT-compiled cosine similarity between L2-normalized vectors.
For L2-normalized data, this is just the dot product.
"""
n = X.shape[0]
m = Y.shape[0]
d = X.shape[1]
sims = np.empty((n, m), dtype=np.float64)
# Parallel loop over X samples
for i in range(n):
for j in range(m):
dot = 0.0
for k in range(d):
dot += X[i, k] * Y[j, k]
sims[i, j] = max(dot, 0.0) # Clip negative similarities
return sims
# ============================================================
# [D] Facility-Location (CELF, deterministic)
# ============================================================
@dataclass
class FacilityLocationSelector:
def __init__(self, n_prototypes=10, deterministic=True, speed_mode=False, verbose=False):
self.n_prototypes = int(n_prototypes)
self.deterministic = bool(deterministic)
self.speed_mode = bool(speed_mode)
self.verbose = bool(verbose)
def select(self, X_l2, weights=None, forbidden=None):
"""
Deterministic CELF for facility-location with:
• content-based tie-breaking (perm-invariant),
• optional client weights (e.g., density),
• optional forbidden candidate set (still count as clients).
Expects rows to be L2-normalized. Works with dense or sparse input.
Returns: (selected_indices, marginal_gains)
"""
import numpy as np, heapq, hashlib
# --- dense float64 view
if sp is not None and sp.isspmatrix(X_l2):
X = X_l2.toarray().astype(np.float64, copy=False)
else:
X = np.asarray(X_l2, dtype=np.float64)
n = X.shape[0]
if n == 0:
return np.array([], dtype=int), np.array([], dtype=float)
# --- client weights (normalize to mean 1 for scale stability)
if weights is None:
w = np.ones(n, dtype=np.float64)
else:
w = np.asarray(weights, dtype=np.float64).ravel()
m = float(w.mean())
w = w / m if m > 0 else np.ones_like(w)
# --- forbidden candidates (excluded from selection, included as clients)
forb = np.zeros(n, dtype=bool)
if forbidden is not None:
forb_idx = np.asarray(list(forbidden), dtype=int)
forb_idx = forb_idx[(forb_idx >= 0) & (forb_idx < n)]
forb[forb_idx] = True
# --- target number of prototypes (cap to available candidates)
k_req = int(getattr(self, "n_prototypes", min(10, n)))
available = n - int(forb.sum())
k = max(0, min(k_req, available))
if k == 0:
return np.array([], dtype=int), np.array([], dtype=float)
# --- permutation-invariant tie-breaker: hash of row content
def row_key(i: int) -> int:
h = hashlib.blake2b(X[i].tobytes(), digest_size=8)
return int.from_bytes(h.digest(), "big", signed=False)
keys = np.fromiter((row_key(i) for i in range(n)), dtype=np.uint64, count=n)
# --- CELF init
best = np.zeros(n, dtype=np.float64) # current best similarity per client
last_eval = np.full(n, -1, dtype=np.int64) # last #selected when gain was computed
last_gain = np.zeros(n, dtype=np.float64)
# Initial exact gains: g0[c] = sum_i w_i * max(0, <x_i, x_c>)
g0 = np.zeros(n, dtype=np.float64)
# block multiply to limit memory
target_bytes = 256 * 1024 * 1024 # 256MB scratch
item = np.dtype(np.float64).itemsize
max_b = max(1, int(target_bytes // max(1, n * item)))
bsz = max(1, min(n, max_b))
XT = X.T
for s in range(0, n, bsz):
e = min(n, s + bsz)
S = X[s:e] @ XT # (e-s, n)
np.maximum(S, 0.0, out=S)
g0 += (w[s:e, None] * S).sum(axis=0, dtype=np.float64)
last_gain[:] = g0
last_eval[:] = 0
# heap items: (-gain_estimate, key, idx) – ties broken by content key
heap = [(-float(g0[c]), int(keys[c]), int(c)) for c in range(n) if not forb[c]]
heapq.heapify(heap)
selected: list[int] = []
gains: list[float] = []
it = 0
while len(selected) < k and heap:
neg_g_est, _, c = heapq.heappop(heap)
if last_eval[c] == it:
# accept candidate
selected.append(c)
gains.append(float(last_gain[c]))
s = X @ X[c]
np.maximum(s, 0.0, out=s)
np.maximum(best, s, out=best)
it += 1
continue
# refresh exact marginal gain vs current 'best'
s = X @ X[c]
improv = s - best
improv[improv < 0.0] = 0.0
g_exact = float((w * improv).sum(dtype=np.float64))
last_gain[c] = g_exact
last_eval[c] = it
heapq.heappush(heap, (-g_exact, int(keys[c]), int(c)))
return np.asarray(selected, dtype=int), np.asarray(gains, dtype=float)
def select(self, X_l2, weights=None, forbidden=None):
"""
Select prototypes using lazy CELF with optional FAISS acceleration.
OPTIMIZED: Uses FAISS for datasets with n > 1,000 samples for massive speedup.
MEMORY OPTIMIZED: Explicit cleanup of similarity matrix after use.
"""
import numpy as np
if sp is not None and sp.isspmatrix(X_l2):
X = X_l2.toarray().astype(np.float64, copy=False)
else:
X = np.asarray(X_l2, dtype=np.float64)
n = X.shape[0]
if n == 0:
return np.array([], dtype=int), np.array([], dtype=float)
# Normalize weights
if weights is None:
w = np.ones(n, dtype=np.float64)
else:
w = np.asarray(weights, dtype=np.float64).ravel()
m = float(w.mean())
w = w / m if m > 0 else np.ones_like(w)
# OPTIMIZED: Use FAISS for large datasets if available
use_faiss = FAISS_AVAILABLE and n > 1000 and not self.speed_mode
if use_faiss:
if self.verbose:
print(f" Using FAISS acceleration for n={n}")
result = self._select_with_faiss(X, w, forbidden)
# MEMORY CLEANUP: Free X copy before returning
_cleanup_memory(X, force_gc=True)
return result
# Otherwise use the cached similarity matrix approach
import heapq, hashlib
# Handle forbidden indices
forb = np.zeros(n, dtype=bool)
if forbidden is not None:
forb_idx = np.asarray(list(forbidden), dtype=int)
forb_idx = forb_idx[(forb_idx >= 0) & (forb_idx < n)]
forb[forb_idx] = True
k_req = int(getattr(self, "n_prototypes", min(10, n)))
available = n - int(forb.sum())
k = max(0, min(k_req, available))
if k == 0:
return np.array([], dtype=int), np.array([], dtype=float)
# Pre-compute similarity matrix
XT = X.T
S = X @ XT
np.maximum(S, 0.0, out=S)
# MEMORY CLEANUP: Free XT after similarity computation
_cleanup_memory(XT)
# Pre-compute weighted candidate similarities
S_weighted = w[None, :] * S
candidate_sims = S_weighted.sum(axis=1)
# MEMORY CLEANUP: Free S_weighted after computing candidate_sims
_cleanup_memory(S_weighted)
# Generate deterministic keys
def row_key(i: int) -> int:
h = hashlib.blake2b(X[i].tobytes(), digest_size=8)
return int.from_bytes(h.digest(), "big", signed=False)
keys = np.fromiter((row_key(i) for i in range(n)), dtype=np.uint64, count=n)
# CELF state tracking
best = np.zeros(n, dtype=np.float64)
last_eval = np.full(n, -1, dtype=np.int64)
last_gain = candidate_sims.copy()
last_eval[:] = 0
# Initialize heap
heap = [(-float(candidate_sims[c]), int(keys[c]), int(c))
for c in range(n) if not forb[c]]
heapq.heapify(heap)
selected = []
gains = []
it = 0
while len(selected) < k and heap:
neg_g_est, _, c = heapq.heappop(heap)
if last_eval[c] == it:
selected.append(c)
gains.append(float(last_gain[c]))
s_c = S[c, :]
np.maximum(best, s_c, out=best)
it += 1
continue
# Lazy evaluation
s_c = S[c, :]
improv = s_c - best
improv[improv < 0.0] = 0.0
g_exact = float((w * improv).sum(dtype=np.float64))
last_gain[c] = g_exact
last_eval[c] = it
heapq.heappush(heap, (-g_exact, int(keys[c]), int(c)))
# MEMORY CLEANUP: Free large arrays before returning
_cleanup_memory(S, X, best, last_gain, candidate_sims, force_gc=True)
return np.asarray(selected, dtype=int), np.asarray(gains, dtype=float)
# ============================================================
# [E] Shapley Significance Engine (NEW in v0.6)
# ============================================================
class ShapleyEarlyStopping:
"""Early stopping for Shapley convergence using relative change."""
def __init__(self, patience: int = 10, tolerance: float = 0.01):
self.patience = patience
self.tolerance = tolerance
self.history = []
self.stable_count = 0
def update(self, shapley_estimates: np.ndarray, n_perms: int) -> Tuple[bool, Dict]:
if n_perms < 20:
return False, {'converged': False, 'n_permutations': n_perms}
self.history.append(shapley_estimates.copy())
if len(self.history) < 2:
return False, {'converged': False, 'n_permutations': n_perms}
old = self.history[-2]
new = self.history[-1]
denom = np.abs(old) + 1e-12
rel_change = np.abs(new - old) / denom
max_rel_change = np.max(rel_change)
mean_rel_change = np.mean(rel_change)
if mean_rel_change < self.tolerance:
self.stable_count += 1
else:
self.stable_count = 0
should_stop = self.stable_count >= self.patience
info = {
'converged': should_stop,
'n_permutations': n_perms,
'mean_rel_change': float(mean_rel_change),
'max_rel_change': float(max_rel_change),
'stable_iterations': self.stable_count
}
return should_stop, info
@jit(nopython=True, cache=True, fastmath=True)
def _compute_marginals_jit(
perm: np.ndarray,
values: np.ndarray,
n_samples: int,
n_features: int
) -> np.ndarray:
"""
JIT-compiled function to compute Shapley marginal contributions.
This is the performance-critical inner loop - compiled to machine code by Numba.
Parameters
----------
perm : array of sample indices in permutation order
values : array of value function results for each coalition size
n_samples : number of samples
n_features : number of features
Returns
-------
shapley_contrib : (n_samples, n_features) array of marginal contributions
"""
shapley_contrib = np.zeros((n_samples, n_features), dtype=np.float64)
for j in range(n_samples):
sample_idx = perm[j]
marginal = values[j+1] - values[j]
# Broadcast marginal across all features
for f in range(n_features):
shapley_contrib[sample_idx, f] = marginal / n_features
return shapley_contrib
@jit(nopython=True, cache=True, fastmath=True)
def _compute_feature_marginals_jit(
perm: np.ndarray,
values: np.ndarray,
n_features: int
) -> np.ndarray:
"""
JIT-compiled function to compute feature-level Shapley marginal contributions.
Parameters
----------
perm : array of feature indices in permutation order
values : array of value function results for each feature coalition size
n_features : number of features
Returns
-------
shapley_contrib : (n_features,) array of marginal contributions
"""
shapley_contrib = np.zeros(n_features, dtype=np.float64)
for j in range(n_features):
feat_idx = perm[j]
marginal = values[j+1] - values[j]
shapley_contrib[feat_idx] = marginal
return shapley_contrib
class ShapleySignificanceEngine:
"""
Compute Shapley values for dual-perspective significance analysis.
Supports two modes:
1. Explanations: Why is this sample archetypal/prototypical/stereotypical?
2. Formative: Which samples create the archetypal/prototypical/stereotypical structure?
"""
def __init__(
self,
n_permutations: int = 100,
random_state: int = 42,
n_jobs: int = -1,
early_stopping_patience: int = 10,
early_stopping_tolerance: float = 0.01,
verbose: bool = False
):
self.n_permutations = n_permutations
self.random_state = random_state
self.n_jobs = n_jobs
self.early_stopping_patience = early_stopping_patience
self.early_stopping_tolerance = early_stopping_tolerance
self.verbose = verbose
self.rng = np.random.RandomState(random_state)
def compute_shapley_values(
self,
X: np.ndarray,
value_function: Callable,
value_function_name: str = "unknown",
context: Optional[Dict] = None
) -> Tuple[np.ndarray, Dict]:
"""
Compute Shapley values using specified value function.
OPTIMIZED: Uses shared memory for parallel processing to avoid data copying.
MEMORY OPTIMIZED: Cleanup batch results immediately after accumulation.
"""
n_samples, n_features = X.shape
if self.verbose:
print(f"\n Computing {value_function_name}...")
print(f" Samples: {n_samples}, Features: {n_features}")
print(f" Max permutations: {self.n_permutations}")
early_stop = ShapleyEarlyStopping(
patience=self.early_stopping_patience,
tolerance=self.early_stopping_tolerance
)
shapley_sum = np.zeros((n_samples, n_features), dtype=np.float64)
n_perms_used = 0
batch_size = max(1, self.n_permutations // 10)
info = {'converged': False, 'mean_rel_change': 0.0}
# OPTIMIZED: Decide parallelization strategy based on data size
use_parallel = self.n_jobs != 1 and n_samples >= 20
# OPTIMIZED: For small datasets or single-threaded, use direct computation
if not use_parallel:
for batch_start in range(0, self.n_permutations, batch_size):
batch_end = min(batch_start + batch_size, self.n_permutations)
batch_perms = [self.rng.permutation(n_samples) for _ in range(batch_end - batch_start)]
for perm in batch_perms:
shapley_contrib = self._process_single_permutation(perm, X, value_function, context)
shapley_sum += shapley_contrib
n_perms_used += 1
# MEMORY CLEANUP: Free batch permutations immediately
_cleanup_memory(batch_perms)
current_estimate = shapley_sum / n_perms_used
should_stop, info = early_stop.update(current_estimate, n_perms_used)
if should_stop and n_perms_used >= 50:
if self.verbose:
print(f" Early stop at {n_perms_used} perms (change: {info['mean_rel_change']:.6f})")
break
else:
# OPTIMIZED: Use threading backend for better memory sharing
for batch_start in range(0, self.n_permutations, batch_size):
batch_end = min(batch_start + batch_size, self.n_permutations)
batch_perms = [self.rng.permutation(n_samples) for _ in range(batch_end - batch_start)]
# Use threading backend for shared memory access
batch_results = Parallel(
n_jobs=self.n_jobs,
backend='threading',
verbose=0
)(
delayed(self._process_single_permutation)(perm, X, value_function, context)
for perm in batch_perms
)
# Accumulate results efficiently
for shapley_contrib in batch_results:
shapley_sum += shapley_contrib
n_perms_used += 1
# MEMORY CLEANUP: Free batch results and permutations immediately
_cleanup_memory(batch_results, batch_perms)
current_estimate = shapley_sum / n_perms_used
should_stop, info = early_stop.update(current_estimate, n_perms_used)
if should_stop and n_perms_used >= 50:
if self.verbose:
print(f" Early stop at {n_perms_used} perms (change: {info['mean_rel_change']:.6f})")
break
Phi = shapley_sum / n_perms_used
# Verify additivity
all_indices = np.arange(n_samples)
if context is not None:
total_actual = value_function(X, all_indices, context)
else:
total_actual = value_function(X, all_indices)
total_from_shapley = np.sum(Phi)
additivity_error = abs(total_from_shapley - total_actual) / (abs(total_actual) + 1e-12)
info = {
'n_permutations_used': n_perms_used,
'converged': info.get('converged', False) if n_perms_used < self.n_permutations else True,
'mean_rel_change': info.get('mean_rel_change', 0.0),
'additivity_error': float(additivity_error),
'total_shapley': float(total_from_shapley),
'total_actual': float(total_actual)
}
if self.verbose:
print(f" ✓ {n_perms_used} perms, additivity error: {additivity_error:.6f}")
# MEMORY CLEANUP: Free shapley_sum before returning Phi (they're different objects)
_cleanup_memory(shapley_sum)
return Phi, info
def compute_feature_shapley_values(
self,
X: np.ndarray,
value_function: Callable,
value_function_name: str = "unknown",
context: Optional[Dict] = None
) -> Tuple[np.ndarray, Dict]:
"""
Compute feature-level Shapley values for each sample.
OPTIMIZED: Uses threading backend for better memory sharing.
"""
n_samples, n_features = X.shape
if self.verbose:
print(f"\n Computing feature-level {value_function_name}...")
print(f" Samples: {n_samples}, Features: {n_features}")
print(f" Max permutations: {self.n_permutations}")
early_stop = ShapleyEarlyStopping(
patience=self.early_stopping_patience,
tolerance=self.early_stopping_tolerance
)
shapley_sum = np.zeros((n_samples, n_features), dtype=np.float64)
n_perms_used = 0
batch_size = max(1, self.n_permutations // 10)
info = {'converged': False, 'mean_rel_change': 0.0}
# OPTIMIZED: Decide parallelization strategy
use_parallel = self.n_jobs != 1 and n_features >= 10
for batch_start in range(0, self.n_permutations, batch_size):
batch_end = min(batch_start + batch_size, self.n_permutations)
# Generate feature permutations for this batch
batch_perms = [self.rng.permutation(n_features) for _ in range(batch_end - batch_start)]
# Process each sample
for sample_idx in range(n_samples):
if use_parallel:
# OPTIMIZED: Threading backend for memory sharing
batch_results = Parallel(
n_jobs=self.n_jobs,
backend='threading',
verbose=0
)(
delayed(self._process_feature_permutation)(
sample_idx, perm, X, value_function, value_function_name, context
)
for perm in batch_perms
)
else:
# Direct computation for small problems
batch_results = [
self._process_feature_permutation(
sample_idx, perm, X, value_function, value_function_name, context
)
for perm in batch_perms
]
for shapley_contrib in batch_results:
shapley_sum[sample_idx, :] += shapley_contrib
n_perms_used += len(batch_perms)
current_estimate = shapley_sum / n_perms_used
should_stop, info = early_stop.update(current_estimate, n_perms_used)
if should_stop and n_perms_used >= 50:
if self.verbose:
print(f" Early stop at {n_perms_used} perms (change: {info['mean_rel_change']:.6f})")
break
Phi = shapley_sum / n_perms_used
# Compute additivity error
total_errors = []
for sample_idx in range(n_samples):
shapley_total = np.sum(Phi[sample_idx, :])
if context is not None:
actual_value = value_function(X[sample_idx:sample_idx+1, :], np.array([sample_idx]), context)
else:
actual_value = value_function(X[sample_idx:sample_idx+1, :], np.array([sample_idx]))
error = abs(shapley_total - actual_value) / (abs(actual_value) + 1e-12)
total_errors.append(error)
additivity_error = np.mean(total_errors)
info_out = {
'n_permutations_used': n_perms_used,
'converged': info.get('converged', False) if n_perms_used < self.n_permutations else True,
'mean_rel_change': info.get('mean_rel_change', 0.0),
'additivity_error': float(additivity_error)
}
if self.verbose:
print(f" {n_perms_used} perms, mean additivity error: {additivity_error:.6f}")
return Phi, info_out
def _process_single_permutation(
self,
perm: np.ndarray,
X: np.ndarray,
value_function: Callable,
context: Optional[Dict]
) -> np.ndarray:
"""
Process one permutation to compute marginal contributions.
OPTIMIZED: Delegates to JIT-compiled helper for massive speedup.
"""
n_samples, n_features = X.shape
shapley_contrib = np.zeros((n_samples, n_features), dtype=np.float64)
# Compute all value function calls first (can't JIT this part due to callable)
values = np.zeros(n_samples + 1, dtype=np.float64)
values[0] = 0.0
for j in range(n_samples):
subset_indices = perm[:j+1]
X_subset = X[subset_indices]
if context is not None:
values[j+1] = value_function(X_subset, subset_indices, context)
else:
values[j+1] = value_function(X_subset, subset_indices)
# Now use JIT-compiled function to compute marginal contributions
shapley_contrib = _compute_marginals_jit(perm, values, n_samples, n_features)
return shapley_contrib
def _process_feature_permutation(
self,
sample_idx: int,
perm: np.ndarray,
X: np.ndarray,