cleverly.effect_curves.EffectCurveResult#

class cleverly.effect_curves.EffectCurveResult(estimand_name: str, modifiers: Modifiers, model: Any, scale: str, in_sample: NDArray[float64], target_sentence: str, inference_status: str, status: str, status_reason: str, lower_bound: float, upper_bound: float, band: CurveBand | None = None, backend: str = 'pandas', identified_effect: Any = None, provenance: Any = None, fit: Any = None, fitted_method: str = 'tmle', sieve: Any = None, clipped_share: float = 0.0, ep_clipped_share: float = 0.0, fit_warnings: tuple[Any, ...] = ())[source]#

A fitted conditional effect curve: its model, its predictions and how it was fitted.

Two fits produce it. A projection fit (method="tmle") produces it through cleverly.estimators.TMLEResult.effect_curve(): the curve is the projection of the conditional contrast onto the declared basis, with pointwise intervals and a band. The EP learner (method="ep") returns it directly: the curve has no interval, and with model=None it estimates the conditional contrast itself, approximated within the final learner’s class. It is not a cleverly.CausalResult: it has no scalar estimate, and the coefficients with their intervals stay on the TMLEResult of a projection fit.

Parameters:
estimand_namestr

"cate" or "log_crr".

modifiersModifiers

The modifier schema.

modelProjectionCurve or EPCurve

The fitted curve, which predicts at new rows.

scale{“difference”, “log_ratio”}

The scale of the contrast.

in_samplendarray

The curve at the rows of the fit.

target_sentencestr

What the curve estimates, in one sentence.

inference_statusstr

The inference status of the coefficients.

status{“supported”, “experimental”}

The support label of the coefficients the curve is built from.

status_reasonstr

Why the curve carries that label, in plain words.

lower_boundfloat

The lower end of the range a contrast of means of the outcome can take.

upper_boundfloat

The upper end of that range.

bandCurveBand or None

The simultaneous band over the grid the fit declared, or None.

backendstr

The dataframe backend of the fit’s data.

identified_effectAny

The identified effect the fit came from, or None for an engine fit.

provenanceProvenance or None

The producing fit’s provenance record.

fitAny

The producing fit, which the curve’s assessment reads and refits: a TMLEResult, or an EPFit.

fitted_method{“tmle”, “ep”}

The method that produced the curve.

sieveSieveRecord or None

How an EP fit set its sieve size, and what its cross-validation read; None for a projection fit.

clipped_sharefloat

The share of in-sample predictions an EP fit with model=None clipped to the range of a contrast of means; 0 for every other curve.

ep_clipped_sharefloat

The share of in-sample rows at which an EP fit’s declared log-ratio final learner put its class-1 probability outside the hull of the fractional labels, so the curve was clipped to it; 0 for every other curve.

fit_warningstuple of FitWarning

The warnings the fit raised, recorded as a point fit records them.

Methods#

EffectCurveResult.assess(*, include_refits: bool = False, include_retargets: bool = False, arguments: Mapping[str, Mapping[str, Any]] | None = None, random_state: int | None = None) → Any[source]#

Run the applicable post-fit assessment battery.

Every sensitivity row refuses on a curve: no sensitivity analysis is derived for a conditional contrast curve (P1). The five curve operations refit the producing estimator, so they run only with include_refits=True.

Parameters:
include_refitsbool

Run requested operations that refit nuisance models.

include_retargetsbool

Include moderate retargets.

argumentsmapping or None

Per-operation keyword arguments.

random_stateint or None

Common seed for stochastic refit operations.

Returns:
AssessmentReport

Validation, diagnostics, and sensitivity in one report.

EffectCurveResult.plot(**kwargs: Any) → Any[source]#

Plot the conditional effect over one modifier.

The curve is drawn over the modifier with its pointwise interval (a projection fit only; an EP curve carries none), a rug of the modifier’s values, and the band at the grid points the fit declared. A difference-scale projection whose model includes a constant term also draws its average effect as a reference line: the mean of the curve over the fitted rows, which equals the fit’s plug-in average effect only then. A curve that reads other modifiers is drawn with each held at a value you give in at=.

Parameters:
**kwargs

Passed to cleverly.plotting.curve(): modifier=, by=, at=, alpha=, outcome_label=, units= and title=.

Returns:
Figure

One panel, or one panel per level of by.

Raises:
ValueError

When the curve reads modifiers that modifier=, by= and at= leave undeclared.

Examples

>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LogisticRegression
>>> from cleverly import CausalStudy, ConditionalContrast, PointTreatment
>>> from cleverly.bases import Linear, Modifiers
>>> rng = np.random.default_rng(0)
>>> W = rng.uniform(-1, 1, 400)
>>> A = rng.binomial(1, 0.5, 400)
>>> Y = rng.binomial(1, 0.3 + 0.2 * A * (W > 0))
>>> frame = pd.DataFrame({"Y": Y, "A": A, "W": W})
>>> study = CausalStudy(
...     frame, design=PointTreatment(outcome="Y", treatment="A", adjustment=("W",))
... )
>>> effect = study.identify(ConditionalContrast(Modifiers(["W"]), model=Linear(["W"])))
>>> curve = effect.estimate(
...     outcome_learner=LogisticRegression(),
...     treatment_learner=LogisticRegression(),
...     cross_fit=False,
...     random_state=0,
... ).effect_curve()
>>> fig = curve.plot()
>>> fig.axes[0].get_title(loc="left")
'Conditional effect by W'
>>> plt.close(fig)
EffectCurveResult.predict(data: Any, *, interval: bool = False, alpha: float = 0.05) → Any[source]#

The curve at new rows, with a pointwise Wald interval on request.

The rows are checked against the modifier schema: a missing column, an undeclared level, or a value outside its domain under outside="refuse" raises, and outside="clip" clips. A projection curve gives an interval; an EP curve refuses interval=True, because its source proves no limit law for the curve.

Parameters:
datadataframe or mapping

Rows holding the modifier columns.

intervalbool

False returns the predictions. True returns a frame with the estimate, its standard error and the interval.

alphafloat

The pointwise interval holds at 1 - alpha, against the coefficients’ own reference: the normal, or t on a few-cluster fit.

Returns:
ndarray or dataframe

The predictions, or a frame in the input’s backend.

Raises:
CapabilityError

If interval=True on an EP curve.

See also

cleverly.estimators.TMLEResult.effect_curve

What returns this result.

cleverly.estimators.TMLEResult.heterogeneity_test

The test of the non-constant terms.

Examples

>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LogisticRegression
>>> from cleverly import CausalStudy, ConditionalContrast, PointTreatment
>>> from cleverly.bases import Linear, Modifiers
>>> rng = np.random.default_rng(0)
>>> W = rng.uniform(-1, 1, 400)
>>> A = rng.binomial(1, 0.5, 400)
>>> Y = rng.binomial(1, 0.3 + 0.2 * A * (W > 0))
>>> frame = pd.DataFrame({"Y": Y, "A": A, "W": W})
>>> study = CausalStudy(
...     frame, design=PointTreatment(outcome="Y", treatment="A", adjustment=("W",))
... )
>>> effect = study.identify(ConditionalContrast(Modifiers(["W"]), model=Linear(["W"])))
>>> fit = effect.estimate(
...     outcome_learner=LogisticRegression(),
...     treatment_learner=LogisticRegression(),
...     cross_fit=False,
...     random_state=0,
... )
>>> curve = fit.effect_curve()
>>> curve.predict({"W": np.array([-0.5, 0.5])}).shape
(2,)
>>> list(curve.predict({"W": np.array([0.5])}, interval=True).columns)
['estimate', 'std_err', 'ci_lower', 'ci_upper']
EffectCurveResult.save(path: Any) → Any[source]#

Write this result to a trusted joblib artifact; see cleverly.load().

Parameters:
pathpath-like

Destination file.

Returns:
Path

The destination path, as given.

EffectCurveResult.summary(*, detail: Literal['short', 'full'] = 'short') → Any[source]#

A printable report of the curve.

Parameters:
detail{“short”, “full”}

"full" adds the band over the declared grid, when there is one.

Returns:
Summary

The report.

EffectCurveResult.to_frame() → Any[source]#

The in-sample predictions, one row per fit row, in the fit’s backend.

Returns:
dataframe

One column, named effect_curve:<estimand>.

EffectCurveResult.validate() → Any[source]#

Run the inexpensive default battery without refitting.

Returns:
ValidationReport

The producing fit’s support, nuisance and score checks.

Attributes#

EffectCurveResult.assessment_family: ClassVar[str] = 'effect_modification'#

The assessment family whose capability rows a curve reads.

EffectCurveResult.backend: str = 'pandas'#
EffectCurveResult.band: CurveBand | None = None#
EffectCurveResult.clipped_share: float = 0.0#
EffectCurveResult.diagnostics#

The curve’s assessment: support, out-of-fold calibration, risk and stability.

The summaries read the fit this curve came from and each refit reruns its estimator, so a curve that keeps neither refuses them through its replay gate. diagnostics.capabilities lists the rows. A controlled direct effect projection refuses before any refit (CDE_CURVE_TOOLS_REFUSAL): the held-out checks build the total effect’s pseudo-outcome.

EffectCurveResult.ep_clipped_share: float = 0.0#
EffectCurveResult.fit: Any = None#
EffectCurveResult.fit_warnings: tuple[Any, ...] = ()#
EffectCurveResult.fitted_method: str = 'tmle'#
EffectCurveResult.identified_effect: Any = None#
EffectCurveResult.outside_share#

The share of in-sample predictions outside the range of a contrast of means.

A projection is a best approximation and can leave that range; it is not clipped. On the log ratio there is no such range and the share is 0.

EffectCurveResult.prediction_column#

The name of the prediction column to_frame() writes.

EffectCurveResult.provenance: Any = None#
EffectCurveResult.replayability#

Which assessment operations survive from the stored curve and its producing fit.

EffectCurveResult.sensitivity#

The sensitivity-analysis facade, whose every row refuses on a curve (P1).

EffectCurveResult.sieve: Any = None#
EffectCurveResult.estimand_name: str#
EffectCurveResult.modifiers: Modifiers#
EffectCurveResult.model: Any#
EffectCurveResult.scale: str#
EffectCurveResult.in_sample: NDArray[float64]#
EffectCurveResult.target_sentence: str#
EffectCurveResult.inference_status: str#
EffectCurveResult.status: str#
EffectCurveResult.status_reason: str#
EffectCurveResult.lower_bound: float#
EffectCurveResult.upper_bound: float#
EffectCurveResult.assessment_cache: AssessmentCache#