cleverly.sensitivity.covariate_balance#

cleverly.sensitivity.covariate_balance(result: LongitudinalResult | ContinuousSurvivalResult, *, estimand: None = None, threshold: float = DEFAULT_THRESHOLD) → BalanceOverTime[source]#
cleverly.sensitivity.covariate_balance(result: TMLEResult, *, estimand: Literal['ate', 'att', 'atc'] | None = None, threshold: float = DEFAULT_THRESHOLD) → CovariateBalance

Compute each covariate’s standardized mean difference, before and after weighting.

Use it to check the treatment model on the covariates you know. A weighted difference near zero says the weights made the groups look alike on that covariate; one that is still large says the model missed something about it. The weights are the fit’s own for the chosen estimand, after the limits the fit put on the propensity for it:

  • "ate": each unit counts as the data’s weight divided by the probability of the arm it received, within g_bounds. Each difference is divided by the pooled standard deviation, the square root of the average of every arm’s variance before weighting (Austin 2009; cobalt’s s.d.denom = "pooled"). With more than two arms this is one spread per covariate, the same in every panel. Each arm is compared with all the others together, so imbalances of opposite sign in two other arms can cancel; cobalt compares pairs instead.

  • "att": the effect among an arm’s own units. That arm’s units keep the data’s weights and the reference arm’s units count as their weight times the odds of that arm against the reference, within g_bounds_conditional. Each difference is divided by the standard deviation in that arm, as cobalt does for the ATT.

  • "atc": the mirror image, among the reference arm, whose standard deviation is the spread.

The spread is computed before the propensity weighting, so the two columns of a row divide by the same number. Indicators of a binary covariate and of each level of a categorical one are standardized the same way; cobalt’s default prints their raw difference in proportions instead. A categorical covariate gets one row per level, a two-level one a single row.

The propensities are the first cross-fitting repeat’s out-of-fold predictions, or the in-sample predictions of a fit that was not cross-fitted. The result is descriptive: it has no interval or test, and a small difference on the covariates listed does not show balance on covariates that were not.

A fit over time (a longitudinal TMLE or SDR fit, a discrete-time survival fit, or a continuous-time survival fit) returns a BalanceOverTime instead, following Jackson (2016). At each treatment it compares the covariates recorded up to that treatment across its levels, within the units that share the same earlier treatments, before and after weighting by the fit’s cumulative treatment and censoring probabilities. It adds a feedback check (covariates recorded after a treatment, across it) and treats leaving the study as one more treatment. A continuous-time survival fit has one treatment, so it reports the baseline comparison and, at each target time, the units whose status is known. Each row’s differences are averaged over the strata of earlier treatments, each counting by its size.

Parameters:
resultTMLEResult, LongitudinalResult or ContinuousSurvivalResult

A fitted result with an estimated or declared treatment mechanism. A LongitudinalResult covers longitudinal and discrete-time survival fits.

estimand{“ate”, “att”, “atc”} or None, default=None

Whose weights to use on a point-treatment fit. It must be one the fit reports; the first of "ate", "att" and "atc" that it reports when omitted. A fit over time takes none.

thresholdfloat, default=0.1

The absolute difference the summary and the plot hold each covariate against.

Returns:
CovariateBalance or BalanceOverTime

The differences, with to_frame(), summary() and plot(): a CovariateBalance for a point-treatment fit, a BalanceOverTime for a fit over time.

Raises:
CapabilityError

When the fit estimated no treatment mechanism, reports no estimand weighted by the probability of each unit’s own arm, is a sequential g-computation fit, which has no weights, or is a fit over time that kept no data.

DataError

When the treatment, or a treatment node of a fit over time, is continuous, which has no groups to compare, or the fit reports no estimate of estimand.

ValueError

When threshold is not positive, estimand is not one of the three, or estimand is given for a fit over time.

See also

cleverly.sensitivity.positivity_report

Overlap of the same propensities, as numbers.

cleverly.plotting.overlap

The propensities’ distribution, as a figure.

Examples

>>> from sklearn.linear_model import LinearRegression, LogisticRegression
>>> from cleverly import ATE, CausalStudy, PointTreatment
>>> from cleverly.datasets import make_linear_ate
>>> from cleverly.sensitivity import covariate_balance
>>> frame, _ = make_linear_ate(n=200, seed=0)
>>> study = CausalStudy(
...     frame,
...     design=PointTreatment(outcome="Y", treatment="A", adjustment=("W1", "W2", "W3", "W4")),
... )
>>> result = study.identify(ATE()).estimate(
...     outcome_learner=LinearRegression(),
...     treatment_learner=LogisticRegression(max_iter=1000),
...     cross_fit=False,
...     random_state=0,
... )
>>> balance = covariate_balance(result)
>>> balance.to_frame()["covariate"].tolist()
['W1', 'W2', 'W3', 'W4']
>>> balance.estimand, balance.cross_fitted
('ate', False)

A longitudinal fit gets one comparison per treatment and covariate, and a feedback check:

>>> from cleverly import LongitudinalTreatment, RegimeMean
>>> from cleverly.datasets import make_longitudinal
>>> 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,
... )
>>> over_time = covariate_balance(result)
>>> over_time.diagnostics
('confounding', 'feedback', 'censoring')
>>> over_time.average(over="history", diagnostic="feedback")["covariate"].tolist()
['L2']