calibrated_explanations.explanations.AlternativeExplanation¶
- class calibrated_explanations.explanations.AlternativeExplanation(calibrated_explanations, index, x, binned, feature_weights, feature_predict, prediction, y_threshold=None, instance_bin=None, condition_source: str = 'prediction')[source]¶
Bases:
CalibratedExplanationClass representing an alternative explanation for a given instance.
Offers alternative explanations by exploring how changes to feature values could alter the model’s prediction.
Initialize an AlternativeExplanation instance.
- Parameters:
calibrated_explanations (CalibratedExplanations) – The parent CalibratedExplanations object.
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 alternative rules.
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.
build_instance_uncertainty()Expose the instance uncertainty payload builder.
build_interval(low, high)Public helper exposing interval construction.
Return structured payload describing alternative feature rules.
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.
counter([only_ensured, include_potential, copy])Shorthand delegator for
counter_explanations().counter_explanations([only_ensured, ...])Return a filtered view of counter alternative explanations.
define_conditions()Define the rule conditions for an instance.
ensured([include_potential, copy])Shorthand delegator for
ensured_explanations().ensured_explanations([include_potential, copy])Return a filtered view of ensured alternative explanations.
filter_features(*[, exclude_features, ...])Filter rules by feature inclusion or exclusion.
filter_rule_sizes(*[, rule_sizes, ...])Filter rules by conjunctive rule size.
get_class_labels()Return the class labels.
get_explainer()Return the explainer object.
get_mode()Return the mode of the explanation ('classification' or 'regression').
get_percentiles()Return the decoded percentile configuration.
get_rule_by_index(index)Return a single alternative rule by its numeric index.
Create alternative rules.
get_rules_by_feature(feature)Return all alternative rules that mention the given feature name.
ignored_features_for_instance()Return the set of feature indices ignored for this instance.
Determine if the explanation is a counter-explanation.
is_multiclass()Determine if the explanation is multiclass.
is_one_sided()Test if a regression explanation is one-sided.
is_probabilistic()Check if the explanation is probabilistic.
is_regression()Check if the explanation is for regression.
Determine if the explanation is a semi-explanation.
Determine if the explanation is a super-explanation.
is_thresholded()Check if the explanation is thresholded.
Return all alternative rules as normalized dicts.
normalize_percentile_value(value)Normalise percentile inputs to decimal fractions.
normalize_threshold_value()Normalise threshold metadata to telemetry-friendly structure.
pareto([include_potential, copy, pareto_cost])Shorthand delegator for
pareto_explanations().pareto_explanations([include_potential, ...])Return output-envelope Pareto alternatives.
parse_condition(feature_name, rule_text)Return the parsed operator/value pair for a rule.
plot([filter_top])Plot the alternative 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_conjunctions()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.
semi([only_ensured, include_potential, copy])Shorthand delegator for
semi_explanations().semi_explanations([only_ensured, ...])Return a filtered view of semi alternative explanations.
super([only_ensured, include_potential, copy])Shorthand delegator for
super_explanations().super_explanations([only_ensured, ...])Return a filtered view of super alternative explanations.
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.
to_telemetry()Return telemetry payload for this explanation instance.
- build_rules_payload() Dict[str, Any][source]¶
Return structured payload describing alternative feature rules.
- get_rules()[source]¶
Create alternative rules.
- Returns:
Array-like – A list of dictionaries containing the alternative rules.
- Return type:
List[Dict[str, List]]
- get_rule_by_index(index: int) Dict[str, Any][source]¶
Return a single alternative rule by its numeric index.
Raises
IndexErrorwhen the index is out of range.
- get_rules_by_feature(feature: str) list[Dict[str, Any]][source]¶
Return all alternative rules that mention the given feature name.
Raises
KeyErrorwhen no matching rules are found.
- super_explanations(only_ensured=False, include_potential=True, copy=True)[source]¶
Return a filtered view of super alternative explanations.
A super alternative reinforces the model’s current prediction.
- Parameters:
only_ensured (bool, default=False) – When
True, keep only alternatives whose uncertainty interval is no wider than the base prediction interval.include_potential (bool, default=True) – Whether to include potential alternatives.
copy (bool, default=True) – When
True, return a newAlternativeExplanation. WhenFalse, filter in place.
- Returns:
The filtered alternative explanation.
- Return type:
Notes
The definition of “super” depends on the task mode:
Classification / probabilistic regression: Treat the output as a calibrated probability with a 0.5 decision boundary. Let
p_base = prediction['predict'].If
p_base > 0.5(predicted positive/event), keep alternatives withp_rule > p_base.Otherwise, keep alternatives with
p_rule < p_base.
Plain regression: Treat the output as a calibrated numeric value. Keep alternatives with a higher predicted output than the base.
Potential alternatives are those where the uncertainty interval spans the decision boundary (classification / probabilistic regression) or covers the base prediction (plain regression).
Examples
>>> alternatives = explainer.explore_alternatives(x_query) >>> super_alts = alternatives[0].super_explanations()
- super(only_ensured=False, include_potential=True, copy=True)[source]¶
Shorthand delegator for
super_explanations().
- semi_explanations(only_ensured=False, include_potential=True, copy=True)[source]¶
Return a filtered view of semi alternative explanations.
A semi alternative moves the prediction toward the decision boundary without crossing it (classification/probabilistic regression) or moves the regression output in the opposite direction of a super alternative (plain regression).
- Parameters:
only_ensured (bool, default=False) – When
True, keep only alternatives whose uncertainty interval is no wider than the base prediction interval.include_potential (bool, default=True) – Whether to include potential alternatives.
copy (bool, default=True) – When
True, return a newAlternativeExplanation. WhenFalse, filter in place.
- Returns:
The filtered alternative explanation.
- Return type:
Notes
Classification / probabilistic regression: Semi alternatives stay on the same side of the 0.5 boundary as the base prediction, but are closer to that boundary than the base (unless marked as potential and
include_potential=True).Plain regression: Semi alternatives keep rules with a lower predicted output than the base prediction.
Examples
>>> alternatives = explainer.explore_alternatives(x_query) >>> semi_alts = alternatives[0].semi_explanations()
- semi(only_ensured=False, include_potential=True, copy=True)[source]¶
Shorthand delegator for
semi_explanations().
- counter_explanations(only_ensured=False, include_potential=True, copy=True)[source]¶
Return a filtered view of counter alternative explanations.
A counter alternative opposes the model’s current prediction.
- Parameters:
only_ensured (bool, default=False) – When
True, keep only alternatives whose uncertainty interval is no wider than the base prediction interval.include_potential (bool, default=True) – Whether to include potential alternatives.
copy (bool, default=True) – When
True, return a newAlternativeExplanation. WhenFalse, filter in place.
- Returns:
The filtered alternative explanation.
- Return type:
Notes
Classification / probabilistic regression: Counter alternatives cross the 0.5 decision boundary. For a base prediction
p_base > 0.5they keep rules withp_rule <= 0.5(and vice-versa).Plain regression: Counter alternatives keep rules with a lower predicted output than the base prediction.
In plain regression,
semi_explanations()andcounter_explanations()currently have the same output semantics.Examples
>>> alternatives = explainer.explore_alternatives(x_query) >>> counter_alts = alternatives[0].counter_explanations()
- counter(only_ensured=False, include_potential=True, copy=True)[source]¶
Shorthand delegator for
counter_explanations().
- ensured_explanations(include_potential=True, copy=True)[source]¶
Return a filtered view of ensured alternative explanations.
Ensured alternatives are those whose uncertainty interval is no wider than the base prediction interval.
- Parameters:
include_potential (bool, default=True) – Whether to include potential alternatives.
copy (bool, default=True) – When
True, return a newAlternativeExplanation. WhenFalse, filter in place.
- Returns:
The filtered alternative explanation.
- Return type:
Notes
This method is task-agnostic: it filters by uncertainty interval width only and therefore works for classification, probabilistic regression, and plain regression.
Examples
>>> alternatives = explainer.explore_alternatives(x_query) >>> ensured = alternatives[0].ensured_explanations()
- ensured(include_potential=True, copy=True)[source]¶
Shorthand delegator for
ensured_explanations().
- pareto_explanations(include_potential: bool = True, copy: bool = True, *, pareto_cost: Literal['uncertainty_width', 'rule_size'] = 'uncertainty_width')[source]¶
Return output-envelope Pareto alternatives.
- Parameters:
include_potential (bool, default=True) – Determines whether to include potential explanations before extracting the Pareto frontier.
copy (bool, default=True) – Determines whether to return a copy of the explanation or modify it in place.
pareto_cost ({"uncertainty_width", "rule_size"}, default="uncertainty_width") – The dimension minimized along the output axis when selecting the frontier.
"uncertainty_width"reproduces the historical behavior (minimize interval width)."rule_size"minimizes the number of changed features in the rule (useful when conjunctions are present).
- Return type:
Notes
Pareto filtering keeps an output-envelope frontier where no alternative can reduce the chosen Pareto cost without changing the output. The output axis is the calibrated probability (classification / probabilistic regression) or the calibrated numeric output (regression).
- pareto(include_potential: bool = True, copy: bool = True, *, pareto_cost: Literal['uncertainty_width', 'rule_size'] = 'uncertainty_width')[source]¶
Shorthand delegator for
pareto_explanations().
- add_conjunctions(n_top_features=5, max_rule_size=2, **kwargs)[source]¶
Add conjunctive alternative rules.
- Parameters:
n_top_features (int, optional) – Number of top features to combine.
max_rule_size (int, optional) – Maximum size of the conjunctions.
**kwargs (dict) – Internal controls for batching, deduplication, and diagnostics.
_use_batched (bool, default True) – Controls batched vs sequential prediction.
_limit_outer_to_ranked (bool, default False) – Whether to rank-filter outer loop candidates.
_dedupe_by_feature_only (bool, default True) – Deduplication strategy for conjunctions.
raise_on_predict_error (bool, default False) – Whether to surface prediction errors.
_fallback_to_legacy_on_zero (bool, default False) – Whether to fall back to legacy on zero created.
- conjunction_stats¶
Summary of attempts, created, skipped, and captured prediction errors.
- Type:
dict
- Returns:
self – Returns a self reference, to allow for method chaining
- Return type:
- plot(filter_top=None, **kwargs)[source]¶
Plot the alternative explanation.
- Parameters:
filter_top (int, optional) – The number of top features to display.
**kwargs (dict) –
Additional plotting arguments, such as:
- showbool, default=True if filename is empty, False otherwise
A boolean parameter that determines whether the plot should be displayed or not. If set to True, the plot will be displayed. If set to False, the plot will not be displayed.
- filenamestr, default=’’
The filename parameter is a string that represents the full path and filename of the plot image file that will be saved. If this parameter is not provided or is an empty string, the plot will not be saved as an image file.
- stylestr, default=’regular’
The style parameter is a string that determines the style of the plot. Possible styles are for
AlternativeExplanation:’regular’ - a regular plot with feature weights and uncertainty intervals (if applicable)
’triangular’ - a triangular plot for alternative explanations highlighting the interplay between the prediction and the uncertainty intervals
’ensured’ - alias for ‘triangular’ (intended for ensured-style alternative interpretation)
- rnk_metricstr, default=’ensured’
The metric used to rank the features. Supported metrics are ‘ensured’, ‘feature_weight’, and ‘uncertainty’.
- rnk_weightfloat, default=0.5
The weight of the uncertainty in the ranking. Used with the ‘ensured’ ranking metric.