cleverly.sensitivity.BalanceOverTime#
- class cleverly.sensitivity.BalanceOverTime(rows: tuple[TimeBalanceRow, ...], treatments: tuple[str, ...], diagnostics: tuple[str, ...], omitted: tuple[tuple[str, str], ...], dropped: tuple[DroppedStrata, ...], threshold: float, n: int, n_repeats: int, cross_fitted: bool, limits: tuple[float, float] | None, bounded_share: float, weighted_data: bool, family: str, notes: tuple[str, ...] = ())[source]#
Covariate balance over time of a fit with weights that vary over time.
"confounding"rows compare the covariates measured at or before a treatment decision across that decision, within the units that share the earlier treatments (Jackson 2016, Table 1, Diagnostic 1 before weighting and Diagnostic 3 after)."feedback"rows compare a covariate measured after an earlier decision across that decision (Diagnostic 2a)."censoring"rows compare the covariates across leaving the study at a time point and staying, within the units that share the treatments so far. A continuous-time survival fit has"confounding"rows at its baseline treatment,"joint"rows that compare the arms among the units whose status at a target time is known, weighted by treatment and censoring, and"censoring"rows that compare those units with their whole arm, weighted by censoring alone.- Parameters:
- rows
tupleofTimeBalanceRow One row per diagnostic, exposure, stratum, comparison and covariate.
- treatments
tupleofstr The treatment decisions compared, in time order.
- diagnostics
tupleofstr The diagnostics with rows.
- omitted
tupleoftupleofstr (diagnostic, reason)for each diagnostic the fit cannot report.- dropped
tupleofDroppedStrata The strata with no comparison, per diagnostic and exposure.
- threshold
float The size an absolute standardized difference is held against.
- n
int The units.
- n_repeats
int The cross-fitting repeats the fit holds; the first one’s probabilities are used.
- cross_fittedbool
Whether the probabilities are out-of-fold predictions; in-sample otherwise.
- limits
tupleoffloatorNone The limits put on each cumulative probability before it is inverted.
- bounded_share
float The share of weighted rows whose cumulative probability those limits moved.
- weighted_databool
Whether the data carried observation weights, which every column uses.
- family{“longitudinal”, “continuous_survival”}
The kind of fit.
- notes
tupleofstr Further readings of this fit’s report, such as the reading of a collaborative fit.
- rows
Examples
>>> from sklearn.linear_model import LinearRegression, LogisticRegression >>> from cleverly import CausalStudy, LongitudinalTreatment, RegimeMean >>> from cleverly.datasets import make_longitudinal >>> from cleverly.sensitivity import covariate_balance >>> frame, _ = make_longitudinal(n=600, seed=0) >>> study = CausalStudy( ... frame, ... design=LongitudinalTreatment( ... outcome="Y", ... treatment=["A1", "A2"], ... baseline=["W1", "W2"], ... time_varying=[[], ["L2"]], ... censoring=["C1", "C2"], ... ), ... ) >>> result = study.identify(RegimeMean({"always": 1, "never": 0})).estimate( ... outcome_learner=LinearRegression(), ... treatment_learner=LogisticRegression(max_iter=1000), ... censoring_learner=LogisticRegression(max_iter=1000), ... cross_fit=False, ... random_state=0, ... ) >>> balance = covariate_balance(result) >>> balance.treatments ('A1', 'A2') >>> frame = balance.average(over="history", diagnostic="confounding") >>> frame[["exposure", "covariate"]].values.tolist() [['A1', 'W1'], ['A1', 'W2'], ['A2', 'W1'], ['A2', 'W2'], ['A2', 'L2']]
Methods#
- BalanceOverTime.average(over: Literal['history', 'time', 'all'] = 'history', *, diagnostic: str | None = None, distances: Sequence[tuple[int, int]] | None = None, backend: str | None = None) Any[source]#
Average the differences over strata, weighting each by its size.
Jackson (2016, Table 2) averages a diagnostic over the earlier treatments, then over time, then over the distance between the covariate and the exposure, each stratum counting by its size: the data’s weights for the unweighted column and the stabilized weights for the weighted one. The averages are of the signed differences, so strata that differ in opposite directions offset each other;
smd_minandsmd_maxgive the range of the strata’s weighted standardized differences.Covariates are matched over time by name. A long panel’s column
"L@2"matches as"L"; on a wide frame each column is its own covariate, soover="time"andover="all"pool a covariate only with itself.- Parameters:
- over{“history”, “time”, “all”}, default=”history”
"history": one row per exposure, comparison and covariate, averaged over the earlier treatments."time": one row per distance and covariate, also averaged over the time points."all": one row per covariate, also averaged over the distances.- diagnostic
strorNone, default=None One diagnostic; every diagnostic with rows when omitted.
- distancessequence
oftupleofintorNone, default=None With
over="all", ranges(low, high)of distance, both ends included, to average within instead of over every distance; one row per range and covariate.- backend{“pandas”, “polars”, “pyarrow”}
orNone, default=None Dataframe backend to return.
- Returns:
dataframeThe grouping columns, then
n_strata,difference_unweighted,difference_weighted,smd_unweighted,smd_weighted,smd_min,smd_max,person_time_unweightedandperson_time_weighted.
- Raises:
CapabilityErrorWhen
diagnosticis one the fit cannot report.ValueErrorWhen
overordiagnosticis not one of the accepted values, ordistancesis passed withoutover="all".
- BalanceOverTime.plot(**kwargs: Any) Any[source]#
Plot the balance over time.
- Parameters:
- **kwargs
Passed to
cleverly.plotting.balance():diagnostic=,view=,nodes=,max_covariates=,labels=and the label options.
- Returns:
FigureThe figure.
- BalanceOverTime.rows_of(diagnostic: str) tuple[TimeBalanceRow, ...][source]#
The rows of one diagnostic.
- Parameters:
- diagnostic{“confounding”, “feedback”, “censoring”, “joint”}
The diagnostic.
- Returns:
tupleofTimeBalanceRowIts rows, in report order.
- Raises:
CapabilityErrorWhen the fit cannot report that diagnostic.
ValueErrorWhen
diagnosticis not one of the four.
- BalanceOverTime.summary(detail: Detail = 'short') Summary[source]#
Return the printed summary of the balance over time.
- Parameters:
- detail{“short”, “full”}, default=”short”
"short"prints, per diagnostic and exposure, each covariate’s difference before and after weighting, averaged over the earlier treatments."full"adds the strata with no comparison.
- Returns:
SummaryA
strwhose value is the printed text. Itsfacts,tables,notesandreadinghold the parts as data.
- BalanceOverTime.to_frame(backend: str | None = None) Any[source]#
Return one row per diagnostic, exposure, stratum, comparison and covariate.
- Parameters:
- backend{“pandas”, “polars”, “pyarrow”}
orNone, default=None Dataframe backend to return.
Noneuses pandas when installed, then the first available backend.
- backend{“pandas”, “polars”, “pyarrow”}
- Returns:
dataframeThe fields of
TimeBalanceRow, one column each.
Attributes#
- BalanceOverTime.rows: tuple[TimeBalanceRow, ...]#