Fitting and reading curves#

fit_dose_response(X, A, Y, outcome_model=None, gps=None, groups=None, pooling='partial', n_folds=5, n_basis=10, cluster=None, fold_groups=None, cov_type='bayes', max_weight_quantile=0.99, add_group_codes=True, max_levels=30, y_pre=None, design=None, nuisance_var=True, n_jobs=None, random_state=0)[source]#

Fit doubly robust dose-response curves in one call.

Cross-fits the outcome model and the dose model, builds the doubly robust pseudo-outcomes of Kennedy et al. (2017) and smooths them against the dose with penalised splines, pooled across groups if given.

Parameters:
Xarray-like or DataFrame

Confounders. Non-numeric DataFrame columns are coded; missing values are allowed.

Aarray-like

The dose (treatment), one value per row.

Yarray-like

The outcome.

outcome_modelsklearn regressor, optional

Model for E[Y | X, A]. None uses default_model(), a spline-ridge and boosting stack.

gpsGPS, DiscreteGPS or BalancingWeights, optional

The weight model. None picks DiscreteGPS when A has at most max_levels distinct values, otherwise GPS (density-based weights, Kennedy et al. 2017). BalancingWeights is an alternative for a population curve (groups=None).

groupsDataFrame, optional

None for one population curve; a DataFrame with one column for flat groups, each shrunk toward the global curve; or several columns, top to bottom (e.g. df[["region", "store"]]). Levels must be nested.

pooling{“partial”, “none”, “complete”}, default “partial”

See HierarchicalDoseResponse.

n_foldsint, default 5

Cross-fitting folds.

n_basisint, default 10

Number of B-spline basis functions for the curve.

clusterarray-like, optional

Cluster ids for the robust covariance types.

fold_groupsarray-like, optional

Ids kept together in cross-fitting (e.g. customer id).

cov_type{“bayes”, “robust_bayes”, “sandwich”}, default “bayes”

Default covariance for intervals.

max_weight_quantilefloat, default 0.99

Weights are capped at this quantile, trading a little bias for a lot of variance.

add_group_codesbool, default True

Add the group labels to X so the nuisance models can use them.

max_levelsint, default 30

A dose with at most this many distinct values is treated as discrete.

y_prearray-like, optional

The outcome before the dose, in the same units. With it, choose design.

design{“did”, “lagged”}, optional

Only used with y_pre (default “did”).

  • "did": fit on the change Y - y_pre. Removes stable unobserved traits, but comparing doses needs strong parallel trends: units on different doses would have followed the same path had their doses been equal.

  • "lagged": keep Y and adjust for y_pre as a confounder. Right when the dose responds to past outcomes rather than to a stable trait.

The two bracket the truth when you don’t know which applies; check "did" with placebo_check() on two pre-periods.

nuisance_varbool, default True

Add the variance from estimating m(a), the outcome model averaged over X (Kennedy et al. 2017), to the “bayes” and “robust_bayes” bands. Costs one extra prediction per row and dose-grid point.

n_jobsint, optional

Parallel jobs for the default models (None = 1, -1 = all cores).

random_stateint, default 0

Seed for the folds and the default models.

Returns:
HierarchicalDoseResponse

The fitted curves, with .nuisances_, .pseudo_outcomes_ and .diagnostics() (overlap and fit checks worth reading first).

See also

placebo_check

Checks the parallel-trends assumption behind design="did".

coverage_check

Checks the bands on data shaped like yours.

Examples

>>> import numpy as np
>>> from drcurves import fit_dose_response
>>> from drcurves.simulate import sim_nonlinear
>>> X, A, Y, truth = sim_nonlinear(n=3000, seed=1)
>>> model = fit_dose_response(X, A, Y)
>>> grid = np.linspace(*np.quantile(A, [0.05, 0.95]), 50)
>>> est, lo, hi, _ = model.band(grid)
class HierarchicalDoseResponse(n_basis=10, pooling='partial', lam_grid=None, n_sweeps=2, gcv_gamma=1.4, cov_type='bayes', lam_int=0.0001, dense_max=300, n_probes=40)[source]#

Partially pooled dose-response curves.

The second stage of fit_dose_response(): regresses pseudo-outcomes on the dose with penalised B-splines. With groups, each group’s spline coefficients are the sum of its ancestors’ deviations, and ridge penalties on the deviations shrink small groups toward their parent (tuned by GCV).

Parameters:
n_basisint, default 10

Number of B-spline basis functions (reduced automatically when the dose takes only a few distinct values).

pooling{“partial”, “none”, “complete”}, default “partial”

"partial": GCV-tuned shrinkage. "none": each group on its own, only smoothness penalised. "complete": one curve for everybody.

lam_gridarray-like, optional

Candidate penalties for GCV; default 9 values from 1e-2 to 1e6.

n_sweepsint, default 2

Coordinate-descent sweeps over the penalties.

gcv_gammafloat, default 1.4

GCV inflation factor (Kim & Gu 2004); above 1 favours smoother fits, which matters because pseudo-outcomes are noisy.

cov_type{“bayes”, “robust_bayes”, “sandwich”}, default “bayes”

Default covariance for intervals. "bayes" is the posterior covariance of the equivalent Bayesian model, as used by mgcv; "robust_bayes" uses a heteroscedasticity-robust data term plus the prior term; "sandwich" ignores penalty bias and is overconfident under shrinkage.

lam_intfloat, default 1e-4

Small ridge on each group’s overall level.

dense_maxint, default 300

Up to this many coefficients the fit is solved densely and exactly; above it, with a sparse LU factorisation.

n_probesint, default 40

Probes for the Hutchinson estimate of the effective degrees of freedom in large models.

fit(a, y, groups=None, cluster=None, penalties=None, nuisance_term=None)[source]#

Fit the pooled curves.

Parameters:
aarray-like

Dose for each row.

yarray-like

Pseudo-outcome (or outcome) for each row.

groupsDataFrame or Series, optional

One column per level, top to bottom; one column for flat groups; None for one curve.

clusterarray-like, optional

Cluster ids for the robust ("sandwich" and "robust_bayes") covariance, e.g. customer id when customers repeat. Don’t cluster at the level whose curves you report.

penaltiestuple, optional

(lam_smooth, [lam_level, ...]) to skip GCV tuning.

nuisance_termtuple, optional

(a_grid, q) from cross_fit_nuisances(..., nuisance_var=True). Adds the variance from estimating m(a) (Kennedy et al. 2017) to the “bayes” and “robust_bayes” covariances.

Returns:
HierarchicalDoseResponse

self.

curve(a_grid, path=None, centre=False, cov_type=None, predictive=True)[source]#

Curve and pointwise standard errors for a group path.

Parameters:
a_gridarray-like

Doses at which to evaluate the curve.

pathtuple, optional

Group path, top to bottom, e.g. ("north", "store_17"). None returns the global block. Under partial pooling that is a shrinkage-weighted “typical group” curve, not the population average E[Y(a)]; for the population curve fit with groups=None. Unknown levels fall back to their parent (a new store gets its region’s curve).

centrebool, default False

Return the shape: the curve minus its mean over a_grid.

cov_typestr, optional

Override the model’s cov_type.

predictivebool, default True

For an unseen group, also include the spread between groups at that level, drawn from the fitted random-effects prior, so a new store’s band is wider than its region’s.

Returns:
estndarray

The curve at a_grid.

sendarray

Pointwise standard errors.

draws(a_grid, path=None, n_draws=4000, centre=False, cov_type=None, seed=0, predictive=True)[source]#

Curves drawn from N(coef, cov).

Parameters:
a_gridarray-like

Doses at which to evaluate the curves.

pathtuple, optional

Group path; see curve().

n_drawsint, default 4000

Number of curves.

centrebool, default False

Centre each curve over a_grid.

cov_typestr, optional

Override the model’s cov_type.

seedint, default 0

Random seed.

predictivebool, default True

For unseen groups, add the between-group spread (see curve()).

Returns:
ndarray

Array of shape (n_draws, len(a_grid)).

band(a_grid, path=None, level=0.95, simultaneous=True, centre=False, cov_type=None, n_draws=10000, seed=0, critical=None)[source]#

Confidence band for a curve.

Parameters:
a_gridarray-like

Doses at which to evaluate the band.

pathtuple, optional

Group path; see curve().

levelfloat, default 0.95

Coverage level.

simultaneousbool, default True

Use a sup-t critical value (the 95th percentile of the largest standardised deviation across the grid), so the band holds for the whole curve at once. That’s what you need for statements like “the curve peaks between x and y”. False gives pointwise bands.

centrebool, default False

Band for the shape (curve minus its mean over a_grid).

cov_typestr, optional

Override the model’s cov_type.

n_drawsint, default 10000

Draws used for the sup-t critical value.

seedint, default 0

Random seed.

criticalfloat, optional

Use this critical value instead, multiplying the standard errors (e.g. the calibrated value from coverage_check()).

Returns:
est, lo, hindarray

The curve and the band’s lower and upper limits.

criticalfloat

The critical value used.

contrast(a_from, a_to, path=None, path_to=None, cov_type=None)[source]#

Difference between two points on the curves, with its standard error.

Returns theta_path_to(a_to) - theta_path(a_from). On the same path this is the effect of moving the dose from a_from to a_to. On different paths at the same dose, it’s how two groups differ at that dose.

Parameters:
a_from, a_tofloat

The two doses.

pathtuple, optional

Group path for a_from; see curve().

path_totuple, optional

Group path for a_to; defaults to path.

cov_typestr, optional

Override the model’s cov_type.

Returns:
estfloat

The difference.

sefloat

Its standard error.

plot(a_grid=None, paths=(None,), labels=None, band='pointwise', level=0.95, centre=False, truth=None, rug=True, ax=None, cov_type=None)[source]#

Plot one or more curves with their bands (needs matplotlib).

Parameters:
a_gridarray-like, optional

Doses to plot; default the fitted dose range.

pathssequence of tuples, default (None,)

Group paths to draw, e.g. [None] or [("north",), ("north", "s17")].

labelssequence of str, optional

Legend labels, one per path.

band{“pointwise”, “simultaneous”, None}, default “pointwise”

Which band to shade.

levelfloat, default 0.95

Band coverage level.

centrebool, default False

Plot shapes (each curve minus its mean).

truthcallable, optional

a -> true curve, drawn dashed (for simulations).

rugbool, default True

Tick marks along the x axis at the observed doses.

axmatplotlib Axes, optional

Axes to draw on.

cov_typestr, optional

Override the model’s cov_type.

Returns:
matplotlib.axes.Axes
optimal_dose(a_grid, path=None, level=0.95, n_draws=4000, maximize=True, cov_type=None, seed=0)[source]#

Dose that maximises (or minimises) the curve, with an interval.

The interval comes from the argmax across curves drawn from the model.

Parameters:
a_gridarray-like

Candidate doses.

pathtuple, optional

Group path; see curve().

levelfloat, default 0.95

Interval level.

n_drawsint, default 4000

Number of curve draws.

maximizebool, default True

False finds the minimum.

cov_typestr, optional

Override the model’s cov_type.

seedint, default 0

Random seed.

Returns:
dict

dose (the optimum of the fitted curve), lo and hi (the interval), at_edge (share of draws whose optimum is at an end of a_grid; if large, the optimum may lie outside the data) and draws (the optimum in each draw).