MCPcopy Create free account
hub / github.com/dmlc/xgboost / test_feature_importances

Method test_feature_importances

tests/python/test_shap.py:12–257  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

10
11class TestSHAP:
12 def test_feature_importances(self) -> None:
13 rng = np.random.RandomState(1994)
14 data = rng.randn(100, 5)
15 target = np.array([0, 1] * 50)
16
17 features = ["Feature1", "Feature2", "Feature3", "Feature4", "Feature5"]
18
19 dm = xgb.DMatrix(data, label=target, feature_names=features)
20 params = {
21 "objective": "multi:softprob",
22 "eval_metric": "mlogloss",
23 "eta": 0.3,
24 "num_class": 3,
25 }
26
27 bst = xgb.train(params, dm, num_boost_round=10)
28
29 # number of feature importances should == number of features
30 scores1 = bst.get_score()
31 scores2 = bst.get_score(importance_type="weight")
32 scores3 = bst.get_score(importance_type="cover")
33 scores4 = bst.get_score(importance_type="gain")
34 scores5 = bst.get_score(importance_type="total_cover")
35 scores6 = bst.get_score(importance_type="total_gain")
36 assert len(scores1) == len(features)
37 assert len(scores2) == len(features)
38 assert len(scores3) == len(features)
39 assert len(scores4) == len(features)
40 assert len(scores5) == len(features)
41 assert len(scores6) == len(features)
42
43 # check backwards compatibility of get_fscore
44 fscores = bst.get_fscore()
45 assert scores1 == fscores
46
47 dtrain, dtest = tm.load_agaricus(__file__)
48
49 def fn(max_depth: int, num_rounds: int) -> None:
50 # train
51 params = {"max_depth": max_depth, "eta": 1}
52 bst = xgb.train(params, dtrain, num_boost_round=num_rounds)
53
54 # predict
55 preds = bst.predict(dtest)
56 contribs = bst.predict(dtest, pred_contribs=True)
57
58 # result should be (number of features + BIAS) * number of rows
59 assert contribs.shape == (dtest.num_row(), dtest.num_col() + 1)
60
61 # sum of contributions should be same as predictions
62 np.testing.assert_array_almost_equal(np.sum(contribs, axis=1), preds)
63
64 # for max_depth, num_rounds in itertools.product(range(0, 3), range(1, 5)):
65 # yield fn, max_depth, num_rounds
66
67 # check that we get the right SHAP values for a basic AND example
68 # (https://arxiv.org/abs/1706.06060)
69 X = np.zeros((4, 2))

Callers

nothing calls this directly

Calls 6

shap_valuesFunction · 0.85
get_scoreMethod · 0.80
get_fscoreMethod · 0.80
DMatrixMethod · 0.45
trainMethod · 0.45
predictMethod · 0.45

Tested by

no test coverage detected