eli5.formatters
This module holds functions that convert Explanation objects
(returned by eli5.explain_weights() and eli5.explain_prediction())
into HTML, text, dict/JSON or pandas DataFrames. The following functions are
also available in eli5 namespace (e.g. eli5.format_as_html):
eli5.formatters.html
- format_as_html(explanation: Explanation, include_styles=True, force_weights=True, show=('method', 'description', 'transition_features', 'targets', 'feature_importances', 'decision_tree'), preserve_density: bool | None = None, highlight_spaces: bool | None = None, horizontal_layout=True, show_feature_values=False) str[source]
Format explanation as html. Most styles are inline, but some are included separately in <style> tag, you can omit them by passing
include_styles=Falseand callformat_html_stylesto render them separately (or just omit them). Withforce_weights=False, weights will not be displayed in a table for predictions where it is possible to show feature weights highlighted in the document. Ifhighlight_spacesis None (default), spaces will be highlighted in feature names only if there are any spaces at the start or at the end of the feature. Setting it to True forces space highlighting, and setting it to False turns it off. Ifhorizontal_layoutis True (default), multiclass classifier weights are laid out horizontally. Ifshow_feature_valuesis True, feature values are shown if present. Default is False.
- format_hsl(hsl_color: tuple[float, float, float]) str[source]
Format hsl color as css color string.
- format_html_styles() str[source]
Format just the styles, use with
format_as_html(explanation, include_styles=False).
- get_weight_range(weights: FeatureWeights) float[source]
Max absolute feature for pos and neg weights.
- probability_color_hsl(probability: float, probability_range: float) tuple[float, float, float][source]
Return HSL color components for given probability, where the max absolute probability is given by probability_range (should always be 1 at the moment).
- remaining_weight_color_hsl(ws: list[FeatureWeight], weight_range: float, pos_neg: str) tuple[float, float, float][source]
Color for “remaining” row. Handles a number of edge cases: if there are no weights in ws or weight_range is zero, assume the worst (most intensive positive or negative color).
- render_targets_weighted_spans(targets: list[TargetExplanation], preserve_density: bool | None) list[str | None][source]
Return a list of rendered weighted spans for targets. Function must accept a list in order to select consistent weight ranges across all targets.
- transformed_probability(prob: float, alpha: float = 0.4) float[source]
Transforms a probability in [0, 1] using the Beta(alpha, alpha) CDF. This function is symmetric about (0.5, 0.5) and raises sharply near 0 and 1, highlighting differences in low and high probabilities. The parameter ‘alpha’ controls the steepness.
eli5.formatters.text
- format_as_text(expl: Explanation, show=('method', 'description', 'transition_features', 'targets', 'feature_importances', 'decision_tree'), highlight_spaces: bool | None = None, show_feature_values: bool = False) str[source]
Format explanation as text.
- Parameters:
expl (eli5.base.Explanation) – Explanation returned by
eli5.explain_weightsoreli5.explain_predictionfunctions.highlight_spaces (bool or None, optional) – Whether to highlight spaces in feature names. This is useful if you work with text and have ngram features which may include spaces at left or right. Default is None, meaning that the value used is set automatically based on vectorizer and feature values.
show_feature_values (bool) – When True, feature values are shown along with feature contributions. Default is False.
show (list[str], optional) – List of sections to show. Allowed values:
‘targets’ - per-target feature weights;
‘transition_features’ - transition features of a CRF model;
‘feature_importances’ - feature importances of a decision tree or an ensemble-based estimator;
‘decision_tree’ - decision tree in a graphical form;
‘method’ - a string with explanation method;
‘description’ - description of explanation method and its caveats.
eli5.formatters.fieldsprovides constants that cover common cases:INFO(method and description),WEIGHTS(all the rest), andALL(all).
eli5.formatters.as_dict
eli5.formatters.as_dataframe
- explain_prediction_df(estimator, doc, **kwargs) DataFrame[source]
Explain prediction and export explanation to
pandas.DataFrameAll keyword arguments are passed toeli5.explain_prediction(). Weights of all features are exported by default.
- explain_prediction_dfs(estimator, doc, **kwargs) dict[str, DataFrame][source]
Explain prediction and export explanation to a dict with
pandas.DataFramevalues (aseli5.formatters.as_dataframe.format_as_dataframes()does). All keyword arguments are passed toeli5.explain_prediction(). Weights of all features are exported by default.
- explain_weights_df(estimator, **kwargs) DataFrame[source]
Explain weights and export them to
pandas.DataFrame. All keyword arguments are passed toeli5.explain_weights(). Weights of all features are exported by default.
- explain_weights_dfs(estimator, **kwargs) dict[str, DataFrame][source]
Explain weights and export them to a dict with
pandas.DataFramevalues (aseli5.formatters.as_dataframe.format_as_dataframes()does). All keyword arguments are passed toeli5.explain_weights(). Weights of all features are exported by default.
- format_as_dataframe(explanation) DataFrame | None[source]
- format_as_dataframe(feature_importances: FeatureImportances) DataFrame
- format_as_dataframe(targets: list[TargetExplanation]) DataFrame
- format_as_dataframe(transition_features: TransitionFeatureWeights) DataFrame
Export an explanation to a single
pandas.DataFrame. In case several dataframes could be exported byeli5.formatters.as_dataframe.format_as_dataframes(), a warning is raised. If no dataframe can be exported,Noneis returned. This function also accepts some components of the explanation as arguments: feature importances, targets, transition features. Note thateli5.explain_weights()limits number of features by default. If you need all features, passtop=Nonetoeli5.explain_weights(), or useexplain_weights_df().
- format_as_dataframes(explanation: Explanation) dict[str, DataFrame][source]
Export an explanation to a dictionary with
pandas.DataFramevalues and string keys that correspond to explanation attributes. Use this method if several dataframes can be exported from a single explanation (e.g. for CRF explanation with has both feature weights and transition matrix). Note thateli5.explain_weights()limits number of features by default. If you need all features, passtop=Nonetoeli5.explain_weights(), or useexplain_weights_dfs().
eli5.formatters.image
- expand_heatmap(heatmap: ndarray, image: Image, resampling_filter: int | None = 1) Image[source]
Resize the
heatmapimage array to fit over the originalimage, using the specifiedresampling_filtermethod. The heatmap is converted to an image in the process.- Parameters:
heatmap (numpy.ndarray) – Heatmap that is to be resized, as an array.
image (PIL.Image.Image) – The image whose dimensions will be resized to.
resampling_filter (int or None) – Interpolation to use when resizing.
See
eli5.format_as_image()for more details on the resampling_filter parameter.
- Raises:
TypeError – if
imageis not a Pillow image instance.- Returns:
resized_heatmap (PIL.Image.Image) – The heatmap, resized, as a PIL image.
- format_as_image(expl, resampling_filter=Image.LANCZOS, colormap=matplotlib.cm.viridis, alpha_limit=0.65)[source]
Format a
eli5.base.Explanationobject as an image.Note that this formatter requires
matplotlibandPillowoptional dependencies.- Parameters:
expl (Explanation) –
eli5.base.Explanationobject to be formatted. It must have animageattribute with a Pillow image that will be overlaid. It must have atargetsattribute, a list ofeli5.base.TargetExplanationinstances that contain the attributeheatmap, a rank 2 numpy array with float values in the interval [0, 1]. Currentlytargetsmust be length 1 (only one target is supported).- raises TypeError:
if
heatmapis not a numpy array.- raises ValueError:
if
heatmapdoes not contain values as floats in the interval [0, 1].- raises TypeError:
if
imageis not a Pillow image.
resampling_filter (int, optional) –
Interpolation ID or Pillow filter to use when resizing the image.
- Example filters from PIL.Image
NEARESTBOXBILINEARHAMMINGBICUBICLANCZOS
See also https://pillow.readthedocs.io/en/stable/handbook/concepts.html#filters.
Note that these attributes are integer values.
Default is
PIL.Image.LANCZOS.colormap (callable, optional) –
Colormap scheme to be applied when converting the heatmap from grayscale to RGB. Either a colormap from matplotlib.cm, or a callable that takes a rank 2 array and returns the colored heatmap as a [0, 1] RGBA numpy array.
- Example colormaps from matplotlib.cm
viridisjetbinary
See also https://matplotlib.org/gallery/color/colormap_reference.html.
Default is
matplotlib.cm.viridis(green/blue to yellow).alpha_limit (float or int, optional) –
Maximum alpha (transparency / opacity) value allowed for the alpha channel pixels in the RGBA heatmap image.
Between 0.0 and 1.0.
Useful when laying the heatmap over the original image, so that the image can be seen over the heatmap.
Default is 0.65.
- raises ValueError:
if
alpha_limitis outside the [0, 1] interval.- raises TypeError:
if
alpha_limitis not float, int, or None.
- Returns:
overlay (PIL.Image.Image) – PIL image instance of the heatmap blended over the image.
- heatmap_to_image(heatmap: ndarray) Image[source]
Convert the numpy array
heatmapto a Pillow image.- Parameters:
heatmap (numpy.ndarray) – Rank 2 grayscale (‘L’) array or rank 3 coloured (‘RGB’ or RGBA’) array, with values in interval [0, 1] as floats.
- Raises:
TypeError – if
heatmapis not a numpy array.ValueError – if
heatmapdoes not contain values as floats in the interval [0, 1].ValueError – if
heatmaprank is neither 2 nor 3.ValueError – if rank 3
heatmapdoes not have 4 (RGBA) or 3 (RGB) channels.
- Returns:
heatmap_image (PIL.Image.Image) – Heatmap as an image with a suitable mode.