itr-methods 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.
Files changed (35) hide show
  1. itr_methods/__init__.py +31 -0
  2. itr_methods/__main__.py +2 -0
  3. itr_methods/_nscf/__init__.py +6 -0
  4. itr_methods/_nscf/api.py +536 -0
  5. itr_methods/_nscf/core/__init__.py +1 -0
  6. itr_methods/_nscf/core/audit_hooks.py +8 -0
  7. itr_methods/_nscf/core/config.py +240 -0
  8. itr_methods/_nscf/core/fusion_solver.py +94 -0
  9. itr_methods/_nscf/core/model.py +132 -0
  10. itr_methods/_nscf/core/penalty.py +100 -0
  11. itr_methods/_nscf/core/refit_selection.py +806 -0
  12. itr_methods/_nscf/core/solver_admm.py +279 -0
  13. itr_methods/_nscf/core/solver_alt.py +881 -0
  14. itr_methods/_nscf/core/trainer.py +309 -0
  15. itr_methods/_nscf/defaults.json +70 -0
  16. itr_methods/_nscf/estimator.py +267 -0
  17. itr_methods/_nscf/exact_prox.py +56 -0
  18. itr_methods/_validation.py +53 -0
  19. itr_methods/doctor.py +35 -0
  20. itr_methods/plotting.py +169 -0
  21. itr_methods/scaf/__init__.py +678 -0
  22. itr_methods/scaf/_solver.py +159 -0
  23. itr_methods-0.1.0.data/data/share/itr_methods/README.md +321 -0
  24. itr_methods-0.1.0.data/data/share/itr_methods/docs/NSCF_TUTORIAL.ipynb +1500 -0
  25. itr_methods-0.1.0.data/data/share/itr_methods/docs/SCAF_TUTORIAL.ipynb +1408 -0
  26. itr_methods-0.1.0.data/data/share/itr_methods/examples/nscf_dendrogram_figure.py +75 -0
  27. itr_methods-0.1.0.data/data/share/itr_methods/examples/quickstart.py +38 -0
  28. itr_methods-0.1.0.data/data/share/itr_methods/examples/scaf_path_figure.py +56 -0
  29. itr_methods-0.1.0.dist-info/METADATA +347 -0
  30. itr_methods-0.1.0.dist-info/RECORD +35 -0
  31. itr_methods-0.1.0.dist-info/WHEEL +5 -0
  32. itr_methods-0.1.0.dist-info/entry_points.txt +2 -0
  33. itr_methods-0.1.0.dist-info/licenses/LICENSE +408 -0
  34. itr_methods-0.1.0.dist-info/licenses/NOTICE.txt +24 -0
  35. itr_methods-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,31 @@
1
+ """Python treatment-policy interfaces for SCAF and NSCF."""
2
+
3
+ from importlib.util import find_spec as _find_spec
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["SCAF"]
7
+ if _find_spec("torch") is not None:
8
+ __all__.append("NSCF")
9
+
10
+
11
+ def __dir__():
12
+ return sorted(set(globals()) | {"SCAF", "NSCF"})
13
+
14
+
15
+ def __getattr__(name):
16
+ if name == "SCAF":
17
+ from .scaf import SCAF
18
+
19
+ return SCAF
20
+ if name == "NSCF":
21
+ try:
22
+ from ._nscf import NSCF
23
+ except ModuleNotFoundError as exc:
24
+ if exc.name == "torch":
25
+ raise ImportError(
26
+ 'NSCF requires PyTorch. Install it in this Python environment '
27
+ 'with: python -m pip install "torch>=2.7".'
28
+ ) from exc
29
+ raise
30
+ return NSCF
31
+ raise AttributeError(name)
@@ -0,0 +1,2 @@
1
+ from .doctor import main
2
+ main()
@@ -0,0 +1,6 @@
1
+ """NSCF treatment-partition discovery and neural treatment policies."""
2
+ from .. import __version__
3
+ from .api import NSCF
4
+ from .estimator import make_anchor, train_anchor
5
+
6
+ __all__ = ["NSCF", "make_anchor", "train_anchor", "__version__"]
@@ -0,0 +1,536 @@
1
+ """Scikit-learn-style treatment-policy interface; CPU execution only."""
2
+ from collections.abc import Mapping
3
+ from numbers import Integral, Real
4
+ import secrets
5
+ import warnings
6
+
7
+ import numpy as np
8
+ from sklearn.base import BaseEstimator
9
+ from sklearn.model_selection import train_test_split
10
+ from sklearn.preprocessing import StandardScaler
11
+ from sklearn.utils.validation import check_array, check_is_fitted
12
+
13
+ from .._validation import check_feature_names, feature_names, treatment_labels
14
+ from .estimator import _arguments, _Discovery, make_anchor, train_anchor
15
+
16
+
17
+ def _features(X):
18
+ return check_array(X, dtype=np.float32, ensure_all_finite=True, copy=True)
19
+
20
+
21
+ def _outcomes(y, n, *, dtype=np.float32):
22
+ y = check_array(y, ensure_2d=False, dtype=dtype, ensure_all_finite=True)
23
+ if y.ndim != 1 or len(y) != n:
24
+ raise ValueError("y must be a one-dimensional outcome array aligned with X")
25
+ return y.copy()
26
+
27
+
28
+ def _encode(labels, treatments):
29
+ mapping = {value: i for i, value in enumerate(treatments)}
30
+ try:
31
+ return np.asarray([mapping[value] for value in labels], dtype=np.int64)
32
+ except KeyError as exc:
33
+ raise ValueError(f"Unknown treatment label: {exc.args[0]!r}") from None
34
+
35
+
36
+ class NSCF(BaseEstimator):
37
+ """Discover treatment-sharing groups and a neural treatment policy.
38
+
39
+ Ordinary fitting trains an unfused anchor, discovers treatment partitions,
40
+ and retains the selected grouped predictor. Named arguments override
41
+ matching config entries. Arguments with default None inherit the discovery
42
+ defaults or the corresponding config values.
43
+
44
+ Parameters
45
+ ----------
46
+ config : mapping or None, default=None
47
+ Advanced overrides for the discovery configuration.
48
+ hidden_layer_sizes : tuple of int or None, default=None
49
+ Widths of the one or two hidden layers. The default widths are 192 and 96.
50
+ dropout : float or None, default=None
51
+ Dropout probability in [0, 1). The default probability is 0.1.
52
+ pretrain_epochs : int or None, default=None
53
+ Epoch cap for training the unfused anchor.
54
+ max_cycles : int or None, default=None
55
+ Maximum number of alternating discovery cycles.
56
+ num_lambdas : int or None, default=None
57
+ Number of fusion penalties in the path, including zero.
58
+ max_lambda : float or None, default=None
59
+ Endpoint of the positive fusion penalty grid.
60
+ admm_epochs : int or None, default=None
61
+ Maximum ADMM iterations per penalty.
62
+ theta_steps : int or None, default=None
63
+ Gradient steps in each ADMM coefficient update.
64
+ refit_epochs : int or None, default=None
65
+ Epoch cap for refitting each candidate grouped predictor.
66
+ patience : int or None, default=None
67
+ Early-stopping patience for validation-based training.
68
+ eval_every : int or None, default=None
69
+ Training epochs between validation evaluations.
70
+ learning_rate : float or None, default=None
71
+ Anchor training learning rate.
72
+ weight_decay : float or None, default=None
73
+ Anchor training weight decay.
74
+ refit_learning_rate : float or None, default=None
75
+ Learning rate for the grouped refit.
76
+ refit_weight_decay : float or None, default=None
77
+ Weight decay for the grouped refit.
78
+ rho : float or None, default=None
79
+ ADMM augmented-Lagrangian penalty.
80
+ random_state : int or None, default=None
81
+ Seed in [0, 2**32). When None, ordinary fit uses config's seed if
82
+ supplied and otherwise draws one. Anchor replay uses the historical
83
+ default seed when neither is supplied.
84
+ validation_fraction : float, default=0.2
85
+ Fraction held out for validation when no validation tuple is supplied.
86
+ standardize : bool, default=True
87
+ Standardize features using statistics from the fitting subset.
88
+ standardize_outcome : bool, default=False
89
+ Center and scale outcomes using the fitting subset in fit. Apply the
90
+ same transformation to validation outcomes and return predictions in
91
+ the original units. The default preserves the original fitting scale.
92
+ This option does not apply to fit_from_anchor.
93
+ outcome_direction : {'maximize', 'minimize'}, default='maximize'
94
+ Direction for treatment recommendations.
95
+ verbose : bool or {0, 1}, default=False
96
+ Print progress during fitting when True or 1. An explicit log callback takes
97
+ precedence in fit_from_anchor.
98
+
99
+ Attributes
100
+ ----------
101
+ treatments_ : ndarray of shape (n_treatments,)
102
+ Original treatment labels in prediction-column order.
103
+ group_ids_ : ndarray of shape (n_treatments,)
104
+ Discovered group IDs aligned with treatments_.
105
+ n_groups_ : int
106
+ Number of discovered treatment groups.
107
+ model_ : torch.nn.Module
108
+ Selected grouped predictor.
109
+ n_features_in_ : int
110
+ Number of input features.
111
+ n_actions_ : int
112
+ Number of observed training treatments.
113
+ scaler_ : sklearn.preprocessing.StandardScaler or None
114
+ Fitted training scaler, when used.
115
+ outcome_scaler_ : sklearn.preprocessing.StandardScaler or None
116
+ Fitted outcome scaler, when used. When present, model_ operates in
117
+ standardized units and the prediction methods return original units.
118
+ config_ : dict
119
+ Resolved configuration for the fitted model.
120
+ random_state_ : int
121
+ Effective seed used for fitting.
122
+ train_indices_, validation_indices_ : ndarray or None
123
+ Row indices for the corresponding subsets of X when available.
124
+ diagnostics_ : dict
125
+ Validation metrics, candidate selection details and fit provenance.
126
+ fusion_path_ : dict
127
+ The selected discovery cycle, zero-based selected_index, selected_lambda,
128
+ evaluated fusion_lambdas, group_ids and validation_mse. Each row of
129
+ group_ids follows treatments_ order. The validation_mse array stores
130
+ the grouped refit score used to compare candidates, in the squared
131
+ units of the outcomes supplied to fit or fit_from_anchor.
132
+ """
133
+
134
+ def __init__(self, config=None, *, hidden_layer_sizes=None, dropout=None,
135
+ pretrain_epochs=None, max_cycles=None, num_lambdas=None,
136
+ max_lambda=None, admm_epochs=None, theta_steps=None,
137
+ refit_epochs=None, patience=None, eval_every=None,
138
+ learning_rate=None, weight_decay=None, refit_learning_rate=None,
139
+ refit_weight_decay=None, rho=None, random_state=None,
140
+ validation_fraction=0.2, standardize=True,
141
+ standardize_outcome=False, outcome_direction="maximize",
142
+ verbose=False):
143
+ # Do not copy or validate constructor parameters: sklearn.clone relies
144
+ # on their identity. Resolve/validate them only when fitting.
145
+ self.config = config
146
+ self.hidden_layer_sizes = hidden_layer_sizes
147
+ self.dropout = dropout
148
+ self.pretrain_epochs = pretrain_epochs
149
+ self.max_cycles = max_cycles
150
+ self.num_lambdas = num_lambdas
151
+ self.max_lambda = max_lambda
152
+ self.admm_epochs = admm_epochs
153
+ self.theta_steps = theta_steps
154
+ self.refit_epochs = refit_epochs
155
+ self.patience = patience
156
+ self.eval_every = eval_every
157
+ self.learning_rate = learning_rate
158
+ self.weight_decay = weight_decay
159
+ self.refit_learning_rate = refit_learning_rate
160
+ self.refit_weight_decay = refit_weight_decay
161
+ self.rho = rho
162
+ self.random_state = random_state
163
+ self.validation_fraction = validation_fraction
164
+ self.standardize = standardize
165
+ self.standardize_outcome = standardize_outcome
166
+ self.outcome_direction = outcome_direction
167
+ self.verbose = verbose
168
+
169
+ def __setstate__(self, state):
170
+ state.setdefault("standardize_outcome", False)
171
+ if "model_" in state:
172
+ state.setdefault("outcome_scaler_", None)
173
+ super().__setstate__(state)
174
+
175
+ def _clear_fit(self):
176
+ for name in list(vars(self)):
177
+ if name.endswith("_"):
178
+ delattr(self, name)
179
+
180
+ def _configuration(self, *, from_anchor=False):
181
+ if self.config is not None and not isinstance(self.config, Mapping):
182
+ raise ValueError("config must be a mapping or None")
183
+ values = dict(self.config or {})
184
+ mapping = {
185
+ "dropout": "dropout", "pretrain_epochs": "train_epochs",
186
+ "max_cycles": "alt_cycles", "num_lambdas": "num_lambda",
187
+ "max_lambda": "max_lambda", "admm_epochs": "admm_epochs",
188
+ "theta_steps": "theta_steps", "refit_epochs": "refit_select_epochs",
189
+ "patience": "patience", "eval_every": "eval_every",
190
+ "learning_rate": "train_lr", "weight_decay": "train_wd",
191
+ "refit_learning_rate": "refit_select_lr",
192
+ "refit_weight_decay": "refit_select_wd", "rho": "rho",
193
+ }
194
+ for name, key in mapping.items():
195
+ if getattr(self, name) is not None:
196
+ values[key] = getattr(self, name)
197
+ if self.hidden_layer_sizes is not None:
198
+ sizes = self.hidden_layer_sizes
199
+ if (
200
+ not isinstance(sizes, (tuple, list))
201
+ or len(sizes) not in (1, 2)
202
+ or any(
203
+ isinstance(size, (bool, np.bool_)) or not isinstance(size, Integral) or size < 1
204
+ for size in sizes
205
+ )
206
+ ):
207
+ raise ValueError("hidden_layer_sizes must contain one or two positive integers")
208
+ values.update(n_hidden_layers=len(sizes), hidden1=sizes[0], hidden2=sizes[-1])
209
+ if self.random_state is not None:
210
+ values["global_seed"] = self.random_state
211
+ elif not from_anchor and "global_seed" not in values:
212
+ values["global_seed"] = secrets.randbits(32)
213
+ try:
214
+ args = _arguments(values)
215
+ except (TypeError, OverflowError) as exc:
216
+ raise ValueError("Invalid numeric configuration; check epochs, lambda grid and rho") from exc
217
+ for key in ("train_epochs", "alt_cycles", "num_lambda", "admm_epochs",
218
+ "theta_steps", "refit_select_epochs", "patience", "eval_every",
219
+ "hidden1", "hidden2", "n_hidden_layers"):
220
+ self._positive_integer(key, getattr(args, key))
221
+ if args.n_hidden_layers not in (1, 2):
222
+ raise ValueError("n_hidden_layers must be 1 or 2")
223
+ for key in ("train_lr", "refit_select_lr", "rho", "max_lambda"):
224
+ self._finite_real(key, getattr(args, key), strictly_positive=True)
225
+ for key in ("train_wd", "refit_select_wd"):
226
+ self._finite_real(key, getattr(args, key))
227
+ self._finite_real("dropout", args.dropout)
228
+ if args.dropout >= 1:
229
+ raise ValueError("dropout must be in [0, 1)")
230
+ if (isinstance(args.global_seed, (bool, np.bool_)) or
231
+ not isinstance(args.global_seed, Integral) or
232
+ not 0 <= args.global_seed < 2**32):
233
+ raise ValueError("random_state/global_seed must be an integer in [0, 2**32)")
234
+ if self.outcome_direction not in ("maximize", "minimize"):
235
+ raise ValueError("outcome_direction must be 'maximize' or 'minimize'")
236
+ if not isinstance(self.standardize, (bool, np.bool_)):
237
+ raise ValueError("standardize must be boolean")
238
+ if not isinstance(self.standardize_outcome, (bool, np.bool_)):
239
+ raise ValueError("standardize_outcome must be boolean")
240
+ if not (isinstance(self.verbose, (bool, np.bool_))
241
+ or (isinstance(self.verbose, Integral) and self.verbose in (0, 1))):
242
+ raise ValueError("verbose must be a boolean or the integer 0 or 1")
243
+ return vars(args).copy()
244
+
245
+ @staticmethod
246
+ def _positive_integer(name, value):
247
+ if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral) or value < 1:
248
+ raise ValueError(f"{name} must be a positive integer")
249
+
250
+ @staticmethod
251
+ def _finite_real(name, value, strictly_positive=False):
252
+ if (isinstance(value, (bool, np.bool_)) or not isinstance(value, Real) or
253
+ not np.isfinite(value) or value < 0 or (strictly_positive and value == 0)):
254
+ qualifier = "positive" if strictly_positive else "nonnegative"
255
+ raise ValueError(f"{name} must be a finite {qualifier} number")
256
+
257
+ def _adopt(self, discovery, config, treatments, scaler, names):
258
+ for name in ("model_", "group_ids_", "n_features_in_", "n_actions_", "diagnostics_", "fusion_path_"):
259
+ setattr(self, name, getattr(discovery, name))
260
+ self.treatments_ = treatments.copy()
261
+ self.n_groups_ = len(np.unique(self.group_ids_))
262
+ self.scaler_ = scaler
263
+ self.config_ = config
264
+ self.random_state_ = int(config["global_seed"])
265
+ self.outcome_direction_ = self.outcome_direction
266
+ if names is not None:
267
+ self.feature_names_in_ = names.copy()
268
+
269
+ def fit(self, X, y, *, treatment, validation_data=None):
270
+ """Fit an NSCF model from observed outcomes.
271
+
272
+ Parameters
273
+ ----------
274
+ X : array-like of shape (n_samples, n_features)
275
+ Finite numeric training covariates.
276
+ y : array-like of shape (n_samples,)
277
+ Finite observed outcomes.
278
+ treatment : array-like of shape (n_samples,)
279
+ Observed labels with at least two treatments. Use either integers or
280
+ nonempty strings throughout.
281
+ validation_data : tuple of array-like or None, default=None
282
+ Independent (X_val, y_val, treatment_val) in that order. When None,
283
+ split the supplied rows by treatment. Supply subject-disjoint
284
+ validation data when observations are repeated within subjects.
285
+
286
+ Returns
287
+ -------
288
+ self : NSCF
289
+ Fitted estimator with the validation-selected model. Scaling uses
290
+ only the fitting subset, and the model is retained without refitting
291
+ on the combined training and validation data.
292
+ """
293
+ self._clear_fit()
294
+ config = self._configuration()
295
+ names = feature_names(X)
296
+ X = _features(X)
297
+ # Preserve input precision until any unit conversion is complete.
298
+ outcome_dtype = np.float64 if self.standardize_outcome else np.float32
299
+ y = _outcomes(y, len(X), dtype=outcome_dtype)
300
+ labels = treatment_labels(treatment, len(X))
301
+ treatments, A = np.unique(labels, return_inverse=True)
302
+ if len(treatments) < 2:
303
+ raise ValueError("Training requires at least two treatments")
304
+ indices = np.arange(len(X))
305
+ if validation_data is None:
306
+ fraction = self.validation_fraction
307
+ if (isinstance(fraction, (bool, np.bool_)) or not isinstance(fraction, Real) or
308
+ not np.isfinite(fraction) or not 0 < fraction < 1):
309
+ raise ValueError("validation_fraction must be a finite number in (0, 1)")
310
+ counts = np.bincount(A)
311
+ if counts.min() < 2:
312
+ raise ValueError("Automatic splitting needs at least two observations per treatment; supply independent validation_data")
313
+ try:
314
+ itrain, ival = train_test_split(indices, test_size=fraction,
315
+ stratify=A, random_state=int(config["global_seed"]))
316
+ except ValueError as exc:
317
+ raise ValueError("Cannot make a stratified train/validation split; increase sample size, adjust validation_fraction, or supply validation_data") from exc
318
+ if len(np.unique(A[itrain])) != len(treatments) or len(np.unique(A[ival])) != len(treatments):
319
+ raise ValueError("Every treatment must occur in both automatic subsets; supply validation_data or increase sample size")
320
+ xt, at, yt = X[itrain], A[itrain], y[itrain]
321
+ xv, av, yv = X[ival], A[ival], y[ival]
322
+ else:
323
+ validation_context = "Invalid validation_data (expected (X_val, y_val, treatment_val))"
324
+ if not isinstance(validation_data, (tuple, list)) or len(validation_data) != 3:
325
+ raise ValueError(validation_context)
326
+ xv, yv, av = validation_data
327
+ check_feature_names(xv, names)
328
+ try:
329
+ xv = _features(xv)
330
+ if xv.shape[1] != X.shape[1]:
331
+ raise ValueError("Validation features must match the training feature dimension")
332
+ yv = _outcomes(yv, len(xv), dtype=outcome_dtype)
333
+ av = _encode(treatment_labels(av, len(xv)), treatments)
334
+ except (TypeError, ValueError) as exc:
335
+ raise ValueError(f"{validation_context}: {exc}") from exc
336
+ if len(np.unique(av)) != len(treatments):
337
+ warnings.warn("Validation data omits some training treatments; model selection may be poorly supported for those arms", UserWarning)
338
+ xt, at, yt = X, A, y
339
+ itrain, ival = indices, None
340
+ scaler = StandardScaler().fit(xt) if self.standardize else None
341
+ if scaler is not None:
342
+ xt, xv = scaler.transform(xt), scaler.transform(xv)
343
+ outcome_scaler = None
344
+ if self.standardize_outcome:
345
+ outcome_scaler = StandardScaler().fit(yt[:, None])
346
+ yt = outcome_scaler.transform(yt[:, None]).ravel()
347
+ yv = outcome_scaler.transform(yv[:, None]).ravel()
348
+ config.update(n_features=X.shape[1], n_actions=len(treatments),
349
+ n_train=len(xt), n_val=len(xv), use_baseline=True)
350
+ anchor = make_anchor(X.shape[1], len(treatments), hidden1=config["hidden1"],
351
+ hidden2=config["hidden2"], dropout=config["dropout"],
352
+ n_hidden_layers=config["n_hidden_layers"], seed=int(config["global_seed"]))
353
+ log_fn = print if self.verbose else None
354
+ anchor = train_anchor(anchor, xt, at, yt, xv, av, yv, config=config, log_fn=log_fn)
355
+ discovery = _Discovery(config).fit_from_anchor(anchor, xt, at, yt, xv, av, yv, log_fn=log_fn)
356
+ self._adopt(discovery, config, treatments, scaler, names)
357
+ self.outcome_scaler_ = outcome_scaler
358
+ if outcome_scaler is not None:
359
+ mse_factor = float(outcome_scaler.scale_[0]) ** 2
360
+ self.diagnostics_["anchor_validation_mse"] *= mse_factor
361
+ self.diagnostics_["validation_mse"] *= mse_factor
362
+ for cycle in self.diagnostics_["cycles"]:
363
+ cycle["validation_mse"] *= mse_factor
364
+ self.fusion_path_["validation_mse"] *= mse_factor
365
+ self.train_indices_, self.validation_indices_ = itrain.copy(), None if ival is None else ival.copy()
366
+ self.diagnostics_.update(entry_point="fit", initialization="fixed_epoch_cap",
367
+ n_train=len(xt), n_validation=len(xv),
368
+ validation_source="explicit" if validation_data is not None else "internal",
369
+ standardized=bool(self.standardize), random_state=self.random_state_)
370
+ return self
371
+
372
+ def fit_from_anchor(self, anchor, X, A, y, X_val, A_val, y_val, *, rng_state=None, log_fn=None):
373
+ """Discover treatment groups from an already fitted unfused anchor.
374
+
375
+ Parameters
376
+ ----------
377
+ anchor : torch.nn.Module
378
+ Unfused NSCF Net whose architecture and treatment order define the fit.
379
+ X, X_val : array-like of shape (n_samples, n_features)
380
+ Training and validation features in the anchor's feature space.
381
+ A, A_val : array-like of shape (n_samples,)
382
+ Integer treatment indices in the anchor's embedding order, starting
383
+ at zero. Every treatment must occur in training.
384
+ y, y_val : array-like of shape (n_samples,)
385
+ Training and validation observed outcomes in the anchor's outcome units.
386
+ rng_state : dict or None, default=None
387
+ Optional replay state with python_rng_state, numpy_rng_state and
388
+ torch_rng_state entries.
389
+ log_fn : callable or None, default=None
390
+ Optional callback accepting the discovery routine's log arguments.
391
+
392
+ Returns
393
+ -------
394
+ self : NSCF
395
+ Fitted estimator. This entry point uses the supplied arrays as-is
396
+ without splitting or standardizing them.
397
+ """
398
+ self._clear_fit()
399
+ config = self._configuration(from_anchor=True)
400
+ names = feature_names(X)
401
+ check_feature_names(X_val, names)
402
+ if log_fn is None and self.verbose:
403
+ log_fn = print
404
+ discovery = _Discovery(config).fit_from_anchor(anchor, X, A, y, X_val, A_val, y_val,
405
+ rng_state=rng_state, log_fn=log_fn)
406
+ # Record the actual supplied architecture, not ignored convenience defaults.
407
+ config.update(n_features=discovery.n_features_in_, n_actions=discovery.n_actions_,
408
+ n_train=len(X), n_val=len(X_val),
409
+ hidden1=anchor.fc1.out_features, hidden2=anchor.feature_dim,
410
+ n_hidden_layers=anchor.n_hidden_layers, dropout=anchor.dropout.p,
411
+ use_baseline=anchor.use_baseline)
412
+ self._adopt(discovery, config, np.arange(discovery.n_actions_), None, names)
413
+ self.outcome_scaler_ = None
414
+ self.train_indices_, self.validation_indices_ = None, None
415
+ self.diagnostics_.update(entry_point="fit_from_anchor", initialization="supplied_anchor",
416
+ n_train=len(X), n_validation=len(X_val), validation_source="explicit",
417
+ standardized=False, rng_state_supplied=rng_state is not None,
418
+ random_state=self.random_state_)
419
+ return self
420
+
421
+ def plot_fusion_dendrogram(self, *, true_groups=None, ax=None):
422
+ """Plot a dendrogram of the selected discovery cycle's fusion path.
423
+
424
+ Parameters
425
+ ----------
426
+ true_groups : array-like of shape (n_treatments,), optional
427
+ Reference labels for coloring branches, in treatments_ order.
428
+ ax : matplotlib.axes.Axes, optional
429
+ Target axes. Create new axes when omitted.
430
+
431
+ Returns
432
+ -------
433
+ matplotlib.axes.Axes
434
+ Dendrogram of the nested prefix, with heights log(1 + 1000 * lambda)
435
+ at recorded merges. The first split is annotated when present.
436
+ The validation-selected penalty is marked when it lies in the
437
+ plotted prefix.
438
+
439
+ Raises
440
+ ------
441
+ ValueError
442
+ If the penalty grid is decreasing or an older saved fit lacks
443
+ candidate partitions.
444
+ """
445
+ from ..plotting import plot_fusion_dendrogram
446
+
447
+ check_is_fitted(self, attributes=["model_", "treatments_"])
448
+ if not hasattr(self, "fusion_path_"):
449
+ raise ValueError("Refit the model to record its fusion path before plotting")
450
+ path = self.fusion_path_
451
+ return plot_fusion_dendrogram(path["fusion_lambdas"], path["group_ids"], self.treatments_,
452
+ selected_index=path["selected_index"], true_groups=true_groups, ax=ax)
453
+
454
+ def predict_outcomes(self, X):
455
+ """Predict each row's outcome under every fitted treatment.
456
+
457
+ Parameters
458
+ ----------
459
+ X : array-like of shape (n_samples, n_features)
460
+ Covariates in the same feature space and order as at fit time.
461
+
462
+ Returns
463
+ -------
464
+ ndarray of shape (n_samples, n_treatments)
465
+ Predictions in the original outcome units. Columns follow treatments_.
466
+ The dtype is float64 when the fit standardized outcomes, and float32
467
+ otherwise.
468
+ """
469
+ check_is_fitted(self, attributes=["model_", "treatments_", "scaler_"])
470
+ check_feature_names(X, getattr(self, "feature_names_in_", None))
471
+ X = _features(X)
472
+ if X.shape[1] != self.n_features_in_:
473
+ raise ValueError("Prediction features must match n_features_in_")
474
+ if self.scaler_ is not None:
475
+ X = self.scaler_.transform(X)
476
+ # Reuse the unmodified expansion from grouped heads to original treatments.
477
+ outcomes = _Discovery.predict_outcomes(self, X)
478
+ if self.outcome_scaler_ is not None:
479
+ return (outcomes.astype(np.float64) * self.outcome_scaler_.scale_[0]
480
+ + self.outcome_scaler_.mean_[0])
481
+ return outcomes
482
+
483
+ def predict(self, X):
484
+ """Recommend a treatment for each row.
485
+
486
+ Parameters
487
+ ----------
488
+ X : array-like of shape (n_samples, n_features)
489
+ Covariates in the same feature space and order as at fit time.
490
+
491
+ Returns
492
+ -------
493
+ ndarray of shape (n_samples,)
494
+ Original labels selected according to outcome_direction. Exact ties
495
+ choose the first treatment in treatments_.
496
+ """
497
+ outcomes = self.predict_outcomes(X)
498
+ choose = np.argmax if self.outcome_direction_ == "maximize" else np.argmin
499
+ return self.treatments_[choose(outcomes, axis=1)]
500
+
501
+ def predict_treatment(self, X):
502
+ """Recommend treatments as in predict.
503
+
504
+ Parameters
505
+ ----------
506
+ X : array-like of shape (n_samples, n_features)
507
+ Covariates in the same feature space and order as at fit time.
508
+
509
+ Returns
510
+ -------
511
+ ndarray of shape (n_samples,)
512
+ Original labels selected according to outcome_direction. Exact ties
513
+ choose the first treatment in treatments_.
514
+ """
515
+ return self.predict(X)
516
+
517
+ def predict_factual(self, X, *, treatment):
518
+ """Predict each row's outcome under its observed treatment.
519
+
520
+ Parameters
521
+ ----------
522
+ X : array-like of shape (n_samples, n_features)
523
+ Covariates in the same feature space and order as at fit time.
524
+ treatment : array-like of shape (n_samples,)
525
+ Observed treatment labels drawn from treatments_.
526
+
527
+ Returns
528
+ -------
529
+ ndarray of shape (n_samples,)
530
+ Factual predictions in the original outcome units.
531
+ The dtype is float64 when the fit standardized outcomes, and float32
532
+ otherwise.
533
+ """
534
+ outcomes = self.predict_outcomes(X)
535
+ A = _encode(treatment_labels(treatment, len(outcomes)), self.treatments_)
536
+ return outcomes[np.arange(len(A)), A]
@@ -0,0 +1 @@
1
+ """Scientific kernels extracted from the paper's private experiment archive."""
@@ -0,0 +1,8 @@
1
+ """Read-only observers for the isolated pilot copy. Never choose/update a model."""
2
+ observer = None
3
+
4
+
5
+ def call(name, *args, **kwargs):
6
+ if observer is not None:
7
+ return getattr(observer, name)(*args, **kwargs)
8
+ return None