File size: 3,594 Bytes
6b5ab1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import pytest

pytest.importorskip("reportlab")
pytest.importorskip("matplotlib")

from utils.report import build_report  # noqa: E402

STATS = [
    {"name": "age", "type": "Numeric", "missing": 0, "unique": 40, "min": 20, "max": 90, "mean": 55.2, "std": 12.1},
    {"name": "sex", "type": "Categorical", "missing": 2, "unique": 2, "top": [["F", 50], ["M", 48]]},
    {"name": "admitted", "type": "Date", "missing": 0, "unique": 90},
    {"name": "outcome", "type": "Categorical", "missing": 0, "unique": 2},
]


def _pdf(data, lang):
    out = build_report(data, lang=lang).getvalue()
    assert out.startswith(b"%PDF") and len(out) > 5000
    return out


@pytest.mark.parametrize("lang", ["es", "en", "fr", "xx"])
def test_classification_report(lang):
    _pdf({
        "dataset_name": "demo.csv", "target_column": "outcome", "n_rows": 100, "n_columns": 4,
        "excluded": ["record_id"], "imputation": {"sex": {"method": "constant", "constant": "U"}},
        "task_type": "binary", "best_model": "LightGBM", "train_time": 12.3, "used_gpu": False,
        "metrics": {"roc_auc": 0.81, "accuracy": 0.77},
        "plot_data": {"labels": ["no", "yes"], "confusion": [[40, 10], [13, 37]],
                      "roc": {"fpr": [0, 0.2, 1], "tpr": [0, 0.7, 1], "threshold": [None, 0.5, 0], "auc": 0.81,
                              "positive_label": "yes"}},
        "feature_importance": {"age": 0.1, "sex": -0.01},
        "leaderboard": [{"model": "LightGBM", "score_val": 0.81, "fit_time": 3.2}, {"model": "KNN", "score_val": None}],
        "stats": STATS,
    }, lang)


def test_regression_and_minimal_reports():
    _pdf({"task_type": "regression", "metrics": {"r2": 0.6, "rmse": 3.1},
          "plot_data": {"y_true": [1, 2, 3, 4], "y_pred": [1.2, 1.9, 3.3, 3.8],
                        "error_hist": {"counts": [1, 2, 1], "edges": [-0.3, -0.1, 0.1, 0.3]}, "n": 4},
          "stats": STATS}, "es")
    # Whatever is missing, a report is still produced
    build_report({}, lang="en")
    build_report({"metrics": {"rmse": float("nan")}, "stats": [{"name": None}], "leaderboard": "x"}, lang="en")


def test_shap_summary_from_array_features():
    import numpy as np
    import pandas as pd
    from utils import plots

    rng = np.random.default_rng(0)
    raw = pd.DataFrame({"age": rng.integers(20, 90, 80), "sex": rng.choice(["F", "M"], 80),
                        "ward": rng.choice(["a", "b", "c"], 80)})
    values = np.column_stack([(raw["age"] - 55) / 30, np.where(raw["sex"] == "M", 0.2, -0.2), rng.normal(0, 0.01, 80)])
    explanation = type("E", (), {"values": values, "feature_names": None, "data": None, "base_values": np.zeros(80)})
    predictor = type("P", (), {"problem_type": "binary", "class_labels": ["no", "yes"]})
    features = raw.assign(sex=(raw["sex"] == "M").astype(int), ward=raw["ward"].map({"a": 0, "b": 1, "c": 2})).to_numpy()
    s = plots.shap_summary_data(explanation, features, raw, predictor, "XGBoost")
    # Without names the columns are positional; with a DataFrame they keep their names
    s = plots.shap_summary_data(explanation, raw.assign(sex=0), raw, predictor, "XGBoost")
    names = [f["name"] for f in s["features"]]
    assert names[0] == "age" and s["features"][0]["direction"] > 0.9 and s["explained_class"] == "yes"
    sex = next(f for f in s["features"] if f["name"] == "sex")
    assert sex["levels"] == ["F", "M"] and sex["direction"] > 0.9
    text = plots.shap_summary_as_text(s)
    assert "higher values of the variable increase" in text and "'M' have higher SHAP" in text
    assert plots.shap_beeswarm_figure(s)