lf2i.estimators.torch_utils package

Submodules

lf2i.estimators.torch_utils.cdf module

class lf2i.estimators.torch_utils.cdf.BrierScoreLoss(*args: Any, **kwargs: Any)[source]

Bases: Module

Cross-product Brier score, diagonal excluded to remove systematic CDF-high bias.

forward(cdf_vals: Tensor, lambda_obs: Tensor) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class lf2i.estimators.torch_utils.cdf.QuantileWeightedCRPSLoss(n_alpha: int = 1000, weight_fn: str | callable = 'gaussian', center: float = 0.1, bandwidth: float = 0.1, beta_a: float = 2.0, beta_b: float = 5.0)[source]

Bases: Module

Pinball loss integrated over α ∈ (0, 1) with a smooth weight function w(α):

L = 2 · mean_{i} ∫ w(α) · ρ_α(λ_i − F̃⁻¹(α; β(θ_i))) dα

The weight function controls which quantile levels the fit prioritises. Built-in options (via weight_fn):

  • 'uniform': w(α) = 1 — standard unweighted CRPS / pinball

  • 'gaussian': w(α) ∝ N(α; center, bandwidth²) — smooth emphasis around a target α level

  • 'beta': w(α) ∝ Beta(α; a, b) — flexible skewed weighting

  • callable: any user-supplied function w(alpha_grid) → Tensor

Parameters:
  • n_alpha (int) – Number of quadrature points over (0, 1). Default 500.

  • weight_fn (str or callable) – Weight function. One of ‘uniform’, ‘gaussian’, ‘beta’, or a callable taking a 1-D Tensor of α values and returning a same-shaped Tensor of non-negative weights.

  • center (float) – Centre of the weight mass for ‘gaussian’. Typically set to the target α level, e.g. 0.1 for a 90% confidence set. Default 0.1.

  • bandwidth (float) – Standard deviation of the Gaussian weight. Smaller = more concentrated. Default 0.1.

  • beta_a (float) – α parameter of Beta weight. Default 2.0.

  • beta_b (float) – β parameter of Beta weight. Default 5.0.

forward(predicted_quantiles: Tensor, lambda_obs: Tensor) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class lf2i.estimators.torch_utils.cdf.SigmoidCDF(*args: Any, **kwargs: Any)[source]

Bases: Module

Sigmoid CDF for modeling test statistic at fixed theta.

Parameterized by a parameter Beta, with location component mu (ED50) and slope component kappa.

Notes

  • Using log_kappa to control values of kappa to (0, infty] for optimization.

forward(lambda_vals: Tensor, mu: Tensor, log_kappa: Tensor) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

quantile(alpha: Tensor, mu: Tensor, log_kappa: Tensor) → Tensor[source]

Inverse CDF of the sigmoid.

class lf2i.estimators.torch_utils.cdf.BetaNetwork(theta_dim: int, hidden_dim: int = 64, n_hidden: int = 2, activation: str = 'elu')[source]

Bases: Module

Shallow feed-forward network mapping parameters of interest θ to the logistic CDF parameters β = (μ, log s).

Parameters:
  • theta_dim (int) – Dimensionality of the parameter of interest.

  • hidden_dim (int) – Width of each hidden layer.

  • n_hidden (int) – Number of hidden layers.

  • activation (str) – Activation function for hidden layers. One of: ‘tanh’, ‘elu’, ‘silu’, ‘relu’. Default ‘elu’.

forward(theta: Tensor) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class lf2i.estimators.torch_utils.cdf.ParametricCDFEstimator(hidden_dim: int = 64, n_hidden: int = 2, activation: str = 'elu', loss: str = 'brier', cdf_model: str = 'sigmoid', n_alpha: int = 500, weight_fn: str | callable = 'gaussian', center: float = 0.1, bandwidth: float = 0.1, beta_a: float = 2.0, beta_b: float = 5.0, normalize_ts: str = 'none', normalize_theta: str = 'none', epochs: int = 500, lr: float = 0.001, batch_size: int = 512, smooth_reg: float = 0.0, knn_k: int = 30, lk_weight: float = 1.0, warmup: int = 0, device: str | None = None, verbose: bool = False)[source]

Bases: object

Parametric CDF estimator for likelihood-free frequentist inference.

Fits a logistic CDF F̃(λ; β(θ)) to the calibration test statistic distribution, where β(θ) = (μ(θ), log kappa(θ)) are the outputs of a shallow neural network trained end-to-end.

Follows a sklearn-style interface:

estimator.fit(test_statistics, poi) estimator.predict_proba(X) # X[:, 0] = λ, X[:, 1:] = θ

This class is used directly as the calibration model stored in lf2i.calibration_model, replacing ParametricCDFPredictor.

Parameters:
  • hidden_dim (int) – Width of each hidden layer in BetaNetwork. Default 64.

  • n_hidden (int) – Number of hidden layers. Default 2.

  • activation (str) – Hidden layer activation. One of ‘elu’, ‘tanh’, ‘silu’, ‘relu’. Default ‘tanh’.

  • loss (str) – Loss function. One of ‘brier’, ‘weighted’. Default ‘brier’.

  • cdf_model (str) – Distributional assumption on local sampling distribution. Default ‘sigmoid’.

  • n_alpha (int) – Quadrature points for ‘weighted’. Default 500.

  • weight_fn (str or callable) – Weight function for ‘weighted’. One of ‘uniform’, ‘gaussian’, ‘beta’, or a callable taking a 1-D alpha Tensor and returning non-negative weights. Default ‘gaussian’.

  • center (float) – Centre of Gaussian weight mass. Set to target α level, e.g. 0.1 for a 90% confidence set. Default 0.1.

  • bandwidth (float) – Standard deviation of Gaussian weight. Default 0.1.

  • beta_a (float) – α parameter of Beta weight. Default 2.0.

  • beta_b (float) – β parameter of Beta weight. Default 5.0.

  • normalize_ts (str) – Whether the test statistic scale should be normalized, from none’, ‘mean-std’, ‘min-max’, ‘percentiles’. Default ‘none’.

  • normalize_theta (str) – Whether the parameter scale should be normalized, from none’, ‘mean-std’, ‘min-max’. Default ‘none’.

  • epochs (int) – Training epochs. Default 500.

  • lr (float) – Adam learning rate. Default 1e-3.

  • batch_size (int) – Mini-batch size. Default 512.

  • device (str, optional) – ‘cuda’ or ‘cpu’. Auto-detected if None.

  • verbose (bool) – Print loss every 100 epochs. Default True.

fit(X: ndarray) → ParametricCDFEstimator[source]

Fit the parametric CDF to calibration data.

Parameters:

X (np.ndarray) – Shape (n, 1 + poi_dim). Column 0 is the test statistic λ(x_i; θ_i), columns 1: are the corresponding parameters of interest θ_i.

Returns:

self

predict_proba(X: ndarray = None, **kwargs) → ndarray[source]

Compute p-values from the fitted parametric CDF.

Follows the sklearn predict_proba convention expected by lf2i: accepts X as a keyword argument and returns a two-column matrix.

Parameters:

X (np.ndarray) – Shape (n, 1 + poi_dim). X[:, 0] — test statistic values λ X[:, 1:] — parameters of interest θ

Returns:

np.ndarray – Shape (n, 2). Column 0 = 1 − CDF(λ | θ), column 1 = CDF(λ | θ). The directionality of p-values is resolved by the caller (e.g. lf2i.inference) based on the test statistic’s acceptance region.

lf2i.estimators.torch_utils.quantile_regressor module

class lf2i.estimators.torch_utils.quantile_regressor.QuantileLoss(quantiles: Sequence[float])[source]

Bases: Module

Quantile loss as a PyTorch module. Note that, although it supports multiple quantiles, there is currently no explicit constraint on their monotonicity to avoid quantile crossings.

Parameters:

quantiles (Sequence[float]) – Target quantiles. Values must be in the range (0, 1).

forward(input: Tensor, target: Tensor) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class lf2i.estimators.torch_utils.quantile_regressor.FeedForwardNN(input_d: int, output_d: int, hidden_layer_shapes: Sequence[int], hidden_activation: Module = ReLU(), dropout_p: float | None = None, batch_norm: bool = False)[source]

Bases: Module

Fully connected neural network.

Parameters:
  • input_d (int) – Dimensionality of the input.

  • output_d (int) – Dimensionality of the output.

  • hidden_layer_shapes (Sequence[int]) – The i-th element represents the number of neurons in the i-th hidden layer.

  • dropout_p (float, optional) – Probability for the dropout layers, by default 0.0 (i.e., no dropout.)

  • batch_norm (bool, optional) – Whether to apply batch normalization between each hidden layer or not.

build_model(batch_norm: bool, dropout_p: float | None) → None[source]
forward(X: Tensor) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class lf2i.estimators.torch_utils.quantile_regressor.Learner(model: Module, optimizer: Optimizer, loss: Module, device: str = 'cpu', verbose: bool = True)[source]

Bases: object

Utility class to train a neural network.

Parameters:
fit(X: Tensor, y: Tensor, epochs: int, batch_size: int) → None[source]
predict(X: Tensor) → Tensor[source]
class lf2i.estimators.torch_utils.quantile_regressor.LearnerRegression(model: Module, optimizer: Optimizer, loss: Module, device: str = 'cpu', verbose: bool = True)[source]

Bases: Learner

predict(X: Tensor) → Tensor[source]
class lf2i.estimators.torch_utils.quantile_regressor.ScaledQuantileRegressor(quantiles: Sequence[float] = (0.5,), poi_dim: int = 1, hidden_layer_shapes: Sequence[int] = (64, 64), hidden_activation: Module | None = None, dropout_p: float | None = None, batch_norm: bool = False, epochs: int = 100, batch_size: int = 64, clamp_extrapolation: bool = True, clamp_lo: float | None = None, clamp_hi: float | None = None, device: str = 'cpu', verbose: bool = False)[source]

Bases: BaseEstimator, RegressorMixin

Feed-forward-NN quantile regressor with input standardization and flat extrapolation beyond the training range – a thin, sklearn-compatible (BaseEstimator/RegressorMixin) wrapper around FeedForwardNN + LearnerRegression + QuantileLoss, usable directly with sklearn.model_selection.RandomizedSearchCV (matching the ‘cat-gb’ calibration path’s own hyperparameter-search mechanism – see lf2i.calibration.critical_values.train_qr_algorithm).

Standardization is data-driven: X is min-max scaled to [0, 1] using its own training-time min/max (fit fresh in .fit(), reused at .predict() time) – no external bounds needed. This matters in practice: an unscaled scalar input spanning thousands of raw units (e.g. an effective temperature in Kelvin) starves a default-initialized Linear`+`ReLU stack of any useful gradient signal.

clamp_lo/clamp_hi: where clamp_extrapolation’s flat region actually kicks in, if set – e.g. the caller’s own grid_lo/grid_hi (a chosen percentile of train+calib theta), not necessarily the same as _lo/_hi below (the raw min/max of whatever theta sample X.fit() was actually called with, used for scaling). Decoupled on purpose: the QR’s own training theta sample can span nearly the full data range even when the caller wants the flat region to start well inside that – leaving clamp_lo/clamp_hi at their None default falls back to _lo/_hi, i.e. the original (pre-decoupling) behavior, unchanged for any existing caller that doesn’t set these.

Parameters:
  • quantiles (Sequence[float], optional) – Target quantile(s), by default (0.5,).

  • poi_dim (int, optional) – Dimensionality of the parameter(s) of interest (the regressor’s input), by default 1.

  • hidden_layer_shapes (Sequence[int], optional) – Hidden layer widths, by default (64, 64).

  • hidden_activation (Optional[torch.nn.Module], optional) – Passed through to FeedForwardNN; None resolves to torch.nn.ReLU(), by default None.

  • dropout_p (Optional[float], optional) – Passed through to FeedForwardNN, by default None.

  • batch_norm (bool, optional) – Passed through to FeedForwardNN, by default False.

  • epochs (int, optional) – By default 100.

  • batch_size (int, optional) – By default 64.

  • clamp_extrapolation (bool) – By default True.

  • clamp_lo (float, optional)

  • clamp_hi (float, optional)

  • device (str, optional) – By default “cpu”.

  • verbose (bool, optional) – By default False – quieter than Learner’s own default, since this is meant to also work inside a hyperparameter search where per-candidate progress bars would be noisy.

fit(X: Tensor, y: Tensor) → ScaledQuantileRegressor[source]
predict(X: Tensor) → Tensor[source]

By default (clamp_extrapolation=True, the CatBoost-matching behavior – see __init__), X is clamped before being fed to the network, so predictions outside the clamp range are a CONSTANT extrapolant (whatever the boundary predicts) rather than the network’s raw, unconstrained – and potentially non-monotonic – output. The clamp range is [self.clamp_lo, self.clamp_hi] when those are set (e.g. to the caller’s own chosen grid bounds); otherwise it falls back to [self._lo, self._hi] (the training data’s own raw min/max, the original pre-decoupling behavior). Existing pickled instances predate both attributes; getattr defaults them to that same fallback rather than raising.

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') → ScaledQuantileRegressor

Configure whether metadata should be requested to be passed to the score method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.

Returns:

self (object) – The updated object.

class lf2i.estimators.torch_utils.quantile_regressor.LearnerClassification(model: Module, optimizer: Optimizer, loss: Module, device: str = 'cpu', verbose: bool = True)[source]

Bases: Learner

predict_proba(X: Tensor) → Tensor[source]