HarriziSaad commited on
Commit
0f36fe3
·
verified ·
1 Parent(s): e623c6b

Update src/utils/reproducibility.py

Browse files
Files changed (1) hide show
  1. src/utils/reproducibility.py +2 -16
src/utils/reproducibility.py CHANGED
@@ -1,4 +1,3 @@
1
- # === 00) Reproducibility: global seeds & deterministic ops ===
2
  def set_seed(seed: int = 1337):
3
  import os, random, numpy as np
4
  os.environ["PYTHONHASHSEED"] = str(seed)
@@ -17,17 +16,12 @@ def set_seed(seed: int = 1337):
17
  print(f"[seed] set to {seed}")
18
  set_seed(1337)
19
 
20
- # === 01) Grouped CV (by ligand or transporter) ===
21
  from sklearn.model_selection import StratifiedGroupKFold
22
 
23
  def make_grouped_cv(n_splits=5, seed=1337):
24
  return StratifiedGroupKFold(n_splits=n_splits, shuffle=True, random_state=seed)
25
 
26
- # Example placeholders (replace with your arrays/Series):
27
- # groups = ligand_ids # or transporter_ids
28
- # cv = make_grouped_cv()
29
 
30
- # === 02) Leakage-safe pipeline (scaler inside Pipeline) + ΔAUPRC evaluation ===
31
  import numpy as np
32
  from sklearn.pipeline import Pipeline
33
  from sklearn.preprocessing import StandardScaler
@@ -49,8 +43,6 @@ def eval_auprc_grouped(X, y, groups, cv=None, estimator=None):
49
  print(f"[AUPRC] {auprc:.4f} | baseline={base:.4f} | Δ={auprc-base:.4f}")
50
  return prob, auprc, base
51
 
52
- # === 03) CV-safe probability calibration helper ===
53
- # NOTE: sklearn's CalibratedClassifierCV ignores 'groups' directly; do manual fold loop for true group-aware calibration.
54
  from sklearn.calibration import calibration_curve
55
  from sklearn.base import clone
56
 
@@ -67,7 +59,6 @@ def cv_calibrated_probs(estimator, X, y, groups, cv=None, method="isotonic"):
67
  proba[test_idx] = cal.predict_proba(X[test_idx])[:,1]
68
  return proba
69
 
70
- # === 04) Active Learning logging utilities ===
71
  import pandas as pd, os, numpy as np
72
  from pathlib import Path
73
 
@@ -84,30 +75,25 @@ def al_log_round(round_id, acquired_idx, scores, y_true, pool_size):
84
  df.to_csv(out, index=False)
85
  print(f"[AL] wrote {out} (pool={pool_size}, acquired={len(acquired_idx)})")
86
 
87
- # === 05) Domain Generalization baseline placeholders (GroupDRO / CORAL) ===
88
- # Minimal CORAL regularizer for linear/MLP torch models; for sklearn, emulate via feature alignment preproc.
89
  def coral_penalty(source, target):
90
  import torch
91
  cs = torch.cov(source.T) if source.ndim==2 else torch.cov(source)
92
  ct = torch.cov(target.T) if target.ndim==2 else torch.cov(target)
93
  return torch.norm(cs - ct, p='fro')
94
 
95
- # GroupDRO would require per-group weighting; keep an interface for later plug-in.
96
  class GroupDROWrapper:
97
  def __init__(self, base_estimator):
98
  self.base = base_estimator
99
  def fit(self, X, y, groups):
100
- # TODO: implement group-wise reweighting loop
101
  return self.base.fit(X, y)
102
  def predict_proba(self, X):
103
  return self.base.predict_proba(X)
104
 
105
- # === 07) Runtime leak check helper ===
106
  def check_scaler_leakage(estimator):
107
  from sklearn.pipeline import Pipeline
108
  ok = isinstance(estimator, Pipeline) and any(hasattr(s, "transform") and s.__class__.__name__.endswith("Scaler")
109
  for _, s in estimator.steps[:-1])
110
  if not ok:
111
- print("⚠️ Potential leakage: estimator is not a Pipeline with scaler → classifier.")
112
  else:
113
- print(" Leakage-safe pipeline detected.")
 
 
1
  def set_seed(seed: int = 1337):
2
  import os, random, numpy as np
3
  os.environ["PYTHONHASHSEED"] = str(seed)
 
16
  print(f"[seed] set to {seed}")
17
  set_seed(1337)
18
 
 
19
  from sklearn.model_selection import StratifiedGroupKFold
20
 
21
  def make_grouped_cv(n_splits=5, seed=1337):
22
  return StratifiedGroupKFold(n_splits=n_splits, shuffle=True, random_state=seed)
23
 
 
 
 
24
 
 
25
  import numpy as np
26
  from sklearn.pipeline import Pipeline
27
  from sklearn.preprocessing import StandardScaler
 
43
  print(f"[AUPRC] {auprc:.4f} | baseline={base:.4f} | Δ={auprc-base:.4f}")
44
  return prob, auprc, base
45
 
 
 
46
  from sklearn.calibration import calibration_curve
47
  from sklearn.base import clone
48
 
 
59
  proba[test_idx] = cal.predict_proba(X[test_idx])[:,1]
60
  return proba
61
 
 
62
  import pandas as pd, os, numpy as np
63
  from pathlib import Path
64
 
 
75
  df.to_csv(out, index=False)
76
  print(f"[AL] wrote {out} (pool={pool_size}, acquired={len(acquired_idx)})")
77
 
 
 
78
  def coral_penalty(source, target):
79
  import torch
80
  cs = torch.cov(source.T) if source.ndim==2 else torch.cov(source)
81
  ct = torch.cov(target.T) if target.ndim==2 else torch.cov(target)
82
  return torch.norm(cs - ct, p='fro')
83
 
 
84
  class GroupDROWrapper:
85
  def __init__(self, base_estimator):
86
  self.base = base_estimator
87
  def fit(self, X, y, groups):
 
88
  return self.base.fit(X, y)
89
  def predict_proba(self, X):
90
  return self.base.predict_proba(X)
91
 
 
92
  def check_scaler_leakage(estimator):
93
  from sklearn.pipeline import Pipeline
94
  ok = isinstance(estimator, Pipeline) and any(hasattr(s, "transform") and s.__class__.__name__.endswith("Scaler")
95
  for _, s in estimator.steps[:-1])
96
  if not ok:
97
+ print(" Potential leakage: estimator is not a Pipeline with scaler → classifier.")
98
  else:
99
+ print(" Leakage-safe pipeline detected.")