Skip to content

API reference

Design

fewlabels.design.DesignParameters(sd_y, r2, design_effect=1.0) dataclass

Inputs for sample size planning.

Attributes:

Name Type Description
sd_y float

Standard deviation of the outcome. For a proportion p it is sqrt(p (1 - p)).

r2 float

Share of the outcome variance explained by the predictions, in [0, 1).

design_effect float

Variance inflation due to clustered sampling, at least one. See :func:~fewlabels.design.design_effect.

with_design_effect(design_effect)

Return a copy with a different design effect.

to_dict()

Return the parameters as a dictionary.

from_proportion(prevalence, sensitivity, specificity, design_effect=1.0) classmethod

Parameters for estimating a prevalence with a binary classifier.

For a binary outcome with prevalence :math:p and a binary prediction with the given sensitivity and specificity, :math:R^2 is the squared correlation between outcome and prediction.

Examples:

>>> params = DesignParameters.from_proportion(0.2, 0.9, 0.95)
>>> round(params.r2, 3)
0.674

from_pilot(y, preds, conservative=True, alpha=0.2, n_boot=2000, design_effect=1.0, seed=None) classmethod

Estimate the parameters from a labelled pilot sample.

Parameters:

Name Type Description Default
y ArrayLike

Pilot outcomes.

required
preds ArrayLike

Pilot predictions, shape (n,) or (n, K).

required
conservative bool

Plan with pessimistic values: the upper 1 - alpha/2 bootstrap quantile of sd_y and the lower alpha/2 quantile of r2. Small pilots give noisy estimates, and an optimistic r2 leads to an underpowered study.

True
alpha float

Error level of the bootstrap bounds when conservative is true.

0.2
n_boot int

Number of bootstrap resamples.

2000
design_effect float

Design effect to store with the parameters.

1.0
seed int | Generator | None

Seed for the bootstrap.

None

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> y = rng.binomial(1, 0.3, 300)
>>> f = np.clip(y + rng.normal(0, 0.4, 300), 0, 1)
>>> point = DesignParameters.from_pilot(y, f, conservative=False)
>>> safe = DesignParameters.from_pilot(y, f, seed=1)
>>> safe.r2 < point.r2
True

fewlabels.design.required_labels(target_half_width, params, n_unlabeled=math.inf, alpha=0.05, alternative='two-sided')

Smallest number of labels that reaches a target margin of error.

Examples:

>>> p = DesignParameters.from_proportion(0.2, 0.9, 0.95)
>>> classical = required_labels(0.02, DesignParameters(p.sd_y, 0.0))
>>> with_ai = required_labels(0.02, p, n_unlabeled=50_000)
>>> classical, with_ai
(1537, 512)

fewlabels.design.required_labels_for_power(effect, params, target_power=0.8, n_unlabeled=math.inf, alpha=0.05, alternative='two-sided')

Smallest number of labels with at least target_power.

Examples:

>>> required_labels_for_power(0.05, DesignParameters(0.5, 0.5))
393

fewlabels.design.power(n, effect, params, n_unlabeled=math.inf, alpha=0.05, alternative='two-sided')

Power of the normal test for a difference effect from the null value.

effect is the true mean minus the null value. For "larger" it should be positive and for "smaller" negative.

Examples:

>>> round(power(500, 0.05, DesignParameters(0.5, 0.5)), 3)
0.885

fewlabels.design.half_width(n, n_unlabeled, params, alpha=0.05, alternative='two-sided')

Return the expected half-width of the confidence interval (margin of error).

Examples:

>>> round(half_width(400, math.inf, DesignParameters(0.5, 0.0)), 4)
0.049

fewlabels.design.ppi_variance(n, n_unlabeled, params)

Variance of the optimally tuned estimator with n labels.

n_unlabeled may be math.inf for a practically unlimited pool.

Examples:

>>> p = DesignParameters(sd_y=0.5, r2=0.6)
>>> round(ppi_variance(100, math.inf, p), 6)
0.001

fewlabels.design.effective_sample_size(n, n_unlabeled, params)

Return the number of labels a classical study would need for the same variance.

Examples:

>>> round(effective_sample_size(100, math.inf, DesignParameters(0.5, 0.75)))
400

fewlabels.design.cost_optimal_allocation(budget, cost_label, cost_prediction, params, max_unlabeled=math.inf, alpha=0.05)

Split a budget between human labels and model predictions.

Each labelled case costs cost_label (including its prediction) and each additional unlabelled case costs cost_prediction, for example an API call. The function searches all feasible numbers of labels and returns the plan with the smallest variance.

Parameters:

Name Type Description Default
budget float

Total budget.

required
cost_label float

Cost per labelled case.

required
cost_prediction float

Cost per unlabelled prediction. May be zero if predictions already exist, in which case max_unlabeled must be finite.

required
params DesignParameters

Design parameters.

required
max_unlabeled float

Size of the available unlabelled pool.

inf
alpha float

Error level used to report the margin of error.

0.05

Examples:

>>> plan = cost_optimal_allocation(10_000, 20.0, 0.05, DesignParameters(0.4, 0.7))
>>> plan.n_labeled, plan.n_unlabeled
(466, 13600)

fewlabels.design.Allocation(n_labeled, n_unlabeled, cost, variance, half_width, effective_labels) dataclass

A labelling plan.

Attributes:

Name Type Description
n_labeled int

Number of cases to label.

n_unlabeled int

Number of additional cases to run the model on.

cost float

Total cost of the plan.

variance, half_width

Expected variance and margin of error.

effective_labels float

Classical sample size with the same precision.

to_dict()

Return the plan as a dictionary.

fewlabels.design.planning_table(n_values, params, n_unlabeled=math.inf, alpha=0.05)

Margin of error with and without predictions for several label counts.

Examples:

>>> rows = planning_table([100, 400], DesignParameters(0.5, 0.6))
>>> [round(r["ppi_half_width"], 3) for r in rows]
[0.062, 0.031]

fewlabels.design.design_effect(mean_cluster_size, icc)

Kish design effect 1 + (m - 1) * icc for clustered sampling.

Parameters:

Name Type Description Default
mean_cluster_size float

Average number of cases per cluster, for example images per patient.

required
icc float

Intra-cluster correlation of the quantity being averaged.

required

Examples:

>>> design_effect(4, 0.25)
1.75

fewlabels.design.explained_variance(y, preds)

Share of the variance of y explained linearly by preds.

This is the population :math:R^2 of the regression of the outcome on the predictions (with intercept), estimated by its sample analogue and truncated to [0, 1].

Examples:

>>> round(explained_variance([0, 1, 0, 1], [0.1, 0.9, 0.2, 0.8]), 3)
0.98

Estimation

fewlabels.estimation.ppi_mean(y, preds_labeled, preds_unlabeled, alpha=0.05, alternative='two-sided', lam='optimal', clip=True, clusters_labeled=None, clusters_unlabeled=None, ridge=0.0)

Prediction-powered estimate and confidence interval for a mean.

Parameters:

Name Type Description Default
y ArrayLike

Gold-standard outcomes of the labelled cases, shape (n,).

required
preds_labeled ArrayLike

Predictions for the labelled cases, shape (n,) for one annotator or (n, K) for K annotators.

required
preds_unlabeled ArrayLike

Predictions for the unlabelled cases, shape (N,) or (N, K).

required
alpha float

Error level of the confidence interval.

0.05
alternative Alternative

"two-sided", "larger" (lower bound only) or "smaller" (upper bound only).

'two-sided'
lam LamSpec

"optimal" estimates the variance minimising weights. A number or an array fixes them; 1 gives the original PPI estimator and 0 the classical sample mean.

'optimal'
clip bool

With one annotator, clip the optimal weight to [0, 1] as in PPI++. Ignored for several annotators, whose optimal weights may be negative to cancel correlated errors.

True
clusters_labeled ArrayLike | None

Optional cluster labels, for example patient or site identifiers. When given, variances are cluster-robust. Sampling is assumed to be independent between clusters.

None
clusters_unlabeled ArrayLike | None

Optional cluster labels, for example patient or site identifiers. When given, variances are cluster-robust. Sampling is assumed to be independent between clusters.

None
ridge float

Relative ridge penalty for the optimal weights. Useful when several annotators are almost collinear.

0.0

Returns:

Type Description
MeanEstimate
Notes

The interval uses the normal approximation. Estimating the weights on the same data introduces an error of smaller order than the standard error, so the interval is asymptotically valid.

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> y = rng.binomial(1, 0.3, 200)
>>> f_lab = np.clip(y + rng.normal(0, 0.3, 200), 0, 1)
>>> f_unl = np.clip(rng.binomial(1, 0.3, 20000) + rng.normal(0, 0.3, 20000), 0, 1)
>>> result = ppi_mean(y, f_lab, f_unl)
>>> bool(result.std_error < result.classical_std_error)
True

fewlabels.estimation.classical_mean(y, alpha=0.05, alternative='two-sided', clusters=None)

Classical labelled-only estimate and normal confidence interval.

Examples:

>>> result = classical_mean([0, 1, 1, 0, 1, 1, 1, 0])
>>> round(result.estimate, 3)
0.625

fewlabels.estimation.MeanEstimate(estimate, std_error, ci_lower, ci_upper, alpha, alternative, lam, n_labeled, n_unlabeled, classical_std_error, method, clustered=False) dataclass

Result of a mean estimation.

Attributes:

Name Type Description
estimate float

Point estimate of the population mean.

std_error float

Estimated standard error.

ci_lower, ci_upper

Confidence interval at level 1 - alpha.

alpha float

Error level of the interval.

alternative Alternative

"two-sided", "larger" or "smaller".

lam tuple[float, ...]

Power tuning weights, one per annotator. Zero for the classical estimator.

n_labeled, n_unlabeled

Sizes of the two samples.

classical_std_error float

Standard error of the labelled-only sample mean on the same data.

method str

Short name of the estimator.

clustered bool

Whether cluster-robust variances were used.

ci property

The confidence interval as a tuple.

width property

Width of the confidence interval (infinite for one-sided intervals).

variance_ratio property

Variance of this estimator divided by the classical variance.

effective_labels property

Number of labels the classical estimator would need for the same precision.

pvalue(null=0.0)

Compute the normal p-value for :math:H_0: \theta = \text{null}.

The alternative hypothesis is the one stored in alternative.

to_dict()

Return the result, including derived quantities, as a dictionary.

fewlabels.estimation.ipw_ppi_mean(y, preds, labeled, pi, alpha=0.05, alternative='two-sided', lam='optimal', clip=True, clusters=None, ridge=0.0)

Inverse probability weighted prediction-powered estimate of a mean.

Parameters:

Name Type Description Default
y ArrayLike

Outcomes for all N cases. Entries of unlabelled cases are ignored and may be NaN.

required
preds ArrayLike

Predictions for all cases, shape (N,) or (N, K).

required
labeled ArrayLike

Boolean labelling indicator of length N.

required
pi ArrayLike

Known labelling probabilities in (0, 1], one per case. They must be the probabilities that were actually used to select the labels.

required
alpha float

Settings of the confidence interval.

0.05
alternative float

Settings of the confidence interval.

0.05
lam LamSpec

"optimal", a number or an array, as in :func:~fewlabels.estimation.ppi_mean. 0 gives the Horvitz-Thompson estimator.

'optimal'
clip bool

Clip a single optimal weight to [0, 1].

True
clusters ArrayLike | None

Optional cluster labels of the N cases for cluster-robust variances. Selection must then be made by cluster.

None
ridge float

Relative ridge penalty for the optimal weights.

0.0

Returns:

Type Description
MeanEstimate

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(1)
>>> f = rng.uniform(size=5000)
>>> y = rng.binomial(1, f)
>>> pi = inclusion_probabilities(np.sqrt(f * (1 - f)), budget=500)
>>> labeled = poisson_sample(pi, seed=2)
>>> result = ipw_ppi_mean(np.where(labeled, y, np.nan), f, labeled, pi)
>>> bool(abs(result.estimate - 0.5) < 0.05)
True

fewlabels.estimation.inclusion_probabilities(scores, budget, floor=0.0)

Labelling probabilities proportional to a score, with an expected budget.

Returns :math:\pi_i = \min(1, \max(\text{floor}, c\, s_i)) with :math:c chosen so that :math:\sum_i \pi_i equals budget. Using the expected absolute prediction error (or, for binary outcomes, :math:\sqrt{p_i (1 - p_i)}) as the score approximately minimises the variance of :func:ipw_ppi_mean, as in active statistical inference.

Parameters:

Name Type Description Default
scores ArrayLike

Nonnegative scores, one per case.

required
budget float

Expected number of labels, between 0 and the number of cases.

required
floor float

Minimum probability for every case. A positive floor keeps the weights bounded and protects against a poorly calibrated score.

0.0

Examples:

>>> pi = inclusion_probabilities([0.0, 1.0, 1.0, 2.0], budget=2, floor=0.1)
>>> round(float(pi.sum()), 6)
2.0

fewlabels.estimation.poisson_sample(pi, seed=None)

Select each case independently with probability pi.

Examples:

>>> poisson_sample([1.0, 0.0, 1.0], seed=0).tolist()
[True, False, True]

Robustness

fewlabels.robustness.selection_sensitivity(y, preds_labeled, preds_unlabeled, gamma=1.0, pi=None, lam=1.0, alpha=0.05, n_boot=1000, seed=None)

Bounds on the prediction-powered estimate under non-random labelling.

The target is the mean outcome over all cases (labelled and unlabelled). The estimator is the mean prediction over all cases plus a weighted mean of the labelled residuals :math:Y_i - \lambda f_i with weights :math:1 / \pi_i.

Parameters:

Name Type Description Default
y ArrayLike

Outcomes of the labelled cases.

required
preds_labeled ArrayLike

Predictions of a single annotator for the labelled and unlabelled cases.

required
preds_unlabeled ArrayLike

Predictions of a single annotator for the labelled and unlabelled cases.

required
gamma float | ArrayLike

One value or a sequence of values of :math:\Gamma \ge 1.

1.0
pi ArrayLike | None

Assumed labelling probabilities of the labelled cases. By default every case is assumed to be labelled with probability n / (n + N), which is the assumption of ordinary PPI.

None
lam float

Fixed power tuning weight. The default 1 is the original PPI estimator.

1.0
alpha float

Error level of the bootstrap interval.

0.05
n_boot int

Number of bootstrap resamples. The same resamples are used for all values of gamma, so the intervals are nested.

1000
seed int | Generator | None

Seed for the bootstrap.

None

Returns:

Type Description
SensitivityResult or list of SensitivityResult

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> y = rng.binomial(1, 0.4, 300)
>>> f_lab = np.clip(y + rng.normal(0, 0.3, 300), 0, 1)
>>> f_unl = np.clip(rng.binomial(1, 0.4, 3000) + rng.normal(0, 0.3, 3000), 0, 1)
>>> res = selection_sensitivity(y, f_lab, f_unl, gamma=[1, 2], seed=1)
>>> res[1].ci_upper - res[1].ci_lower > res[0].ci_upper - res[0].ci_lower
True

fewlabels.robustness.tipping_point(y, preds_labeled, preds_unlabeled, null, pi=None, lam=1.0, alpha=0.05, n_boot=1000, max_gamma=100.0, tol=0.001, seed=None)

Smallest :math:\Gamma at which the sensitivity interval contains null.

A large tipping point means that the conclusion survives strong departures from random labelling. Returns 1.0 if the interval already contains null at :math:\Gamma = 1, and math.inf if it excludes null up to max_gamma.

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> y = rng.binomial(1, 0.4, 400)
>>> f_lab = np.clip(y + rng.normal(0, 0.3, 400), 0, 1)
>>> f_unl = np.clip(rng.binomial(1, 0.4, 4000) + rng.normal(0, 0.3, 4000), 0, 1)
>>> g = tipping_point(y, f_lab, f_unl, null=0.3, seed=1)
>>> 1.0 < g < 100.0
True

fewlabels.robustness.SensitivityResult(gamma, estimate, lower, upper, ci_lower, ci_upper, alpha) dataclass

Bounds on the estimate for one value of :math:\Gamma.

Attributes:

Name Type Description
gamma float

Sensitivity parameter.

estimate float

Estimate under the assumed probabilities (:math:\Gamma = 1).

lower, upper

Smallest and largest estimate compatible with the model.

ci_lower, ci_upper

Percentile bootstrap interval that covers the identified set.

alpha float

Error level of the interval.

contains(value)

Whether the sensitivity interval contains value.

to_dict()

Return the result as a dictionary.

fewlabels.robustness.annotator_report(y, preds, names=None)

Measure bias, error correlation and usefulness of several annotators.

Parameters:

Name Type Description Default
y ArrayLike

Gold-standard outcomes of the labelled cases.

required
preds ArrayLike

Predictions of K annotators, shape (n, K).

required
names Sequence[str] | None

Optional annotator names.

None

Returns:

Type Description
AnnotatorReport

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> y = rng.normal(size=500)
>>> shared = rng.normal(size=500)
>>> preds = np.column_stack([y + shared + rng.normal(size=500) for _ in range(3)])
>>> report = annotator_report(y, preds)
>>> round(report.mean_error_correlation, 1)
0.5

fewlabels.robustness.AnnotatorReport(names, bias, error_sd, error_correlation, mean_error_correlation, effective_annotators, r2_single, r2_average, r2_combined, notes=tuple()) dataclass

Summary of the annotators' agreement with the gold labels.

Attributes:

Name Type Description
names tuple[str, ...]

Annotator names.

bias tuple[float, ...]

Mean error pred - y of each annotator.

error_sd tuple[float, ...]

Standard deviation of each annotator's error.

error_correlation tuple[tuple[float, ...], ...]

Correlation matrix of the errors, shape (K, K).

mean_error_correlation float

Average off-diagonal error correlation.

effective_annotators float

:math:K / (1 + (K - 1) \bar\rho), the number of independent annotators that would give the same benefit from averaging.

r2_single tuple[float, ...]

Share of the outcome variance explained by each annotator alone.

r2_average float

Share explained by the simple average of all annotators.

r2_combined float

Share explained by the best linear combination, which is what :func:~fewlabels.estimation.ppi_mean approximately achieves.

to_dict()

Return the report as a dictionary.

summary()

Plain text table of the report.

ppi_py compatibility

fewlabels.compat.ppi_mean_ci(Y, Yhat, Yhat_unlabeled, alpha=0.1, alternative='two-sided', lam=None, coord=None, w=None, w_unlabeled=None, lam_optim_mode='overall')

Prediction-powered confidence interval for the mean (ppi_py interface).

Note the ppi_py default alpha=0.1 (90 % intervals).

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> y = rng.normal(size=100)
>>> lower, upper = ppi_mean_ci(y, y + rng.normal(0, 0.1, 100), rng.normal(size=1000))
>>> bool(lower[0] < upper[0])
True

fewlabels.compat.ppi_mean_pointestimate(Y, Yhat, Yhat_unlabeled, lam=None, coord=None, w=None, w_unlabeled=None, lam_optim_mode='overall')

Prediction-powered point estimate of the mean (ppi_py interface).

lam=None estimates the power tuning weight, lam=1 gives PPI and lam=0 the classical mean. coord is accepted for compatibility and ignored, as in ppi_py's mean estimator.

Examples:

>>> import numpy as np
>>> ppi_mean_pointestimate(np.array([1.0, 0.0]), np.array([1.0, 0.0]),
...                        np.array([1.0, 1.0, 0.0, 1.0]), lam=1).round(3).tolist()
[0.75]

fewlabels.compat.ppi_mean_pval(Y, Yhat, Yhat_unlabeled, null=0.0, alternative='two-sided', lam=None, coord=None, w=None, w_unlabeled=None, lam_optim_mode='overall')

Prediction-powered p-value for the mean (ppi_py interface).

As in ppi_py, the estimated weight is not clipped in this function.

Examples:

>>> import numpy as np
>>> y = np.array([1.0, 1.2, 0.9, 1.1, 1.0, 0.95])
>>> p = ppi_mean_pval(y, y, np.array([1.0, 1.05, 0.98, 1.02]), null=0.0)
>>> bool(p[0] < 1e-6)
True

fewlabels.compat.classical_mean_ci(Y, w=None, alpha=0.1, alternative='two-sided')

Classical normal confidence interval for the mean (ppi_py interface).

Examples:

>>> lower, upper = classical_mean_ci([0.0, 1.0, 1.0, 1.0])
>>> bool(lower < 0.75 < upper)
True

Datasets

fewlabels.datasets.make_ppi_data(n, n_unlabeled, prevalence=0.3, noise=0.25, bias=0.0, seed=None)

Binary outcomes with a calibrated-looking but noisy model score.

The prediction is clip(y + bias + noise * eps, 0, 1).

Examples:

>>> data = make_ppi_data(100, 1000, seed=0)
>>> data.y.shape, data.preds_unlabeled.shape
((100,), (1000,))

fewlabels.datasets.make_annotator_data(n, n_unlabeled, n_annotators=3, shared_error=0.6, own_error=0.4, biases=None, seed=None)

Continuous outcomes rated by several annotators with correlated errors.

Each annotator predicts y + bias_k + shared_error * s + own_error * e_k with a shared error s common to all annotators, so the error correlation is shared_error**2 / (shared_error**2 + own_error**2).

Examples:

>>> data = make_annotator_data(200, 2000, n_annotators=4, seed=0)
>>> data.preds_labeled.shape
(200, 4)

fewlabels.datasets.make_clustered_data(n_clusters, n_clusters_unlabeled, cluster_size=5, icc=0.3, noise=0.5, seed=None)

Continuous outcomes in clusters, such as several images per patient.

Outcomes have unit variance with intra-cluster correlation icc. Model errors share the same cluster structure.

Examples:

>>> data = make_clustered_data(50, 500, cluster_size=4, seed=0)
>>> data.y.shape, int(data.clusters_labeled.max()) + 1
((200,), 50)