calibrated_explanations.explanations.CalibratedExplanation¶
- class calibrated_explanations.explanations.CalibratedExplanation(calibrated_explanations, index, x, binned, feature_weights, feature_predict, prediction, y_threshold=None, instance_bin=None, condition_source: str = 'prediction')[source]¶
Bases:
ABCAbstract base class for storing and visualizing calibrated explanations.
This class defines the interface and shared functionality for different types of calibrated explanations.
Initialize a CalibratedExplanation instance.
- Parameters:
calibrated_explanations (
CalibratedExplanations) – The parentCalibratedExplanationsobject.index (int) – The index of the instance being explained.
x (array-like) – The test dataset containing the instances to be explained.
binned (dict) – A mapping of binned feature values.
feature_weights (dict) – A mapping of feature weights.
feature_predict (dict) – A mapping of feature predictions.
prediction (dict) – A mapping containing the prediction results.
y_threshold (float or tuple, optional) – The threshold for binary classification or regression explanations.
instance_bin (int, optional) – The bin index of the instance.
- Attributes:
predictGet the prediction from the prediction dictionary.
prediction_intervalGet the prediction interval from the prediction dictionary.
Methods
add_conjunctions([n_top_features, max_rule_size])Add conjunctive rules to the explanation.
add_new_rule_condition(feature, rule_boundary)Create a new rule condition for a numerical feature.
build_condition_payload(feature_index, ...)Expose condition payload building for external use.
Expose the instance uncertainty payload builder.
build_interval(low, high)Public helper exposing interval construction.
Return structured rule payload separating core content from metadata.
build_uncertainty_payload(*, value, low, ...)Create a structured uncertainty payload.
compute_confidence_level(percentiles)Compute confidence level from decimal percentiles.
convert_condition_value(raw_value, fallback)Convert textual condition payloads to structured values.
copy()Create a shallow copy of the explanation object.
Define the rule conditions for an instance.
filter_features(*[, exclude_features, ...])Filter rules by feature inclusion or exclusion.
filter_rule_sizes(*[, rule_sizes, ...])Filter rules by conjunctive rule size.
Return the class labels.
Return the explainer object.
get_mode()Return the mode of the explanation ('classification' or 'regression').
Return the decoded percentile configuration.
Return the set of feature indices ignored for this instance.
Determine if the explanation is multiclass.
Test if a regression explanation is one-sided.
Check if the explanation is probabilistic.
Check if the explanation is for regression.
Check if the explanation is thresholded.
normalize_percentile_value(value)Normalise percentile inputs to decimal fractions.
Normalise threshold metadata to telemetry-friendly structure.
parse_condition(feature_name, rule_text)Return the parsed operator/value pair for a rule.
plot([filter_top])Plot the explanation.
predict_conjunction_tuple(rule_value_set, ...)Calculate the prediction for a conjunctive rule using batched inference.
predict_conjunctive(rule_value_set, ...[, ...])Public wrapper around the conjunctive prediction helper.
rank_features([feature_weights, width, ...])Rank the features based on their weights.
Remove any conjunctive rules.
reset()Reset the explanation to its original state.
safe_feature_name(feature_index)Return the human-readable name for a feature index.
to_dataframe(*args, **kwargs)Return the narrative output as a pandas DataFrame.
to_narrative([template_path, ...])Generate narrative explanation for this single instance.
to_python_number(value)Convert numpy/scalar values to native Python types suitable for telemetry.
Return telemetry payload for this explanation instance.
- filter_features(*, exclude_features=None, include_features=None, copy=True)[source]¶
Filter rules by feature inclusion or exclusion.
- Parameters:
exclude_features (str, int, or list of str/int, optional) – Features to exclude. Rules containing these features will be removed.
include_features (str, int, or list of str/int, optional) – Features to include. Only rules containing these features will be kept.
copy (bool, default=True) – If True, return a copy of the explanation. If False, modify in place.
- Returns:
Filtered explanation.
- Return type:
- abstract build_rules_payload() Dict[str, Any][source]¶
Return structured rule payload separating core content from metadata.
- property prediction_interval¶
Get the prediction interval from the prediction dictionary.
- Returns:
A tuple containing (low, high) values of the prediction interval.
- Return type:
tuple
- property predict¶
Get the prediction from the prediction dictionary.
- Returns:
A prediction value.
- Return type:
float
- copy()[source]¶
Create a shallow copy of the explanation object.
- Returns:
A shallow copy of the explanation object.
- Return type:
- ignored_features_for_instance()[source]¶
Return the set of feature indices ignored for this instance.
Combines collection-level
features_to_ignorewith any per-instance mask exposed viafeature_filter_per_instance_ignore.
- rank_features(feature_weights=None, width=None, num_to_show=None)[source]¶
Rank the features based on their weights.
- Parameters:
feature_weights (dict, optional) – A mapping of feature weights.
width (dict, optional) – A mapping of feature widths.
num_to_show (int, optional) – The number of features to show.
- Returns:
The sorted indices of the features.
- Return type:
list
- is_one_sided() bool[source]¶
Test if a regression explanation is one-sided.
- Returns:
bool
- Return type:
True if one of the low or high percentiles is infinite
- is_thresholded() bool[source]¶
Check if the explanation is thresholded.
- Returns:
bool
- Return type:
True if the y_threshold is not None
- is_regression() bool[source]¶
Check if the explanation is for regression.
- Returns:
bool
- Return type:
True if mode is ‘regression’
- is_probabilistic() bool[source]¶
Check if the explanation is probabilistic.
- Returns:
bool
- Return type:
True if mode is ‘classification’ or is_thresholded and is_regression are True
- abstract plot(filter_top=None, **kwargs)[source]¶
Plot the explanation.
- Parameters:
filter_top (int, optional) – The number of top features to display.
**kwargs (dict) – Additional plotting arguments. See each subclass.
See also
FactualExplanation.plot()Refer to the docstring for plot in FactualExplanation for details.
AlternativeExplanation.plot()Refer to the docstring for plot in AlternativeExplanation for details.
FastExplanation.plot()Refer to the docstring for plot in FastExplanation for details.
- to_narrative(template_path=None, expertise_level=('beginner', 'advanced'), output_format='dataframe', conjunction_separator=' AND ', align_weights=True, **kwargs)[source]¶
Generate narrative explanation for this single instance.
This method provides a clean API for generating human-readable narratives from a single calibrated explanation using customizable templates.
- Parameters:
template_path (str or None, default=None) – Path to the narrative template file (YAML or JSON). If None or the file doesn’t exist, the built-in default template is used.
expertise_level (str or tuple of str, default=("beginner", "advanced")) – The expertise level(s) for narrative generation. Can be a single level or a tuple of levels. Valid values: “beginner”, “intermediate”, “advanced”.
output_format (str, default="dataframe") – Output format. Valid values: “dataframe”, “text”, “html”, “dict”, “markdown”.
conjunction_separator (str, default=" AND ") – Separator to use for conjunctive rules. Conjunctive rules combine multiple feature conditions (e.g., “Glucose > 120 AND BMI > 28”).
align_weights (bool, default=True) – If True, vertically align columns in the narrative output. For factual explanations this aligns the weight marker (”— weight …”). For alternative explanations this aligns the “then” keyword in rule lines. If False, no alignment is applied.
**kwargs (dict) – Additional keyword arguments passed to the narrative plugin.
- Returns:
The generated narrative in the requested format: - “dataframe”: pandas DataFrame with one row - “text”: formatted text string - “html”: HTML table with one row - “dict”: dictionary with narrative fields
- Return type:
pd.DataFrame or str or dict
- Raises:
FileNotFoundError – If the template file is not found and no default is available.
ValueError – If an invalid expertise level or output format is specified.
ImportError – If pandas is not available and output_format=”dataframe” is requested.
Examples
>>> from calibrated_explanations import CalibratedExplainer >>> explainer = CalibratedExplainer(model, x_train, y_train) >>> explanations = explainer.explain_factual(x_test) >>> single_explanation = explanations[0] >>> narrative = single_explanation.to_narrative( ... expertise_level=("beginner", "advanced"), ... output_format="dataframe" ... ) >>> print(narrative)
See also
CalibratedExplanations.to_narrative()Generate narratives for a collection of explanations.
plot()Plot explanations with various visual styles.
- to_dataframe(*args, **kwargs)[source]¶
Return the narrative output as a pandas DataFrame.
Call
to_narrative()withoutput_format='dataframe'and return the resulting DataFrame. Accepts the same arguments asto_narrative().
- abstract add_conjunctions(n_top_features=5, max_rule_size=2)[source]¶
Add conjunctive rules to the explanation.
- Parameters:
n_top_features (int, optional) – Number of top features to combine.
max_rule_size (int, optional) – Maximum size of the conjunctions.
- Return type:
- filter_rule_sizes(*, rule_sizes: Any | None = None, size_range: Tuple[int, int] | None = None, copy: bool = True)[source]¶
Filter rules by conjunctive rule size.
- Parameters:
rule_sizes (int or sequence of int, optional) – Explicit rule sizes to keep (e.g., 1, 2, 3).
size_range (tuple(int, int), optional) – Inclusive (min_size, max_size) range of rule sizes to keep.
copy (bool, default=True) – If True, return a filtered copy without mutating the original.
- static to_python_number(value: Any) Any[source]¶
Convert numpy/scalar values to native Python types suitable for telemetry.
- static normalize_percentile_value(value: Any) float | None[source]¶
Normalise percentile inputs to decimal fractions.
- get_percentiles() Tuple[float | None, float | None] | None[source]¶
Return the decoded percentile configuration.
- static compute_confidence_level(percentiles: Tuple[float | None, float | None] | None) float | None[source]¶
Compute confidence level from decimal percentiles.
- normalize_threshold_value() Any[source]¶
Normalise threshold metadata to telemetry-friendly structure.
- build_uncertainty_payload(*, value: Any, low: Any, high: Any, representation: str, percentiles: Tuple[float | None, float | None] | None = None, threshold: Any = None, include_percentiles: bool = True) Dict[str, Any]¶
Create a structured uncertainty payload.
- static build_interval(low: Any, high: Any) Dict[str, Any][source]¶
Public helper exposing interval construction.
- build_instance_uncertainty() Dict[str, Any][source]¶
Expose the instance uncertainty payload builder.
- safe_feature_name(feature_index: Any) str[source]¶
Return the human-readable name for a feature index.
- static convert_condition_value(raw_value: str | None, fallback: Any) Any[source]¶
Convert textual condition payloads to structured values.
- parse_condition(feature_name: str, rule_text: str) Tuple[str, str | None][source]¶
Return the parsed operator/value pair for a rule.
- build_condition_payload(feature_index: Any, rule_text: str, feature_value: Any, display_value: Any) Dict[str, Any][source]¶
Expose condition payload building for external use.
- define_conditions()[source]¶
Define the rule conditions for an instance.
- Returns:
A list of conditions for each feature in the instance.
- Return type:
list[str]
- predict_conjunction_tuple(rule_value_set, original_features, perturbed, threshold, predicted_class, bins=None)[source]¶
Calculate the prediction for a conjunctive rule using batched inference.
- predict_conjunctive(rule_value_set, original_features, perturbed, threshold, predicted_class, bins=None, use_batched=False)[source]¶
Public wrapper around the conjunctive prediction helper.
- add_new_rule_condition(feature, rule_boundary)[source]¶
Create a new rule condition for a numerical feature.
- Parameters:
feature (int or str) – The feature index or name.
rule_boundary (int or float) – The value to define as rule condition.
- Return type:
Notes
The function will return the same explanation if the rule is already included or if the feature is categorical.
No implementation is provided for the
FastExplanationclass.