calibrated_explanations.explanations.FactualExplanation

class calibrated_explanations.explanations.FactualExplanation(calibrated_explanations, index, x, binned, feature_weights, feature_predict, prediction, y_threshold=None, instance_bin=None, condition_source: str = 'prediction')[source]

Bases: CalibratedExplanation

Class for storing and visualizing factual explanations.

Provides factual explanations for a given instance, highlighting features that contribute to the model’s prediction.

Initialize a FactualExplanation 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:
predict

Get the prediction from the prediction dictionary.

prediction_interval

Get the prediction interval from the prediction dictionary.

Methods

add_conjunctions([n_top_features, max_rule_size])

Add conjunctive factual 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.

build_rules_payload()

Return structured payload describing factual 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.

define_conditions()

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.

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 factual rule by its numeric index.

get_rules()

Create factual rules.

get_rules_by_feature(feature)

Return all factual rules that mention the given feature name.

ignored_features_for_instance()

Return the set of feature indices ignored for this instance.

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.

is_thresholded()

Check if the explanation is thresholded.

list_rules()

Return all factual rules as normalized dicts.

normalize_percentile_value(value)

Normalise percentile inputs to decimal fractions.

normalize_threshold_value()

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 factual explanation for a given instance.

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.

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 factual feature rules.

get_rule_by_index(index: int) Dict[str, Any][source]

Return a single factual rule by its numeric index.

Raises IndexError when the index is out of range.

get_rules_by_feature(feature: str) list[Dict[str, Any]][source]

Return all factual rules that mention the given feature name.

Raises KeyError when no matching rules are found.

list_rules() list[Dict[str, Any]][source]

Return all factual rules as normalized dicts.

get_rules()[source]

Create factual rules.

Returns:

A list of dictionaries containing the factual rules.

Return type:

List[Dict[str, List]]

add_conjunctions(n_top_features=5, max_rule_size=2, **kwargs)[source]

Add conjunctive factual rules.

Builds conjunctions by iterating over feature combinations from current_size = 2 up to max_rule_size. For each size the method ranks existing rules, then pairs every outer-loop feature (from the original factual rules) with top-ranked inner-loop candidates stored in ConjunctionState. Duplicate feature combinations are deduplicated and predictions are obtained via predict_conjunctive().

Parameters:
  • n_top_features (int, optional) – Number of top features to consider when ranking candidates.

  • max_rule_size (int, optional) – Maximum number of features in a single conjunctive rule.

  • _use_batched (bool) – Use vectorized batch prediction (default True).

  • _limit_outer_to_ranked (bool) – Restrict outer loop to rank-filtered features (default False).

  • _dedupe_by_feature_only (bool) – Deduplicate by feature index only, ignoring sampled values (default True).

  • raise_on_predict_error (bool) – Re-raise prediction exceptions instead of silently skipping (default False).

  • _fallback_to_legacy_on_zero (bool) – Fall back to the legacy implementation when no conjunctions are created (default False).

Returns:

self – Returns a self reference, to allow for method chaining.

Return type:

FactualExplanation

Notes

After the call, self.conjunction_stats contains a diagnostic dict with keys "attempts", "created", "skipped" (Counter), and "predict_errors" (list of up to 5 captured exception messages).

plot(filter_top=None, **kwargs)[source]

Plot the factual explanation for a given instance.

Parameters:
  • filter_top (int, optional) – The number of top features to display.

  • **kwargs (dict) –

    Additional plotting arguments:

    • show (bool): default=True if filename is empty, False otherwise. Determines whether the plot should be displayed or not.

    • filename (str): default=’’. The full path and filename of the plot image file that will be saved. If not provided or empty, the plot will not be saved.

    • uncertainty (bool): default=False. Whether to plot the uncertainty intervals for the feature weights.

    • style (str): default=’regular’. The style of the plot. Possible styles:

      • ’regular’ - a regular plot with feature weights and uncertainty intervals.

      • ’narrative’ - generate human-readable narrative explanations.

    • rnk_metric (str): default=’feature_weight’. The metric used to rank the features. Supported metrics are ‘ensured’, ‘feature_weight’, and ‘uncertainty’.

    • rnk_weight (float): default=0.5. The weight of the uncertainty in the ranking. Used with the ‘ensured’ ranking metric.