Skip to content

Visualizers

sklearn-protocol .fit().show() diagnostic visualizer classes.

Ferrum — a statistical visualization library with a Rust core.

AlphaSelectionVisualizer

Bases: FerrumVisualizer

Visualize cross-validated scores over a regularization-strength grid.

Wraps alpha_selection_chart in the sklearn visualizer protocol. Designed for regularized regressors such as Ridge, Lasso, and ElasticNet — estimators that expose an alpha hyperparameter controlling L1/L2 penalty strength. For each value in alphas, cross-validation produces a mean score; the alpha that maximises the mean test score is stored as best_alpha in _metrics, and the corresponding score as best_score.

Parameters:

Name Type Description Default
model Any

Unfitted regularized regressor with an alpha hyperparameter (e.g. sklearn.linear_model.Ridge, Lasso, ElasticNet). Passing an estimator without an alpha parameter will raise at fit time.

required
alphas array - like

Grid of regularization-strength values to evaluate. Passed directly to the underlying alpha_selection compute; log-spaced grids (e.g. np.logspace(-4, 4, 50)) are typical.

required
cv int

Number of cross-validation folds.

5
scoring str or callable

Sklearn scoring string or callable. Defaults to the estimator's own score method when None.

None
log_scale bool

Whether to render the x-axis (alpha values) on a log scale. Defaults to True because alpha grids are almost always log-spaced.

True
highlight_best bool

When True, draws a vertical rule at the alpha value that maximises the mean test score.

True
mark dict

Per-layer mark overrides. See alpha_selection_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to ModelSource. The folds come from sklearn's unshuffled K-fold split for the integer cv, which is deterministic without a seed, so this value does not change the result. It does not seed the wrapped estimator.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.linear_model import Ridge
>>> import numpy as np
>>> viz = fm.AlphaSelectionVisualizer(
...     Ridge(), alphas=np.logspace(-4, 4, 40), cv=5
... ).fit(X_train, y_train)
>>> chart = viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

CVScoresVisualizer

Bases: FerrumVisualizer

Visualize the distribution of per-fold cross-validation scores.

Wraps cv_scores_chart in the sklearn visualizer protocol. After fit(X, y), _metrics contains test_mean (mean test-fold score across all folds) and test_std (standard deviation of test-fold scores).

Parameters:

Name Type Description Default
model Any

Unfitted or fitted sklearn-compatible estimator.

required
cv int

Number of cross-validation folds.

5
scoring str or callable

Sklearn scoring string or callable. Defaults to the estimator's own score method when None.

None
kind ('box', 'bar', 'strip')

Chart geometry used to display the fold-score distributions.

"box"
split ('both', 'test', 'train')

Which CV splits to include in the chart. "both" shows train and test folds side by side; "test" or "train" shows only one.

"both"
mark dict

Per-layer mark overrides. See cv_scores_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to ModelSource. The folds come from sklearn's unshuffled K-fold split for the integer cv, which is deterministic without a seed, so this value does not change the result. It does not seed the wrapped estimator.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.ensemble import RandomForestClassifier
>>> viz = fm.CVScoresVisualizer(
...     RandomForestClassifier(n_estimators=100), cv=10, kind="box"
... ).fit(X_train, y_train)
>>> chart = viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

CalibrationVisualizer

Bases: FerrumVisualizer

Calibration (reliability) diagram for a probability classifier.

Wraps ModelSource.calibration_curve(). Records the mean squared deviation between mean_predicted and fraction_positive as calibration_error — one entry per model, keyed calibration_error[<model name>], for a symmetric *models overlay, since no single pooled number describes them all. Under compare= (which distinguishes a base model) there is a single calibration_error, the base model's own.

Parameters:

Name Type Description Default
*models Any

One or more fitted classifiers. Pass a single model for a single-curve diagram; pass two or more (or a single dict positional argument like {"a": m_a, "b": m_b}) to overlay multiple curves via ComparedModelSource. The multi-model form is symmetric: no model is the base, so has_score is False and _metrics carries one keyed entry per model. Use compare= instead when one model is the subject and the rest are rivals.

()
n_bins int

Number of bins for the calibration histogram.

10
strategy ('uniform', 'quantile')

Bin-edge strategy (matches sklearn.calibration).

"uniform"
annotate_brier bool

Overlay a per-series Brier-score text label.

True
subtitle str or None

Optional subtitle rendered beneath the active chart title.

None
compare dict of str -> estimator or None

Additional estimators to overlay against the single positional model, with the same distinguished-base semantics as ROCVisualizer/PRVisualizer/ DiscriminationThresholdVisualizer: the positional model is the base (label "base"), and _metrics["calibration_error"], __repr__ and .score() all describe it, never a rival. Routes through the same _build_compare_source those three use at fit time, so the reserved-"base"-key and non-dict refusals are identical, and renders exactly what calibration_chart(model, X, y, compare=...) renders. Mutually exclusive with the symmetric *models overlay -- supplying both raises ValueError (added 2026-09-13, #212).

None
mark dict

Per-layer mark overrides. See calibration_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int
None
theme Theme
None

Examples:

>>> import ferrum as fm
>>> viz = fm.CalibrationVisualizer(clf, n_bins=5).fit(X, y)
>>> viz_overlay = fm.CalibrationVisualizer(clf_a, clf_b).fit(X, y)
>>> viz_vs_rival = fm.CalibrationVisualizer(clf, compare={"rival": clf_b}).fit(X, y)

has_score property

has_score: bool

True iff score returns a real metric rather than the fallback.

A symmetric *models overlay has no single .score to report, so has_score is False and score returns 0.0 — the two stay mutually consistent. A single-model calibration keeps the base model.score behavior unchanged, and so does a compare= overlay: its base model is the subject, exactly as for ROCVisualizer/PRVisualizer/ DiscriminationThresholdVisualizer.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

score

score(X: Any, y: Any) -> float

Return the base model's .score; 0.0 for a symmetric overlay.

Overlaying several models symmetrically has no single well-defined score, so rather than silently returning only the first model's metric this returns the documented 0.0 no-single-score fallback (consistent with has_score being False). Under compare= the positional model is the base and scores normally.

ClassBalanceVisualizer

Bases: FerrumVisualizer

Bar chart of per-class label counts, computed from target labels alone.

Accepts both the standard sklearn fit(X, y) signature and the label-only shorthand fit(y) — when the second argument is omitted, the first positional argument is treated as the label array. No model is required; pass nothing for the model argument (it is always None internally).

After fit, _metrics contains:

  • n_classes — number of unique class labels.
  • imbalance_ratio — max_count / max(min_count, 1), where 1.0 indicates perfectly balanced classes and larger values indicate increasing imbalance.

Parameters:

Name Type Description Default
random_state int

Accepted for API symmetry with model-backed visualizers but intentionally never consumed — ClassBalanceVisualizer overrides fit() and never constructs a ModelSource. Documented as a permanent no-op so callers that script over visualizers don't have to special-case which ones accept the kwarg.

None
mark dict

Per-layer mark overrides. See class_balance_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> viz = fm.ClassBalanceVisualizer().fit(X, y)
>>> viz.show()                   # returns the per-class count bar Chart
>>> viz._metrics["imbalance_ratio"]

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ClassPredictionErrorVisualizer

Bases: FerrumVisualizer

Stacked-bar chart of actual-class composition per predicted class.

For each predicted class label on the x-axis, the bar is stacked by the true class, showing how often a predicted class is correct vs. confused with another class. When normalize=True every bar is scaled to 100 % so proportions are comparable across imbalanced classes.

After fit, overall accuracy (total correct / total predictions, computed from raw counts regardless of normalize) is stored in _metrics["accuracy"].

Parameters:

Name Type Description Default
model Any

Fitted sklearn classifier that exposes predict.

required
normalize bool

When True, each predicted-class bar is scaled to sum to 1 (100 % stacked view). When False, bars show absolute counts.

False
show_counts bool

Overlay per-segment count (or percentage) text on each bar.

True
mark dict

Per-layer mark overrides. See class_prediction_error_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to ModelSource for any randomness in data prep.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> viz = fm.ClassPredictionErrorVisualizer(model).fit(X, y)
>>> viz.show()                   # returns the stacked-bar Chart
>>> viz._metrics["accuracy"]     # proportion of correct predictions

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ClassificationReportVisualizer

Bases: FerrumVisualizer

Per-class precision, recall, and F1-score heatmap with text overlay.

Wraps _classification_report_chart(). Produces a rect-mark heatmap with one row per class and columns for precision, recall, and F1. Records f1_macro (macro-averaged F1 across all classes, computed via sklearn.metrics.f1_score) as the headline scalar metric.

Parameters:

Name Type Description Default
model Any

Fitted classifier implementing predict.

required
mark dict

Per-layer mark overrides. See classification_report_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to ModelSource for reproducible train/test splits.

None
theme Theme

Ferrum theme applied to the output chart.

None

Examples:

>>> import ferrum as fm
>>> viz = fm.ClassificationReportVisualizer(clf).fit(X, y)
>>> viz._metrics["f1_macro"]
0.91
>>> viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ConfusionMatrixVisualizer

Bases: FerrumVisualizer

Confusion-matrix heatmap with per-cell counts or normalized fractions.

Wraps ModelSource.confusion_matrix(). Renders a rect-mark heatmap with cell-value text overlaid. Records accuracy (diagonal sum / total, always computed from raw counts regardless of the normalize setting).

Parameters:

Name Type Description Default
model Any

Fitted classifier implementing predict.

required
normalize ('true', 'pred', 'all')

Row-normalization strategy passed to the chart builder. "true" normalizes each row by the true-class total (recall fractions); "pred" by the predicted-class total (precision fractions); "all" by the grand total; None shows raw counts.

"true"
annotate bool

Whether to overlay per-cell numeric text on the heatmap.

True
mark dict

Per-layer mark overrides. See confusion_matrix_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to ModelSource for reproducible train/test splits.

None
theme Theme

Ferrum theme applied to the output chart.

None

Examples:

>>> import ferrum as fm
>>> viz = fm.ConfusionMatrixVisualizer(clf).fit(X, y)
>>> viz._metrics["accuracy"]
0.94
>>> viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

CooksDistanceVisualizer

Bases: FerrumVisualizer

Cook's distance diagnostic for a regression estimator.

Surfaces max_studentized (the largest absolute studentized residual) as a quick proxy for influential observations; the leverage-aware Cook's D itself is materialized by ModelSource.predictions().cooks_distance for linear estimators and is rendered by mark_residuals(cook_threshold=...). This visualizer plots the residuals chart with the leverage panel enabled.

Parameters:

Name Type Description Default
model Any

Fitted regression estimator (must expose coef_ for the leverage-aware Cook's distance).

required
threshold float or 'auto'

Cook's-distance threshold for highlighting outliers on the residuals-vs-leverage panel. Forwarded to _residuals_chart_from_source(cook_threshold=...), which injects _cook_outlier_x / _cook_outlier_y columns (keyed on leverage and the studentized residual) and the leverage panel renders them as a red-filled overlay layer. "auto" uses the conventional 4 / n rule (Hair et al.). Kept as threshold= (not cook_threshold=, the builder's own spelling) for back-compat -- an adjudicated shape drift, not unified (batch G decision doc, G5).

None
kind ('studentized', 'raw', 'scaled')

Residual variant underlying the leverage panel's y axis.

"studentized"
panels "auto", None, "single", or list of str

Panel selection, with residuals_chart(panels=...)'s vocabulary. The default renders just the residuals_vs_leverage panel; "auto" renders the canonical 4-panel grid; an explicit list renders those panels. None and "single" render the single residuals-vs-fitted panel, which has no leverage view.

("residuals_vs_leverage",)
annotate_metrics bool

Overlay a top-right corner annotation showing R^2/RMSE/MAE on the residuals-vs-fitted panel, when present.

True
subtitle str or None

Optional subtitle rendered beneath the active chart title.

None
mark dict

Per-layer mark overrides. See cooks_distance_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int
None
theme Theme
None

Examples:

>>> import ferrum as fm
>>> viz = fm.CooksDistanceVisualizer(linear_model).fit(X, y)
>>> viz._metrics["max_studentized"]
3.42

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

DiscriminationThresholdVisualizer

Bases: FerrumVisualizer

Sweep a decision threshold for a binary classifier and plot four metric curves.

Evaluates precision, recall, f1, and queue_rate (or a caller-supplied subset) at n_thresholds evenly-spaced probability thresholds between 0 and 1. After fit, the F1-maximising threshold and its F1 score are available via _metrics.

Parameters:

Name Type Description Default
model Any

Fitted binary sklearn estimator that exposes predict_proba.

required
n_thresholds int

Number of probability thresholds to evaluate across [0, 1].

50
metrics tuple of str

Which per-threshold metrics to include as curves in the chart. Passed through to the underlying ModelSource.discrimination_threshold call and to mark_discrimination_threshold.

("precision", "recall", "f1", "queue_rate")
cv Any

Cross-validation strategy forwarded to ModelSource.discrimination_threshold. None uses the model as-is (no CV averaging).

None
threshold_line bool

When True, overlays a vertical rule at the F1-maximising threshold (matches the figure-level discrimination_threshold_chart(threshold_line=True)).

False
optimum_label bool

Overlay a text label naming the F1-maximising threshold. Same "f1"-in-metrics= requirement as threshold_line (#189): an explicit optimum_label=True/threshold_line=True with no "f1" in metrics= raises ValueError; leaving the parameter unset keeps the pre-#189 silent omission.

True
subtitle str or None

Optional subtitle rendered beneath the active chart title.

None
compare dict of str -> estimator or None

Additional estimators to compare against model. Routes through _resolve_source (the same path discrimination_threshold_chart uses) at fit time, so model is treated as the base curve (label "base"). _metrics["best_threshold"]/["best_f1"] and .score() always describe the base model, never a compared rival's threshold sweep -- compare= always has one distinguished base model (unlike CalibrationVisualizer's symmetric *models), so the headline metric is restricted to its rows. show() returns a ConcatChart of one panel per model (small multiples, shared scales), each titled with its model name; the "base" panel's optimum_label therefore annotates the same threshold/F1 pair _metrics and __repr__ report. Changed 2026-09-13 (#213): before, this visualizer rendered every model's sweep stacked into one panel with a single pooled optimum, which is precisely the number its own repr contradicted.

None
mark dict

Per-layer mark overrides. See discrimination_threshold_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to ModelSource for any randomness in CV splits.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> viz = fm.DiscriminationThresholdVisualizer(model).fit(X, y)
>>> viz.show()                   # returns the four-curve Chart
>>> viz._metrics["best_threshold"], viz._metrics["best_f1"]

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ElbowVisualizer

Bases: FerrumVisualizer

Elbow / score sweep over a range of k for a clusterer class.

Unlike other ferrum visualizers, ElbowVisualizer takes a model class (e.g. KMeans) — not a fitted instance — and constructs and fits one model per k value when fit builds its source, the per-k score frame. No ModelSource is built; per-k models are transient and discarded after their score is recorded. Renders a score-vs-k line chart.

Records best_k — the integer k whose score is optimal for the selected metric — as the headline metric. For "distortion" the optimal score is the minimum; for "silhouette" and "calinski_harabasz" it is the maximum (higher is better).

Parameters:

Name Type Description Default
model_class type

Uninstantiated clustering class (e.g. sklearn.cluster.KMeans). Must accept n_clusters, random_state, and n_init keyword arguments and expose .inertia_ after fitting (for the "distortion" metric) or .labels_ (for "silhouette" / "calinski_harabasz").

required
ks sequence of int

The candidate k values to sweep (e.g. range(2, 11)). Note that "silhouette" and "calinski_harabasz" are undefined at k == 1 — such entries are silently skipped from the score sweep.

required
metric ('distortion', 'silhouette', 'calinski_harabasz')

Score to optimize. "distortion" (sum of squared distances to the nearest centroid, i.e. .inertia_) is minimized; "silhouette" (mean Rousseeuw silhouette coefficient) and "calinski_harabasz" (Calinski–Harabasz / Variance Ratio Criterion) are maximized. Any other value raises ValueError.

"distortion"
random_state int

Integer seed passed as random_state to every per-k model instantiation. When None, seed 0 is used.

None
mark dict

Per-layer mark overrides. See elbow_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.cluster import KMeans
>>> viz = fm.ElbowVisualizer(KMeans, ks=range(2, 9)).fit(X)
>>> viz.show()
>>> viz._metrics["best_k"]

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

FeatureImportancesVisualizer

Bases: FerrumVisualizer

Visualize feature importances from a fitted sklearn estimator.

Wraps importance_chart in the sklearn-protocol visualizer interface. method="builtin" reads feature_importances_ or coef_ directly from the estimator (std is 0 in this case). method="permutation" runs sklearn.inspection.permutation_importance using the supplied random_state seed. The headline metric recorded in _metrics is top_feature_importance — the importance of the highest-ranked feature after sorting.

Parameters:

Name Type Description Default
model Any

Fitted sklearn-compatible estimator. Must expose feature_importances_ or coef_ (method="builtin") or support predict / predict_proba (method="permutation").

required
method ('builtin', 'permutation')

Strategy for extracting importances. "builtin" reads the estimator attribute directly (zero standard deviation). "permutation" shuffles each feature and measures the drop in score.

"builtin"
top_k int or None

Maximum number of features to display, ranked by importance. Pass None to show all features.

20
orient ('horizontal', 'vertical')

Bar orientation in the rendered chart.

"horizontal"
error_bars bool

Whether to draw ±1 std error bars. Has no visual effect when method="builtin" because std is always 0 in that case.

True
show_values bool

Overlay the formatted importance value at the end of each bar.

True
subtitle str or None

Optional subtitle rendered beneath the "Feature importance" title.

None
mark dict

Per-layer mark overrides. See importance_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int or None

RNG seed forwarded to permutation_importance. Ignored when method="builtin".

None
theme Theme or None

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.ensemble import RandomForestClassifier
>>> model = RandomForestClassifier(n_estimators=50, random_state=0).fit(X_train, y_train)
>>> viz = fm.FeatureImportancesVisualizer(model).fit(X_train, y_train)
>>> viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

FerrumVisualizer

Base class for sklearn-protocol model-diagnostic visualizers.

Concrete visualizers override the _build_source, _materialize and _build_chart hooks, never fit. fit runs all three in the class's voice (:func:ferrum._entry.voiced_as) and stamps the class name on the chart (:func:ferrum._entry.stamp_entry), so every warning and refusal about the chart names the class. A malformed mark= refuses at fit before any hook runs, so before anything is computed from the model.

Parameters:

Name Type Description Default
model Any

Fitted estimator that will be wrapped in a ModelSource at fit time. Pass None for no-model visualizers (rank / parallel coordinates / class balance).

None
random_state int

Seed forwarded to the underlying ModelSource. Ignored when the wrapped derived-data compute is deterministic.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> viz = fm.ROCVisualizer(model, random_state=0).fit(X, y)
>>> viz.show()                # returns a Chart
>>> viz._metrics              # headline metric(s)

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

InterclusterDistanceVisualizer

Bases: FerrumVisualizer

Cluster-center 2D embedding with cluster-size bubble overlay.

Projects cluster centers into 2D via the algorithm selected by method and renders a bubble chart where each bubble represents one cluster; bubble area encodes the cluster's sample count. Built on ferrum.intercluster_distance_chart.

Takes a fitted clustering estimator that exposes cluster_centers_ (e.g. KMeans): the centers are what the chart embeds, so a clusterer without them (e.g. AgglomerativeClustering, which exposes only n_clusters) raises AttributeError at fit.

Records max_intercluster_dist — the largest Euclidean distance from any cluster center to the centroid of all centers in the 2D embedding — as a rough measure of how spread-out the clusters are.

Parameters:

Name Type Description Default
model Any

Fitted clustering estimator (e.g. KMeans instance) that exposes cluster_centers_.

required
method str

Dimensionality-reduction algorithm forwarded to ModelSource.intercluster_distance. Typical values include "mds" and "tsne".

"mds"
k int

Number of clusters to embed. None (default) infers it from the wrapped model's n_clusters or cluster_centers_ attribute; an explicit value overrides that inference.

None
random_state int

Seed forwarded to the underlying ModelSource. Controls reproducibility for stochastic layout algorithms.

None
mark dict

Per-layer mark overrides. See intercluster_distance_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.cluster import KMeans
>>> model = KMeans(n_clusters=5, random_state=0).fit(X)
>>> viz = fm.InterclusterDistanceVisualizer(model).fit(X)
>>> viz.show()
>>> viz._metrics["max_intercluster_dist"]

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

LearningCurveVisualizer

Bases: FerrumVisualizer

Visualize training and cross-validation scores as training size grows.

Wraps learning_curve_chart in the sklearn visualizer protocol. Call fit(X, y) to run cross-validation across the requested training-size grid; call show() to retrieve the rendered Chart. The headline metric final_test_score (mean test score at the largest training size) is recorded in _metrics and shown in repr.

Parameters:

Name Type Description Default
model Any

Unfitted or fitted sklearn-compatible estimator.

required
cv int

Number of cross-validation folds passed to sklearn.model_selection.learning_curve.

5
scoring str or callable

Sklearn scoring string or callable. Defaults to the estimator's own score method when None.

None
train_sizes array - like

Relative or absolute training-set sizes to evaluate. Passed directly to learning_curve; defaults to np.linspace(0.1, 1.0, 5) when None.

None
ci_style ('band', 'errorbar')

How to render the cross-validation confidence interval. "band" draws a shaded ribbon; "errorbar" draws a vertical rule per point.

"band"
subtitle str or None

Optional subtitle rendered beneath the "Learning curve" title.

None
mark dict

Per-layer mark overrides. See learning_curve_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to ModelSource and from there to sklearn's learning_curve, which shuffles the training data with it before splitting. None seeds that shuffle with 0, so the default is reproducible too. It does not seed the wrapped estimator.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.linear_model import LogisticRegression
>>> viz = fm.LearningCurveVisualizer(
...     LogisticRegression(), cv=5, scoring="accuracy"
... ).fit(X_train, y_train)
>>> chart = viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ManifoldVisualizer

Bases: FerrumVisualizer

Low-dimensional manifold-embedding scatter (UMAP / t-SNE / PCA).

Projects the input data to two dimensions via the method selected by method and renders a point chart with axes dim_0 / dim_1 colored by cluster label. The embedding is computed by ModelSource.embeddings and cached so _build_chart does not recompute it.

Takes a fitted clustering estimator whose labels_ attribute is used to color points. Pass model=None only if you override _build_source in a subclass and supply labels_ by other means.

Records n_samples — the number of rows in the embedding — as the headline metric.

Parameters:

Name Type Description Default
model Any

Fitted clustering estimator (e.g. KMeans instance) that exposes labels_. Defaults to None (for subclass overrides).

None
method str

Embedding algorithm forwarded to ModelSource.embeddings. Typical values are "umap", "tsne", and "pca".

"umap"
random_state int

Seed forwarded to the underlying ModelSource. Controls reproducibility for stochastic embeddings such as UMAP and t-SNE.

None
mark dict

Per-layer mark overrides. See manifold_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.cluster import KMeans
>>> model = KMeans(n_clusters=4, random_state=0).fit(X)
>>> viz = fm.ManifoldVisualizer(model, method="umap").fit(X)
>>> viz.show()
>>> viz._metrics["n_samples"]

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

PCAVarianceVisualizer

Bases: FerrumVisualizer

PCA scree plot showing explained variance per principal component.

Retrieves per-component explained-variance ratios via ModelSource.pca_variance and renders a bar chart of explained-variance ratio vs. component index, optionally limited to the first n_components components. Built on ferrum.pca_scree_chart.

Takes a fitted decomposition estimator (e.g. sklearn.decomposition.PCA instance) that exposes explained_variance_ratio_.

Records first_component_var — the fraction of total variance captured by the first principal component — as the headline metric.

Parameters:

Name Type Description Default
model Any

Fitted decomposition estimator (e.g. PCA instance) that exposes explained_variance_ratio_.

required
n_components int

Number of components to display in the scree plot. When None, all components present in the model are shown.

None
cumulative_line bool

Overlay a cumulative-explained-variance line.

True
threshold float

Horizontal reference rule at this target cumulative-variance fraction. None omits the rule.

0.95
subtitle str or None

Optional subtitle rendered beneath the "PCA Explained Variance" title.

None
mark dict

Per-layer mark overrides. See pca_scree_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to the underlying ModelSource. Ignored when the PCA variance computation is deterministic.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.decomposition import PCA
>>> model = PCA(n_components=10).fit(X)
>>> viz = fm.PCAVarianceVisualizer(model, n_components=5).fit(X)
>>> viz.show()
>>> viz._metrics["first_component_var"]

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

PRVisualizer

Bases: FerrumVisualizer

Precision-recall curve(s) for binary or multiclass classifiers.

Wraps ModelSource.pr_curve(). Records ap_mean (average precision averaged across classes) as the headline metric.

Parameters:

Name Type Description Default
model Any

Fitted classifier exposing predict_proba or decision_function.

required
per_class bool

Render one curve per class. When False, only the averaged curve is rendered.

True
average ('macro', 'micro', 'weighted')

Averaging method used when per_class=False.

"macro"
annotate_ap bool

Overlay one text label per curve showing the AP value.

True
iso_lines bool

Overlay F1-score iso-contour lines.

False
subtitle str or None

Optional subtitle rendered beneath the active chart title.

None
compare dict of str -> estimator or None

Additional estimators to overlay against model. Routes through _resolve_source (the same path pr_chart uses) at fit time, so model is treated as the base curve (label "base"). _metrics["ap_mean"] and .score() always describe the base model, never a compared rival -- compare= always has one distinguished base model (unlike CalibrationVisualizer's symmetric *models), so the headline metric is restricted to its rows.

None
mark dict

Per-layer mark overrides. See pr_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int
None
theme Theme
None

Examples:

>>> import ferrum as fm
>>> viz = fm.PRVisualizer(clf).fit(X, y)
>>> viz._metrics["ap_mean"]
0.88

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ParallelCoordinatesVisualizer

Bases: FerrumVisualizer

Visualize multivariate samples as a parallel-coordinates chart.

A no-model visualizer (model=None) that draws one polyline per sample across a set of parallel vertical axes (one per feature). Its source is the samples themselves, so no ModelSource is built.

Records n_samples and n_features in _metrics so the repr surfaces the chart's shape.

Parameters:

Name Type Description Default
features list of str

Subset of column names to include as axes. When None, all non-hue columns are used.

None
hue str

Column of the X passed to fit used to color-encode each sample line; it is not drawn as an axis. None produces a single-color chart unless fit(X, y) is called with y — in that case y is attached as the hue column automatically.

None
rescale ('minmax', 'zscore', None)

Per-axis normalization applied before plotting.

  • "minmax" — rescale each axis to [0, 1].
  • "zscore" — standardize each axis to zero mean, unit variance.
  • None — no rescaling; raw values are plotted.
"minmax"
alpha float

Opacity of each sample line (0 = fully transparent, 1 = opaque).

0.5
mark dict

Per-layer mark overrides. See parallel_coordinates_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Accepted for API symmetry with model-backed visualizers but intentionally never consumed — this visualizer bypasses ModelSource entirely. Documented as a permanent no-op so callers that script over visualizers don't have to special-case which ones accept the kwarg.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> import polars as pl
>>> df = pl.DataFrame({
...     "sepal_length": [5.1, 4.9, 7.0, 6.4, 6.3, 5.8],
...     "sepal_width": [3.5, 3.0, 3.2, 3.2, 3.3, 2.7],
...     "petal_length": [1.4, 1.4, 4.7, 4.5, 6.0, 5.1],
...     "species": ["setosa", "setosa", "versicolor", "versicolor",
...                 "virginica", "virginica"],
... })
>>> viz = fm.ParallelCoordinatesVisualizer(hue="species", rescale="minmax")
>>> viz.fit(df)
ParallelCoordinatesVisualizer(n_samples=6.0000, n_features=3.0000)
>>> viz.show()
Chart(mark='line', encoding=[])

Without hue, the y passed to fit colors the lines:

>>> viz = fm.ParallelCoordinatesVisualizer().fit(
...     df.drop("species"), df["species"]
... )
>>> viz.show()
Chart(mark='line', encoding=[])

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

PredictionErrorVisualizer

Bases: FerrumVisualizer

Actual-vs-predicted scatter for a regression estimator.

Wraps ModelSource.predictions(). Records rmse as the headline metric; the chart shows y_true on x and y_pred on y with an optional identity line and CI / reference band overlays.

Parameters:

Name Type Description Default
model Any

Fitted regression estimator.

required
reference_line bool

Overlay the dashed y = x diagonal.

True
ci float

Confidence level in (0, 1). When set, overlays a ribbon spanning the central ci fraction of residuals around the reference line. Raises ValueError if not in (0, 1).

None
reference_band bool

When True (and ci is None), overlays a ±1 RMSE ribbon around the reference line.

False
mark dict

Per-layer mark overrides. See prediction_error_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int
None
theme Theme
None

Examples:

>>> import ferrum as fm
>>> viz = fm.PredictionErrorVisualizer(model, ci=0.95).fit(X, y)
>>> viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ROCVisualizer

Bases: FerrumVisualizer

ROC curve(s) for binary or multiclass classifiers.

Wraps ModelSource.roc_curve(). per_class=True (default) draws one curve per class; pass per_class=False to plot a single averaged curve. Records auc_mean as the headline metric.

Parameters:

Name Type Description Default
model Any

Fitted classifier (must implement predict_proba or decision_function).

required
micro bool

Compute the micro-averaged AUC. Kept as a boolean flag (not the builder's own average= spelling) for back-compat -- an adjudicated shape drift, not unified (batch G decision doc, G5).

True
macro bool

Compute the macro-averaged AUC. Takes precedence over micro when choosing which averaged curve to plot at per_class=False.

True
per_class bool

Render one curve per class. When False, only the averaged curve is rendered.

True
annotate_auc bool

Overlay one text label per curve showing the AUC value.

True
subtitle str or None

Optional subtitle rendered beneath the active chart title.

None
compare dict of str -> estimator or None

Additional estimators to overlay against model. Routes through _resolve_source (the same path roc_chart uses) at fit time, so model is treated as the base curve (label "base"). _metrics["auc_mean"] and .score() always describe the base model, never a compared rival -- compare= always has one distinguished base model (unlike CalibrationVisualizer's symmetric *models), so the headline metric is restricted to its rows.

None
mark dict

Per-layer mark overrides. See roc_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int
None
theme Theme
None

Examples:

>>> import ferrum as fm
>>> viz = fm.ROCVisualizer(clf).fit(X, y)
>>> viz._metrics["auc_mean"]
0.92

has_score property

has_score: bool

True iff score returns a real AUC rather than the fallback.

ROC scores from class probabilities, so unlike the base class it is scoreable when the model exposes predict_proba even with no .score method. Mirrors the exact branch taken in score, so the two can never drift.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

Rank1DVisualizer

Bases: FerrumVisualizer

Rank features by a univariate statistic and display as a bar chart.

A no-model visualizer (model=None) that computes a scalar score for each feature column and renders them as a ranked horizontal or vertical bar chart. Its source is the score frame itself, so no ModelSource is built.

Records top_feature_score (the score of the highest-ranked feature) in _metrics.

Parameters:

Name Type Description Default
algorithm ('shapiro', 'variance', 'covariance')

Scoring algorithm.

  • "shapiro" — Shapiro-Wilk W statistic (normality score).
  • "variance" — variance of each feature column.
  • "covariance" — absolute covariance with the target y. Requires y to be passed at fit time; raises ValueError when y is None.
"shapiro"
orient ('horizontal', 'vertical')

Bar orientation of the resulting chart.

"horizontal"
top_k int

If given, display only the top top_k features. None shows all features.

None
color_field str

Column of the computed ranking forwarded to the chart's color encoding: one of "feature", "score" or "rank". The fitted data's own columns are gone by the time the bars are encoded, so naming one fails with ValueError: unknown column when the chart renders. None produces a single-color chart.

None
mark dict

Per-layer mark overrides. See rank1d_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Accepted for API symmetry with model-backed visualizers but intentionally never consumed — this visualizer bypasses ModelSource entirely. Documented as a permanent no-op so callers that script over visualizers don't have to special-case which ones accept the kwarg.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Raises:

Type Description
ValueError

When algorithm="covariance" and y is None at fit time.

Examples:

>>> import ferrum as fm
>>> import polars as pl
>>> df = pl.DataFrame({
...     "alcohol": [13.2, 12.4, 14.1, 12.0, 13.7, 12.9],
...     "ash": [2.4, 2.1, 2.6, 2.0, 2.5, 2.2],
...     "hue": [1.0, 0.9, 1.1, 0.8, 1.05, 0.95],
...     "target": [0, 1, 0, 1, 0, 1],
... })
>>> X, y = df.drop("target"), df["target"]
>>> viz = fm.Rank1DVisualizer(algorithm="variance").fit(X)
>>> viz.show()
Chart(mark='bar', encoding=['x', 'y'])

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

Rank2DVisualizer

Bases: FerrumVisualizer

Rank feature pairs by pairwise correlation and display as a heatmap.

A no-model visualizer (model=None) that computes an N×N correlation matrix and renders it as an annotated heatmap. Its source is the correlation frame itself, so no ModelSource is built.

The "kendall" algorithm routes pairwise computation through ferrum._core.kendall_tau_b (Rust) for performance.

Records max_abs_corr (the largest absolute off-diagonal correlation value) in _metrics — useful for detecting multicollinearity at a glance.

Parameters:

Name Type Description Default
algorithm ('pearson', 'spearman', 'kendall', 'covariance')

Pairwise association measure.

  • "pearson" — Pearson linear correlation coefficient.
  • "spearman" — Spearman rank correlation.
  • "kendall" — Kendall tau-b, computed via ferrum._core.kendall_tau_b for performance.
  • "covariance" — raw covariance (not normalized to [-1, 1]).
"pearson"
annot bool

Whether to annotate each heatmap cell with its numeric value.

True
mark dict

Per-layer mark overrides. See rank2d_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Accepted for API symmetry with model-backed visualizers but intentionally never consumed — this visualizer bypasses ModelSource entirely. Documented as a permanent no-op so callers that script over visualizers don't have to special-case which ones accept the kwarg.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> import polars as pl
>>> df = pl.DataFrame({
...     "alcohol": [13.2, 12.4, 14.1, 12.0, 13.7, 12.9],
...     "ash": [2.4, 2.1, 2.6, 2.0, 2.5, 2.2],
...     "hue": [1.0, 0.9, 1.1, 0.8, 1.05, 0.95],
...     "target": [0, 1, 0, 1, 0, 1],
... })
>>> X = df.drop("target")
>>> viz = fm.Rank2DVisualizer(algorithm="spearman").fit(X)
>>> viz.show()
Chart(mark='rect', encoding=[])

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ResidualsVisualizer

Bases: FerrumVisualizer

Residuals-vs-fitted diagnostic for a regression estimator.

Wraps ModelSource.predictions(). Records rmse and mae as headline metrics; the chart shows y_pred on x and the chosen residual variant on y with a horizontal reference line at zero.

Parameters:

Name Type Description Default
model Any

Fitted regression estimator (must implement predict).

required
kind ('studentized', 'raw', 'scaled')

Which residual variant to plot. "studentized" uses the leverage-aware hat-matrix form when model exposes coef_; otherwise falls back to internally-studentized (residual / std).

"studentized"
cook_threshold float, "auto", or None

Cook's-distance threshold for outlier highlighting on the residuals-vs-fitted (and, in a multi-panel layout, residuals-vs-leverage) view. See residuals_chart.

None
panels "auto", None, "single", or list of str

Panel selection, matching residuals_chart(panels=...). "auto" renders the canonical 4-panel diagnostic grid (residuals-vs-fitted, QQ, scale-location, residuals-vs-leverage); None or "single" (the default) renders just the residuals-vs-fitted panel. The "auto" expansion is shared with residuals_chart via _resolve_residuals_panels so ResidualsVisualizer(panels="auto") renders the same 4-panel grid.

None
annotate_metrics bool

Overlay a top-right corner annotation showing R^2/RMSE/MAE.

True
subtitle str or None

Optional subtitle rendered beneath the active chart title.

None
mark dict

Per-layer mark overrides. See residuals_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Forwarded to the underlying ModelSource.

None
theme Theme
None

Examples:

>>> import ferrum as fm
>>> viz = fm.ResidualsVisualizer(model).fit(X, y)
>>> viz._metrics["rmse"]
1.234
>>> viz.show()

Canonical 4-panel diagnostic grid, matching residuals_chart(panels="auto"):

>>> fm.ResidualsVisualizer(model, panels="auto").fit(X, y).show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

SHAPBarVisualizer

Bases: _SHAPBaseMixin, FerrumVisualizer

Mean-absolute SHAP per feature as a horizontal bar chart.

Parameters mirror SHAPBeeswarmVisualizer (minus zero_line, which has no meaning for a bar chart); see that class for the full parameter list.

Examples:

>>> import ferrum as fm
>>> from sklearn.ensemble import GradientBoostingClassifier
>>> model = GradientBoostingClassifier().fit(X_train, y_train)
>>> viz = fm.SHAPBarVisualizer(model).fit(X_test, y_test).show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

SHAPBeeswarmVisualizer

Bases: _SHAPBaseMixin, FerrumVisualizer

Per-sample SHAP scatter colored by z-scored feature value.

Parameters:

Name Type Description Default
model Any

Fitted sklearn-compatible estimator supported by the shap library (e.g. tree ensembles, linear models).

required
max_display int

Maximum number of features ranked by order.

20
order ('abs_mean', 'mean', 'max', 'none')

Feature ranking criterion (shared vocabulary with Chart.mark_shap_beeswarm(order=)). "abs_mean" ranks by descending mean absolute SHAP; "max" by descending max absolute SHAP (surfaces high-impact-outlier features); "mean" by descending signed mean SHAP; "none" keeps the first max_display features in row-encounter order, unranked.

"abs_mean"
background Any

Background dataset passed to the SHAP explainer for kernel- SHAP models. Tree SHAP ignores this.

None
per_class bool

Facet by class on multi-class classifiers.

False
zero_line bool

Overlay a dashed vertical rule at shap_value == 0.

True
mark dict

Per-layer mark overrides. See shap_beeswarm_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state forwarded to ``FerrumVisualizer``.
None
theme forwarded to ``FerrumVisualizer``.
None

Examples:

>>> import ferrum as fm
>>> viz = fm.SHAPBeeswarmVisualizer(model, max_display=15).fit(X, y)
>>> viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

SHAPVisualizer

Bases: FerrumVisualizer

Visualize SHAP values from a fitted sklearn estimator.

Wraps the shap_chart family in the sklearn-protocol visualizer interface. Requires the shap library (pip install ferrum[shap]). Three chart kinds are supported: "beeswarm" shows per-sample SHAP scatter colored by feature value; "bar" shows mean absolute SHAP aggregated per feature; "waterfall" shows the cumulative contribution for a single sample selected by sample_idx. The headline metric recorded in _metrics is top_abs_shap — the maximum mean absolute SHAP value across all features.

Parameters:

Name Type Description Default
model Any

Fitted sklearn-compatible estimator supported by the shap library (e.g. tree ensembles, linear models with a shap.Explainer).

required
kind ('beeswarm', 'bar', 'waterfall')

Chart style to render. "waterfall" requires sample_idx to be set; a ValueError is raised at .show() time if it is omitted.

"beeswarm"
max_display int

Maximum number of features to include in the chart, ranked by mean absolute SHAP value.

20
sample_idx int or None

Row index of the sample to explain. Required when kind="waterfall"; ignored for "beeswarm" and "bar".

None
order ('abs_mean', 'mean', 'max', 'none')

Feature ordering strategy applied to all three kind values (shared vocabulary with Chart.mark_shap_beeswarm(order=)). "abs_mean" ranks features by descending mean(|shap_value|) across the dataset; "max" ranks by descending max(|shap_value|) (surfaces high-impact-outlier features; also the kind="bar" x-value aggregation for this one setting); "mean" ranks by descending signed mean(shap_value); "none" keeps the first max_display features in row-encounter order, unranked. For kind="bar" with any other order, the bar's x-value is mean(|shap_value|); for kind="waterfall" order selects which features are shown for the single sample and the order they appear in.

"abs_mean"
background Any or None

Background dataset passed to the SHAP explainer for models that require a reference distribution (e.g. kernel SHAP). Pass None to use the explainer's default.

None
per_class bool

Facet by class on multi-class classifiers. Applies to all three kind values (matches SHAPBeeswarmVisualizer / SHAPBarVisualizer / SHAPWaterfallVisualizer).

False
zero_line bool

Overlay a dashed vertical rule at shap_value == 0. Only meaningful for kind="beeswarm" -- the "bar"/"waterfall" builders have no zero_line= parameter to forward it to, same as their dedicated-visualizer siblings.

True
random_state int or None

RNG seed forwarded to the underlying ModelSource. Ignored when SHAP computation is deterministic.

None
mark dict

Per-layer mark overrides. See the shap_*_chart family.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
theme Theme or None

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.ensemble import GradientBoostingClassifier
>>> model = GradientBoostingClassifier(random_state=0).fit(X_train, y_train)
>>> viz = fm.SHAPVisualizer(model, kind="beeswarm").fit(X_train, y_train)
>>> viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

SHAPWaterfallVisualizer

Bases: _SHAPBaseMixin, FerrumVisualizer

Cumulative per-feature SHAP contributions for one sample.

Parameters:

Name Type Description Default
model Any

Fitted sklearn-compatible estimator supported by the shap library.

required
sample_idx int

Row index (0-based) of the sample to explain. Required.

required
max_display int

Maximum number of features to include in the waterfall, ranked by order.

20
order ('abs_mean', 'mean', 'max', 'none')

Feature ranking criterion (shared vocabulary with Chart.mark_shap_beeswarm(order=); drives both the top-max_display selection and the bar order).

"abs_mean"
background Any

Background dataset passed to the SHAP explainer.

None
per_class bool

Facet by class on multi-class classifiers.

False
mark dict

Per-layer mark overrides. See shap_waterfall_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state forwarded to ``FerrumVisualizer``.
None
theme forwarded to ``FerrumVisualizer``.
None

Raises:

Type Description
ValueError

If sample_idx is missing at __init__ time.

Examples:

>>> import ferrum as fm
>>> viz = fm.SHAPWaterfallVisualizer(model, sample_idx=3).fit(X, y)
>>> viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

SilhouetteVisualizer

Bases: FerrumVisualizer

Rousseeuw silhouette plot for a fitted clusterer.

Computes per-sample silhouette coefficients via ModelSource.silhouette and renders a horizontal bar chart sorted by cluster, one bar per sample. Records mean_silhouette — the grand mean silhouette coefficient averaged across all samples — as the headline metric.

Takes a fitted estimator (not a class); for the k-sweep variant use ElbowVisualizer.

Parameters:

Name Type Description Default
model Any

Fitted clustering estimator (e.g. sklearn.cluster.KMeans instance) that exposes labels_ (and optionally cluster_centers_).

required
k int

Restrict the silhouette computation to this many clusters. None (default) uses every cluster the fitted model produced.

None
subtitle str or None

Optional subtitle rendered beneath the "Silhouette Plot" title. Leaves the chart title-less when None (the default), matching silhouette_chart.

None
mark dict

Per-layer mark overrides. See silhouette_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to the underlying ModelSource. Ignored when the silhouette computation is deterministic.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.cluster import KMeans
>>> model = KMeans(n_clusters=3, random_state=0).fit(X)
>>> viz = fm.SilhouetteVisualizer(model).fit(X)
>>> viz.show()
>>> viz._metrics["mean_silhouette"]

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.

ValidationCurveVisualizer

Bases: FerrumVisualizer

Visualize train/test scores as a single hyperparameter is swept.

Wraps validation_curve_chart in the sklearn visualizer protocol. For each value in values, sklearn.model_selection.validation_curve runs cv folds and records the mean score. The value that maximises the mean test score is stored as best_param in _metrics; the corresponding mean score is stored as best_test_score.

Parameters:

Name Type Description Default
model Any

Unfitted or fitted sklearn-compatible estimator.

required
param str

Name of the hyperparameter to sweep, e.g. "C" for LogisticRegression or "max_depth" for tree estimators. Must be a valid __init__ parameter of model.

required
values array - like

Grid of candidate values for param. Passed directly to sklearn.model_selection.validation_curve as param_range.

required
cv int

Number of cross-validation folds.

5
scoring str or callable

Sklearn scoring string or callable. Defaults to the estimator's own score method when None.

None
log_scale bool or 'auto'

Whether to render the x-axis (param values) on a log scale. "auto" enables log scale when the ratio between the largest and smallest value exceeds 100.

"auto"
ci_style ('band', 'errorbar')

How to render the cross-validation confidence interval. "band" draws a shaded ribbon; "errorbar" draws a vertical rule per point.

"band"
subtitle str or None

Optional subtitle rendered beneath the "Validation curve" title.

None
mark dict

Per-layer mark overrides. See validation_curve_chart.

None
encode dict

Additional encoding kwargs merged via Chart.encode(**encode).

None
properties dict

Chart properties merged via Chart.properties(**properties).

None
layers list

Extra layers appended via Chart.layer(*layers).

None
random_state int

Seed forwarded to ModelSource. The folds come from sklearn's unshuffled K-fold split for the integer cv, which is deterministic without a seed, so this value does not change the result. It does not seed the wrapped estimator.

None
theme Theme

Per-chart theme override. Falls back to the global default when None.

None

Examples:

>>> import ferrum as fm
>>> from sklearn.svm import SVC
>>> import numpy as np
>>> viz = fm.ValidationCurveVisualizer(
...     SVC(), param="C", values=np.logspace(-3, 3, 7), cv=5
... ).fit(X_train, y_train)
>>> chart = viz.show()

has_score property

has_score: bool

Whether score returns a real test-set metric.

Derived from behavior rather than hand-maintained: True exactly when the wrapped model exposes a .score method (so the inherited score delegates to it), False for genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow) whose score returns the 0.0 fallback. Mirrors the guard in score, so the two can never drift.

Subclasses that override score with a different scoreability condition (e.g. ROCVisualizer, which scores from predict_proba) or that wrap multiple models with no single metric (e.g. a multi-model overlay) override this property to keep the two in lockstep — has_score is True for an instance iff its score returns a real metric rather than the 0.0 fallback.

fit

fit(X: Any, y: Any = None) -> 'FerrumVisualizer'

Materialize derived data from X / y and build the chart.

Builds the source (_build_source), calls _materialize to populate _metrics, then _build_chart to assemble the ferrum Chart, all speaking as the class. A malformed mark= refuses first, before the source is built. Returns self for method chaining.

Parameters:

Name Type Description Default
X array - like

Feature matrix. Accepted types match ModelSource.__init__.

required
y array - like

Target vector. Required by most classification / regression diagnostics; optional for unsupervised variants.

None

Returns:

Type Description
FerrumVisualizer

self — the fitted visualizer instance.

score

score(X: Any, y: Any) -> float

Delegate to self.model.score(X, y) when the model supports it.

For model-backed visualizers (the common case) this returns the wrapped estimator's own .score metric — r2_score for a regressor, accuracy for a classifier, etc. Genuinely no-model visualizers (rank / parallel-coordinates / class-balance / elbow, all constructed with model=None) fall through to the 0.0 fallback so they satisfy the sklearn visualizer protocol without raising.

Subclasses whose score is not the estimator's own .score (e.g. ROCVisualizer returns roc_auc_score) override this.

Parameters:

Name Type Description Default
X array - like

Feature matrix, same type accepted by fit.

required
y array - like

True target values.

required

Returns:

Type Description
float

self.model.score(X, y) when the wrapped model exposes a .score method; 0.0 otherwise.

show

show() -> Any

Return the ferrum Chart for this visualizer.

Must be called after fit; raises RuntimeError otherwise. The returned Chart can be rendered in a notebook (_repr_svg_), saved with .save(path), or composed with other charts via + / /.

Returns:

Type Description
Chart

The assembled diagnostic chart.

Raises:

Type Description
RuntimeError

If fit has not been called yet.