Skip to content

Commit 17ee018

Browse files
committed
Test.
1 parent a51534e commit 17ee018

File tree

7 files changed

+66
-41
lines changed

7 files changed

+66
-41
lines changed

python-package/xgboost/sklearn.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
# coding: utf-8
2-
# pylint: disable=too-many-arguments, too-many-locals, invalid-name, fixme, R0912, C0302
1+
# pylint: disable=too-many-arguments, too-many-locals, invalid-name, fixme, too-many-lines
32
"""Scikit-Learn Wrapper interface for XGBoost."""
43
import copy
54
import warnings
@@ -544,8 +543,8 @@ def get_xgb_params(self) -> Dict[str, Any]:
544543
params = self.get_params()
545544
# Parameters that should not go into native learner.
546545
wrapper_specific = {
547-
'importance_type', 'kwargs', 'missing', 'n_estimators',
548-
"enable_categorical", "use_label_encoder",
546+
'importance_type', 'kwargs', 'missing', 'n_estimators', 'use_label_encoder',
547+
"enable_categorical"
549548
}
550549
filtered = {}
551550
for k, v in params.items():
@@ -1148,33 +1147,31 @@ def fit(
11481147
) -> "XGBClassifier":
11491148
# pylint: disable = attribute-defined-outside-init,too-many-statements
11501149
evals_result: TrainingCallback.EvalsLog = {}
1150+
11511151
if _is_cudf_df(y) or _is_cudf_ser(y):
11521152
import cupy as cp # pylint: disable=E0401
11531153

11541154
self.classes_ = cp.unique(y.values)
11551155
self.n_classes_ = len(self.classes_)
11561156
expected_classes = cp.arange(self.n_classes_)
1157-
if (
1158-
self.classes_.shape != expected_classes.shape
1159-
or not (self.classes_ == expected_classes).all()
1160-
):
1161-
raise ValueError("Invalid classes")
11621157
elif _is_cupy_array(y):
11631158
import cupy as cp # pylint: disable=E0401
11641159

11651160
self.classes_ = cp.unique(y)
11661161
self.n_classes_ = len(self.classes_)
11671162
expected_classes = cp.arange(self.n_classes_)
1168-
if (
1169-
self.classes_.shape != expected_classes.shape
1170-
or not (self.classes_ == expected_classes).all()
1171-
):
1172-
raise ValueError("Invalid classes")
11731163
else:
11741164
self.classes_ = np.unique(np.asarray(y))
11751165
self.n_classes_ = len(self.classes_)
1176-
if not np.array_equal(self.classes_, np.arange(self.n_classes_)):
1177-
raise ValueError("Invalid classes")
1166+
expected_classes = np.arange(self.n_classes_)
1167+
if (
1168+
self.classes_.shape != expected_classes.shape
1169+
or not (self.classes_ == expected_classes).all()
1170+
):
1171+
raise ValueError(
1172+
f"Invalid classes inferred from unique values of `y`. "
1173+
f"Expected: {expected_classes}, got {self.classes_}"
1174+
)
11781175

11791176
params = self.get_xgb_params()
11801177

tests/python-gpu/test_from_cudf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ def test_cudf_training_with_sklearn():
208208
y_cudf_series = ss(data=y.iloc[:, 0])
209209

210210
for y_obj in [y_cudf, y_cudf_series]:
211-
clf = xgb.XGBClassifier(gpu_id=0, tree_method='gpu_hist', use_label_encoder=False)
211+
clf = xgb.XGBClassifier(gpu_id=0, tree_method='gpu_hist')
212212
clf.fit(X_cudf, y_obj, sample_weight=cudf_weights, base_margin=cudf_base_margin,
213213
eval_set=[(X_cudf, y_obj)])
214214
pred = clf.predict(X_cudf)

tests/python-gpu/test_from_cupy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def test_cupy_training_with_sklearn():
122122
base_margin = np.random.random(50)
123123
cupy_base_margin = cp.array(base_margin)
124124

125-
clf = xgb.XGBClassifier(gpu_id=0, tree_method="gpu_hist", use_label_encoder=False)
125+
clf = xgb.XGBClassifier(gpu_id=0, tree_method="gpu_hist")
126126
clf.fit(
127127
X,
128128
y,

tests/python-gpu/test_gpu_basic_models.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,20 @@
77
# Don't import the test class, otherwise they will run twice.
88
import test_callback as test_cb # noqa
99
import test_basic_models as test_bm
10+
import testing as tm
1011
rng = np.random.RandomState(1994)
1112

1213

1314
class TestGPUBasicModels:
1415
cpu_test_cb = test_cb.TestCallbacks()
1516
cpu_test_bm = test_bm.TestModels()
1617

17-
def run_cls(self, X, y, deterministic):
18-
cls = xgb.XGBClassifier(tree_method='gpu_hist',
19-
deterministic_histogram=deterministic,
20-
single_precision_histogram=True)
18+
def run_cls(self, X, y):
19+
cls = xgb.XGBClassifier(tree_method='gpu_hist', single_precision_histogram=True)
2120
cls.fit(X, y)
2221
cls.get_booster().save_model('test_deterministic_gpu_hist-0.json')
2322

24-
cls = xgb.XGBClassifier(tree_method='gpu_hist',
25-
deterministic_histogram=deterministic,
26-
single_precision_histogram=True)
23+
cls = xgb.XGBClassifier(tree_method='gpu_hist', single_precision_histogram=True)
2724
cls.fit(X, y)
2825
cls.get_booster().save_model('test_deterministic_gpu_hist-1.json')
2926

@@ -49,19 +46,22 @@ def test_deterministic_gpu_hist(self):
4946
kClasses = 4
5047
# Create large values to force rounding.
5148
X = np.random.randn(kRows, kCols) * 1e4
52-
y = np.random.randint(0, kClasses, size=kRows) * 1e4
49+
y = np.random.randint(0, kClasses, size=kRows)
5350

54-
model_0, model_1 = self.run_cls(X, y, True)
51+
model_0, model_1 = self.run_cls(X, y)
5552
assert model_0 == model_1
5653

54+
@pytest.mark.skipif(**tm.no_sklearn())
5755
def test_invalid_gpu_id(self):
58-
X = np.random.randn(10, 5) * 1e4
59-
y = np.random.randint(0, 2, size=10) * 1e4
56+
from sklearn.datasets import load_digits
57+
X, y = load_digits(return_X_y=True)
6058
# should pass with invalid gpu id
6159
cls1 = xgb.XGBClassifier(tree_method='gpu_hist', gpu_id=9999)
6260
cls1.fit(X, y)
6361
# should throw error with fail_on_invalid_gpu_id enabled
64-
cls2 = xgb.XGBClassifier(tree_method='gpu_hist', gpu_id=9999, fail_on_invalid_gpu_id=True)
62+
cls2 = xgb.XGBClassifier(
63+
tree_method='gpu_hist', gpu_id=9999, fail_on_invalid_gpu_id=True
64+
)
6565
try:
6666
cls2.fit(X, y)
6767
assert False, "Should have failed with with fail_on_invalid_gpu_id enabled"

tests/python-gpu/test_gpu_pickling.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ def test_pickled_predictor(self):
146146

147147
os.remove(model_path)
148148

149+
@pytest.mark.skipif(**tm.no_sklearn())
149150
def test_predict_sklearn_pickle(self):
150151
from sklearn.datasets import load_digits
151152
x, y = load_digits(return_X_y=True)

tests/python-gpu/test_gpu_with_sklearn.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ def test_categorical():
5656
X, y = load_svmlight_file(os.path.join(data_dir, "agaricus.txt.train"))
5757
clf = xgb.XGBClassifier(
5858
tree_method="gpu_hist",
59-
use_label_encoder=False,
6059
enable_categorical=True,
6160
n_estimators=10,
6261
)
@@ -98,3 +97,36 @@ def check_predt(X, y):
9897

9998
X = cudf.DataFrame(X)
10099
check_predt(X, y)
100+
101+
102+
@pytest.mark.skipif(**tm.no_cupy())
103+
@pytest.mark.skipif(**tm.no_cudf())
104+
def test_classififer():
105+
from sklearn.datasets import load_digits
106+
import cupy as cp
107+
import cudf
108+
109+
X, y = load_digits(return_X_y=True)
110+
y *= 10
111+
112+
clf = xgb.XGBClassifier(tree_method="gpu_hist", n_estimators=1)
113+
114+
# numpy
115+
with pytest.raises(ValueError, match=r"Invalid classes.*"):
116+
clf.fit(X, y)
117+
118+
# cupy
119+
X, y = cp.array(X), cp.array(y)
120+
with pytest.raises(ValueError, match=r"Invalid classes.*"):
121+
clf.fit(X, y)
122+
123+
# cudf
124+
X, y = cudf.DataFrame(X), cudf.DataFrame(y)
125+
with pytest.raises(ValueError, match=r"Invalid classes.*"):
126+
clf.fit(X, y)
127+
128+
# pandas
129+
X, y = load_digits(return_X_y=True, as_frame=True)
130+
y *= 10
131+
with pytest.raises(ValueError, match=r"Invalid classes.*"):
132+
clf.fit(X, y)

tests/python/test_with_sklearn.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,6 @@ def test_feature_importances_gain():
283283
random_state=0, tree_method="exact",
284284
learning_rate=0.1,
285285
importance_type="gain",
286-
use_label_encoder=False,
287286
).fit(X, y)
288287

289288
exp = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
@@ -306,7 +305,6 @@ def test_feature_importances_gain():
306305
tree_method="exact",
307306
learning_rate=0.1,
308307
importance_type="gain",
309-
use_label_encoder=False,
310308
).fit(X, y)
311309
np.testing.assert_almost_equal(xgb_model.feature_importances_, exp)
312310

@@ -315,14 +313,11 @@ def test_feature_importances_gain():
315313
tree_method="exact",
316314
learning_rate=0.1,
317315
importance_type="gain",
318-
use_label_encoder=False,
319316
).fit(X, y)
320317
np.testing.assert_almost_equal(xgb_model.feature_importances_, exp)
321318

322319
# no split can be found
323-
cls = xgb.XGBClassifier(
324-
min_child_weight=1000, tree_method="hist", n_estimators=1, use_label_encoder=False
325-
)
320+
cls = xgb.XGBClassifier(min_child_weight=1000, tree_method="hist", n_estimators=1)
326321
cls.fit(X, y)
327322
assert np.all(cls.feature_importances_ == 0)
328323

@@ -497,7 +492,7 @@ def dummy_objective(y_true, y_preds):
497492
X, y
498493
)
499494

500-
cls = xgb.XGBClassifier(use_label_encoder=False, n_estimators=1)
495+
cls = xgb.XGBClassifier(n_estimators=1)
501496
cls.fit(X, y)
502497

503498
is_called = [False]
@@ -923,7 +918,7 @@ def test_RFECV():
923918
bst = xgb.XGBClassifier(booster='gblinear', learning_rate=0.1,
924919
n_estimators=10,
925920
objective='binary:logistic',
926-
random_state=0, verbosity=0, use_label_encoder=False)
921+
random_state=0, verbosity=0)
927922
rfecv = RFECV(estimator=bst, step=1, cv=3, scoring='roc_auc')
928923
rfecv.fit(X, y)
929924

@@ -934,7 +929,7 @@ def test_RFECV():
934929
n_estimators=10,
935930
objective='multi:softprob',
936931
random_state=0, reg_alpha=0.001, reg_lambda=0.01,
937-
scale_pos_weight=0.5, verbosity=0, use_label_encoder=False)
932+
scale_pos_weight=0.5, verbosity=0)
938933
rfecv = RFECV(estimator=bst, step=1, cv=3, scoring='neg_log_loss')
939934
rfecv.fit(X, y)
940935

@@ -943,7 +938,7 @@ def test_RFECV():
943938
rfecv = RFECV(estimator=reg)
944939
rfecv.fit(X, y)
945940

946-
cls = xgb.XGBClassifier(use_label_encoder=False)
941+
cls = xgb.XGBClassifier()
947942
rfecv = RFECV(estimator=cls, step=1, cv=3,
948943
scoring='neg_mean_squared_error')
949944
rfecv.fit(X, y)

0 commit comments

Comments
 (0)