|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | +import pytest |
| 4 | + |
| 5 | +from explainerdashboard import ClassifierExplainer |
| 6 | +from explainerdashboard.explainer_plots import ( |
| 7 | + plotly_actual_vs_col, |
| 8 | + plotly_preds_vs_col, |
| 9 | + plotly_residuals_vs_col, |
| 10 | + plotly_shap_violin_plot, |
| 11 | +) |
| 12 | + |
| 13 | + |
| 14 | +class NoClassesModel: |
| 15 | + """Classifier-like model without classes_ attribute.""" |
| 16 | + |
| 17 | + def predict_proba(self, X): |
| 18 | + n = len(X) |
| 19 | + p = np.full(n, 0.6) |
| 20 | + return np.c_[1 - p, p] |
| 21 | + |
| 22 | + def predict(self, X): |
| 23 | + return (self.predict_proba(X)[:, 1] > 0.5).astype(int) |
| 24 | + |
| 25 | + |
| 26 | +@pytest.mark.parametrize( |
| 27 | + "plot_fn,args", |
| 28 | + [ |
| 29 | + ( |
| 30 | + plotly_shap_violin_plot, |
| 31 | + ( |
| 32 | + pd.Series(["a", 1, np.nan, "b"], name="mixed_cat", dtype=object), |
| 33 | + np.array([0.1, -0.2, 0.0, 0.3]), |
| 34 | + ), |
| 35 | + ), |
| 36 | + ( |
| 37 | + plotly_residuals_vs_col, |
| 38 | + ( |
| 39 | + np.array([1.0, 2.0, 3.0, 4.0]), |
| 40 | + np.array([1.1, 1.9, 2.8, 4.2]), |
| 41 | + pd.Series(["a", 1, np.nan, "b"], name="mixed_cat", dtype=object), |
| 42 | + ), |
| 43 | + ), |
| 44 | + ( |
| 45 | + plotly_actual_vs_col, |
| 46 | + ( |
| 47 | + np.array([1.0, 2.0, 3.0, 4.0]), |
| 48 | + np.array([1.1, 1.9, 2.8, 4.2]), |
| 49 | + pd.Series(["a", 1, np.nan, "b"], name="mixed_cat", dtype=object), |
| 50 | + ), |
| 51 | + ), |
| 52 | + ( |
| 53 | + plotly_preds_vs_col, |
| 54 | + ( |
| 55 | + np.array([1.0, 2.0, 3.0, 4.0]), |
| 56 | + np.array([1.1, 1.9, 2.8, 4.2]), |
| 57 | + pd.Series(["a", 1, np.nan, "b"], name="mixed_cat", dtype=object), |
| 58 | + ), |
| 59 | + ), |
| 60 | + ], |
| 61 | +) |
| 62 | +def test_plot_functions_do_not_crash_on_mixed_categorical_values(plot_fn, args): |
| 63 | + try: |
| 64 | + plot_fn(*args) |
| 65 | + except TypeError as exc: |
| 66 | + pytest.fail(f"Mixed categorical sorting should not crash: {exc}") |
| 67 | + |
| 68 | + |
| 69 | +def test_classifier_explainer_without_classes_handles_mixed_target_labels(): |
| 70 | + X = pd.DataFrame({"a": [1, 2, 3, 4], "b": [0, 1, 0, 1]}) |
| 71 | + y = pd.Series([0, "1", 0, "1"], dtype=object) |
| 72 | + |
| 73 | + try: |
| 74 | + explainer = ClassifierExplainer(NoClassesModel(), X, y, shap="kernel") |
| 75 | + except TypeError as exc: |
| 76 | + pytest.fail(f"Mixed target-label sorting should not crash: {exc}") |
| 77 | + |
| 78 | + assert len(explainer.labels) == 2 |
0 commit comments