forked from dmlc/xgboost
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathordinal.py
More file actions
869 lines (694 loc) · 27.9 KB
/
ordinal.py
File metadata and controls
869 lines (694 loc) · 27.9 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
"""Tests for the ordinal re-coder."""
import itertools
import os
import tempfile
from concurrent.futures import ThreadPoolExecutor
from functools import cache as fcache
from typing import Any, Tuple, Type, TypeVar
import numpy as np
import pytest
from .._typing import EvalsLog
from ..core import DMatrix, ExtMemQuantileDMatrix, QuantileDMatrix
from ..data import _lazy_load_cudf_is_cat
from ..training import train
from .data import (
IteratorForTest,
is_pd_cat_dtype,
make_batches,
make_categorical,
memory,
)
from .updater import get_basescore
from .utils import Device, assert_allclose, predictor_equal
@fcache
def get_df_impl(device: Device) -> Tuple[Type, Type]:
"""Get data frame implementation based on the ]device."""
if device == "cpu":
import pandas as pd
Df = pd.DataFrame
Ser = pd.Series
else:
import cudf
Df = cudf.DataFrame
Ser = cudf.Series
return Df, Ser
def asarray(device: Device, data: Any) -> np.ndarray:
"""Wrapper to get an array."""
if device == "cpu":
return np.asarray(data)
import cupy as cp
return cp.asarray(data)
def comp_booster(device: Device, Xy: DMatrix, booster: str) -> None:
"""Compare the results from DMatrix and Booster."""
cats_dm = Xy.get_categories(export_to_arrow=True).to_arrow()
assert cats_dm is not None
rng = np.random.default_rng(2025)
Xy.set_label(rng.normal(size=Xy.num_row()))
bst = train({"booster": booster, "device": device}, Xy, 1)
cats_bst = bst.get_categories(export_to_arrow=True).to_arrow()
assert cats_bst is not None
assert cats_dm == cats_bst
def run_cat_container(device: Device) -> None:
"""Basic tests for the container class used by the DMatrix."""
def run_dispatch(device: Device, DMatrixT: Type) -> None:
Df, _ = get_df_impl(device)
# Basic test with a single feature
df = Df({"c": ["cdef", "abc"]}, dtype="category")
categories = df.c.cat.categories
Xy = DMatrixT(df, enable_categorical=True)
assert Xy.feature_names == ["c"]
assert Xy.feature_types == ["c"]
results = Xy.get_categories(export_to_arrow=True).to_arrow()
assert results is not None
results_di = dict(results)
assert len(results_di["c"]) == len(categories)
for i in range(len(results_di["c"])):
assert str(results_di["c"][i]) == str(categories[i]), (
results_di["c"][i],
categories[i],
)
# Test with missing values.
df = Df({"c": ["cdef", None, "abc", "abc"]}, dtype="category")
Xy = DMatrixT(df, enable_categorical=True)
cats = Xy.get_categories(export_to_arrow=True).to_arrow()
assert cats is not None
cats_id = dict(cats)
ser = cats_id["c"].to_pandas()
assert ser.iloc[0] == "abc"
assert ser.iloc[1] == "cdef"
assert ser.size == 2
csr = Xy.get_data()
assert csr.data.size == 3
assert_allclose(device, csr.data, np.array([1.0, 0.0, 0.0]))
assert_allclose(device, csr.indptr, np.array([0, 1, 1, 2, 3]))
assert_allclose(device, csr.indices, np.array([0, 0, 0]))
comp_booster(device, Xy, "gbtree")
comp_booster(device, Xy, "dart")
# Test with explicit null-terminated strings.
df = Df({"c": ["cdef", None, "abc", "abc\0"]}, dtype="category")
Xy = DMatrixT(df, enable_categorical=True)
comp_booster(device, Xy, "gbtree")
comp_booster(device, Xy, "dart")
with pytest.raises(ValueError, match="export_to_arrow"):
Xy.get_categories(export_to_arrow=False).to_arrow()
for dm in (DMatrix, QuantileDMatrix):
run_dispatch(device, dm)
# pylint: disable=too-many-statements
def run_cat_container_mixed(device: Device) -> None:
"""Run checks with mixed types."""
import pandas as pd
try:
is_cudf_cat = _lazy_load_cudf_is_cat()
except ImportError:
def is_cudf_cat(_: Any) -> bool:
return False
n_samples = int(2**10)
def check(Xy: DMatrix, X: pd.DataFrame) -> None:
cats = Xy.get_categories(export_to_arrow=True).to_arrow()
assert cats is not None
cats_di = dict(cats)
for fname in X.columns:
if is_pd_cat_dtype(X[fname].dtype) or is_cudf_cat(X[fname].dtype):
vf = cats_di[fname]
assert vf is not None
aw_list = sorted(vf.to_pylist())
if is_cudf_cat(X[fname].dtype):
pd_list: list = X[fname].unique().to_arrow().to_pylist()
else:
pd_list = X[fname].unique().tolist()
if np.nan in pd_list: # pandas
pd_list.remove(np.nan)
if None in pd_list: # cudf
pd_list.remove(None)
pd_list = sorted(pd_list)
assert aw_list == pd_list
else:
assert cats_di[fname] is None
if not hasattr(Xy, "ref"): # not quantile DMatrix.
assert not isinstance(Xy, QuantileDMatrix)
with tempfile.TemporaryDirectory() as tmpdir:
fname = os.path.join(tmpdir, "DMatrix.binary")
Xy.save_binary(fname)
Xy_1 = DMatrix(fname)
cats_1 = Xy_1.get_categories(export_to_arrow=True).to_arrow()
assert cats_1 is not None
cats_1_di = dict(cats_1)
for k, v_0 in cats_di.items():
v_1 = cats_1_di[k]
if v_0 is None:
assert v_1 is None
else:
assert v_1 is not None
assert v_0.to_pylist() == v_1.to_pylist()
comp_booster(device, Xy, "gbtree")
comp_booster(device, Xy, "dart")
def run_dispatch(DMatrixT: Type) -> None:
# full str type
X, y = make_categorical(
n_samples, 16, 7, onehot=False, cat_dtype=np.str_, device=device
)
Xy = DMatrixT(X, y, enable_categorical=True)
check(Xy, X)
# str type, mixed with numerical features
X, y = make_categorical(
n_samples,
16,
7,
onehot=False,
cat_ratio=0.5,
cat_dtype=np.str_,
device=device,
)
Xy = DMatrixT(X, y, enable_categorical=True)
check(Xy, X)
# str type, mixed with numerical features and missing values
X, y = make_categorical(
n_samples,
16,
7,
onehot=False,
cat_ratio=0.5,
sparsity=0.5,
cat_dtype=np.str_,
device=device,
)
Xy = DMatrixT(X, y, enable_categorical=True)
check(Xy, X)
# int type
X, y = make_categorical(
n_samples, 16, 7, onehot=False, cat_dtype=np.int64, device=device
)
Xy = DMatrixT(X, y, enable_categorical=True)
check(Xy, X)
# int type, mixed with numerical features
X, y = make_categorical(
n_samples,
16,
7,
onehot=False,
cat_ratio=0.5,
cat_dtype=np.int64,
device=device,
)
Xy = DMatrixT(X, y, enable_categorical=True)
check(Xy, X)
# int type, mixed with numerical features and missing values
X, y = make_categorical(
n_samples,
16,
7,
onehot=False,
cat_ratio=0.5,
sparsity=0.5,
cat_dtype=np.int64,
device=device,
)
Xy = DMatrixT(X, y, enable_categorical=True)
check(Xy, X)
for dm in (DMatrix, QuantileDMatrix):
run_dispatch(dm)
# No category
batches = make_batches(
n_samples_per_batch=128, n_features=4, n_batches=1, use_cupy=device == "cuda"
)
X, y, w = map(lambda x: x[0], batches)
for DMatrixT in (DMatrix, QuantileDMatrix):
Xy = DMatrixT(X, y, weight=w)
all_num = Xy.get_categories(export_to_arrow=True).to_arrow()
assert all_num is not None
for _, v in all_num:
assert v is None
with pytest.raises(ValueError, match="export_to_arrow"):
Xy.get_categories(export_to_arrow=False).to_arrow()
def run_cat_container_iter(device: Device) -> None:
"""Test the categories container for iterator-based inputs."""
n_batches = 4
n_features = 8
n_samples_per_batch = 64
n_cats = 5
X, y = [], []
for _ in range(n_batches):
X_i, y_i = make_categorical(
n_samples_per_batch,
n_features,
n_cats,
onehot=False,
sparsity=0.5,
cat_dtype=np.int64,
device=device,
)
X.append(X_i)
y.append(y_i)
it = IteratorForTest(X, y, None, cache="cache", on_host=device == "cuda")
Xy = ExtMemQuantileDMatrix(it, enable_categorical=True)
cats = Xy.get_categories(export_to_arrow=True).to_arrow()
assert cats is not None and len(cats) == n_features
cats_di = dict(cats)
for _, v in cats_di.items():
assert v is not None
assert v.null_count == 0
assert len(v) == n_cats
def _basic_example(device: Device) -> Tuple[Any, Any, np.ndarray, np.ndarray]:
Df, _ = get_df_impl(device)
enc = Df({"c": ["cdef", "abc", "def"]}, dtype="category")
codes = enc.c.cat.codes # 1, 0, 2
assert_allclose(device, asarray(device, codes), np.array([1, 0, 2]))
encoded = np.array([codes.iloc[2], codes.iloc[1]]) # def, abc
np.testing.assert_allclose(encoded, [2, 0])
reenc = Df({"c": ["def", "abc"]}, dtype="category") # same as `encoded`
codes = reenc.c.cat.codes
assert_allclose(device, codes, np.array([1, 0]))
y = np.array([0, 1, 2])
return enc, reenc, encoded, y
def run_basic_predict(DMatrixT: Type, device: Device, tdevice: Device) -> None:
"""Enable tests with mixed devices."""
enc, reenc, encoded, y = _basic_example(device)
Xy = DMatrixT(enc, y, enable_categorical=True)
booster = train({"device": tdevice}, Xy, num_boost_round=4)
predt0 = booster.inplace_predict(reenc)
predt1 = booster.inplace_predict(encoded)
assert_allclose(device, predt0, predt1)
fmat = DMatrixT(reenc, enable_categorical=True)
predt2 = booster.predict(fmat)
assert_allclose(device, predt0, predt2)
def run_cat_predict(device: Device) -> None:
"""Basic tests for re-coding during prediction."""
Df, _ = get_df_impl(device)
for dm in (DMatrix, QuantileDMatrix):
run_basic_predict(dm, device, device)
def run_mixed(DMatrixT: Type) -> None:
df = Df({"b": [2, 1, 3], "c": ["cdef", "abc", "def"]}, dtype="category")
y = np.array([0, 1, 2])
# used with the next df
b_codes = df.b.cat.codes
assert_allclose(device, asarray(device, b_codes), np.array([1, 0, 2]))
# pick codes of 3, 1
b_encoded = np.array([b_codes.iloc[2], b_codes.iloc[1]])
c_codes = df.c.cat.codes
assert_allclose(device, asarray(device, c_codes), np.array([1, 0, 2]))
# pick codes of "def", "abc"
c_encoded = np.array([c_codes.iloc[2], c_codes.iloc[1]])
encoded = np.stack([b_encoded, c_encoded], axis=1)
Xy = DMatrixT(df, y, enable_categorical=True)
booster = train({"device": device}, Xy, num_boost_round=4)
df = Df({"b": [3, 1], "c": ["def", "abc"]}, dtype="category")
predt0 = booster.inplace_predict(df)
predt1 = booster.inplace_predict(encoded)
assert_allclose(device, predt0, predt1)
fmat = DMatrixT(df, enable_categorical=True)
predt2 = booster.predict(fmat)
assert_allclose(device, predt0, predt2)
for dm in (DMatrix, QuantileDMatrix):
run_mixed(dm)
def run_cat_invalid(device: Device) -> None:
"""Basic tests for invalid inputs."""
Df, Ser = get_df_impl(device)
y = np.array([0, 1, 2])
def run_invalid(DMatrixT: Type) -> None:
df = Df({"b": [2, 1, 3], "c": ["cdef", "abc", "def"]}, dtype="category")
Xy = DMatrixT(df, y, enable_categorical=True)
booster = train({"device": device}, Xy, num_boost_round=4)
df["b"] = df["b"].astype(np.int64)
with pytest.raises(ValueError, match="The data type doesn't match"):
booster.inplace_predict(df)
Xy = DMatrixT(df, y, enable_categorical=True)
with pytest.raises(ValueError, match="The data type doesn't match"):
booster.predict(Xy)
df = Df(
{"b": [2, 1, 3, 4], "c": ["cdef", "abc", "def", "bbc"]}, dtype="category"
)
with pytest.raises(ValueError, match="Found a category not in the training"):
booster.inplace_predict(df)
for dm in (DMatrix, QuantileDMatrix):
run_invalid(dm)
df = Df({"b": [2, 1, 3], "c": ["cdef", "abc", "def"]}, dtype="category")
Xy = DMatrix(df, y, enable_categorical=True)
booster = train({"device": device}, Xy, num_boost_round=4)
df["c"] = Ser(asarray(device, [0, 1, 1]), dtype="category")
msg = "index type must match between the training and test set"
with pytest.raises(ValueError, match=msg):
booster.inplace_predict(df)
with pytest.raises(ValueError, match=msg):
DMatrix(df, enable_categorical=True, feature_types=booster.get_categories())
with pytest.raises(ValueError, match=msg):
QuantileDMatrix(
df, enable_categorical=True, feature_types=booster.get_categories()
)
def run_cat_oov_in_range(device: Device) -> None:
"""Test OOV categories whose sorted insertion point is inside the training set."""
Df, _ = get_df_impl(device)
def check(train_df: Any, pred_df: Any, y: np.ndarray) -> None:
for DMatrixT in (DMatrix, QuantileDMatrix):
Xy = DMatrixT(train_df, y, enable_categorical=True)
booster = train({"device": device}, Xy, num_boost_round=1)
with pytest.raises(
ValueError, match="Found a category not in the training"
):
booster.inplace_predict(pred_df)
fmat = DMatrixT(pred_df, enable_categorical=True)
with pytest.raises(
ValueError, match="Found a category not in the training"
):
booster.predict(fmat)
# "B2" is absent from training but sorts between "B" and "C".
train_df = Df({"cat": ["A", "B", "C", "A", "B", "B"], "x": [1, 2, 3, 4, 5, 6]})
train_df["cat"] = train_df["cat"].astype("category")
pred_df = Df({"cat": ["B2", "C"], "x": [2, 2]})
pred_df["cat"] = pred_df["cat"].astype("category")
check(train_df, pred_df, np.array([0, 1, 0, 1, 0, 1]))
# Numeric category 4 is absent from training but sorts between 3 and 5.
# XGBoost accepts only dense codes. In this test case, even though the categories
# are not contiguous, the code can still be dense.
train_df = Df({"cat": [1, 3, 5, 1, 3, 3], "x": [1, 2, 3, 4, 5, 6]})
train_df["cat"] = train_df["cat"].astype("category")
pred_df = Df({"cat": [4, 5], "x": [2, 2]})
pred_df["cat"] = pred_df["cat"].astype("category")
check(train_df, pred_df, np.array([0, 1, 0, 1, 0, 1]))
def run_cat_thread_safety(device: Device) -> None:
"""Basic tests for thread safety."""
X, y = make_categorical(2048, 16, 112, onehot=False, cat_ratio=0.5, device=device)
Xy = QuantileDMatrix(X, y, enable_categorical=True)
booster = train({"device": device}, Xy, num_boost_round=10)
def run_thread_safety(DMatrixT: Type) -> bool:
Xy = DMatrixT(X, enable_categorical=True)
predt0 = booster.predict(Xy)
predt1 = booster.inplace_predict(X)
assert_allclose(device, predt0, predt1)
return True
futures = []
n_cpus = os.cpu_count()
assert n_cpus is not None
for dm in (DMatrix, QuantileDMatrix):
with ThreadPoolExecutor(max_workers=max(n_cpus, 10)) as e:
for _ in range(32):
fut = e.submit(run_thread_safety, dm)
futures.append(fut)
for f in futures:
assert f.result()
U = TypeVar("U", DMatrix, QuantileDMatrix)
def _make_dm(DMatrixT: Type[U], ref: DMatrix, *args: Any, **kwargs: Any) -> U:
if DMatrixT is QuantileDMatrix:
return DMatrixT(*args, ref=ref, enable_categorical=True, **kwargs)
return DMatrixT(*args, enable_categorical=True, **kwargs)
def _run_predt(
device: Device,
DMatrixT: Type,
pred_contribs: bool,
pred_interactions: bool,
pred_leaf: bool,
) -> None:
enc, reenc, encoded, y = _basic_example(device)
Xy = DMatrixT(enc, y, enable_categorical=True)
booster = train({"device": device}, Xy, num_boost_round=4)
predt_0 = booster.predict(
_make_dm(DMatrixT, ref=Xy, data=reenc),
pred_contribs=pred_contribs,
pred_interactions=pred_interactions,
pred_leaf=pred_leaf,
)
predt_1 = booster.predict(
_make_dm(DMatrixT, ref=Xy, data=encoded.reshape(2, 1), feature_names=["c"]),
pred_contribs=pred_contribs,
pred_interactions=pred_interactions,
pred_leaf=pred_leaf,
)
assert_allclose(device, predt_0, predt_1)
def run_cat_shap(device: Device) -> None:
"""Basic tests for SHAP values."""
for dm in (DMatrix, QuantileDMatrix):
_run_predt(
device, dm, pred_contribs=True, pred_interactions=False, pred_leaf=False
)
for dm in (DMatrix, QuantileDMatrix):
_run_predt(
device, dm, pred_contribs=False, pred_interactions=True, pred_leaf=False
)
def run_cat_leaf(device: Device) -> None:
"""Basic tests for leaf prediction."""
# QuantileDMatrix is not supported by leaf.
_run_predt(
device, DMatrix, pred_contribs=False, pred_interactions=False, pred_leaf=True
)
# pylint: disable=too-many-locals
@memory.cache
def make_recoded(device: Device, *, n_features: int = 4096) -> Tuple:
"""Synthesize a test dataset with changed encoding."""
Df, _ = get_df_impl(device)
import pandas as pd
# Test large column numbers. XGBoost makes some specializations for slim datasets,
# make sure we cover all the cases.
n_samples = 1024
# Same between old and new, with 0 ("a") and 1 ("b") exchanged their position.
old_cats = ["a", "b", "c", "d"]
new_cats = ["b", "a", "c", "d"]
mapping = {0: 1, 1: 0}
rng = np.random.default_rng(2025)
col_numeric = rng.uniform(0, 1, size=(n_samples, n_features // 2))
col_categorical = rng.integers(
low=0, high=4, size=(n_samples, n_features // 2), dtype=np.int32
)
df = {} # avoid fragmentation warning from pandas
for c in range(n_features):
if c % 2 == 0:
col = col_numeric[:, c // 2]
else:
codes = col_categorical[:, c // 2]
col = pd.Categorical.from_codes(
categories=old_cats,
codes=codes,
)
df[f"f{c}"] = col
enc = Df(df)
y = rng.normal(size=n_samples)
reenc = enc.copy()
for c in range(n_features):
if c % 2 == 0:
continue
name = f"f{c}"
codes_ser = reenc[name].cat.codes
if hasattr(codes_ser, "to_pandas"): # cudf
codes_ser = codes_ser.to_pandas()
new_codes = codes_ser.replace(mapping)
reenc[name] = pd.Categorical.from_codes(categories=new_cats, codes=new_codes)
reenc = Df(reenc)
assert (reenc.iloc[:, 1].cat.codes != enc.iloc[:, 1].cat.codes).any()
return enc, reenc, y, col_numeric, col_categorical
def run_specified_cat( # pylint: disable=too-many-locals
device: Device,
) -> None:
"""Run with manually specified category encoding."""
import pandas as pd
# Same between old and new, with 0 ("a") and 1 ("b") exchanged their position.
old_cats = ["a", "b", "c", "d"]
new_cats = ["b", "a", "c", "d"]
col0 = np.arange(0, 9)
col1 = pd.Categorical.from_codes(
# b, b, c, d, a, c, c, d, a
categories=old_cats,
codes=[1, 1, 2, 3, 0, 2, 2, 3, 0],
)
df = pd.DataFrame({"f0": col0, "f1": col1})
Df, _ = get_df_impl(device)
df = Df(df)
rng = np.random.default_rng(2025)
y = rng.uniform(size=df.shape[0])
for dm in (DMatrix, QuantileDMatrix):
Xy = dm(df, y, enable_categorical=True)
booster = train({"device": device}, Xy)
predt0 = booster.predict(Xy)
predt1 = booster.inplace_predict(df)
assert_allclose(device, predt0, predt1)
col1 = pd.Categorical.from_codes(
# b, b, c, d, a, c, c, d, a
categories=new_cats,
codes=[0, 0, 2, 3, 1, 2, 2, 3, 1],
)
df1 = Df({"f0": col0, "f1": col1})
predt2 = booster.inplace_predict(df1)
assert_allclose(device, predt0, predt2)
enc, reenc, y, col_numeric, col_categorical = make_recoded(device)
Xy = DMatrix(enc, y, enable_categorical=True)
booster = train({"device": device}, Xy)
predt0 = booster.predict(Xy)
predt1 = booster.inplace_predict(enc)
assert_allclose(device, predt0, predt1)
Xy = DMatrix(reenc, y, enable_categorical=True)
predt2 = booster.predict(Xy)
assert_allclose(device, predt0, predt2)
array = np.empty(shape=(reenc.shape[0], reenc.shape[1]))
array[:, enc.dtypes == "category"] = col_categorical
array[:, enc.dtypes != "category"] = col_numeric
if device == "cuda":
import cupy as cp
array = cp.array(array)
predt3 = booster.inplace_predict(array)
assert_allclose(device, predt0, predt3)
def run_validation(device: Device) -> None:
"""Check the validation dataset is using the correct encoding."""
enc, reenc, y, _, _ = make_recoded(device)
Xy = DMatrix(enc, y, enable_categorical=True)
Xy_valid = DMatrix(reenc, y, enable_categorical=True)
evals_result: EvalsLog = {}
train(
{"device": device},
Xy,
evals=[(Xy, "Train"), (Xy_valid, "Valid")],
evals_result=evals_result,
)
# Evaluation dataset should have the exact same performance as the training dataset.
assert_allclose(
device, evals_result["Train"]["rmse"], evals_result["Valid"]["rmse"]
)
def run_recode_dmatrix(device: Device) -> None:
"""Test re-coding inpput for DMatrix."""
import pandas as pd
Df, _ = get_df_impl(device)
# String index
old_cats = ["a", "b", "c", "d"]
new_cats = ["b", "a", "c", "d"]
col0 = np.arange(0, 9)
col1 = pd.Categorical.from_codes(
# b, b, c, d, a, c, c, d, a
categories=old_cats,
codes=[1, 1, 2, 3, 0, 2, 2, 3, 0],
)
df = Df({"f0": col0, "f1": col1})
Xy = DMatrix(df, enable_categorical=True)
cats_0 = Xy.get_categories(export_to_arrow=True)
assert Xy.feature_types == ["int", "c"]
col1 = pd.Categorical.from_codes(
# b, b, c, d, a, c, c, d, a
categories=new_cats,
codes=[0, 0, 2, 3, 1, 2, 2, 3, 1],
)
df = Df({"f0": col0, "f1": col1})
Xy = DMatrix(df, enable_categorical=True, feature_types=cats_0)
# feature_types is still correct
assert Xy.feature_names == ["f0", "f1"]
assert Xy.feature_types == ["int", "c"]
cats_1 = Xy.get_categories(export_to_arrow=True)
assert cats_0.to_arrow() == cats_1.to_arrow()
# Numeric index
col0 = pd.Categorical.from_codes(
categories=[5, 6, 7, 8],
codes=[0, 0, 2, 3, 1, 2, 2, 3, 1],
)
Df, _ = get_df_impl(device)
df = Df({"cat": col0})
for DMatrixT in (DMatrix, QuantileDMatrix):
Xy = DMatrixT(df, enable_categorical=True)
cats_0 = Xy.get_categories(export_to_arrow=True)
assert cats_0 is not None
Xy = DMatrixT(df, enable_categorical=True, feature_types=cats_0)
cats_1 = Xy.get_categories(export_to_arrow=True)
assert cats_1 is not None
assert cats_0.to_arrow() == cats_1.to_arrow()
# Recode
for DMatrixT in (DMatrix, QuantileDMatrix):
enc, reenc, y, _, _ = make_recoded(device)
Xy_0 = DMatrixT(enc, y, enable_categorical=True)
cats_0 = Xy_0.get_categories(export_to_arrow=True)
assert cats_0 is not None
Xy_1 = DMatrixT(reenc, y, feature_types=cats_0, enable_categorical=True)
cats_1 = Xy_1.get_categories(export_to_arrow=True)
assert cats_1 is not None
assert cats_0.to_arrow() == cats_1.to_arrow()
assert predictor_equal(Xy_0, Xy_1)
def run_training_continuation(device: Device) -> None:
"""Test re-coding for training continuation."""
enc, reenc, y, _, _ = make_recoded(device)
def check(Xy_0: DMatrix, Xy_1: DMatrix) -> None:
params = {"device": device}
r = 2
evals_result_0: EvalsLog = {}
booster_0 = train(
params,
Xy_0,
evals=[(Xy_1, "Valid")],
num_boost_round=r,
evals_result=evals_result_0,
)
evals_result_1: EvalsLog = {}
booster_1 = train(
params,
Xy_1,
evals=[(Xy_1, "Valid")],
xgb_model=booster_0,
num_boost_round=r,
evals_result=evals_result_1,
)
assert get_basescore(booster_0) == get_basescore(booster_1)
evals_result_2: EvalsLog = {}
booster_2 = train(
params,
Xy_0,
evals=[(Xy_1, "Valid")],
num_boost_round=r * 2,
evals_result=evals_result_2,
)
# Check evaluation results
eval_concat = evals_result_0["Valid"]["rmse"] + evals_result_1["Valid"]["rmse"]
eval_full = evals_result_2["Valid"]["rmse"]
np.testing.assert_allclose(eval_full, eval_concat)
# Test inference
for a, b in itertools.product([enc, reenc], [enc, reenc]):
predt_0 = booster_1.inplace_predict(a)
predt_1 = booster_2.inplace_predict(b)
assert_allclose(device, predt_0, predt_1, rtol=1e-5)
# With DMatrix
for a, b in itertools.product([Xy_0, Xy_1], [Xy_0, Xy_1]):
predt_0 = booster_1.predict(a)
predt_1 = booster_2.predict(b)
assert_allclose(device, predt_0, predt_1, rtol=1e-5)
for Train, Valid in itertools.product(
[DMatrix, QuantileDMatrix], [DMatrix, QuantileDMatrix]
):
Xy_0 = Train(enc, y, enable_categorical=True)
if Valid is QuantileDMatrix:
Xy_1 = Valid(
reenc,
y,
enable_categorical=True,
feature_types=Xy_0.get_categories(),
ref=Xy_0,
)
else:
Xy_1 = Valid(
reenc, y, enable_categorical=True, feature_types=Xy_0.get_categories()
)
check(Xy_0, Xy_1)
def run_update(device: Device) -> None:
"""Test with individual updaters."""
enc, reenc, y, _, _ = make_recoded(device)
Xy = DMatrix(enc, y, enable_categorical=True)
booster_0 = train({"device": device}, Xy, num_boost_round=4)
model_0 = booster_0.save_raw()
cats_0 = booster_0.get_categories()
Xy_1 = DMatrix(reenc, y, feature_types=cats_0, enable_categorical=True)
booster_1 = train(
{
"device": device,
"updater": "prune",
"process_type": "update",
},
Xy_1,
num_boost_round=4,
xgb_model=booster_0,
)
model_1 = booster_1.save_raw()
assert model_0 == model_1 # also compares the cat container inside
def run_recode_dmatrix_predict(device: Device) -> None:
"""Run prediction with re-coded DMatrix."""
enc, reenc, y, _, _ = make_recoded(device)
for DMatrixT in (DMatrix, QuantileDMatrix):
Xy = DMatrix(enc, y, enable_categorical=True)
booster = train({"device": device}, Xy, num_boost_round=4)
cats_0 = booster.get_categories()
Xy_1 = _make_dm(DMatrixT, Xy, reenc, y, feature_types=cats_0)
Xy_2 = _make_dm(DMatrixT, Xy, reenc, y)
predt_0 = booster.predict(Xy)
predt_1 = booster.predict(Xy_1)
predt_2 = booster.predict(Xy_2)
predt_3 = booster.inplace_predict(enc)
for predt in (predt_1, predt_2, predt_3):
assert_allclose(device, predt_0, predt)