Skip to content

API Reference

Top-level API

Run bootstrap estimation.

Parameters

data : array-like or pandas Series/DataFrame Observed sample. statistic : callable (array) -> float. If vectorized=True, must accept (array_2d, axis=1) -> array_1d. method : str One of: bca, percentile, basic, studentized, poisson, bernoulli, bayesian, subsampling, mbb, cbb, stationary, tapered, sieve, wild, cluster, strata. ci_method : str or None CI construction for generator-based methods: "percentile" or "basic". Defaults to "percentile". vectorized : bool If True, statistic is called as statistic(batch, axis=1). n_jobs : int Parallelism for jackknife in BCa (effective only for n ≥ 2000).

Source code in src/bootstrapx/api.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
def bootstrap(
    data: Any,
    statistic: Callable[..., float],
    *,
    method: str = "bca",
    n_resamples: int = 9999,
    batch_size: int | None = None,
    confidence_level: float = 0.95,
    ci_method: str | None = None,
    backend: str = "auto",
    random_state: int | np.random.Generator | None = None,
    vectorized: bool = False,
    n_jobs: int = 1,
    **kwargs: Any,
) -> BootstrapResult:
    """Run bootstrap estimation.

    Parameters
    ----------
    data : array-like or pandas Series/DataFrame
        Observed sample.
    statistic : callable
        ``(array) -> float``.  If ``vectorized=True``, must accept
        ``(array_2d, axis=1) -> array_1d``.
    method : str
        One of: bca, percentile, basic, studentized, poisson, bernoulli,
        bayesian, subsampling, mbb, cbb, stationary, tapered, sieve,
        wild, cluster, strata.
    ci_method : str or None
        CI construction for generator-based methods: ``"percentile"`` or
        ``"basic"``.  Defaults to ``"percentile"``.
    vectorized : bool
        If ``True``, ``statistic`` is called as ``statistic(batch, axis=1)``.
    n_jobs : int
        Parallelism for jackknife in BCa (effective only for n ≥ 2000).
    """
    method = method.lower().strip()
    if method not in _ALL_METHODS:
        raise ValueError(
            f"Unknown method {method!r}. Choose from {sorted(_ALL_METHODS)}."
        )

    arr = validate_data(data, allow_2d=(method in _HIER_METHODS))
    n = arr.shape[0]

    rng: np.random.Generator = (
        random_state
        if isinstance(random_state, np.random.Generator)
        else np.random.default_rng(random_state)
    )

    if batch_size is None:
        batch_size = auto_batch_size(n, n_resamples)

    backend_kind = resolve_backend(backend)
    theta_hat = float(statistic(arr))

    if method in _CI_CAPABLE:
        boot_stats = apply_statistic_batched(
            arr, statistic, batch_size, n_resamples, backend_kind, rng,
            vectorized=vectorized,
        )

        if method == "percentile":
            ci = percentile_interval(boot_stats, confidence_level)

        elif method == "basic":
            ci = basic_interval(boot_stats, theta_hat, confidence_level)

        elif method == "bca":
            ci = bca_interval(
                boot_stats, arr, statistic, theta_hat, confidence_level,
                n_jobs=n_jobs,
            )

        elif method == "studentized":
            n_inner = int(kwargs.get("n_inner", 50))
            boot_se = np.empty(n_resamples, dtype=np.float64)
            done = 0
            while done < n_resamples:
                bs = min(batch_size, n_resamples - done)
                outer_idx = rng.integers(0, n, size=(bs, n))
                # Vectorise inner SE: draw (n_inner, n) indices once per outer sample
                inner_idx = rng.integers(0, n, size=(n_inner, n))
                for b in range(bs):
                    sample = arr[outer_idx[b]]
                    inner_vals = np.array(
                        [float(statistic(sample[inner_idx[k]])) for k in range(n_inner)]
                    )
                    boot_se[done + b] = float(np.std(inner_vals, ddof=1))
                done += bs
            ci = studentized_interval(
                arr, statistic, theta_hat, boot_stats, boot_se, confidence_level,
            )

    else:
        if method == "bayesian":
            gen = bayesian_resample(arr, n_resamples, batch_size, rng)
            boot_stats_list = _collect_bayesian(gen, statistic, rng)  # pass rng!

        elif method == "poisson":
            gen = poisson_resample(arr, n_resamples, batch_size, rng)
            boot_stats_list = _collect_weighted(gen, statistic, arr)

        elif method == "bernoulli":
            prob = float(kwargs.get("prob", 0.5))
            gen = bernoulli_resample(arr, n_resamples, batch_size, rng, prob=prob)
            boot_stats_list = _collect_weighted(gen, statistic, arr)

        elif method == "cluster":
            cids = kwargs.get("cluster_ids")
            if cids is None:
                raise ValueError("cluster method requires `cluster_ids` kwarg.")
            gen = cluster_resample(arr, np.asarray(cids), n_resamples, batch_size, rng)
            boot_stats_list = _collect_arrays(gen, statistic)

        elif method == "strata":
            sids = kwargs.get("strata_ids")
            if sids is None:
                raise ValueError("strata method requires `strata_ids` kwarg.")
            gen = strata_resample(arr, np.asarray(sids), n_resamples, batch_size, rng)
            boot_stats_list = _collect_arrays(gen, statistic)

        elif method == "subsampling":
            ss = kwargs.get("subsample_size")
            gen = subsampling_resample(arr, n_resamples, batch_size, rng, subsample_size=ss)
            boot_stats_list = _collect_arrays(gen, statistic)

        elif method == "mbb":
            bl = int(kwargs.get("block_length", 10))
            gen = mbb_resample(arr, n_resamples, batch_size, rng, block_length=bl)
            boot_stats_list = _collect_arrays(gen, statistic)

        elif method == "cbb":
            bl = int(kwargs.get("block_length", 10))
            gen = cbb_resample(arr, n_resamples, batch_size, rng, block_length=bl)
            boot_stats_list = _collect_arrays(gen, statistic)

        elif method == "stationary":
            mb = float(kwargs.get("mean_block", 10.0))
            gen = stationary_resample(arr, n_resamples, batch_size, rng, mean_block=mb)
            boot_stats_list = _collect_arrays(gen, statistic)

        elif method == "tapered":
            bl = int(kwargs.get("block_length", 10))
            tp = str(kwargs.get("taper", "tukey"))
            gen = tapered_block_resample(
                arr, n_resamples, batch_size, rng, block_length=bl, taper=tp,
            )
            boot_stats_list = _collect_arrays(gen, statistic)

        elif method == "sieve":
            ar = kwargs.get("ar_order")
            gen = sieve_resample(arr, n_resamples, batch_size, rng, ar_order=ar)
            boot_stats_list = _collect_arrays(gen, statistic)

        elif method == "wild":
            fit = kwargs.get("fitted")
            dist = str(kwargs.get("distribution", "rademacher"))
            gen = wild_resample(arr, n_resamples, batch_size, rng, fitted=fit, distribution=dist)
            boot_stats_list = _collect_arrays(gen, statistic)

        else:
            raise ValueError(f"Method {method!r} not implemented.")

        boot_stats = np.array(boot_stats_list, dtype=np.float64)

        _ci_method = (ci_method or "percentile").lower()
        if _ci_method == "basic":
            ci = basic_interval(boot_stats, theta_hat, confidence_level)
        else:
            ci = percentile_interval(boot_stats, confidence_level)

    return BootstrapResult(
        confidence_interval=ci,
        bootstrap_distribution=boot_stats,
        theta_hat=theta_hat,
        standard_error=float(np.std(boot_stats, ddof=1)),
        n_resamples=len(boot_stats),
        method=method,
    )

Container for bootstrap estimation results.

Source code in src/bootstrapx/api.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
@dataclass
class BootstrapResult:
    """Container for bootstrap estimation results."""

    confidence_interval: ConfidenceInterval
    bootstrap_distribution: np.ndarray
    theta_hat: float
    standard_error: float
    n_resamples: int
    method: str
    extra: dict[str, Any] = field(default_factory=dict)

    def __repr__(self) -> str:
        ci = self.confidence_interval
        return (
            f"BootstrapResult(method={self.method!r}, "
            f"theta_hat={self.theta_hat:.6g}, "
            f"se={self.standard_error:.6g}, "
            f"CI=[{ci.low:.6g}, {ci.high:.6g}])"
        )
Source code in src/bootstrapx/stats/confidence.py
20
21
22
23
24
25
26
27
28
29
30
31
@dataclass
class ConfidenceInterval:
    low: float
    high: float
    method: str

    def __contains__(self, value: float) -> bool:
        return self.low <= value <= self.high

    @property
    def width(self) -> float:
        return self.high - self.low

Integrations

Bases: BaseCrossValidator

Bootstrap cross-validator compatible with scikit-learn's CV API.

Generates n_splits bootstrap train/test splits. Each training set is a bootstrap resample of size n (with replacement); the test set contains the out-of-bag (OOB) observations not selected for training.

Parameters

n_splits : int, default=200 Number of bootstrap iterations. random_state : int or np.random.Generator or None Seed for reproducibility.

Notes

  • Usable with cross_val_score, cross_validate, GridSearchCV.
  • OOB test set size ≈ 0.368 × n per split (Poisson approximation).
  • For the 0.632 bootstrap estimator of generalization error, average 0.368 * oob_score + 0.632 * train_score across splits.
Source code in src/bootstrapx/compat/sklearn_cv.py
44
45
46
47
48
49
50
51
52
53
54
55
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
class BootstrapCV(BaseCrossValidator):
    """Bootstrap cross-validator compatible with scikit-learn's CV API.

    Generates ``n_splits`` bootstrap train/test splits. Each training set
    is a bootstrap resample of size ``n`` (with replacement); the test set
    contains the out-of-bag (OOB) observations not selected for training.

    Parameters
    ----------
    n_splits : int, default=200
        Number of bootstrap iterations.
    random_state : int or np.random.Generator or None
        Seed for reproducibility.

    Notes
    -----
    - Usable with ``cross_val_score``, ``cross_validate``, ``GridSearchCV``.
    - OOB test set size ≈ 0.368 × n per split (Poisson approximation).
    - For the 0.632 bootstrap estimator of generalization error, average
      ``0.368 * oob_score + 0.632 * train_score`` across splits.
    """

    def __init__(self, n_splits: int = 200, random_state: int | np.random.Generator | None = None):
        self.n_splits = n_splits
        self.random_state = random_state

    def split(self, X, y=None, groups=None):
        X, y, groups = indexable(X, y, groups)
        n = len(X)
        rng = (
            self.random_state
            if isinstance(self.random_state, np.random.Generator)
            else np.random.default_rng(self.random_state)
        )
        all_idx = np.arange(n)
        for _ in range(self.n_splits):
            train = rng.integers(0, n, size=n)
            test = np.setdiff1d(all_idx, train)
            if len(test) == 0:
                continue
            yield train, test

    def get_n_splits(self, X=None, y=None, groups=None) -> int:
        return self.n_splits

    def _iter_test_indices(self, X=None, y=None, groups=None):
        # Required by BaseCrossValidator but not used directly
        n = len(X)  # type: ignore[arg-type]
        rng = np.random.default_rng(self.random_state)
        all_idx = np.arange(n)
        for _ in range(self.n_splits):
            train = rng.integers(0, n, size=n)
            yield np.setdiff1d(all_idx, train)

Accessor registered as pd.Series.bootstrap.

Source code in src/bootstrapx/compat/pandas_accessor.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 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
class _BootstrapSeriesAccessor:
    """Accessor registered as ``pd.Series.bootstrap``."""

    def __init__(self, obj: pd.Series):
        self._obj = obj

    def ci(
        self,
        statistic: Callable[..., float],
        *,
        method: str = "bca",
        n_resamples: int = 9999,
        confidence_level: float = 0.95,
        random_state: int | None = None,
        **kwargs: Any,
    ) -> BootstrapResult:
        """Run bootstrap and return a :class:`~bootstrapx.BootstrapResult`."""
        return bootstrap(
            self._obj,
            statistic,
            method=method,
            n_resamples=n_resamples,
            confidence_level=confidence_level,
            random_state=random_state,
            **kwargs,
        )

    def bca(
        self,
        statistic: Callable[..., float],
        n_resamples: int = 9999,
        confidence_level: float = 0.95,
        random_state: int | None = None,
    ) -> BootstrapResult:
        """Shortcut for ``method='bca'``."""
        return self.ci(
            statistic,
            method="bca",
            n_resamples=n_resamples,
            confidence_level=confidence_level,
            random_state=random_state,
        )

    def percentile(
        self,
        statistic: Callable[..., float],
        n_resamples: int = 9999,
        confidence_level: float = 0.95,
        random_state: int | None = None,
    ) -> BootstrapResult:
        """Shortcut for ``method='percentile'``."""
        return self.ci(
            statistic,
            method="percentile",
            n_resamples=n_resamples,
            confidence_level=confidence_level,
            random_state=random_state,
        )

bca(statistic, n_resamples=9999, confidence_level=0.95, random_state=None)

Shortcut for method='bca'.

Source code in src/bootstrapx/compat/pandas_accessor.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def bca(
    self,
    statistic: Callable[..., float],
    n_resamples: int = 9999,
    confidence_level: float = 0.95,
    random_state: int | None = None,
) -> BootstrapResult:
    """Shortcut for ``method='bca'``."""
    return self.ci(
        statistic,
        method="bca",
        n_resamples=n_resamples,
        confidence_level=confidence_level,
        random_state=random_state,
    )

ci(statistic, *, method='bca', n_resamples=9999, confidence_level=0.95, random_state=None, **kwargs)

Run bootstrap and return a :class:~bootstrapx.BootstrapResult.

Source code in src/bootstrapx/compat/pandas_accessor.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def ci(
    self,
    statistic: Callable[..., float],
    *,
    method: str = "bca",
    n_resamples: int = 9999,
    confidence_level: float = 0.95,
    random_state: int | None = None,
    **kwargs: Any,
) -> BootstrapResult:
    """Run bootstrap and return a :class:`~bootstrapx.BootstrapResult`."""
    return bootstrap(
        self._obj,
        statistic,
        method=method,
        n_resamples=n_resamples,
        confidence_level=confidence_level,
        random_state=random_state,
        **kwargs,
    )

percentile(statistic, n_resamples=9999, confidence_level=0.95, random_state=None)

Shortcut for method='percentile'.

Source code in src/bootstrapx/compat/pandas_accessor.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def percentile(
    self,
    statistic: Callable[..., float],
    n_resamples: int = 9999,
    confidence_level: float = 0.95,
    random_state: int | None = None,
) -> BootstrapResult:
    """Shortcut for ``method='percentile'``."""
    return self.ci(
        statistic,
        method="percentile",
        n_resamples=n_resamples,
        confidence_level=confidence_level,
        random_state=random_state,
    )

Accessor registered as pd.DataFrame.bootstrap.

Applies bootstrap column-wise and returns a summary DataFrame.

Source code in src/bootstrapx/compat/pandas_accessor.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
class _BootstrapDataFrameAccessor:
    """Accessor registered as ``pd.DataFrame.bootstrap``.

    Applies bootstrap column-wise and returns a summary DataFrame.
    """

    def __init__(self, obj: pd.DataFrame):
        self._obj = obj

    def summary(
        self,
        statistic: Callable[..., float],
        *,
        method: str = "bca",
        n_resamples: int = 9999,
        confidence_level: float = 0.95,
        random_state: int | None = None,
        **kwargs: Any,
    ) -> pd.DataFrame:
        """Return a DataFrame with bootstrap CI summary for each column.

        Returns
        -------
        pd.DataFrame
            Index: column names of the original DataFrame.
            Columns: ``theta_hat``, ``ci_low``, ``ci_high``, ``se``, ``method``.
        """
        rows = []
        for col in self._obj.columns:
            r = bootstrap(
                self._obj[col],
                statistic,
                method=method,
                n_resamples=n_resamples,
                confidence_level=confidence_level,
                random_state=random_state,
                **kwargs,
            )
            rows.append({
                "column": col,
                "theta_hat": r.theta_hat,
                "ci_low": r.confidence_interval.low,
                "ci_high": r.confidence_interval.high,
                "se": r.standard_error,
                "method": r.method,
            })
        return pd.DataFrame(rows).set_index("column")

    def ci(
        self,
        statistic: Callable[..., float],
        *,
        method: str = "bca",
        n_resamples: int = 9999,
        confidence_level: float = 0.95,
        random_state: int | None = None,
        **kwargs: Any,
    ) -> pd.DataFrame:
        """Alias for :meth:`summary`."""
        return self.summary(
            statistic,
            method=method,
            n_resamples=n_resamples,
            confidence_level=confidence_level,
            random_state=random_state,
            **kwargs,
        )

ci(statistic, *, method='bca', n_resamples=9999, confidence_level=0.95, random_state=None, **kwargs)

Alias for :meth:summary.

Source code in src/bootstrapx/compat/pandas_accessor.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def ci(
    self,
    statistic: Callable[..., float],
    *,
    method: str = "bca",
    n_resamples: int = 9999,
    confidence_level: float = 0.95,
    random_state: int | None = None,
    **kwargs: Any,
) -> pd.DataFrame:
    """Alias for :meth:`summary`."""
    return self.summary(
        statistic,
        method=method,
        n_resamples=n_resamples,
        confidence_level=confidence_level,
        random_state=random_state,
        **kwargs,
    )

summary(statistic, *, method='bca', n_resamples=9999, confidence_level=0.95, random_state=None, **kwargs)

Return a DataFrame with bootstrap CI summary for each column.

Returns

pd.DataFrame Index: column names of the original DataFrame. Columns: theta_hat, ci_low, ci_high, se, method.

Source code in src/bootstrapx/compat/pandas_accessor.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def summary(
    self,
    statistic: Callable[..., float],
    *,
    method: str = "bca",
    n_resamples: int = 9999,
    confidence_level: float = 0.95,
    random_state: int | None = None,
    **kwargs: Any,
) -> pd.DataFrame:
    """Return a DataFrame with bootstrap CI summary for each column.

    Returns
    -------
    pd.DataFrame
        Index: column names of the original DataFrame.
        Columns: ``theta_hat``, ``ci_low``, ``ci_high``, ``se``, ``method``.
    """
    rows = []
    for col in self._obj.columns:
        r = bootstrap(
            self._obj[col],
            statistic,
            method=method,
            n_resamples=n_resamples,
            confidence_level=confidence_level,
            random_state=random_state,
            **kwargs,
        )
        rows.append({
            "column": col,
            "theta_hat": r.theta_hat,
            "ci_low": r.confidence_interval.low,
            "ci_high": r.confidence_interval.high,
            "se": r.standard_error,
            "method": r.method,
        })
    return pd.DataFrame(rows).set_index("column")