Skip to content

Plotting

Diagnostic plots for fitted estimators.

Every function takes a fitted estimator and draws on matplotlib axes. The same plots are available as methods: estimator.plot(kind=...) and estimator.plot_<kind>(...).

Available kinds
  • "memberships" — the learned fuzzy sets, one panel per feature.
  • "history" — loss or a metric per epoch, with the validation curve and the best epoch when they were recorded.
  • "rules" — the rule base as a table: the fuzzy set that each rule uses on each feature.
  • "rule_activation" — mean normalized firing strength of each rule, split by class when labels are given.
  • "diagnostics" — confusion matrix and decision margin for classifiers; predicted against observed and residuals for regressors.
  • "feature_importance" — the features that weigh most in the consequents.
  • "gates" — the gates of the features and rules that a gated family kept, with the thresholds they passed.
Conventions
  • matplotlib is an optional dependency (pip install highfis[plot]) and is only imported when a plot is requested.
  • Single-panel plots accept ax and return the Axes. Multi-panel plots accept a sequence of axes in ax and return the Figure.
  • In an interactive session or a notebook a plot is displayed and nothing is returned, as with a plot command; in a script, or with show=False, the Axes or the Figure is returned and nothing is displayed. save="figure.pdf" writes the figure to a file in both cases.
  • The colours come from one theme, changed with :func:set_plot_theme, and each plot takes colors or cmap for a single figure. No function changes rcParams.

PlotTheme dataclass

Colours shared by every plot of the package.

Attributes:

Name Type Description
colors tuple[str, ...]

Colours of the things that are told apart by name: the fuzzy sets of a feature, in the membership plot and in the table of the rule base, the training and validation curves, the classes.

sequential str

Colormap of the tables whose cells are amounts, from little to much: the confusion matrix and the rule activation.

reference str

Colour of the lines that mark a reference: thresholds, the decision boundary, the best epoch.

Source code in highfis/plotting.py
@dataclass(frozen=True)
class PlotTheme:
    """Colours shared by every plot of the package.

    Attributes:
        colors: Colours of the things that are told apart by name: the fuzzy sets of a
            feature, in the membership plot and in the table of the rule base, the training
            and validation curves, the classes.
        sequential: Colormap of the tables whose cells are amounts, from little to much:
            the confusion matrix and the rule activation.
        reference: Colour of the lines that mark a reference: thresholds, the decision
            boundary, the best epoch.
    """

    colors: tuple[str, ...] = _OKABE_ITO
    sequential: str = "Blues"
    reference: str = "0.4"

get_plot_theme

Return the colours that the plots use.

Source code in highfis/plotting.py
def get_plot_theme() -> PlotTheme:
    """Return the colours that the plots use."""
    return _theme

plot

Draw the plot named kind for a fitted estimator.

Parameters:

Name Type Description Default
estimator Any

A fitted estimator.

required
kind str

One of "memberships" (default), "history", "rules", "rule_activation", "diagnostics", "feature_importance" or "gates".

'memberships'
**kwargs Any

Arguments of the corresponding plot_<kind> function, among them show.

{}

Returns:

Type Description
Any

The Axes or Figure returned by that function, or None when the figure

Any

was displayed.

Source code in highfis/plotting.py
def plot(estimator: Any, kind: str = "memberships", **kwargs: Any) -> Any:
    """Draw the plot named *kind* for a fitted estimator.

    Args:
        estimator: A fitted estimator.
        kind: One of ``"memberships"`` (default), ``"history"``, ``"rules"``,
            ``"rule_activation"``, ``"diagnostics"``, ``"feature_importance"`` or ``"gates"``.
        **kwargs: Arguments of the corresponding ``plot_<kind>`` function, among them
            ``show``.

    Returns:
        The ``Axes`` or ``Figure`` returned by that function, or ``None`` when the figure
        was displayed.
    """
    if kind not in _PLOTTERS:
        raise ValueError(f"kind must be one of {list(PLOT_KINDS)}; got {kind!r}")
    return _PLOTTERS[kind](estimator, **kwargs)

plot_diagnostics

Plot two views of the predictions on (X, y).

For a classifier: the confusion matrix, and the decision margin of every sample grouped by its true class. The margin is the probability given to the true class minus the highest probability given to another class, so it is negative for the samples that are misclassified.

For a regressor: predicted against observed values, and the residuals against the observed values.

Parameters:

Name Type Description Default
estimator Any

A fitted estimator.

required
X Any

Data to predict.

required
y Any

True labels or targets for X.

required
cmap str | None

Colormap of the confusion matrix. None uses the sequential colormap of the theme (see :func:set_plot_theme).

None
colors Sequence[str] | None

Colours of the classes in the decision margin, or of the points of a regressor. None uses the theme.

None
ax Any

Two axes to draw on. None creates a new figure.

None
show

Display the figure and return nothing (True), or return it without displaying (False). None displays in an interactive session or a notebook, and returns it in a script or when ax is given.

required
save

Path of a file to write the figure to, in the format of its extension.

required

Returns:

Type Description
Any

The Figure holding the two panels.

Source code in highfis/plotting.py
@_shown
def plot_diagnostics(
    estimator: Any,
    X: Any,
    y: Any,
    *,
    cmap: str | None = None,
    colors: Sequence[str] | None = None,
    ax: Any = None,
) -> Any:
    """Plot two views of the predictions on ``(X, y)``.

    For a classifier: the confusion matrix, and the decision margin of every sample
    grouped by its true class. The margin is the probability given to the true class minus
    the highest probability given to another class, so it is negative for the samples that
    are misclassified.

    For a regressor: predicted against observed values, and the residuals against the
    observed values.

    Args:
        estimator: A fitted estimator.
        X: Data to predict.
        y: True labels or targets for ``X``.
        cmap: Colormap of the confusion matrix. ``None`` uses the sequential colormap of
            the theme (see :func:`set_plot_theme`).
        colors: Colours of the classes in the decision margin, or of the points of a
            regressor. ``None`` uses the theme.
        ax: Two axes to draw on. ``None`` creates a new figure.
        show: Display the figure and return nothing (``True``), or return it without
            displaying (``False``). ``None`` displays in an interactive session or a
            notebook, and returns it in a script or when ``ax`` is given.
        save: Path of a file to write the figure to, in the format of its extension.

    Returns:
        The ``Figure`` holding the two panels.
    """
    check_is_fitted(estimator, "model_")
    fig, axes = _axes(ax, 2, ncols=2, panel_size=(3.6, 3.2))
    draw = _classification_diagnostics if is_classifier(estimator) else _regression_diagnostics
    draw(estimator, X, np.asarray(y), axes, cmap, _colours(colors))
    return fig

plot_feature_importance

Plot the features that weigh most in the consequents of the fitted model.

The importance is the one of estimator.feature_importance(): the mean magnitude of the consequent coefficients of each feature, normalized to sum to one. Features are named as in fit when the data had names, and by their column otherwise.

Parameters:

Name Type Description Default
estimator Any

A fitted estimator.

required
top int | None

Number of features to draw, from the most important. None draws all.

20
colors Sequence[str] | None

Colour of the bars, as a sequence whose first colour is used. None uses the theme (see :func:set_plot_theme).

None
ax Any

Axes to draw on. None creates a new figure.

None
show

Display the figure and return nothing (True), or return it without displaying (False). None displays in an interactive session or a notebook, and returns it in a script or when ax is given.

required
save

Path of a file to write the figure to, in the format of its extension.

required

Returns:

Type Description
Any

The Axes with the bar chart.

Source code in highfis/plotting.py
@_shown
def plot_feature_importance(
    estimator: Any, *, top: int | None = 20, colors: Sequence[str] | None = None, ax: Any = None
) -> Any:
    """Plot the features that weigh most in the consequents of the fitted model.

    The importance is the one of ``estimator.feature_importance()``: the mean magnitude of
    the consequent coefficients of each feature, normalized to sum to one. Features are
    named as in ``fit`` when the data had names, and by their column otherwise.

    Args:
        estimator: A fitted estimator.
        top: Number of features to draw, from the most important. ``None`` draws all.
        colors: Colour of the bars, as a sequence whose first colour is used. ``None`` uses
            the theme (see :func:`set_plot_theme`).
        ax: Axes to draw on. ``None`` creates a new figure.
        show: Display the figure and return nothing (``True``), or return it without
            displaying (``False``). ``None`` displays in an interactive session or a
            notebook, and returns it in a script or when ``ax`` is given.
        save: Path of a file to write the figure to, in the format of its extension.

    Returns:
        The ``Axes`` with the bar chart.
    """
    check_is_fitted(estimator, "model_")
    importance = estimator.feature_importance()
    if importance is None:
        raise ValueError("this model has no consequent coefficients to compute a feature importance from")
    importance = np.asarray(importance, dtype=float)
    labels = _feature_labels(estimator)
    order = np.argsort(-importance)
    if top is not None:
        order = order[: int(top)]

    _, (panel,) = _axes(ax, 1, ncols=1, panel_size=(4.8, max(2.4, 0.22 * len(order) + 1.0)))
    panel.barh(np.arange(len(order)), importance[order], color=_colours(colors)[0])
    panel.set_yticks(np.arange(len(order)), [labels[position] for position in order])
    panel.invert_yaxis()
    panel.set_xlabel("Feature importance")
    return panel

plot_gates

Plot the gates of the features and of the rules that a gated family kept.

Only DG-TSK, DG-ALETSK and FSRE-ADATSK have gates. The bars are the gate values at the end of the phase that trained them, for the features in selected_features_ and for the rules of the fitted model, and the dashed line is the threshold they passed. The gate of FSRE-ADATSK is an odd function, so its magnitude is drawn.

Parameters:

Name Type Description Default
estimator Any

A fitted estimator of a gated family.

required
colors Sequence[str] | None

Colour of the bars, as a sequence whose first colour is used. None uses the theme (see :func:set_plot_theme).

None
ax Any

Two axes to draw on, for the features and for the rules. None creates a new figure.

None
show

Display the figure and return nothing (True), or return it without displaying (False). None displays in an interactive session or a notebook, and returns it in a script or when ax is given.

required
save

Path of a file to write the figure to, in the format of its extension.

required

Returns:

Type Description
Any

The Figure with the two panels.

Source code in highfis/plotting.py
@_shown
def plot_gates(estimator: Any, *, colors: Sequence[str] | None = None, ax: Any = None) -> Any:
    """Plot the gates of the features and of the rules that a gated family kept.

    Only DG-TSK, DG-ALETSK and FSRE-ADATSK have gates. The bars are the gate values at the
    end of the phase that trained them, for the features in ``selected_features_`` and for
    the rules of the fitted model, and the dashed line is the threshold they passed. The
    gate of FSRE-ADATSK is an odd function, so its magnitude is drawn.

    Args:
        estimator: A fitted estimator of a gated family.
        colors: Colour of the bars, as a sequence whose first colour is used. ``None`` uses
            the theme (see :func:`set_plot_theme`).
        ax: Two axes to draw on, for the features and for the rules. ``None`` creates a
            new figure.
        show: Display the figure and return nothing (``True``), or return it without
            displaying (``False``). ``None`` displays in an interactive session or a
            notebook, and returns it in a script or when ``ax`` is given.
        save: Path of a file to write the figure to, in the format of its extension.

    Returns:
        The ``Figure`` with the two panels.
    """
    check_is_fitted(estimator, "model_")
    feature_gates, rule_gates = estimator.get_feature_gates(), estimator.get_rule_gates()
    if feature_gates is None or rule_gates is None:
        raise ValueError("only DG-TSK, DG-ALETSK and FSRE-ADATSK have gates to plot")
    thresholds = _gate_thresholds(estimator.history_)
    panels = (
        ("Feature gates", np.abs(np.asarray(feature_gates, dtype=float)).ravel(), _feature_labels(estimator)),
        ("Rule gates", np.abs(np.asarray(rule_gates, dtype=float)).ravel(), None),
    )

    fig, axes = _axes(ax, 2, ncols=2, panel_size=(4.4, 3.0))
    for panel, (title, values, labels), threshold in zip(axes, panels, thresholds, strict=True):
        positions = np.arange(len(values))
        panel.bar(positions, values, color=_colours(colors)[0])
        if threshold is not None:
            panel.axhline(threshold, color=_theme.reference, linestyle="--")
            title = f"{title} (dashed: threshold {threshold:.2f})"
        if labels is None:
            labels = [f"Rule {rule}" for rule in positions]
        if len(values) <= 30:
            slanted = len(values) > 4
            panel.set_xticks(positions, labels, rotation=60 if slanted else 0, ha="right" if slanted else "center")
        else:
            panel.set_xticks([])
        panel.set_ylim(0.0, 1.1 * max(float(values.max()), threshold or 0.0))
        panel.set_ylabel("Gate value")
        panel.set_title(title)
    return fig

plot_history

Plot the training loss, or a metric, per epoch.

The validation curve is drawn when a validation set was passed to fit, and the best epoch is marked when early stopping recorded one. Families that train in several phases (DG-TSK, DG-ALETSK, FSRE-ADATSK) get one panel per phase, side by side and on the same vertical scale.

Parameters:

Name Type Description Default
estimator Any

A fitted estimator.

required
metric str | None

Name of a metric recorded during fit (for example "accuracy"). None plots the loss.

None
colors Sequence[str] | None

Colours of the training and of the validation curve. None uses the theme (see :func:set_plot_theme).

None
ax Any

Axes to draw on, one per training phase. None creates a new figure.

None
show

Display the figure and return nothing (True), or return it without displaying (False). None displays in an interactive session or a notebook, and returns it in a script or when ax is given.

required
save

Path of a file to write the figure to, in the format of its extension.

required

Returns:

Type Description
Any

The Axes with the curves, or the Figure holding one panel per phase for a

Any

family that trains in several phases.

Source code in highfis/plotting.py
@_shown
def plot_history(
    estimator: Any, metric: str | None = None, *, colors: Sequence[str] | None = None, ax: Any = None
) -> Any:
    """Plot the training loss, or a metric, per epoch.

    The validation curve is drawn when a validation set was passed to ``fit``, and the
    best epoch is marked when early stopping recorded one. Families that train in several
    phases (DG-TSK, DG-ALETSK, FSRE-ADATSK) get one panel per phase, side by side and on
    the same vertical scale.

    Args:
        estimator: A fitted estimator.
        metric: Name of a metric recorded during ``fit`` (for example ``"accuracy"``).
            ``None`` plots the loss.
        colors: Colours of the training and of the validation curve. ``None`` uses the
            theme (see :func:`set_plot_theme`).
        ax: Axes to draw on, one per training phase. ``None`` creates a new figure.
        show: Display the figure and return nothing (``True``), or return it without
            displaying (``False``). ``None`` displays in an interactive session or a
            notebook, and returns it in a script or when ``ax`` is given.
        save: Path of a file to write the figure to, in the format of its extension.

    Returns:
        The ``Axes`` with the curves, or the ``Figure`` holding one panel per phase for a
        family that trains in several phases.
    """
    check_is_fitted(estimator, "model_")
    phases = _history_phases(estimator.history_)
    name = "loss" if metric is None else metric
    if metric is not None and metric not in _available_metrics(phases):
        raise ValueError(f"metric {metric!r} was not recorded during fit; available: {_available_metrics(phases)}")

    several = len(phases) > 1
    fig, panels = _axes(ax, len(phases), ncols=len(phases), panel_size=(3.4, 3.0) if several else (4.8, 3.2))
    for index, (panel, (label, phase)) in enumerate(zip(panels, phases, strict=True)):
        _draw_phase(panel, phase, name, _colours(colors))
        if label:
            panel.set_title(label[0].upper() + label[1:])
        if index == 0:
            panel.set_ylabel(name.replace("_", " ").capitalize())
            if panel.get_legend_handles_labels()[0]:
                panel.legend()
    if several:
        # One vertical scale, so that the level reached by a phase can be compared with the next.
        limits = [panel.get_ylim() for panel in panels]
        for panel in panels:
            panel.set_ylim(min(lo for lo, _ in limits), max(hi for _, hi in limits))
        return fig
    return panels[0]

plot_memberships

Plot the learned fuzzy sets, one panel per feature.

Parameters:

Name Type Description Default
estimator Any

A fitted estimator.

required
features Sequence[int | str] | None

Features to show, as names or as column indices of the data seen in fit. None shows every feature, or the max_features most important ones when the model has more.

None
X Any

Optional data. When given, each panel spans the range of its column; otherwise the range is taken from the parameters of the fuzzy sets.

None
max_features int

Number of features shown when features is None.

6
n_points int

Number of points used to draw each curve.

200
set_names Sequence[str] | None

Names of the fuzzy sets of a feature, from the lowest to the highest, used when their number matches. By default two, three and five sets are named low ... high, as in :meth:rules_as_text.

None
colors Sequence[str] | None

Colours of the fuzzy sets, from the lowest to the highest. None uses the theme (see :func:set_plot_theme).

None
ax Any

Axes to draw on, one per feature. None creates a new figure.

None
show

Display the figure and return nothing (True), or return it without displaying (False). None displays in an interactive session or a notebook, and returns it in a script or when ax is given.

required
save

Path of a file to write the figure to, in the format of its extension.

required

Returns:

Type Description
Any

The Figure holding the panels.

Source code in highfis/plotting.py
@_shown
def plot_memberships(
    estimator: Any,
    features: Sequence[int | str] | None = None,
    *,
    X: Any = None,
    max_features: int = 6,
    n_points: int = 200,
    set_names: Sequence[str] | None = None,
    colors: Sequence[str] | None = None,
    ax: Any = None,
) -> Any:
    """Plot the learned fuzzy sets, one panel per feature.

    Args:
        estimator: A fitted estimator.
        features: Features to show, as names or as column indices of the data seen in
            ``fit``. ``None`` shows every feature, or the ``max_features`` most important
            ones when the model has more.
        X: Optional data. When given, each panel spans the range of its column; otherwise
            the range is taken from the parameters of the fuzzy sets.
        max_features: Number of features shown when ``features`` is ``None``.
        n_points: Number of points used to draw each curve.
        set_names: Names of the fuzzy sets of a feature, from the lowest to the highest,
            used when their number matches. By default two, three and five sets are named
            ``low`` ... ``high``, as in :meth:`rules_as_text`.
        colors: Colours of the fuzzy sets, from the lowest to the highest. ``None`` uses the
            theme (see :func:`set_plot_theme`).
        ax: Axes to draw on, one per feature. ``None`` creates a new figure.
        show: Display the figure and return nothing (``True``), or return it without
            displaying (``False``). ``None`` displays in an interactive session or a
            notebook, and returns it in a script or when ``ax`` is given.
        save: Path of a file to write the figure to, in the format of its extension.

    Returns:
        The ``Figure`` holding the panels.
    """
    check_is_fitted(estimator, "model_")
    positions = _select_features(estimator, features, max_features)
    labels = _feature_labels(estimator)
    model_names = [str(name) for name in estimator.model_.input_names]
    mf_params = estimator.get_mf_params()
    input_mfs = estimator.model_.membership_layer.input_mfs
    data = None if X is None else estimator._select_model_features(np.asarray(X))

    fig, axes = _axes(ax, len(positions), ncols=min(3, len(positions)), panel_size=(3.2, 2.4))
    legends: list[list[str]] = []
    palette = _colours(colors)
    for panel, position in zip(axes, positions, strict=True):
        name = model_names[position]
        lo, hi = _feature_range(mf_params[name], None if data is None else data[:, position])
        # The centres are added to the grid so that the peak of a narrow set is not missed.
        centres = [p.get("mean", p.get("center")) for p in mf_params[name]]
        centres = [c for c in centres if c is not None and lo <= c <= hi]
        points = np.unique(np.concatenate([np.linspace(lo, hi, n_points), centres]))
        grid = torch.as_tensor(points, dtype=estimator._model_dtype(), device=str(estimator.device))
        names = _set_labels(mf_params[name], set_names)
        located = [j for j in range(len(names)) if names[j] is not None]
        # The colour follows the position of a set among those of its feature, from the
        # lowest to the highest, so that a name has the same colour on every panel.
        rank = {j: i for i, j in enumerate(sorted(located, key=lambda j: _set_position(mf_params[name][j])))}
        with torch.no_grad():
            for j in located:
                curve = input_mfs[name][j](grid).cpu().numpy()
                panel.plot(grid.cpu().numpy(), curve, label=names[j], color=palette[rank[j] % len(palette)])
        legends.append([str(names[j]) for j in sorted(located, key=rank.__getitem__)])
        panel.set_title(labels[position])
        panel.set_ylim(0.0, 1.05)
        panel.set_xlabel("Feature value")
        panel.set_ylabel("Membership degree")
    # The same sets on every panel: one legend beside the panels, where it hides no curve.
    shared = ax is None and len(set(map(tuple, legends))) == 1 and 0 < len(legends[0]) <= _MAX_LEGEND_ENTRIES
    for panel, entries in zip(axes[:1] if shared else axes, legends, strict=False):
        if not 0 < len(entries) <= _MAX_LEGEND_ENTRIES:
            continue
        by_label = dict(zip(*reversed(panel.get_legend_handles_labels()), strict=True))
        handles = [by_label[entry] for entry in entries]
        if shared:
            fig.legend(handles, entries, loc="outside right upper", title="Fuzzy set")
        else:
            panel.legend(handles, entries, fontsize="small")
    return fig

plot_rule_activation

Plot the mean normalized firing strength of each rule.

Parameters:

Name Type Description Default
estimator Any

A fitted estimator.

required
X Any

Data on which the rules are evaluated.

required
y Any

Optional class labels, for classifiers only. When given, the mean activation is computed separately for the samples of each class.

None
cmap str | None

Colormap of the table drawn when y is given. None uses the sequential colormap of the theme (see :func:set_plot_theme).

None
colors Sequence[str] | None

Colour of the bars drawn when y is not given, as a sequence whose first colour is used. None uses the theme.

None
ax Any

Axes to draw on. None creates a new figure.

None
show

Display the figure and return nothing (True), or return it without displaying (False). None displays in an interactive session or a notebook, and returns it in a script or when ax is given.

required
save

Path of a file to write the figure to, in the format of its extension.

required

Returns:

Type Description
Any

The Axes with the heatmap (labels given) or the bar chart (no labels).

Source code in highfis/plotting.py
@_shown
def plot_rule_activation(
    estimator: Any,
    X: Any,
    y: Any = None,
    *,
    cmap: str | None = None,
    colors: Sequence[str] | None = None,
    ax: Any = None,
) -> Any:
    """Plot the mean normalized firing strength of each rule.

    Args:
        estimator: A fitted estimator.
        X: Data on which the rules are evaluated.
        y: Optional class labels, for classifiers only. When given, the mean activation is
            computed separately for the samples of each class.
        cmap: Colormap of the table drawn when ``y`` is given. ``None`` uses the sequential
            colormap of the theme (see :func:`set_plot_theme`).
        colors: Colour of the bars drawn when ``y`` is not given, as a sequence whose first
            colour is used. ``None`` uses the theme.
        ax: Axes to draw on. ``None`` creates a new figure.
        show: Display the figure and return nothing (``True``), or return it without
            displaying (``False``). ``None`` displays in an interactive session or a
            notebook, and returns it in a script or when ``ax`` is given.
        save: Path of a file to write the figure to, in the format of its extension.

    Returns:
        The ``Axes`` with the heatmap (labels given) or the bar chart (no labels).
    """
    check_is_fitted(estimator, "model_")
    activation = estimator.rule_activation(X)
    n_rules = activation.shape[1]
    rule_labels = [f"Rule {r}" for r in range(n_rules)]
    _, (panel,) = _axes(ax, 1, ncols=1, panel_size=(4.8, max(2.4, 0.3 * n_rules + 1.2)))

    if y is None:
        panel.barh(np.arange(n_rules), activation.mean(axis=0), color=_colours(colors)[0])
        panel.set_xlabel("Mean rule activation")
        panel.invert_yaxis()
    else:
        if not is_classifier(estimator):
            raise ValueError("y groups the activations by class, so it only applies to classifiers")
        y = np.asarray(y)
        classes = estimator.classes_
        by_class = np.stack([activation[y == c].mean(axis=0) for c in classes], axis=1)
        _annotated_heatmap(panel, by_class, cmap, lambda v: f"{v:.2f}")
        panel.set_xticks(np.arange(len(classes)), [str(c) for c in classes])
        panel.set_xlabel("True class")
        panel.set_title("Mean rule activation")
    if n_rules <= 30:
        panel.set_yticks(np.arange(n_rules), rule_labels)
    else:
        panel.set_ylabel("Rule")
    return panel

plot_rules

Plot the rule base as a table: one row per rule, one column per feature.

Each cell is the fuzzy set that the rule uses on the feature. A set has the colour it has in :func:plot_memberships, the first colour for the lowest set of a feature, and in small rule bases it is labelled with the initials of its name: VL for very low, M for medium. A blank cell is a feature that the rule does not use.

Parameters:

Name Type Description Default
estimator Any

A fitted estimator.

required
features Sequence[int | str] | None

Features to show, as names or as column indices of the data seen in fit. None shows every feature or, when the model has more than max_features, the features that tell the rules apart: those on which a rule departs from the fuzzy set it uses on most features, then the most important ones.

None
max_features int

Number of features shown when features is None.

12
set_names Sequence[str] | None

Names of the fuzzy sets of a feature, as in :func:plot_memberships.

None
colors Sequence[str] | None

Colours of the fuzzy sets, from the lowest to the highest. None uses the theme (see :func:set_plot_theme).

None
cmap str | None

Colormap that shades the cells from the lowest set to the highest, in place of one colour per set. It is also what is used, with the sequential colormap of the theme, when a feature has more sets than there are colours.

None
ax Any

Axes to draw on. None creates a new figure.

None
show

Display the figure and return nothing (True), or return it without displaying (False). None displays in an interactive session or a notebook, and returns it in a script or when ax is given.

required
save

Path of a file to write the figure to, in the format of its extension.

required

Returns:

Type Description
Any

The Axes with the table.

Source code in highfis/plotting.py
@_shown
def plot_rules(
    estimator: Any,
    features: Sequence[int | str] | None = None,
    *,
    max_features: int = 12,
    set_names: Sequence[str] | None = None,
    colors: Sequence[str] | None = None,
    cmap: str | None = None,
    ax: Any = None,
) -> Any:
    """Plot the rule base as a table: one row per rule, one column per feature.

    Each cell is the fuzzy set that the rule uses on the feature. A set has the colour it
    has in :func:`plot_memberships`, the first colour for the lowest set of a feature, and
    in small rule bases it is labelled with the initials of its name: ``VL`` for *very
    low*, ``M`` for *medium*. A blank cell is a feature that the rule does not use.

    Args:
        estimator: A fitted estimator.
        features: Features to show, as names or as column indices of the data seen in
            ``fit``. ``None`` shows every feature or, when the model has more than
            ``max_features``, the features that tell the rules apart: those on which a
            rule departs from the fuzzy set it uses on most features, then the most
            important ones.
        max_features: Number of features shown when ``features`` is ``None``.
        set_names: Names of the fuzzy sets of a feature, as in :func:`plot_memberships`.
        colors: Colours of the fuzzy sets, from the lowest to the highest. ``None`` uses the
            theme (see :func:`set_plot_theme`).
        cmap: Colormap that shades the cells from the lowest set to the highest, in place
            of one colour per set. It is also what is used, with the sequential colormap
            of the theme, when a feature has more sets than there are colours.
        ax: Axes to draw on. ``None`` creates a new figure.
        show: Display the figure and return nothing (``True``), or return it without
            displaying (``False``). ``None`` displays in an interactive session or a
            notebook, and returns it in a script or when ``ax`` is given.
        save: Path of a file to write the figure to, in the format of its extension.

    Returns:
        The ``Axes`` with the table.
    """
    check_is_fitted(estimator, "model_")
    labels = _feature_labels(estimator)
    model_names = [str(name) for name in estimator.model_.input_names]
    mf_params = estimator.get_mf_params()
    table = estimator.model_.get_rule_table()
    if features is None and len(model_names) > max_features:
        positions = _distinguishing_features(estimator, table, model_names, max_features)
    else:
        positions = _select_features(estimator, features, max_features)

    levels = np.full((len(table), len(positions)), np.nan)  # position of the set among those of its feature
    n_sets = 1
    text: list[list[str]] = [["" for _ in positions] for _ in table]
    for column, position in enumerate(positions):
        name = model_names[position]
        names = _set_labels(mf_params[name], set_names)
        located = (j for j, label in enumerate(names) if label is not None)
        order = sorted(located, key=lambda j: _set_position(mf_params[name][j]))
        rank = {j: i for i, j in enumerate(order)}
        n_sets = max(n_sets, len(order))
        for row, rule in enumerate(table):
            j = int(rule[name])
            if j in rank:
                levels[row, column] = rank[j]
                text[row][column] = _abbreviation(str(names[j]))

    size = (max(3.6, 0.62 * len(positions) + 1.6), max(2.4, 0.3 * len(table) + 1.4))
    _, (panel,) = _axes(ax, 1, ncols=1, panel_size=size)
    palette = _colours(colors)
    if cmap is None and n_sets <= len(palette):
        from matplotlib.colors import ListedColormap

        shades: Any = ListedColormap(list(palette[:n_sets]), name="fuzzy sets")
        image = panel.imshow(levels, cmap=shades, aspect="auto", vmin=-0.5, vmax=n_sets - 0.5)
    else:
        image = panel.imshow(levels, cmap=cmap or _theme.sequential, aspect="auto", vmin=0.0, vmax=max(n_sets - 1, 1))
    if levels.size <= _RULE_TABLE_MAX_ANNOTATED_CELLS:
        for (row, column), value in np.ndenumerate(levels):
            if not np.isnan(value):
                colour = _text_colour(image, float(value))
                panel.text(column, row, text[row][column], ha="center", va="center", color=colour, fontsize="small")
    panel.set_xticks(np.arange(len(positions)), [labels[p] for p in positions], rotation=60, ha="right")
    if len(table) <= 30:
        panel.set_yticks(np.arange(len(table)), [f"Rule {rule['rule_id']}" for rule in table])
    else:
        panel.set_ylabel("Rule")
    panel.set_title("Fuzzy set of each feature in each rule")
    return panel

reset_plot_theme

Go back to the colours of the package.

Source code in highfis/plotting.py
def reset_plot_theme() -> PlotTheme:
    """Go back to the colours of the package."""
    global _theme
    _theme = PlotTheme()
    return _theme

set_plot_theme

Change the colours of every plot drawn from now on.

Only the arguments given are changed. Colours are anything matplotlib accepts as a colour, and colormaps are names of matplotlib colormaps.

Parameters:

Name Type Description Default
colors Sequence[str] | None

Colours of the things told apart by name, in the order they are used.

None
sequential str | None

Colormap of the confusion matrix and of the rule activation.

None
reference str | None

Colour of the reference lines.

None

Returns:

Type Description
PlotTheme

The theme now in use.

Source code in highfis/plotting.py
def set_plot_theme(
    *,
    colors: Sequence[str] | None = None,
    sequential: str | None = None,
    reference: str | None = None,
) -> PlotTheme:
    """Change the colours of every plot drawn from now on.

    Only the arguments given are changed. Colours are anything matplotlib accepts as a
    colour, and colormaps are names of matplotlib colormaps.

    Args:
        colors: Colours of the things told apart by name, in the order they are used.
        sequential: Colormap of the confusion matrix and of the rule activation.
        reference: Colour of the reference lines.

    Returns:
        The theme now in use.
    """
    global _theme
    changes: dict[str, Any] = {"sequential": sequential, "reference": reference}
    if colors is not None:
        if len(colors) == 0:
            raise ValueError("colors must have at least one colour")
        changes["colors"] = tuple(colors)
    _theme = replace(_theme, **{key: value for key, value in changes.items() if value is not None})
    return _theme