Skip to content

Density ratios: scorequant.ratios

Model density ratios enter through one provider, DensityRatioScore, with a declared parameterization. A parameterization's scores method applies the same map to a ratio array.

DensityRatioScore dataclass

DensityRatioScore(
    ratio: Callable[[ArrayLike], ArrayLike],
    parameterization: RatioParameterization,
    *,
    provenance: ScoreProvenance | None = None,
    schema: ScoreSchema | None = None,
)

Map observations to model density ratios and evaluate declared scores.

The ratio callback is the statistical representation: any oracle for the component density ratios — an analytic formula, a calibrated classifier, a direct ratio estimator such as KLIEP or uLSIF, or an external ratio model — determines the score once a parameterization declares how the components combine. Ratio estimation, calibration, and cross-fitting stay outside the library.

Parameters:

  • ratio (Callable[[ArrayLike], ArrayLike]) –

    Callable [N, D] -> [N, K] returning finite nonnegative model density ratios, defined up to one common event-wise factor.

  • parameterization (RatioParameterization) –

    IntensityParameterization or MixtureParameterization declaring the ratio-to-score map and the reference point.

  • provenance (ScoreProvenance | None, default: None ) –

    Optional score provenance. Estimated ratios are the default (kind="estimated_ratio"); an analytic ratio may declare kind="exact" under the same caller responsibility as ScoreFunction. Parameterization facts are always recorded in provenance.ratio and a conflicting supplied record is rejected. Declaring provenance.ratio.gauges makes the provider refuse ratio columns taken against different measures.

from_classifier classmethod

from_classifier(
    predict: Callable[[ArrayLike], ArrayLike],
    class_priors: ArrayLike,
    parameterization: RatioParameterization,
    *,
    calibration: str | None = None,
    description: str | None = None,
    metadata: Mapping[str, JsonValue] | None = None,
) -> DensityRatioScore

Build a ratio provider from a calibrated multiclass classifier.

The classifier is one estimator of density ratios: calibrated posteriors eta_k under training priors pi_k give r_k = eta_k / pi_k up to a common event-wise factor, so the scores are (eta_k / pi_k) / sum_j theta_j eta_j / pi_j under the intensity parameterization. When pi is proportional to theta_0 the denominator is identically one. The provider always records estimated provenance — a classifier-derived ratio can never claim exact Fisher semantics — and declares every column in the "training_mixture" gauge.

Parameters:

  • predict (Callable[[ArrayLike], ArrayLike]) –

    Callable [N, D] -> [N, K] returning calibrated posterior rows summing to one.

  • class_priors (ArrayLike) –

    Strictly positive training priors with shape [K] and unit sum.

  • parameterization (RatioParameterization) –

    Ratio-to-score map; K must match its component count.

  • calibration (str | None, default: None ) –

    Optional name of the upstream calibration method, recorded in provenance.

  • description (str | None, default: None ) –

    Optional free-form provenance carried on the score record.

  • metadata (str | None, default: None ) –

    Optional free-form provenance carried on the score record.

score

score(
    observations: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> ndarray

Evaluate the ratio callback and apply the declared score map.

MixtureParameterization dataclass

MixtureParameterization(
    reference_fractions: ArrayLike,
    *,
    reference_component: int = -1,
)

Declare a normalized mixture with one simplex-dependent component.

The model is p(x; theta) = sum_k theta_k phi_k(x) with sum_k theta_k = 1; the reference component is dependent, so scores have K - 1 columns.

Parameters:

  • reference_fractions (ArrayLike) –

    Strictly positive mixture fractions theta_0 with shape [K] and unit sum.

  • reference_component (int, default: -1 ) –

    Component treated as dependent under the simplex constraint.

n_components property

n_components: int

Number of ratio columns the parameterization consumes.

scores

scores(
    ratios: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> ndarray

Return the [N, K - 1] constrained-mixture scores.

Columns follow the original component order with the reference component omitted; each is (r_k - r_ref) / sum_j theta_j r_j.

IntensityParameterization dataclass

IntensityParameterization(coefficients: ArrayLike)

Declare an extended linear-intensity model over component ratios.

The model is lambda(x; theta) = sum_k theta_k phi_k(x) with free, unconstrained coefficients, so every one of the K score columns is retained, including the overall-normalization direction.

Parameters:

  • coefficients (ArrayLike) –

    Finite reference coefficients theta_0 with shape [K].

n_components property

n_components: int

Number of ratio columns the parameterization consumes.

scores

scores(
    ratios: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> ndarray

Return the [N, K] intensity scores r_k / sum_j theta_j r_j.

The map is invariant under a common event-wise rescaling of a row, so density ratios in any gauge, component densities included, yield exactly the component scores phi_k / lambda.

CentralLogRatioScore dataclass

CentralLogRatioScore(
    predict: Callable[[ArrayLike], ArrayLike],
    deltas: ArrayLike,
    class_priors: ArrayLike,
    *,
    description: str | None = None,
    metadata: Mapping[str, JsonValue] | None = None,
    schema: ScoreSchema | None = None,
)

Estimate central finite-difference scores from paired density ratios.

A calibrated classifier trained to separate samples generated at theta_0 - delta e_p from theta_0 + delta e_p estimates the directional log density ratio, and (log(p_plus / p_minus) - log(pi_plus / pi_minus)) / (2 delta) is a central finite-difference estimate of the score component s_p. The prediction callback must return shape [N, P, 2] with class order (minus, plus); a two-dimensional [N, 2] input is accepted for a single score direction. Provenance is always estimated.

Parameters:

  • predict (Callable[[ArrayLike], ArrayLike]) –

    Callable returning calibrated minus/plus probability pairs.

  • deltas (ArrayLike) –

    Strictly positive finite-difference offsets with shape [P].

  • class_priors (ArrayLike) –

    Training priors per direction with shape [2] or [P, 2]; rows are normalized to sum to one.

  • description (str | None, default: None ) –

    Optional free-form provenance carried on the score record.

  • metadata (str | None, default: None ) –

    Optional free-form provenance carried on the score record.

provenance property

provenance: ScoreProvenance

Return estimated-ratio provenance with the central-difference facts.

score

score(
    observations: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> ndarray

Apply prior correction and divide central logits by 2 * delta.

RatioProvenance dataclass

RatioProvenance(
    estimator: str | None = None,
    parameterization: RatioParameterizationKind
    | None = None,
    coefficients: tuple[float, ...] | None = None,
    reference_fractions: tuple[float, ...] | None = None,
    reference_component: int | None = None,
    training_priors: tuple[float, ...]
    | tuple[tuple[float, float], ...]
    | None = None,
    calibration: str | None = None,
    deltas: tuple[float, ...] | None = None,
    gauges: tuple[str, ...] | None = None,
)

Describe how a model density-ratio representation was obtained.

Together with ScoreProvenance.kind and reference_point, these fields reconstruct the statistical representation behind a ratio-derived score: which estimator produced the ratios, under which training priors and calibration, and through which parameterization they became scores. Fields that do not apply to a given construction stay None.

gauges names, for each ratio column, the measure that column is a density ratio against: "training_mixture" for prior-corrected classifier posteriors, "absolute" for a Monte Carlo or analytic density, or any label of the caller's choosing. The score map cancels only a factor common to every column of an event, so columns declared in different gauges are refused when the record is built; no provider, score sample or saved rule can carry them. None declares nothing and is not checked.

__post_init__

__post_init__() -> None

Refuse ratio columns declared against different measures.

Every ratio-to-score map is invariant only under a factor common to all columns of one event. Columns in different gauges, such as a prior-corrected classifier ratio over p_train next to an absolute Monte Carlo density, leave the event-dependent p_train(x) uncancelled, and every score is silently wrong.

to_dict

to_dict() -> dict[str, JsonValue]

Return a JSON-compatible ratio-provenance mapping.

ratios_from_posteriors

ratios_from_posteriors(
    posteriors: ArrayLike,
    class_priors: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> ndarray

Convert calibrated class posteriors into model density ratios.

Parameters:

  • posteriors (ArrayLike) –

    Calibrated class-posterior matrix with shape [N, K]. Rows must be finite, nonnegative, and sum to one.

  • class_priors (ArrayLike) –

    Strictly positive class priors under which posteriors were estimated, with shape [K] and unit sum.

Returns:

  • ndarray –

    Ratio matrix r_k(x) = posteriors_k(x) / class_priors_k with shape [N, K]: the component density ratios phi_k(x) / p_train(x), where p_train is the training mixture. The common event-wise factor p_train cancels in every downstream score map.

Raises:

  • ContractError –

    If shapes, finiteness, nonnegativity, or simplex normalization violate the posterior contract.

Notes

Only a calibrated posterior carries ratio information. A ranking score or an arbitrary monotone transform of a likelihood ratio is not sufficient: score construction needs a quantitatively meaningful ratio, so calibration or a ratio-estimation loss is required upstream.

The function does not calibrate, clip, or renormalize classifier output. Those operations change the implied density ratios and belong to the upstream ratio-estimation workflow.

ratio_closure_report

ratio_closure_report(
    ratios: ArrayLike,
    weights: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> RatioClosureReport

Check that density ratios integrate to one under the declared measure.

Parameters:

  • ratios (ArrayLike) –

    Finite nonnegative model density ratios with shape [N, K], relative to the measure the weights carry.

  • weights (ArrayLike) –

    Finite nonnegative weights with shape [N] and at least one positive entry, carrying the reference measure of the ratio denominator.

Returns:

  • RatioClosureReport –

    Per-component weighted means sum_i w_i r_ik / sum_i w_i and their largest absolute deviation from one.

Raises:

  • ContractError –

    If shapes, finiteness, or nonnegativity violate the contract.

Notes

For exact ratios r_k = phi_k / p_ref every column integrates to one under the reference measure, so a nonzero residual bounds estimator bias from below: it is model error, never compression loss. The test is joint in the estimator, the declared training priors, and the measure, and it is necessary but not sufficient — closure never justifies upgrading estimated provenance to exact.

RatioClosureReport dataclass

RatioClosureReport(
    normalizers: ndarray, max_residual: float
)

Report how far model density ratios are from unit normalization.

Exact component ratios relative to a reference measure integrate to one under that measure: sum_i w_i r_ik / sum_i w_i == 1 for every component k when the weights carry the measure the ratio denominator defines. A large residual signals estimator bias, a misdeclared training prior, or a measure mismatch. The check is necessary but not sufficient: a ratio can close marginally while still being wrong pointwise, so a small residual never upgrades estimated provenance.

Attributes:

  • normalizers (ndarray) –

    Weighted mean of each ratio column, shape [K].

  • max_residual (float) –

    Largest absolute deviation of normalizers from one.

to_dict

to_dict() -> dict[str, JsonValue]

Return a JSON-compatible closure representation.