cleverly.plotting.calibration#
- cleverly.plotting.calibration(source: Any, *, regimen: str | None = None, horizon: int | None = None, cause: str | None = None, time_label: str = 'Time point', title: str | Literal[False] | None = None, subtitle: str | Literal[False] | None = None, xlabel: str | Sequence[str] | None = None, ylabel: str | Sequence[str] | None = None, legend: str | Literal[False] = 'top', figsize: tuple[float, float] | None = None, ax: Axes | None = None) Figure[source]#
Plot whether predictions match what was measured, bin by bin.
Use it to see where along the range of predictions a model over- or understates, which a single slope hides. Two kinds of source are drawn.
A
CurveCalibration(fromcurve.diagnostics.calibration()) plots each bin’s measured effect, a doubly robust contrast, against the bin’s mean predicted effect. The calibration slope and intercept are in the subtitle. On the difference scale they come from the least-squares projection of the doubly robust pseudo-outcome on the prediction, and on the log-ratio scale they minimise the one-step log-ratio loss; either way they are not the slope of the drawn bins.A
NuisanceModelReport, a fit’sresult.diagnostics.nuisance_models()or the result itself plots the observed rate against the mean predicted probability of each probability model (the treatment model, a binary outcome model, and the missingness and intermediate models a fit has), with point area showing the rows in the bin. The logistic calibration slope of out-of-fold predictions is in the subtitle. An in-sample fit shows no slope, because an unpenalized logistic model with an intercept has an in-sample slope of 1 by construction, and a collaborative working treatment model or a declared treatment law shows none either, because neither is an estimate of the treatment law.A longitudinal fit, or its
diagnostics.nuisance_models(), draws one such panel per probability model and time point: each treatment, censoring and hazard model, and the outcome regressions of one regimen, horizon and cause.Bins are descriptive: no interval is drawn.
- Parameters:
- source
CurveCalibrationorNuisanceModelReportorTMLEResultorLongitudinalResult What to plot. A fit’s
NuisanceDiagnosticsand a longitudinal fit’sdiagnostics.nuisance_models()are accepted too.- regimen
strorNone, default=None On a longitudinal fit or its nuisance report, the regimen whose outcome regressions are drawn; the first when omitted. The treatment and censoring models serve every regimen and are always drawn.
- horizon
intorNone, default=None The horizon of those outcome regressions on a fit with several; the largest when omitted.
- cause
strorNone, default=None Their cause under competing events; the first when omitted.
- time_label
str, default=”Time point” Words for a time point on a longitudinal fit’s panels.
- title
str,FalseorNone, default=None The title; a short description of the figure when omitted, and none when
False.- subtitle
str,FalseorNone, default=None The line under the title; the plot’s own, which names the estimate and its headline number, when omitted, and none when
False.- xlabel
str, sequenceofstrorNone, default=None The x-axis label. A string replaces the first labelled panel’s label and the same label wherever it repeats; a sequence gives each labelled panel its own, in reading order.
- ylabel
str, sequenceofstrorNone, default=None The y-axis label, given as for
xlabel.- legend{“top”, “right”, “bottom”}
orFalse, default=”top” Where the key goes: above the axes, right of them, or under the figure;
Falsedraws no key.- figsize
tupleoffloatorNone, default=None Width and height in inches of a figure the plot creates.
- ax
AxesorNone, default=None Axes to draw on. Only for a single panel.
- source
- Returns:
FigureOne panel per probability model (and time point, on a longitudinal fit), or one panel for a curve.
- Raises:
ValueErrorWhen a curve calibration has no finite bin, or
axis given for more than one panel.CapabilityErrorWhen the source holds no probability model with a calibration table (a
ValueErrorsubclass, for a point and a longitudinal source alike), or is a continuous-time survival or adaptive TMLE fit, or the latter’s nuisance report, which keep no calibration table.DataErrorWhen the regimen, horizon or cause is not in a longitudinal report.
See also
cleverly.plotting.learnersWhich learners carry the models.
Notes
The figure carries no note text. It does not mark an experimental fit or band, one whose interval has no checked coverage because no registered study covers it or a stated condition applies, such as too few clusters: read
notes()on the figure before you publish it. For this plot the notes say the bins are descriptive, which predictions they use, and how the slope and intercept are computed. On a longitudinal fit they also say which cross-fitting draw and which regimen’s outcome regressions are drawn.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 ATE, CausalStudy, PointTreatment >>> from cleverly.plotting import calibration >>> rng = np.random.default_rng(0) >>> w = rng.normal(size=(300, 2)) >>> a = rng.binomial(1, 1 / (1 + np.exp(-0.6 * w[:, 0]))) >>> y = rng.binomial(1, 1 / (1 + np.exp(-(0.4 * w[:, 1] + 0.8 * a - 0.3)))) >>> frame = pd.DataFrame({"Y": y, "A": a, "W1": w[:, 0], "W2": w[:, 1]}) >>> study = CausalStudy( ... frame, design=PointTreatment(outcome="Y", treatment="A", adjustment=("W1", "W2")) ... ) >>> result = study.identify(ATE()).estimate( ... outcome_learner=LogisticRegression(max_iter=1000), ... treatment_learner=LogisticRegression(max_iter=1000), ... n_folds=3, ... random_state=0, ... ) >>> fig = calibration(result) >>> fig.texts[0].get_text() 'Calibration of predicted probabilities' >>> plt.close(fig)