|
1 | 1 | """Tests for evaluation metrics."""
|
2 |
| -from typing import Dict |
| 2 | +from typing import Dict, List |
3 | 3 |
|
4 | 4 | import numpy as np
|
| 5 | +import pytest |
5 | 6 |
|
6 | 7 | import xgboost as xgb
|
| 8 | +from xgboost.compat import concat |
| 9 | +from xgboost.core import _parse_eval_str |
| 10 | + |
| 11 | + |
| 12 | +def check_precision_score(tree_method: str) -> None: |
| 13 | + """Test for precision with ranking and classification.""" |
| 14 | + datasets = pytest.importorskip("sklearn.datasets") |
| 15 | + |
| 16 | + X, y = datasets.make_classification( |
| 17 | + n_samples=1024, n_features=4, n_classes=2, random_state=2023 |
| 18 | + ) |
| 19 | + qid = np.zeros(shape=y.shape) # same group |
| 20 | + |
| 21 | + ltr = xgb.XGBRanker(n_estimators=2, tree_method=tree_method) |
| 22 | + ltr.fit(X, y, qid=qid) |
| 23 | + |
| 24 | + # re-generate so that XGBoost doesn't evaluate the result to 1.0 |
| 25 | + X, y = datasets.make_classification( |
| 26 | + n_samples=512, n_features=4, n_classes=2, random_state=1994 |
| 27 | + ) |
| 28 | + |
| 29 | + ltr.set_params(eval_metric="pre@32") |
| 30 | + result = _parse_eval_str( |
| 31 | + ltr.get_booster().eval_set(evals=[(xgb.DMatrix(X, y), "Xy")]) |
| 32 | + ) |
| 33 | + score_0 = result[1][1] |
| 34 | + |
| 35 | + X_list = [] |
| 36 | + y_list = [] |
| 37 | + n_query_groups = 3 |
| 38 | + q_list: List[np.ndarray] = [] |
| 39 | + for i in range(n_query_groups): |
| 40 | + # same for all groups |
| 41 | + X, y = datasets.make_classification( |
| 42 | + n_samples=512, n_features=4, n_classes=2, random_state=1994 |
| 43 | + ) |
| 44 | + X_list.append(X) |
| 45 | + y_list.append(y) |
| 46 | + q = np.full(shape=y.shape, fill_value=i, dtype=np.uint64) |
| 47 | + q_list.append(q) |
| 48 | + |
| 49 | + qid = concat(q_list) |
| 50 | + X = concat(X_list) |
| 51 | + y = concat(y_list) |
| 52 | + |
| 53 | + result = _parse_eval_str( |
| 54 | + ltr.get_booster().eval_set(evals=[(xgb.DMatrix(X, y, qid=qid), "Xy")]) |
| 55 | + ) |
| 56 | + assert result[1][0].endswith("pre@32") |
| 57 | + score_1 = result[1][1] |
| 58 | + assert score_1 == score_0 |
7 | 59 |
|
8 | 60 |
|
9 | 61 | def check_quantile_error(tree_method: str) -> None:
|
|
0 commit comments