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 throughcleverly.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 withmodel=Noneit estimates the conditional contrast itself, approximated within the final learner’s class. It is not acleverly.CausalResult: it has no scalar estimate, and the coefficients with their intervals stay on theTMLEResultof a projection fit.- Parameters:
- estimand_name
str "cate"or"log_crr".- modifiers
Modifiers The modifier schema.
- model
ProjectionCurveorEPCurve The fitted curve, which predicts at new rows.
- scale{“difference”, “log_ratio”}
The scale of the contrast.
- in_sample
ndarray The curve at the rows of the fit.
- target_sentence
str What the curve estimates, in one sentence.
- inference_status
str The inference status of the coefficients.
- status{“supported”, “experimental”}
The support label of the coefficients the curve is built from.
- status_reason
str Why the curve carries that label, in plain words.
- lower_bound
float The lower end of the range a contrast of means of the outcome can take.
- upper_bound
float The upper end of that range.
- band
CurveBandorNone The simultaneous band over the grid the fit declared, or
None.- backend
str The dataframe backend of the fit’s data.
- identified_effect
Any The identified effect the fit came from, or
Nonefor an engine fit.- provenance
ProvenanceorNone The producing fit’s provenance record.
- fit
Any The producing fit, which the curve’s assessment reads and refits: a
TMLEResult, or anEPFit.- fitted_method{“tmle”, “ep”}
The method that produced the curve.
- sieve
SieveRecordorNone How an EP fit set its sieve size, and what its cross-validation read;
Nonefor a projection fit.- clipped_share
float The share of in-sample predictions an EP fit with
model=Noneclipped to the range of a contrast of means; 0 for every other curve.- ep_clipped_share
float 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_warnings
tupleofFitWarning The warnings the fit raised, recorded as a point fit records them.
- estimand_name
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:
- Returns:
AssessmentReportValidation, 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=andtitle=.
- Returns:
FigureOne panel, or one panel per level of
by.
- Raises:
ValueErrorWhen the curve reads modifiers that
modifier=,by=andat=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, andoutside="clip"clips. A projection curve gives an interval; an EP curve refusesinterval=True, because its source proves no limit law for the curve.- Parameters:
- data
dataframeormapping Rows holding the modifier columns.
- intervalbool
Falsereturns the predictions.Truereturns a frame with the estimate, its standard error and the interval.- alpha
float The pointwise interval holds at
1 - alpha, against the coefficients’ own reference: the normal, or t on a few-cluster fit.
- data
- Returns:
ndarrayordataframeThe predictions, or a frame in the input’s backend.
- Raises:
CapabilityErrorIf
interval=Trueon an EP curve.
See also
cleverly.estimators.TMLEResult.effect_curveWhat returns this result.
cleverly.estimators.TMLEResult.heterogeneity_testThe 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:
PathThe 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:
SummaryThe report.
Attributes#
- EffectCurveResult.assessment_family: ClassVar[str] = 'effect_modification'#
The assessment family whose capability rows a curve reads.
- 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.capabilitieslists 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.
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.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.in_sample: NDArray[float64]#
- EffectCurveResult.assessment_cache: AssessmentCache#