Skip to content

DeLong

Use DeLong to compare two scores on the same cases with known outcomes. alternative="greater" tests whether the candidate AUROC is higher; "less" tests whether it is lower; "two-sided" tests for a difference in either direction. AUROC is the area under the receiver operating characteristic curve.

Question Does the candidate model rank cases better or worse overall?
Inputs y_true known outcomes; predictions from candidate and reference for the same cases
Run Call with (alternative); the default asymptotic test needs no setup; permutation uses .set_permutation(...)
statistic AUROC(candidate) - AUROC(reference)
alternative Caller selects two-sided, greater, or less
import numpy as np
import samesame as ss

y_true = np.array([0, 0, 0, 1, 1, 1])
candidate = np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9])
reference = np.array([0.4, 0.5, 0.6, 0.5, 0.6, 0.7])

test = ss.DeLong(y_true, candidate, reference)
result = test(alternative="greater")
print(result.pvalue, result.statistic)
print(result.extra["auroc"])

Expected output: AUROC gap 0.22, with candidate AUROC 1.0 and reference AUROC 0.78. The candidate has higher rank discrimination on this sample.

By default, DeLong uses a normal approximation that accounts for paired scores. For a permutation test, set inference="permutation" and configure .set_permutation(seed, n_permutations, batch). It swaps candidate and reference predictions within each case.

The default calculation is deterministic and stores each AUROC, the estimated standard error (se), and the test statistic (z). If the variance is zero, the p-value is 1.0 for tied AUROCs or 0.0 when the difference supports the requested direction.

Choose a calculation method

The default asymptotic test is a good starting point for routine comparisons. Consider permutation for small samples, AUROCs near 0 or 1, or when you want the same kind of comparison as the other paired tests. Set inference="permutation" and configure .set_permutation(...).

See API: Testing for permutation settings and batch.

Edge cases

  • Tied values receive midranks (the average rank of the tied observations). No random jitter is added.
  • Inputs are matched by position. Keep the labels and both prediction arrays in the same row order.
  • Asymptotic extra holds per-model "auroc", "se", and "z".
  • Permutation extra["null"] is a read-only array of evaluated statistics. It can be shorter than the requested n_permutations when SciPy enumerates all possible arrangements.
  • Permutation extra["n_permutations"] holds the requested count; extra["auroc"] holds each model's AUROC.
  • Select alternative for each call. Use "greater" when you want to test whether the candidate's AUROC is higher.

Reference

samesame.DeLong

Bases: _PairedScorersBase

Compare how well two models rank cases with a known outcome.

Use this paired test when overall ranking matters. It compares AUROC values, the probability of ranking a case with the outcome above one without it (ties count as half). It does not compare the models' full trade-offs across cutoffs.

Parameters:

Name Type Description Default
y_true NDArray[int_]

Binary labels (0/1) with shape (n_samples,). Both classes must exist. The class copies and freezes the array.

required
candidate NDArray[float64]

Scores under test with shape (n_samples,). The minuend uses statistic = AUROC(candidate) - AUROC(reference). The class copies and freezes the array.

required
reference NDArray[float64]

Provide baseline scores with shape (n_samples,). The test subtracts these scores. The class copies and freezes the array.

required
inference Literal['permutation', 'asymptotic']

"asymptotic" is the default. It uses the paired midrank covariance with a normal-theory p-value. "permutation" swaps candidate and reference within each observation. Configure it with :meth:set_permutation.

'asymptotic'
Notes

Order is positional. alternative="greater" tests whether the candidate AUROC is higher than the reference AUROC; "less" tests whether it is lower. The default asymptotic method uses a paired covariance estimate and a normal reference distribution. The permutation method swaps candidate and reference predictions within each case; its null is within-case exchangeability.

See Also

MannWhitneyU : Two-sample permutation test of rank separation. Dsos : One-sided tail-weighted test in a defined harm direction.

Examples:

>>> import numpy as np
>>> import samesame as ss
>>> y_true = np.array([0, 0, 0, 1, 1, 1])
>>> candidate = np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9])
>>> reference = np.array([0.4, 0.5, 0.6, 0.5, 0.6, 0.7])
>>> test = ss.DeLong(y_true, candidate, reference)
>>> result = test(alternative="greater")
>>> result.test_name
'DeLong (asymptotic)'
>>> round(float(result.statistic), 3)
0.222
>>> round(float(result.pvalue), 3)
0.143
>>> round(float(result.extra["auroc"]["candidate"]), 3)
1.0
>>> round(float(result.extra["auroc"]["reference"]), 3)
0.778
>>> perm = ss.DeLong(
...     y_true, candidate, reference, inference="permutation"
... ).set_permutation(seed=42, n_permutations=64)
>>> presult = perm(alternative="greater")
>>> presult.test_name
'DeLong (permutation)'
>>> round(float(presult.statistic), 3)
0.222
>>> round(float(presult.pvalue), 3)
0.062
>>> presult.alternative
'greater'
Source code in src/samesame/_paired.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
class DeLong(_PairedScorersBase):
    """Compare how well two models rank cases with a known outcome.

    Use this paired test when overall ranking matters. It compares AUROC
    values, the probability of ranking a case with the outcome above one
    without it (ties count as half). It does not compare the models' full
    trade-offs across cutoffs.

    Parameters
    ----------
    y_true :
        Binary labels (``0``/``1``) with shape ``(n_samples,)``. Both
        classes must exist. The class copies and freezes the array.
    candidate :
        Scores under test with shape ``(n_samples,)``. The minuend uses
        ``statistic = AUROC(candidate) - AUROC(reference)``. The class copies
        and freezes the array.
    reference :
        Provide baseline scores with shape ``(n_samples,)``. The test
        subtracts these scores. The class copies and freezes the array.
    inference :
        ``"asymptotic"`` is the default. It uses the paired midrank
        covariance with a normal-theory p-value. ``"permutation"``
        swaps candidate and reference within each observation.
        Configure it with :meth:`set_permutation`.

    Notes
    -----
    Order is positional. ``alternative="greater"`` tests whether the
    candidate AUROC is higher than the reference AUROC;
    ``"less"`` tests whether it is lower. The default asymptotic method
    uses a paired covariance estimate and a normal reference distribution.
    The permutation method swaps candidate and reference predictions
    within each case; its null is within-case exchangeability.

    See Also
    --------
    MannWhitneyU : Two-sample permutation test of rank separation.
    Dsos : One-sided tail-weighted test in a defined harm direction.

    Examples
    --------
    >>> import numpy as np
    >>> import samesame as ss
    >>> y_true = np.array([0, 0, 0, 1, 1, 1])
    >>> candidate = np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9])
    >>> reference = np.array([0.4, 0.5, 0.6, 0.5, 0.6, 0.7])
    >>> test = ss.DeLong(y_true, candidate, reference)
    >>> result = test(alternative="greater")
    >>> result.test_name
    'DeLong (asymptotic)'
    >>> round(float(result.statistic), 3)
    0.222
    >>> round(float(result.pvalue), 3)
    0.143
    >>> round(float(result.extra["auroc"]["candidate"]), 3)
    1.0
    >>> round(float(result.extra["auroc"]["reference"]), 3)
    0.778
    >>> perm = ss.DeLong(
    ...     y_true, candidate, reference, inference="permutation"
    ... ).set_permutation(seed=42, n_permutations=64)
    >>> presult = perm(alternative="greater")
    >>> presult.test_name
    'DeLong (permutation)'
    >>> round(float(presult.statistic), 3)
    0.222
    >>> round(float(presult.pvalue), 3)
    0.062
    >>> presult.alternative
    'greater'
    """

    def __init__(
        self,
        y_true: NDArray[np.int_],
        candidate: NDArray[np.float64],
        reference: NDArray[np.float64],
        inference: Literal["permutation", "asymptotic"] = "asymptotic",
    ) -> None:
        super().__init__(y_true, candidate, reference, inference)

    def __call__(
        self,
        alternative: Literal["two-sided", "greater", "less"] = "two-sided",
    ) -> TestResult:
        """Compare AUROC values of candidate against reference.

        Parameters
        ----------
        alternative :
            Tested direction. ``"two-sided"`` tests any difference.
            ``"greater"`` tests higher candidate AUROC. ``"less"`` tests
            lower candidate AUROC.

        Returns
        -------
        TestResult
            The call dispatches on ``inference``. Asymptotic results use
            ``test_name="DeLong (asymptotic)"``. Their ``extra`` carries
            per-scorer ``auroc``, ``se``, and ``z``. Permutation results
            use ``test_name="DeLong (permutation)"``. Their ``extra``
            carries read-only ``"null"``, ``"n_permutations"``, and
            per-scorer ``"auroc"``.

        Raises
        ------
        ValueError
            If `alternative` is not ``"two-sided"``, ``"greater"``, or
            ``"less"``.
        """
        if alternative not in ("two-sided", "greater", "less"):
            raise ValueError(
                f"alternative must be 'two-sided', 'greater', or 'less', "
                f"got {alternative!r}"
            )
        if self._inference == "permutation":
            return self._permutation(alternative)
        return self._asymptotic(alternative)

    def _asymptotic(
        self, alternative: Literal["two-sided", "greater", "less"]
    ) -> TestResult:
        """Return the normal-theory comparison from midrank covariance."""
        diff, se, z, auc_c, auc_r = _delong_moments(
            self.y_true, self._candidate, self._reference
        )
        if alternative == "two-sided":
            pvalue = float(2.0 * norm.sf(abs(z)))
        elif alternative == "greater":
            pvalue = float(norm.sf(z))
        else:
            pvalue = float(norm.cdf(z))
        return TestResult(
            pvalue=pvalue,
            statistic=diff,
            test_name="DeLong (asymptotic)",
            alternative=alternative,
            extra={
                "auroc": {"candidate": auc_c, "reference": auc_r},
                "se": se,
                "z": float(z),
            },
        )

    def _permutation(
        self, alternative: Literal["two-sided", "greater", "less"]
    ) -> TestResult:
        """Return the paired swap null.

        Labels stay fixed. Unordered score pairs stay fixed.
        ``permutation_type="samples"`` swaps candidate and reference
        within each observation.
        """
        m, n, auc_c, auc_r, pos = self._paired_aurocs()

        def vec_stat(
            c: NDArray[np.float64], r: NDArray[np.float64], axis: int = -1
        ) -> NDArray[np.float64]:
            cc = np.asarray(c)
            rr = np.asarray(r)
            rc = rankdata(cc, axis=-1)
            rd = rankdata(rr, axis=-1)
            denom = m * n
            base = m * (m + 1.0) / 2.0
            if rc.ndim == 1:
                return np.asarray(
                    (rc[pos].sum() - base) / denom - (rd[pos].sum() - base) / denom
                )
            return (rc[:, pos].sum(axis=1) - base) / denom - (
                rd[:, pos].sum(axis=1) - base
            ) / denom

        return self._run_swap_permutations(
            vec_stat,
            alternative,
            "DeLong (permutation)",
            alternative,
            auc_c,
            auc_r,
        )

__call__(alternative='two-sided')

Compare AUROC values of candidate against reference.

Parameters:

Name Type Description Default
alternative Literal['two-sided', 'greater', 'less']

Tested direction. "two-sided" tests any difference. "greater" tests higher candidate AUROC. "less" tests lower candidate AUROC.

'two-sided'

Returns:

Type Description
TestResult

The call dispatches on inference. Asymptotic results use test_name="DeLong (asymptotic)". Their extra carries per-scorer auroc, se, and z. Permutation results use test_name="DeLong (permutation)". Their extra carries read-only "null", "n_permutations", and per-scorer "auroc".

Raises:

Type Description
ValueError

If alternative is not "two-sided", "greater", or "less".

Source code in src/samesame/_paired.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def __call__(
    self,
    alternative: Literal["two-sided", "greater", "less"] = "two-sided",
) -> TestResult:
    """Compare AUROC values of candidate against reference.

    Parameters
    ----------
    alternative :
        Tested direction. ``"two-sided"`` tests any difference.
        ``"greater"`` tests higher candidate AUROC. ``"less"`` tests
        lower candidate AUROC.

    Returns
    -------
    TestResult
        The call dispatches on ``inference``. Asymptotic results use
        ``test_name="DeLong (asymptotic)"``. Their ``extra`` carries
        per-scorer ``auroc``, ``se``, and ``z``. Permutation results
        use ``test_name="DeLong (permutation)"``. Their ``extra``
        carries read-only ``"null"``, ``"n_permutations"``, and
        per-scorer ``"auroc"``.

    Raises
    ------
    ValueError
        If `alternative` is not ``"two-sided"``, ``"greater"``, or
        ``"less"``.
    """
    if alternative not in ("two-sided", "greater", "less"):
        raise ValueError(
            f"alternative must be 'two-sided', 'greater', or 'less', "
            f"got {alternative!r}"
        )
    if self._inference == "permutation":
        return self._permutation(alternative)
    return self._asymptotic(alternative)