Skip to content

Bootstrap

Bootstrap

Computes a two-sided bootstrap confidence interval of a statistic. Note that \( \alpha \) is then defined as \( \frac{1 - \text{confidence}}{2} \). Regardless of method, the result will be a three-tuple of (lower, mean, upper). The process is as follows:

  • Resample 100% of the data with replacement for iterations
  • Compute the statistic on each resample

If the method is standard,

  • Compute the mean \( \hat{\theta} \) of the bootstrap statistics
  • Compute the standard error of the bootstrap statistics. Note that the standard error of any statistic is defined as the standard deviation of its sampling distribution.
  • Compute the Z-score

    \[ z_{\alpha} = \phi^{-1}(\alpha) \]

    where \( \phi^{-1} \) is the quantile, inverse CDF, or percent-point function

Then the "Standard" or "First-Order Normal Approximation" interval is

\[ \hat{\theta} \pm z_{\alpha} \times \hat{\sigma} \]

If the method is percentile, we stop here and compute the interval of the bootstrap distribution that is symmetric about the median and contains confidence of the bootstrap statistics. Then the "Percentile" interval is

\[ [\text{percentile}(\hat{\theta}^{*}, \alpha), \text{percentile}(\hat{\theta}^{*}, 1 - \alpha)] \]

where \( \hat{\theta}^{*} \) is the vector of bootstrap statistics.

If the method is basic,

  • Compute the statistic on the original data
  • Compute the "Percentile" interval

Then the "Basic" or "Reverse Percentile" interval is

\[ [2\hat{\theta} - PCI_u, 2\hat{\theta} - PCI_l,] \]

where \( \hat{\theta} \) is the statistic on the original data, \( PCI_u \) is the upper bound of the "Percentile" interval, and \( PCI_l \) is the lower bound of the "Percentile" interval.

If the method is BCa,

  • Compute the statistic on the original data \( \hat{\theta} \)
  • Compute the statistic on the data with the \( i^{th} \) row deleted (jacknife)
  • Compute the bias correction factor as

    \[ \hat{z_0} = \phi^{-1}( \frac{\sum_{i=1}^B \hat{\theta_i}^{*} \le \hat{\theta} + \sum_{i=1}^B \hat{\theta_i}^{*} \leq \hat{\theta}}{2 * B} ) \]

    where \( \hat{\theta}^{*} \) is the vector of bootstrap statistics and \( B \) is the length of that vector.

  • Compute the acceleration factor as

    \[ \hat{a} = \frac{1}{6} \frac{ \sum_{i=1}^{N} (\hat{\theta_{(.)}} - \hat{\theta_i})^3 }{ \sum_{i=1}^{N} [(\hat{\theta_{(.)}} - \hat{\theta_i})^2]^{1.5} } \]

    where \( \hat{\theta_{(.)}} \) is the mean of the jacknife statistics and \( \hat{\theta_i} \) is the \( i^{th} \) element of the jacknife vector.

  • Compute the lower and upper percentiles as

    \[ \alpha_l = \phi( \hat{z_0} + \frac{\hat{z_0} + z_{\alpha}}{1 - \hat{a}(\hat{z} + z_{\alpha})} ) \]

    and

    \[ \alpha_u = \phi( \hat{z_0} + \frac{ \hat{z_0} + z_{1 - \alpha} }{ 1 - \hat{a}(\hat{z} + z_{1-\alpha}) } ) \]

Then the "BCa" or "Bias-Corrected and Accelerated" interval is

\[ [\text{percentile}(\hat{\theta}^{*}, \alpha_l), \text{percentile}(\hat{\theta}^{*}, \alpha_u)] \]

where \( \hat{\theta}^{*} \) is the vector of bootstrap statistics.

Parameters:

Name Type Description Default
iterations int

How many times to resample the data, by default 1_000

1000
confidence float

The confidence level, by default 0.95

0.95
method Literal['standard', 'percentile', 'basic', 'BCa']

Whether to return the Percentile, Basic / Reverse Percentile, or Bias Corrected and Accelerated Interval, by default "percentile"

'percentile'
seed Optional[int]

Seed that controls resampling. Set this to any integer to make results reproducible, by default None

None
n_jobs Optional[int]

How many threads to run with. None means let the executor decide, and 1 means run sequentially, by default None

None
chunksize Optional[int]

The chunksize for each thread. None means let the executor decide, by default None

None

Raises:

Type Description
ValueError

If the method is not one of standard, percentile, basic, or BCa

Examples:

import rapidstats
ci = rapidstats.Bootstrap(seed=208).mean([1, 2, 3])
(1.0, 1.9783333333333328, 3.0)

Source code in python/rapidstats/_bootstrap.py
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 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
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
class Bootstrap:
    r"""Computes a two-sided bootstrap confidence interval of a statistic. Note that
    \( \alpha \) is then defined as \( \frac{1 - \text{confidence}}{2} \). Regardless
    of method, the result will be a three-tuple of (lower, mean, upper). The process is
    as follows:

    - Resample 100% of the data with replacement for `iterations`
    - Compute the statistic on each resample

    If the method is `standard`,

    - Compute the mean \( \hat{\theta} \) of the bootstrap statistics
    - Compute the standard error of the bootstrap statistics. Note that the standard
    error of any statistic is defined as the standard deviation of its sampling
    distribution.
    - Compute the Z-score

        \[ z_{\alpha} = \phi^{-1}(\alpha) \]

        where \( \phi^{-1} \) is the quantile, inverse CDF, or percent-point function

    Then the "Standard" or "First-Order Normal Approximation" interval is

    \[ \hat{\theta} \pm z_{\alpha} \times \hat{\sigma} \]

    If the method is `percentile`, we stop here and compute the interval of the
    bootstrap distribution that is symmetric about the median and contains
    `confidence` of the bootstrap statistics. Then the "Percentile" interval is

    \[
        [\text{percentile}(\hat{\theta}^{*}, \alpha),
        \text{percentile}(\hat{\theta}^{*}, 1 - \alpha)]
    \]

    where \( \hat{\theta}^{*} \) is the vector of bootstrap statistics.

    If the method is `basic`,

    - Compute the statistic on the original data
    - Compute the "Percentile" interval

    Then the "Basic" or "Reverse Percentile" interval is

    \[
        [2\hat{\theta} - PCI_u,
        2\hat{\theta} - PCI_l,]
    \]

    where \( \hat{\theta} \) is the statistic on the original data, \( PCI_u \) is the
    upper bound of the "Percentile" interval, and \( PCI_l \) is the lower bound of the
    "Percentile" interval.

    If the method is `BCa`,

    - Compute the statistic on the original data \( \hat{\theta} \)
    - Compute the statistic on the data with the \( i^{th} \) row deleted (jacknife)
    - Compute the bias correction factor as

        \[
            \hat{z_0} = \phi^{-1}(
                \frac{\sum_{i=1}^B \hat{\theta_i}^{*} \le \hat{\theta}
                + \sum_{i=1}^B \hat{\theta_i}^{*} \leq \hat{\theta}}{2 * B}
            )
        \]

        where \( \hat{\theta}^{*} \) is the vector of bootstrap statistics and \( B \)
        is the length of that vector.

    - Compute the acceleration factor as

        \[
            \hat{a} = \frac{1}{6} \frac{
                \sum_{i=1}^{N} (\hat{\theta_{(.)}} - \hat{\theta_i})^3
            }{
                \sum_{i=1}^{N} [(\hat{\theta_{(.)}} - \hat{\theta_i})^2]^{1.5}
            }
        \]

        where \( \hat{\theta_{(.)}} \) is the mean of the jacknife statistics and
        \( \hat{\theta_i} \) is the \( i^{th} \) element of the jacknife vector.

    - Compute the lower and upper percentiles as

        \[
            \alpha_l = \phi(
                \hat{z_0} + \frac{\hat{z_0} + z_{\alpha}}{1 - \hat{a}(\hat{z} + z_{\alpha})}
            )
        \]

        and

        \[
            \alpha_u = \phi(
                \hat{z_0} + \frac{
                    \hat{z_0} + z_{1 - \alpha}
                }{
                    1 - \hat{a}(\hat{z} + z_{1-\alpha})
                }
            )
        \]

    Then the "BCa" or "Bias-Corrected and Accelerated" interval is

    \[
        [\text{percentile}(\hat{\theta}^{*}, \alpha_l),
        \text{percentile}(\hat{\theta}^{*}, \alpha_u)]
    \]

    where \( \hat{\theta}^{*} \) is the vector of bootstrap statistics.

    Parameters
    ----------
    iterations : int, optional
        How many times to resample the data, by default 1_000
    confidence : float, optional
        The confidence level, by default 0.95
    method : Literal["standard", "percentile", "basic", "BCa"], optional
        Whether to return the Percentile, Basic / Reverse Percentile, or
        Bias Corrected and Accelerated Interval, by default "percentile"
    seed : Optional[int], optional
        Seed that controls resampling. Set this to any integer to make results
        reproducible, by default None
    n_jobs: Optional[int], optional
        How many threads to run with. None means let the executor decide, and 1 means
        run sequentially, by default None
    chunksize: Optional[int], optional
        The chunksize for each thread. None means let the executor decide, by default
        None

    Raises
    ------
    ValueError
        If the method is not one of `standard`, `percentile`, `basic`, or `BCa`

    Examples
    --------
    ``` py
    import rapidstats
    ci = rapidstats.Bootstrap(seed=208).mean([1, 2, 3])
    ```
    (1.0, 1.9783333333333328, 3.0)
    """

    def __init__(
        self,
        iterations: int = 1_000,
        confidence: float = 0.95,
        method: Literal["standard", "percentile", "basic", "BCa"] = "percentile",
        seed: Optional[int] = None,
        n_jobs: Optional[int] = None,
        chunksize: Optional[int] = None,
    ) -> None:
        if method not in ("standard", "percentile", "basic", "BCa"):
            raise ValueError(
                f"Invalid confidence interval method `{method}`, only `standard`, `percentile`, `basic`, and `BCa` are supported",
            )

        self.iterations = iterations
        self.confidence = confidence
        self.seed = seed
        self.alpha = (1 - confidence) / 2
        self.method = method
        self.n_jobs = n_jobs
        self.chunksize = chunksize

        self._params = {
            "iterations": self.iterations,
            "alpha": self.alpha,
            "method": self.method,
            "seed": self.seed,
            "n_jobs": self.n_jobs,
            "chunksize": self.chunksize,
        }

    def run(
        self, df: pl.DataFrame, stat_func: StatFunc, **kwargs
    ) -> ConfidenceInterval:
        """Run bootstrap for an arbitrary function that accepts a Polars DataFrame and
        returns a scalar real number.

        Parameters
        ----------
        df : pl.DataFrame
            The data to pass to `stat_func`
        stat_func : StatFunc
            A callable that takes a Polars DataFrame as its first argument and returns
            a scalar real number.

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, higher)

        Added in version 0.1.0
        ----------------------
        """
        default = {"executor": "threads", "preserve_order": False}
        for k, v in default.items():
            if k not in kwargs:
                kwargs[k] = v

        func = functools.partial(_bs_func, df=df, stat_func=stat_func)

        if self.seed is None:
            iterable = (None for _ in range(self.iterations))
        else:
            iterable = (self.seed + i for i in range(self.iterations))

        bootstrap_stats = [
            x for x in _run_concurrent(func, iterable, **kwargs) if not math.isnan(x)
        ]

        if len(bootstrap_stats) == 0:
            return (math.nan, math.nan, math.nan)

        if self.method == "standard":
            return _standard_interval(bootstrap_stats, self.alpha)
        elif self.method == "percentile":
            return _percentile_interval(bootstrap_stats, self.alpha)
        elif self.method == "basic":
            original_stat = stat_func(df)
            return _basic_interval(original_stat, bootstrap_stats, self.alpha)
        elif self.method == "BCa":
            original_stat = stat_func(df)
            jacknife_stats = [x for x in _jacknife(df, stat_func) if not math.isnan(x)]

            return _bca_interval(
                original_stat, bootstrap_stats, jacknife_stats, self.alpha
            )
        else:
            # We shouldn't hit this since we check method in __init__, but it makes the
            # type-checker happy
            raise ValueError("Invalid method")

    def confusion_matrix(
        self,
        y_true: ArrayLike,
        y_pred: ArrayLike,
        beta: float = 1.0,
    ) -> BootstrappedConfusionMatrix:
        r"""Bootstrap confusion matrix. See [rapidstats.metrics.confusion_matrix][] for
        more details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_pred : ArrayLike
            Predicted target
        beta : float, optional
            \( \beta \) to use in \( F_\beta \), by default 1

        Returns
        -------
        BootstrappedConfusionMatrix
            A dataclass of confusion matrix metrics as (lower, mean, upper). See
            [rapidstats._bootstrap.BootstrappedConfusionMatrix][] for more details.

        Added in version 0.1.0
        ----------------------
        """
        df = _y_true_y_pred_to_df(y_true, y_pred)

        return BootstrappedConfusionMatrix(
            *_bootstrap_confusion_matrix(df, beta, **self._params)
        )

    def confusion_matrix_at_thresholds(
        self,
        y_true: ArrayLike,
        y_score: ArrayLike,
        thresholds: Optional[list[float]] = None,
        metrics: Iterable[ConfusionMatrixMetric] = DefaultConfusionMatrixMetrics,
        strategy: LoopStrategy = "auto",
        beta: float = 1.0,
    ) -> pl.DataFrame:
        r"""Bootstrap confusion matrix at thresholds. See
        [rapidstats.metrics.confusion_matrix_at_thresholds][] for more details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_score : ArrayLike
            Predicted scores
        thresholds : Optional[list[float]], optional
            The thresholds to compute `y_pred` at, i.e. y_score >= t. If None,
            uses every score present in `y_score`, by default None
        metrics : Iterable[ConfusionMatrixMetric], optional
            The metrics to compute, by default DefaultConfusionMatrixMetrics
        strategy : LoopStrategy, optional
            Computation method, by default "auto"
        beta : float, optional
            \( \beta \) to use in \( F_\beta \), by default 1

        Returns
        -------
        pl.DataFrame
            A DataFrame of `threshold`, `metric`, `lower`, `mean`, and `upper`

        Raises
        ------
        NotImplementedError
            When `strategy` is `cum_sum` and `method` is `BCa`

        Added in version 0.1.0
        ----------------------
        """
        df = _y_true_y_score_to_df(y_true, y_score).rename({"y_score": "threshold"})
        final_cols = ["threshold", "metric", "lower", "mean", "upper"]

        strategy = _set_loop_strategy(thresholds, strategy)

        if strategy == "loop":
            cms: list[pl.DataFrame] = []
            for t in tqdm(set(thresholds or y_score)):
                cm = (
                    self.confusion_matrix(
                        df["y_true"], df["threshold"].ge(t), beta=beta
                    )
                    .to_polars()
                    .with_columns(pl.lit(t).alias("threshold"))
                )
                cms.append(cm)

            return pl.concat(cms, how="vertical").with_columns(
                pl.col("lower", "mean", "upper").fill_nan(None)
            )
        elif strategy == "cum_sum":
            if thresholds is None:
                thresholds = df["threshold"].unique()

            def _cm_inner(pf: PolarsFrame) -> pl.LazyFrame:
                return (
                    pf.lazy()
                    .pipe(_base_confusion_matrix_at_thresholds)
                    .pipe(_full_confusion_matrix_from_base, beta=beta)
                    .unique("threshold")
                    .pipe(_map_to_thresholds, thresholds)
                    .drop("_threshold_actual")
                )

            def _cm(i: int) -> pl.LazyFrame:
                sample_df = df.sample(fraction=1, with_replacement=True, seed=i)

                return _cm_inner(sample_df)

            cms: list[pl.LazyFrame] = _run_concurrent(
                _cm,
                (
                    (self.seed + i for i in range(self.iterations))
                    if self.seed is not None
                    else (None for _ in range(self.iterations))
                ),
            )

            def _process_results(lf: pl.LazyFrame) -> pl.LazyFrame:
                return (
                    lf.select("threshold", *metrics)
                    .unpivot(index="threshold")
                    .rename({"variable": "metric"})
                )

            bootstrap_lf = pl.concat(cms, how="vertical").pipe(_process_results)

            lf = bootstrap_lf.group_by("threshold", "metric")

            if self.method == "standard":
                return (
                    _standard_interval_polars(lf, self.alpha)
                    .select(final_cols)
                    .collect()
                )
            elif self.method == "percentile":
                return (
                    _percentile_interval_polars(lf, self.alpha)
                    .select(final_cols)
                    .collect()
                )
            elif self.method == "basic":
                original = (
                    _cm_inner(df)
                    .select("threshold", *metrics)
                    .pipe(_map_to_thresholds, thresholds)
                    .unpivot(index="threshold")
                    .rename({"variable": "metric", "value": "original"})
                )

                return (
                    _percentile_interval_polars(lf, self.alpha)
                    .join(
                        original,
                        on=["threshold", "metric"],
                        how="left",
                        validate="1:1",
                    )
                    .pipe(_basic_interval_polars)
                    .select(final_cols)
                    .collect()
                )
            elif self.method == "BCa":
                raise NotImplementedError(
                    "Method `BCa` not implemented for strategy `cum_sum` due to https://github.com/pola-rs/polars/issues/20951"
                )
                original_lf = (
                    _cm_inner(df)
                    .select("threshold", *metrics)
                    .pipe(_map_to_thresholds, thresholds)
                    .unpivot(index="threshold")
                    .rename({"variable": "metric", "value": "original_value"})
                )
                jacknife_lf = pl.concat(_jacknife(df, _cm_inner), how="vertical").pipe(
                    _process_results
                )

                return (
                    _bca_interval_polars(
                        original_lf,
                        bootstrap_lf=bootstrap_lf,
                        jacknife_lf=jacknife_lf,
                        alpha=self.alpha,
                        by=["threshold", "metric"],
                    )
                    .select(final_cols)
                    .collect()
                )

    def roc_auc(
        self,
        y_true: ArrayLike,
        y_score: ArrayLike,
    ) -> ConfidenceInterval:
        """Bootstrap ROC-AUC. See [rapidstats.metrics.roc_auc][] for more details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_score : ArrayLike
            Predicted scores

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)

        Added in version 0.1.0
        ----------------------
        """
        df = _y_true_y_score_to_df(y_true, y_score).with_columns(
            pl.col("y_true").cast(pl.Float64)
        )

        return _bootstrap_roc_auc(df, **self._params)

    def average_precision(
        self, y_true: ArrayLike, y_score: ArrayLike
    ) -> ConfidenceInterval:
        """Bootstrap average precision. See [rapidstats.metrics.average_precision][] for more
        details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_score : ArrayLike
            Predicted scores

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)

        Added in version 0.1.0
        ----------------------
        """
        df = (
            _y_true_y_score_to_df(y_true, y_score)
            .rename({"y_score": "threshold"})
            .drop_nulls()
        )

        def _cm_inner(pf: PolarsFrame) -> pl.LazyFrame:
            return (
                pf.lazy()
                .pipe(_base_confusion_matrix_at_thresholds)
                .pipe(_full_confusion_matrix_from_base)
                .select("threshold", "precision", "tpr")
            )

        def _cm(i: int) -> pl.LazyFrame:
            sample_df = df.sample(fraction=1, with_replacement=True, seed=i)

            return _cm_inner(sample_df)

        cms: list[pl.LazyFrame] = _run_concurrent(
            _cm,
            (
                (self.seed + i for i in range(self.iterations))
                if self.seed is not None
                else (None for _ in range(self.iterations))
            ),
        )

        cms = [
            cm.with_columns(pl.lit(i).alias("iteration")) for i, cm in enumerate(cms)
        ]

        bootstrap_stats = (
            pl.concat(cms, how="vertical")
            .sort("threshold")
            .group_by("iteration", maintain_order=True)
            .agg(
                _ap_from_pr_curve(pl.col("precision"), pl.col("tpr")).alias(
                    "average_precision"
                )
            )
            .collect()["average_precision"]
            .to_list()
        )

        if self.method == "standard":
            return _standard_interval(bootstrap_stats, self.alpha)
        elif self.method == "percentile":
            return _percentile_interval(bootstrap_stats, self.alpha)
        elif self.method == "basic":
            original_stat = _ap(y_true, y_score)

            return _basic_interval(original_stat, bootstrap_stats, self.alpha)
        elif self.method == "BCa":
            original_stat = _ap(y_true, y_score)

            def _cm_jacknife(i):
                j_df = df.filter(pl.col("index").ne(i))

                return _cm_inner(j_df).with_columns(pl.lit(i).alias("iteration"))

            df = df.with_row_index("index")
            cms = _run_concurrent(_cm_jacknife, range(df.height))
            jacknife_stats = (
                pl.concat(cms, how="vertical")
                .sort("threshold")
                .group_by("iteration", maintain_order=True)
                .agg(
                    _ap_from_pr_curve(pl.col("precision"), pl.col("tpr")).alias(
                        "average_precision"
                    )
                )
                .collect()["average_precision"]
                .to_list()
            )

            return _bca_interval(
                original_stat, bootstrap_stats, jacknife_stats, self.alpha
            )

    def max_ks(self, y_true: ArrayLike, y_score: ArrayLike) -> ConfidenceInterval:
        """Bootstrap Max-KS. See [rapidstats.metrics.max_ks][] for more details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_score : ArrayLike
            Predicted scores

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)

        Added in version 0.1.0
        ----------------------
        """
        df = _y_true_y_score_to_df(y_true, y_score)

        return _bootstrap_max_ks(df, **self._params)

    def brier_loss(self, y_true: ArrayLike, y_score: ArrayLike) -> ConfidenceInterval:
        """Bootstrap Brier loss. See [rapidstats.metrics.brier_loss][] for more details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_score : ArrayLike
            Predicted scores

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)
        """
        df = _y_true_y_score_to_df(y_true, y_score)

        return _bootstrap_brier_loss(df, **self._params)

    def mean(self, y: ArrayLike) -> ConfidenceInterval:
        """Bootstrap mean.

        Parameters
        ----------
        y : ArrayLike
            A 1D-array

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)

        Added in version 0.1.0
        ----------------------
        """
        df = pl.DataFrame({"y": y})

        return _bootstrap_mean(df, **self._params)

    def adverse_impact_ratio(
        self, y_pred: ArrayLike, protected: ArrayLike, control: ArrayLike
    ) -> ConfidenceInterval:
        """Bootstrap AIR. See [rapidstats.metrics.adverse_impact_ratio][] for more details.

        Parameters
        ----------
        y_pred : ArrayLike
            Predicted target
        protected : ArrayLike
            An array of booleans identifying the protected class
        control : ArrayLike
            An array of booleans identifying the control class

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)

        Added in version 0.1.0
        ----------------------
        """
        df = pl.DataFrame(
            {"y_pred": y_pred, "protected": protected, "control": control}
        ).cast(pl.Boolean)

        return _bootstrap_adverse_impact_ratio(df, **self._params)

    def adverse_impact_ratio_at_thresholds(
        self,
        y_score: ArrayLike,
        protected: ArrayLike,
        control: ArrayLike,
        thresholds: Optional[list[float]] = None,
        strategy: LoopStrategy = "auto",
    ) -> pl.DataFrame:
        """Bootstrap AIR at thresholds. See
        [rapidstats.metrics.adverse_impact_ratio_at_thresholds][] for more details.

        Parameters
        ----------
        y_score : ArrayLike
            Predicted scores
        protected : ArrayLike
            An array of booleans identifying the protected class
        control : ArrayLike
            An array of booleans identifying the control class
        thresholds : Optional[list[float]], optional
            The thresholds to compute `is_predicted_negative` at, i.e. y_score < t.
            If None, uses every score present in `y_score`, by default None
        strategy : LoopStrategy, optional
            Computation method, by default "auto"

        Returns
        -------
        pl.DataFrame
            A DataFrame of `threshold`, `lower`, `mean`, and `upper`

        Raises
        ------
        NotImplementedError
            When `strategy` is `cum_sum` and `method` is `BCa`
        """
        df = pl.DataFrame(
            {"y_score": y_score, "protected": protected, "control": control}
        ).with_columns(pl.col("protected", "control").cast(pl.Boolean))

        strategy = _set_loop_strategy(thresholds, strategy)

        if strategy == "loop":
            airs: list[dict[str, float]] = []
            for t in tqdm(set(thresholds or y_score)):
                lower, mean, upper = self.adverse_impact_ratio(
                    df["y_score"].lt(t), df["protected"], df["control"]
                )
                airs.append(
                    {"threshold": t, "lower": lower, "mean": mean, "upper": upper}
                )

            return pl.DataFrame(airs).fill_nan(None).pipe(_fill_infinite, None)

        elif strategy == "cum_sum":
            if thresholds is None:
                thresholds = df["y_score"]

            def _air(i: int) -> pl.LazyFrame:
                sample_df = df.sample(fraction=1, with_replacement=True, seed=i)

                return _air_at_thresholds_core(sample_df, thresholds)

            airs: list[pl.LazyFrame] = _run_concurrent(
                _air,
                (
                    (self.seed + i for i in range(self.iterations))
                    if self.seed is not None
                    else (None for _ in range(self.iterations))
                ),
            )
            bootstrap_lf = (
                pl.concat(airs, how="vertical")
                .rename({"air": "value"})
                .with_columns(
                    _expr_fill_infinite(pl.col("value").fill_nan(None)).alias("value")
                )
            )

            lf = bootstrap_lf.group_by("threshold")

            final_cols = ["threshold", "lower", "mean", "upper"]

            if self.method == "standard":
                return (
                    _standard_interval_polars(lf, self.alpha)
                    .select(final_cols)
                    .collect()
                )
            elif self.method == "percentile":
                return (
                    _percentile_interval_polars(lf, self.alpha)
                    .select(final_cols)
                    .collect()
                )
            elif self.method == "basic":
                original = (
                    _air_at_thresholds_core(df)
                    .rename({"air": "original"})
                    .unique("threshold")
                )

                return (
                    _percentile_interval_polars(lf, self.alpha)
                    .join(original, on="threshold", how="left", validate="1:1")
                    .pipe(_basic_interval_polars)
                    .select(final_cols)
                    .collect()
                )
            elif self.method == "BCa":
                raise NotImplementedError(
                    "Method `BCa` not implemented for strategy `cum_sum` due to https://github.com/pola-rs/polars/issues/20951"
                )
                original_lf = (
                    _air_at_thresholds_core(df, thresholds)
                    .rename({"air": "original_value"})
                    .unique("threshold")
                )
                jacknife_lf = (
                    pl.concat(_jacknife(df, _air_at_thresholds_core), how="vertical")
                    .rename({"air": "value"})
                    .unique("threshold")
                )

                return (
                    _bca_interval_polars(
                        original_lf,
                        bootstrap_lf=bootstrap_lf.rename({"air": "value"}),
                        jacknife_lf=jacknife_lf,
                        alpha=self.alpha,
                        by=["threshold"],
                    )
                    .select(final_cols)
                    .collect()
                )

    def mean_squared_error(
        self, y_true: ArrayLike, y_score: ArrayLike
    ) -> ConfidenceInterval:
        r"""Bootstrap MSE. See [rapidstats.metrics.mean_squared_error][] for more details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_score : ArrayLike
            Predicted scores

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)

        Added in version 0.1.0
        ----------------------
        """
        return _bootstrap_mean_squared_error(
            _regression_to_df(y_true, y_score), **self._params
        )

    def root_mean_squared_error(
        self, y_true: ArrayLike, y_score: ArrayLike
    ) -> ConfidenceInterval:
        r"""Bootstrap RMSE. See [rapidstats.metrics.root_mean_squared_error][] for more details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_score : ArrayLike
            Predicted scores

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)

        Added in version 0.1.0
        ----------------------
        """
        return _bootstrap_root_mean_squared_error(
            _regression_to_df(y_true, y_score), **self._params
        )

    def r2(self, y_true: ArrayLike, y_score: ArrayLike) -> ConfidenceInterval:
        """Bootstrap R2. See [rapidstats.metrics.r2][] for more details.

        Parameters
        ----------
        y_true : ArrayLike
            Ground truth target
        y_score : ArrayLike
            Predicted scores

        Returns
        -------
        ConfidenceInterval
            A tuple of (lower, mean, upper)

        Added in version 0.1.0
        ----------------------
        """
        return _bootstrap_r2(_regression_to_df(y_true, y_score), **self._params)

adverse_impact_ratio(y_pred, protected, control)

Bootstrap AIR. See rapidstats.metrics.adverse_impact_ratio for more details.

Parameters:

Name Type Description Default
y_pred ArrayLike

Predicted target

required
protected ArrayLike

An array of booleans identifying the protected class

required
control ArrayLike

An array of booleans identifying the control class

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
def adverse_impact_ratio(
    self, y_pred: ArrayLike, protected: ArrayLike, control: ArrayLike
) -> ConfidenceInterval:
    """Bootstrap AIR. See [rapidstats.metrics.adverse_impact_ratio][] for more details.

    Parameters
    ----------
    y_pred : ArrayLike
        Predicted target
    protected : ArrayLike
        An array of booleans identifying the protected class
    control : ArrayLike
        An array of booleans identifying the control class

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)

    Added in version 0.1.0
    ----------------------
    """
    df = pl.DataFrame(
        {"y_pred": y_pred, "protected": protected, "control": control}
    ).cast(pl.Boolean)

    return _bootstrap_adverse_impact_ratio(df, **self._params)

adverse_impact_ratio_at_thresholds(y_score, protected, control, thresholds=None, strategy='auto')

Bootstrap AIR at thresholds. See rapidstats.metrics.adverse_impact_ratio_at_thresholds for more details.

Parameters:

Name Type Description Default
y_score ArrayLike

Predicted scores

required
protected ArrayLike

An array of booleans identifying the protected class

required
control ArrayLike

An array of booleans identifying the control class

required
thresholds Optional[list[float]]

The thresholds to compute is_predicted_negative at, i.e. y_score < t. If None, uses every score present in y_score, by default None

None
strategy LoopStrategy

Computation method, by default "auto"

'auto'

Returns:

Type Description
DataFrame

A DataFrame of threshold, lower, mean, and upper

Raises:

Type Description
NotImplementedError

When strategy is cum_sum and method is BCa

Source code in python/rapidstats/_bootstrap.py
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
def adverse_impact_ratio_at_thresholds(
    self,
    y_score: ArrayLike,
    protected: ArrayLike,
    control: ArrayLike,
    thresholds: Optional[list[float]] = None,
    strategy: LoopStrategy = "auto",
) -> pl.DataFrame:
    """Bootstrap AIR at thresholds. See
    [rapidstats.metrics.adverse_impact_ratio_at_thresholds][] for more details.

    Parameters
    ----------
    y_score : ArrayLike
        Predicted scores
    protected : ArrayLike
        An array of booleans identifying the protected class
    control : ArrayLike
        An array of booleans identifying the control class
    thresholds : Optional[list[float]], optional
        The thresholds to compute `is_predicted_negative` at, i.e. y_score < t.
        If None, uses every score present in `y_score`, by default None
    strategy : LoopStrategy, optional
        Computation method, by default "auto"

    Returns
    -------
    pl.DataFrame
        A DataFrame of `threshold`, `lower`, `mean`, and `upper`

    Raises
    ------
    NotImplementedError
        When `strategy` is `cum_sum` and `method` is `BCa`
    """
    df = pl.DataFrame(
        {"y_score": y_score, "protected": protected, "control": control}
    ).with_columns(pl.col("protected", "control").cast(pl.Boolean))

    strategy = _set_loop_strategy(thresholds, strategy)

    if strategy == "loop":
        airs: list[dict[str, float]] = []
        for t in tqdm(set(thresholds or y_score)):
            lower, mean, upper = self.adverse_impact_ratio(
                df["y_score"].lt(t), df["protected"], df["control"]
            )
            airs.append(
                {"threshold": t, "lower": lower, "mean": mean, "upper": upper}
            )

        return pl.DataFrame(airs).fill_nan(None).pipe(_fill_infinite, None)

    elif strategy == "cum_sum":
        if thresholds is None:
            thresholds = df["y_score"]

        def _air(i: int) -> pl.LazyFrame:
            sample_df = df.sample(fraction=1, with_replacement=True, seed=i)

            return _air_at_thresholds_core(sample_df, thresholds)

        airs: list[pl.LazyFrame] = _run_concurrent(
            _air,
            (
                (self.seed + i for i in range(self.iterations))
                if self.seed is not None
                else (None for _ in range(self.iterations))
            ),
        )
        bootstrap_lf = (
            pl.concat(airs, how="vertical")
            .rename({"air": "value"})
            .with_columns(
                _expr_fill_infinite(pl.col("value").fill_nan(None)).alias("value")
            )
        )

        lf = bootstrap_lf.group_by("threshold")

        final_cols = ["threshold", "lower", "mean", "upper"]

        if self.method == "standard":
            return (
                _standard_interval_polars(lf, self.alpha)
                .select(final_cols)
                .collect()
            )
        elif self.method == "percentile":
            return (
                _percentile_interval_polars(lf, self.alpha)
                .select(final_cols)
                .collect()
            )
        elif self.method == "basic":
            original = (
                _air_at_thresholds_core(df)
                .rename({"air": "original"})
                .unique("threshold")
            )

            return (
                _percentile_interval_polars(lf, self.alpha)
                .join(original, on="threshold", how="left", validate="1:1")
                .pipe(_basic_interval_polars)
                .select(final_cols)
                .collect()
            )
        elif self.method == "BCa":
            raise NotImplementedError(
                "Method `BCa` not implemented for strategy `cum_sum` due to https://github.com/pola-rs/polars/issues/20951"
            )
            original_lf = (
                _air_at_thresholds_core(df, thresholds)
                .rename({"air": "original_value"})
                .unique("threshold")
            )
            jacknife_lf = (
                pl.concat(_jacknife(df, _air_at_thresholds_core), how="vertical")
                .rename({"air": "value"})
                .unique("threshold")
            )

            return (
                _bca_interval_polars(
                    original_lf,
                    bootstrap_lf=bootstrap_lf.rename({"air": "value"}),
                    jacknife_lf=jacknife_lf,
                    alpha=self.alpha,
                    by=["threshold"],
                )
                .select(final_cols)
                .collect()
            )

average_precision(y_true, y_score)

Bootstrap average precision. See rapidstats.metrics.average_precision for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_score ArrayLike

Predicted scores

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
def average_precision(
    self, y_true: ArrayLike, y_score: ArrayLike
) -> ConfidenceInterval:
    """Bootstrap average precision. See [rapidstats.metrics.average_precision][] for more
    details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_score : ArrayLike
        Predicted scores

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)

    Added in version 0.1.0
    ----------------------
    """
    df = (
        _y_true_y_score_to_df(y_true, y_score)
        .rename({"y_score": "threshold"})
        .drop_nulls()
    )

    def _cm_inner(pf: PolarsFrame) -> pl.LazyFrame:
        return (
            pf.lazy()
            .pipe(_base_confusion_matrix_at_thresholds)
            .pipe(_full_confusion_matrix_from_base)
            .select("threshold", "precision", "tpr")
        )

    def _cm(i: int) -> pl.LazyFrame:
        sample_df = df.sample(fraction=1, with_replacement=True, seed=i)

        return _cm_inner(sample_df)

    cms: list[pl.LazyFrame] = _run_concurrent(
        _cm,
        (
            (self.seed + i for i in range(self.iterations))
            if self.seed is not None
            else (None for _ in range(self.iterations))
        ),
    )

    cms = [
        cm.with_columns(pl.lit(i).alias("iteration")) for i, cm in enumerate(cms)
    ]

    bootstrap_stats = (
        pl.concat(cms, how="vertical")
        .sort("threshold")
        .group_by("iteration", maintain_order=True)
        .agg(
            _ap_from_pr_curve(pl.col("precision"), pl.col("tpr")).alias(
                "average_precision"
            )
        )
        .collect()["average_precision"]
        .to_list()
    )

    if self.method == "standard":
        return _standard_interval(bootstrap_stats, self.alpha)
    elif self.method == "percentile":
        return _percentile_interval(bootstrap_stats, self.alpha)
    elif self.method == "basic":
        original_stat = _ap(y_true, y_score)

        return _basic_interval(original_stat, bootstrap_stats, self.alpha)
    elif self.method == "BCa":
        original_stat = _ap(y_true, y_score)

        def _cm_jacknife(i):
            j_df = df.filter(pl.col("index").ne(i))

            return _cm_inner(j_df).with_columns(pl.lit(i).alias("iteration"))

        df = df.with_row_index("index")
        cms = _run_concurrent(_cm_jacknife, range(df.height))
        jacknife_stats = (
            pl.concat(cms, how="vertical")
            .sort("threshold")
            .group_by("iteration", maintain_order=True)
            .agg(
                _ap_from_pr_curve(pl.col("precision"), pl.col("tpr")).alias(
                    "average_precision"
                )
            )
            .collect()["average_precision"]
            .to_list()
        )

        return _bca_interval(
            original_stat, bootstrap_stats, jacknife_stats, self.alpha
        )

brier_loss(y_true, y_score)

Bootstrap Brier loss. See rapidstats.metrics.brier_loss for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_score ArrayLike

Predicted scores

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Source code in python/rapidstats/_bootstrap.py
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
def brier_loss(self, y_true: ArrayLike, y_score: ArrayLike) -> ConfidenceInterval:
    """Bootstrap Brier loss. See [rapidstats.metrics.brier_loss][] for more details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_score : ArrayLike
        Predicted scores

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)
    """
    df = _y_true_y_score_to_df(y_true, y_score)

    return _bootstrap_brier_loss(df, **self._params)

confusion_matrix(y_true, y_pred, beta=1.0)

Bootstrap confusion matrix. See rapidstats.metrics.confusion_matrix for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_pred ArrayLike

Predicted target

required
beta float

\( \beta \) to use in \( F_\beta \), by default 1

1.0

Returns:

Type Description
BootstrappedConfusionMatrix

A dataclass of confusion matrix metrics as (lower, mean, upper). See rapidstats._bootstrap.BootstrappedConfusionMatrix for more details.

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
def confusion_matrix(
    self,
    y_true: ArrayLike,
    y_pred: ArrayLike,
    beta: float = 1.0,
) -> BootstrappedConfusionMatrix:
    r"""Bootstrap confusion matrix. See [rapidstats.metrics.confusion_matrix][] for
    more details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_pred : ArrayLike
        Predicted target
    beta : float, optional
        \( \beta \) to use in \( F_\beta \), by default 1

    Returns
    -------
    BootstrappedConfusionMatrix
        A dataclass of confusion matrix metrics as (lower, mean, upper). See
        [rapidstats._bootstrap.BootstrappedConfusionMatrix][] for more details.

    Added in version 0.1.0
    ----------------------
    """
    df = _y_true_y_pred_to_df(y_true, y_pred)

    return BootstrappedConfusionMatrix(
        *_bootstrap_confusion_matrix(df, beta, **self._params)
    )

confusion_matrix_at_thresholds(y_true, y_score, thresholds=None, metrics=DefaultConfusionMatrixMetrics, strategy='auto', beta=1.0)

Bootstrap confusion matrix at thresholds. See rapidstats.metrics.confusion_matrix_at_thresholds for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_score ArrayLike

Predicted scores

required
thresholds Optional[list[float]]

The thresholds to compute y_pred at, i.e. y_score >= t. If None, uses every score present in y_score, by default None

None
metrics Iterable[ConfusionMatrixMetric]

The metrics to compute, by default DefaultConfusionMatrixMetrics

DefaultConfusionMatrixMetrics
strategy LoopStrategy

Computation method, by default "auto"

'auto'
beta float

\( \beta \) to use in \( F_\beta \), by default 1

1.0

Returns:

Type Description
DataFrame

A DataFrame of threshold, metric, lower, mean, and upper

Raises:

Type Description
NotImplementedError

When strategy is cum_sum and method is BCa

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
def confusion_matrix_at_thresholds(
    self,
    y_true: ArrayLike,
    y_score: ArrayLike,
    thresholds: Optional[list[float]] = None,
    metrics: Iterable[ConfusionMatrixMetric] = DefaultConfusionMatrixMetrics,
    strategy: LoopStrategy = "auto",
    beta: float = 1.0,
) -> pl.DataFrame:
    r"""Bootstrap confusion matrix at thresholds. See
    [rapidstats.metrics.confusion_matrix_at_thresholds][] for more details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_score : ArrayLike
        Predicted scores
    thresholds : Optional[list[float]], optional
        The thresholds to compute `y_pred` at, i.e. y_score >= t. If None,
        uses every score present in `y_score`, by default None
    metrics : Iterable[ConfusionMatrixMetric], optional
        The metrics to compute, by default DefaultConfusionMatrixMetrics
    strategy : LoopStrategy, optional
        Computation method, by default "auto"
    beta : float, optional
        \( \beta \) to use in \( F_\beta \), by default 1

    Returns
    -------
    pl.DataFrame
        A DataFrame of `threshold`, `metric`, `lower`, `mean`, and `upper`

    Raises
    ------
    NotImplementedError
        When `strategy` is `cum_sum` and `method` is `BCa`

    Added in version 0.1.0
    ----------------------
    """
    df = _y_true_y_score_to_df(y_true, y_score).rename({"y_score": "threshold"})
    final_cols = ["threshold", "metric", "lower", "mean", "upper"]

    strategy = _set_loop_strategy(thresholds, strategy)

    if strategy == "loop":
        cms: list[pl.DataFrame] = []
        for t in tqdm(set(thresholds or y_score)):
            cm = (
                self.confusion_matrix(
                    df["y_true"], df["threshold"].ge(t), beta=beta
                )
                .to_polars()
                .with_columns(pl.lit(t).alias("threshold"))
            )
            cms.append(cm)

        return pl.concat(cms, how="vertical").with_columns(
            pl.col("lower", "mean", "upper").fill_nan(None)
        )
    elif strategy == "cum_sum":
        if thresholds is None:
            thresholds = df["threshold"].unique()

        def _cm_inner(pf: PolarsFrame) -> pl.LazyFrame:
            return (
                pf.lazy()
                .pipe(_base_confusion_matrix_at_thresholds)
                .pipe(_full_confusion_matrix_from_base, beta=beta)
                .unique("threshold")
                .pipe(_map_to_thresholds, thresholds)
                .drop("_threshold_actual")
            )

        def _cm(i: int) -> pl.LazyFrame:
            sample_df = df.sample(fraction=1, with_replacement=True, seed=i)

            return _cm_inner(sample_df)

        cms: list[pl.LazyFrame] = _run_concurrent(
            _cm,
            (
                (self.seed + i for i in range(self.iterations))
                if self.seed is not None
                else (None for _ in range(self.iterations))
            ),
        )

        def _process_results(lf: pl.LazyFrame) -> pl.LazyFrame:
            return (
                lf.select("threshold", *metrics)
                .unpivot(index="threshold")
                .rename({"variable": "metric"})
            )

        bootstrap_lf = pl.concat(cms, how="vertical").pipe(_process_results)

        lf = bootstrap_lf.group_by("threshold", "metric")

        if self.method == "standard":
            return (
                _standard_interval_polars(lf, self.alpha)
                .select(final_cols)
                .collect()
            )
        elif self.method == "percentile":
            return (
                _percentile_interval_polars(lf, self.alpha)
                .select(final_cols)
                .collect()
            )
        elif self.method == "basic":
            original = (
                _cm_inner(df)
                .select("threshold", *metrics)
                .pipe(_map_to_thresholds, thresholds)
                .unpivot(index="threshold")
                .rename({"variable": "metric", "value": "original"})
            )

            return (
                _percentile_interval_polars(lf, self.alpha)
                .join(
                    original,
                    on=["threshold", "metric"],
                    how="left",
                    validate="1:1",
                )
                .pipe(_basic_interval_polars)
                .select(final_cols)
                .collect()
            )
        elif self.method == "BCa":
            raise NotImplementedError(
                "Method `BCa` not implemented for strategy `cum_sum` due to https://github.com/pola-rs/polars/issues/20951"
            )
            original_lf = (
                _cm_inner(df)
                .select("threshold", *metrics)
                .pipe(_map_to_thresholds, thresholds)
                .unpivot(index="threshold")
                .rename({"variable": "metric", "value": "original_value"})
            )
            jacknife_lf = pl.concat(_jacknife(df, _cm_inner), how="vertical").pipe(
                _process_results
            )

            return (
                _bca_interval_polars(
                    original_lf,
                    bootstrap_lf=bootstrap_lf,
                    jacknife_lf=jacknife_lf,
                    alpha=self.alpha,
                    by=["threshold", "metric"],
                )
                .select(final_cols)
                .collect()
            )

max_ks(y_true, y_score)

Bootstrap Max-KS. See rapidstats.metrics.max_ks for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_score ArrayLike

Predicted scores

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
def max_ks(self, y_true: ArrayLike, y_score: ArrayLike) -> ConfidenceInterval:
    """Bootstrap Max-KS. See [rapidstats.metrics.max_ks][] for more details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_score : ArrayLike
        Predicted scores

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)

    Added in version 0.1.0
    ----------------------
    """
    df = _y_true_y_score_to_df(y_true, y_score)

    return _bootstrap_max_ks(df, **self._params)

mean(y)

Bootstrap mean.

Parameters:

Name Type Description Default
y ArrayLike

A 1D-array

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
def mean(self, y: ArrayLike) -> ConfidenceInterval:
    """Bootstrap mean.

    Parameters
    ----------
    y : ArrayLike
        A 1D-array

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)

    Added in version 0.1.0
    ----------------------
    """
    df = pl.DataFrame({"y": y})

    return _bootstrap_mean(df, **self._params)

mean_squared_error(y_true, y_score)

Bootstrap MSE. See rapidstats.metrics.mean_squared_error for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_score ArrayLike

Predicted scores

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
def mean_squared_error(
    self, y_true: ArrayLike, y_score: ArrayLike
) -> ConfidenceInterval:
    r"""Bootstrap MSE. See [rapidstats.metrics.mean_squared_error][] for more details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_score : ArrayLike
        Predicted scores

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)

    Added in version 0.1.0
    ----------------------
    """
    return _bootstrap_mean_squared_error(
        _regression_to_df(y_true, y_score), **self._params
    )

r2(y_true, y_score)

Bootstrap R2. See rapidstats.metrics.r2 for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_score ArrayLike

Predicted scores

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
def r2(self, y_true: ArrayLike, y_score: ArrayLike) -> ConfidenceInterval:
    """Bootstrap R2. See [rapidstats.metrics.r2][] for more details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_score : ArrayLike
        Predicted scores

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)

    Added in version 0.1.0
    ----------------------
    """
    return _bootstrap_r2(_regression_to_df(y_true, y_score), **self._params)

roc_auc(y_true, y_score)

Bootstrap ROC-AUC. See rapidstats.metrics.roc_auc for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_score ArrayLike

Predicted scores

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
def roc_auc(
    self,
    y_true: ArrayLike,
    y_score: ArrayLike,
) -> ConfidenceInterval:
    """Bootstrap ROC-AUC. See [rapidstats.metrics.roc_auc][] for more details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_score : ArrayLike
        Predicted scores

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)

    Added in version 0.1.0
    ----------------------
    """
    df = _y_true_y_score_to_df(y_true, y_score).with_columns(
        pl.col("y_true").cast(pl.Float64)
    )

    return _bootstrap_roc_auc(df, **self._params)

root_mean_squared_error(y_true, y_score)

Bootstrap RMSE. See rapidstats.metrics.root_mean_squared_error for more details.

Parameters:

Name Type Description Default
y_true ArrayLike

Ground truth target

required
y_score ArrayLike

Predicted scores

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, upper)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
def root_mean_squared_error(
    self, y_true: ArrayLike, y_score: ArrayLike
) -> ConfidenceInterval:
    r"""Bootstrap RMSE. See [rapidstats.metrics.root_mean_squared_error][] for more details.

    Parameters
    ----------
    y_true : ArrayLike
        Ground truth target
    y_score : ArrayLike
        Predicted scores

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, upper)

    Added in version 0.1.0
    ----------------------
    """
    return _bootstrap_root_mean_squared_error(
        _regression_to_df(y_true, y_score), **self._params
    )

run(df, stat_func, **kwargs)

Run bootstrap for an arbitrary function that accepts a Polars DataFrame and returns a scalar real number.

Parameters:

Name Type Description Default
df DataFrame

The data to pass to stat_func

required
stat_func StatFunc

A callable that takes a Polars DataFrame as its first argument and returns a scalar real number.

required

Returns:

Type Description
ConfidenceInterval

A tuple of (lower, mean, higher)

Added in version 0.1.0
Source code in python/rapidstats/_bootstrap.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def run(
    self, df: pl.DataFrame, stat_func: StatFunc, **kwargs
) -> ConfidenceInterval:
    """Run bootstrap for an arbitrary function that accepts a Polars DataFrame and
    returns a scalar real number.

    Parameters
    ----------
    df : pl.DataFrame
        The data to pass to `stat_func`
    stat_func : StatFunc
        A callable that takes a Polars DataFrame as its first argument and returns
        a scalar real number.

    Returns
    -------
    ConfidenceInterval
        A tuple of (lower, mean, higher)

    Added in version 0.1.0
    ----------------------
    """
    default = {"executor": "threads", "preserve_order": False}
    for k, v in default.items():
        if k not in kwargs:
            kwargs[k] = v

    func = functools.partial(_bs_func, df=df, stat_func=stat_func)

    if self.seed is None:
        iterable = (None for _ in range(self.iterations))
    else:
        iterable = (self.seed + i for i in range(self.iterations))

    bootstrap_stats = [
        x for x in _run_concurrent(func, iterable, **kwargs) if not math.isnan(x)
    ]

    if len(bootstrap_stats) == 0:
        return (math.nan, math.nan, math.nan)

    if self.method == "standard":
        return _standard_interval(bootstrap_stats, self.alpha)
    elif self.method == "percentile":
        return _percentile_interval(bootstrap_stats, self.alpha)
    elif self.method == "basic":
        original_stat = stat_func(df)
        return _basic_interval(original_stat, bootstrap_stats, self.alpha)
    elif self.method == "BCa":
        original_stat = stat_func(df)
        jacknife_stats = [x for x in _jacknife(df, stat_func) if not math.isnan(x)]

        return _bca_interval(
            original_stat, bootstrap_stats, jacknife_stats, self.alpha
        )
    else:
        # We shouldn't hit this since we check method in __init__, but it makes the
        # type-checker happy
        raise ValueError("Invalid method")

BootstrappedConfusionMatrix dataclass

Result object returned by rapidstats.Bootstrap().confusion_matrix.

See rapidstats.metrics.ConfusionMatrix for a detailed breakdown of the attributes stored in this class. However, instead of storing the statistic, it stores the bootstrapped confidence interval as (lower, mean, upper).

Source code in python/rapidstats/_bootstrap.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@dataclasses.dataclass
class BootstrappedConfusionMatrix:
    """Result object returned by `rapidstats.Bootstrap().confusion_matrix`.

    See [rapidstats.metrics.ConfusionMatrix][] for a detailed breakdown of the attributes stored in
    this class. However, instead of storing the statistic, it stores the bootstrapped
    confidence interval as (lower, mean, upper).
    """

    tn: ConfidenceInterval
    fp: ConfidenceInterval
    fn: ConfidenceInterval
    tp: ConfidenceInterval
    tpr: ConfidenceInterval
    fpr: ConfidenceInterval
    fnr: ConfidenceInterval
    tnr: ConfidenceInterval
    prevalence: ConfidenceInterval
    prevalence_threshold: ConfidenceInterval
    informedness: ConfidenceInterval
    precision: ConfidenceInterval
    false_omission_rate: ConfidenceInterval
    plr: ConfidenceInterval
    nlr: ConfidenceInterval
    acc: ConfidenceInterval
    balanced_accuracy: ConfidenceInterval
    fbeta: ConfidenceInterval
    folkes_mallows_index: ConfidenceInterval
    mcc: ConfidenceInterval
    threat_score: ConfidenceInterval
    markedness: ConfidenceInterval
    fdr: ConfidenceInterval
    npv: ConfidenceInterval
    dor: ConfidenceInterval
    ppr: ConfidenceInterval
    pnr: ConfidenceInterval

    def to_polars(self) -> pl.DataFrame:
        """Transform the dataclass to a long Polars DataFrame with columns
        `metric`, `lower`, `mean`, and `upper`.

        Returns
        -------
        pl.DataFrame
            A DataFrame with columns `metric`, `lower`, `mean`, and `upper`
        """
        dct = self.__dict__
        lower = []
        mean = []
        upper = []
        for l, m, u in dct.values():  # noqa: E741
            lower.append(l)
            mean.append(m)
            upper.append(u)

        return pl.DataFrame(
            {
                "metric": dct.keys(),
                "lower": lower,
                "mean": mean,
                "upper": upper,
            }
        )

to_polars()

Transform the dataclass to a long Polars DataFrame with columns metric, lower, mean, and upper.

Returns:

Type Description
DataFrame

A DataFrame with columns metric, lower, mean, and upper

Source code in python/rapidstats/_bootstrap.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def to_polars(self) -> pl.DataFrame:
    """Transform the dataclass to a long Polars DataFrame with columns
    `metric`, `lower`, `mean`, and `upper`.

    Returns
    -------
    pl.DataFrame
        A DataFrame with columns `metric`, `lower`, `mean`, and `upper`
    """
    dct = self.__dict__
    lower = []
    mean = []
    upper = []
    for l, m, u in dct.values():  # noqa: E741
        lower.append(l)
        mean.append(m)
        upper.append(u)

    return pl.DataFrame(
        {
            "metric": dct.keys(),
            "lower": lower,
            "mean": mean,
            "upper": upper,
        }
    )