pymargins.Margins

class pymargins.Margins(model, *, phi: Callable | None = <object object>, phi_inv: Callable | None = <object object>, vcov: str | ndarray | dict | None = <object object>, weights: ndarray | None = <object object>, at: str | dict | Callable = <object object>, level: float = <object object>, method: Literal['delta', 'simulation', 'bootstrap']=<object object>, kappa_threshold: float = <object object>, rng_seed: int | None = <object object>, n_sim: int = <object object>, n_boot: int = <object object>, n_jobs: int = <object object>, gradient_backend: Literal['autodiff', 'fd', 'wrapped_fd']=<object object>, fd_step: float = <object object>, diagnostics: bool = <object object>, cluster: Any | None = <object object>, block_size: int | None = <object object>, bootstrap_config: dict | None = <object object>, progress_bar: bool = <object object>, matching: Any | None = <object object>, formula: str | None = <object object>, data: DataFrame | None = <object object>, strict: bool = False, adapter: ModelAdapter | None = None)

Wrapper around a fitted model exposing marginal-effects analysis.

Parameters:
  • model (fitted result object) – From statsmodels, linearmodels, or sklearn (with limitations). The adapter is auto-detected unless explicitly provided.

  • phi (callable, optional) –

    Back-transform from inference scale to reporting scale. Applied to CI endpoints. Default: None (identity scale). Common choices:

    jnp.exp                  # log scale (ratios, RR, fold-change)
    scipy.special.expit      # logit scale (odds ratios, probabilities)
    jnp.expm1                # lift scale (RR - 1)
    jnp.tanh                 # Fisher z scale (correlations)
    

  • phi_inv (callable, optional) – Forward transform from reporting scale to inference scale. Required if phi is non-identity. Used for converting user-supplied null values in hypothesis tests onto the inference scale.

  • vcov (str, ndarray, dict, or None, default None) – Variance estimator specification. None uses the framework default. Strings like “HC0”-“HC3” request robust flavors. A dict like {“type”: “cluster”, “groups”: ids} requests cluster-robust SEs. An ndarray uses a user-supplied Σ̂ directly.

  • weights (array-like, optional) – Aggregation weights (distinct from any sampling weights baked into the model fit). Used when computing AME-style averages and when constructing weighted summary points for typical/mean/etc.

  • at (str, dict, or callable, default "overall") –

    Where to evaluate predictions and marginal effects, following statsmodels convention. Common values:

    "overall"   # per-row, then average (AME / AAP)
    "mean"      # evaluate at the mean of all variables (MEM)
    "typical"   # type-aware: median continuous, mode discrete
    "median"    # median of all
    "mode"      # mode of all (errors on continuous)
    dict        # per-variable specification with "_default" key
    callable    # (data) -> 1-row representative DataFrame
    

  • level (float, default 0.95) – Confidence level for CIs.

  • method (str, default "delta") – Default inference method: “delta”, “simulation”, or “bootstrap”.

  • kappa_threshold (float, default 0.3) – Curvature above which delta auto-falls-back to simulation. Set to infinity to disable automatic fallback.

  • n_sim (int, default 4000) – Number of simulation draws for Krinsky–Robb simulation inference.

  • n_boot (int, default 1000) – Number of bootstrap replicates for bootstrap inference.

  • n_jobs (int, default 1) – Number of parallel workers for bootstrap refits. -1 uses all available cores. Uses thread-based parallelization with BLAS threads limited to 1 per worker to prevent oversubscription.

  • gradient_backend (str, default "auto") – Gradient method. “auto” uses the adapter’s recommendation. Manual choices: “autodiff”, “fd”, “wrapped_fd”.

  • fd_step (float, default 1e-6) – Step size for FD-based gradients. The default is calibrated for float64 precision.

  • diagnostics (bool, default True) – Whether to compute κ and other diagnostics on every call. Disable for performance in tight loops.

  • cluster (array-like, optional) – Cluster IDs for cluster bootstrap. When provided and method='bootstrap', resamples clusters with replacement instead of individual rows. Must be the same length as the training data and must not contain NaN. Any hashable type is accepted (strings, integers, tuples, etc.). Mutually exclusive with block_size.

  • block_size (int, optional) – Block length for block bootstrap. When provided and method='bootstrap', resamples contiguous blocks with replacement instead of individual rows. Mutually exclusive with cluster.

  • bootstrap_config (dict, optional) –

    Advanced bootstrap options. Supported keys:

    • "block_type": "moving" (default), "nonoverlapping", or "circular"

  • progress_bar (bool, default False) – Whether to show a progress bar during bootstrap execution. Requires tqdm to be installed.

  • strict (bool, default False) – If True, no defaults are inferred — every analytical choice must be explicit at construction. Useful for pre-registered or audit-relevant work. Implementation detail: when strict, any unspecified config argument raises rather than using its default.

  • adapter (ModelAdapter, optional) – Explicit adapter overriding auto-detection. Useful for unusual models or when customizing predict semantics.

__init__(model, *, phi: Callable | None = <object object>, phi_inv: Callable | None = <object object>, vcov: str | ndarray | dict | None = <object object>, weights: ndarray | None = <object object>, at: str | dict | Callable = <object object>, level: float = <object object>, method: Literal['delta', 'simulation', 'bootstrap']=<object object>, kappa_threshold: float = <object object>, rng_seed: int | None = <object object>, n_sim: int = <object object>, n_boot: int = <object object>, n_jobs: int = <object object>, gradient_backend: Literal['autodiff', 'fd', 'wrapped_fd']=<object object>, fd_step: float = <object object>, diagnostics: bool = <object object>, cluster: Any | None = <object object>, block_size: int | None = <object object>, bootstrap_config: dict | None = <object object>, progress_bar: bool = <object object>, matching: Any | None = <object object>, formula: str | None = <object object>, data: DataFrame | None = <object object>, strict: bool = False, adapter: ModelAdapter | None = None)

Methods

__init__(model, *, phi, phi_inv, vcov, ...)

contrasts(*, scenarios, contrasts[, outcome])

Linear combination(s) of predictions across scenarios.

correlation_scale(model, **kwargs)

Fisher z scale: contrasts on z; reported as correlations.

diagnose([n_samples, rng_seed])

Session-level κ diagnostic across the design space.

dydx(variables, *[, atexog, over, ...])

Slope (∂μ/∂x_j) for continuous covariates.

dyex(variable, **kwargs)

Semi-elasticity: (∂y/∂x) * x.

evaluate(*, scenarios, compose[, outcome])

Arbitrary differentiable function of scenario predictions.

eydx(variable, **kwargs)

Semi-elasticity: (∂y/∂x) / y.

eyex(variable, **kwargs)

Elasticity: (∂y/∂x) * x / y, evaluated at the session's at.

from_formula(model, formula, data, **kwargs)

Construct a Margins session with an explicit formula.

from_posterior(model, posterior_draws, *[, ...])

Construct a Margins session from posterior draws of β.

linear_scale(model, **kwargs)

Identity scale: contrasts are absolute differences.

log_scale(model, **kwargs)

Log scale: contrasts are log-ratios; reported as ratios.

logit_scale(model, **kwargs)

Logit scale: contrasts are log-odds-ratios; reported as ORs.

predict(*[, atexog, over, transform, label, ...])

Adjusted prediction (level quantity).

rmst(*, horizon[, atexog, over, n_grid])

Restricted mean survival time up to horizon.

summary()

One-paragraph summary of the analytical posture.

wtp(attribute, price, **kwargs)

Willingness to pay: -(∂U/∂attribute) / (∂U/∂price).