-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathtest_engine.py
4310 lines (3847 loc) · 169 KB
/
test_engine.py
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
import copy
import itertools
import json
import math
import pickle
import platform
import random
import re
from os import getenv
from pathlib import Path
from shutil import copyfile
import numpy as np
import psutil
import pytest
from scipy.sparse import csr_matrix, isspmatrix_csc, isspmatrix_csr
from sklearn.datasets import load_svmlight_file, make_blobs, make_multilabel_classification
from sklearn.metrics import average_precision_score, log_loss, mean_absolute_error, mean_squared_error, roc_auc_score
from sklearn.model_selection import GroupKFold, TimeSeriesSplit, train_test_split
import lightgbm as lgb
from lightgbm.compat import PANDAS_INSTALLED, pd_DataFrame, pd_Series
from .utils import (
SERIALIZERS,
dummy_obj,
load_breast_cancer,
load_digits,
load_iris,
logistic_sigmoid,
make_synthetic_regression,
mse_obj,
pickle_and_unpickle_object,
sklearn_multiclass_custom_objective,
softmax,
)
decreasing_generator = itertools.count(0, -1)
def logloss_obj(preds, train_data):
y_true = train_data.get_label()
y_pred = logistic_sigmoid(preds)
grad = y_pred - y_true
hess = y_pred * (1.0 - y_pred)
return grad, hess
def multi_logloss(y_true, y_pred):
return np.mean([-math.log(y_pred[i][y]) for i, y in enumerate(y_true)])
def top_k_error(y_true, y_pred, k):
if k == y_pred.shape[1]:
return 0
max_rest = np.max(-np.partition(-y_pred, k)[:, k:], axis=1)
return 1 - np.mean((y_pred[np.arange(len(y_true)), y_true] > max_rest))
def constant_metric(preds, train_data):
return ("error", 0.0, False)
def decreasing_metric(preds, train_data):
return ("decreasing_metric", next(decreasing_generator), False)
def categorize(continuous_x):
return np.digitize(continuous_x, bins=np.arange(0, 1, 0.01))
def test_binary():
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
params = {
"objective": "binary",
"metric": "binary_logloss",
"verbose": -1,
"num_iteration": 50, # test num_iteration in dict here
}
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=20, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
ret = log_loss(y_test, gbm.predict(X_test))
assert ret < 0.14
assert len(evals_result["valid_0"]["binary_logloss"]) == 50
assert evals_result["valid_0"]["binary_logloss"][-1] == pytest.approx(ret)
def test_rf():
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
params = {
"boosting_type": "rf",
"objective": "binary",
"bagging_freq": 1,
"bagging_fraction": 0.5,
"feature_fraction": 0.5,
"num_leaves": 50,
"metric": "binary_logloss",
"verbose": -1,
}
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=50, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
ret = log_loss(y_test, gbm.predict(X_test))
assert ret < 0.19
assert evals_result["valid_0"]["binary_logloss"][-1] == pytest.approx(ret)
@pytest.mark.parametrize("objective", ["regression", "regression_l1", "huber", "fair", "poisson", "quantile"])
def test_regression(objective):
X, y = make_synthetic_regression()
y = np.abs(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
params = {"objective": objective, "metric": "l2", "verbose": -1}
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=50, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
ret = mean_squared_error(y_test, gbm.predict(X_test))
if objective == "huber":
assert ret < 430
elif objective == "fair":
assert ret < 296
elif objective == "poisson":
assert ret < 193
elif objective == "quantile":
assert ret < 1311
else:
assert ret < 343
assert evals_result["valid_0"]["l2"][-1] == pytest.approx(ret)
def test_missing_value_handle():
X_train = np.zeros((100, 1))
y_train = np.zeros(100)
trues = random.sample(range(100), 20)
for idx in trues:
X_train[idx, 0] = np.nan
y_train[idx] = 1
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_train, y_train)
params = {"metric": "l2", "verbose": -1, "boost_from_average": False}
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=20, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
ret = mean_squared_error(y_train, gbm.predict(X_train))
assert ret < 0.005
assert evals_result["valid_0"]["l2"][-1] == pytest.approx(ret)
def test_missing_value_handle_more_na():
X_train = np.ones((100, 1))
y_train = np.ones(100)
trues = random.sample(range(100), 80)
for idx in trues:
X_train[idx, 0] = np.nan
y_train[idx] = 0
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_train, y_train)
params = {"metric": "l2", "verbose": -1, "boost_from_average": False}
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=20, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
ret = mean_squared_error(y_train, gbm.predict(X_train))
assert ret < 0.005
assert evals_result["valid_0"]["l2"][-1] == pytest.approx(ret)
def test_missing_value_handle_na():
x = [0, 1, 2, 3, 4, 5, 6, 7, np.nan]
y = [1, 1, 1, 1, 0, 0, 0, 0, 1]
X_train = np.array(x).reshape(len(x), 1)
y_train = np.array(y)
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_train, y_train)
params = {
"objective": "regression",
"metric": "auc",
"verbose": -1,
"boost_from_average": False,
"min_data": 1,
"num_leaves": 2,
"learning_rate": 1,
"min_data_in_bin": 1,
"zero_as_missing": False,
}
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=1, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
pred = gbm.predict(X_train)
np.testing.assert_allclose(pred, y)
ret = roc_auc_score(y_train, pred)
assert ret > 0.999
assert evals_result["valid_0"]["auc"][-1] == pytest.approx(ret)
def test_missing_value_handle_zero():
x = [0, 1, 2, 3, 4, 5, 6, 7, np.nan]
y = [0, 1, 1, 1, 0, 0, 0, 0, 0]
X_train = np.array(x).reshape(len(x), 1)
y_train = np.array(y)
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_train, y_train)
params = {
"objective": "regression",
"metric": "auc",
"verbose": -1,
"boost_from_average": False,
"min_data": 1,
"num_leaves": 2,
"learning_rate": 1,
"min_data_in_bin": 1,
"zero_as_missing": True,
}
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=1, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
pred = gbm.predict(X_train)
np.testing.assert_allclose(pred, y)
ret = roc_auc_score(y_train, pred)
assert ret > 0.999
assert evals_result["valid_0"]["auc"][-1] == pytest.approx(ret)
def test_missing_value_handle_none():
x = [0, 1, 2, 3, 4, 5, 6, 7, np.nan]
y = [0, 1, 1, 1, 0, 0, 0, 0, 0]
X_train = np.array(x).reshape(len(x), 1)
y_train = np.array(y)
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_train, y_train)
params = {
"objective": "regression",
"metric": "auc",
"verbose": -1,
"boost_from_average": False,
"min_data": 1,
"num_leaves": 2,
"learning_rate": 1,
"min_data_in_bin": 1,
"use_missing": False,
}
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=1, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
pred = gbm.predict(X_train)
assert pred[0] == pytest.approx(pred[1])
assert pred[-1] == pytest.approx(pred[0])
ret = roc_auc_score(y_train, pred)
assert ret > 0.83
assert evals_result["valid_0"]["auc"][-1] == pytest.approx(ret)
@pytest.mark.parametrize(
"use_quantized_grad",
[
pytest.param(
True,
marks=pytest.mark.skipif(
getenv("TASK", "") == "cuda",
reason="Skip because quantized training with categorical features is not supported for cuda version",
),
),
False,
],
)
def test_categorical_handle(use_quantized_grad):
x = [0, 1, 2, 3, 4, 5, 6, 7]
y = [0, 1, 0, 1, 0, 1, 0, 1]
X_train = np.array(x).reshape(len(x), 1)
y_train = np.array(y)
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_train, y_train)
params = {
"objective": "regression",
"metric": "auc",
"verbose": -1,
"boost_from_average": False,
"min_data": 1,
"num_leaves": 2,
"learning_rate": 1,
"min_data_in_bin": 1,
"min_data_per_group": 1,
"cat_smooth": 1,
"cat_l2": 0,
"max_cat_to_onehot": 1,
"zero_as_missing": True,
"categorical_column": 0,
"use_quantized_grad": use_quantized_grad,
}
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=1, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
pred = gbm.predict(X_train)
np.testing.assert_allclose(pred, y)
ret = roc_auc_score(y_train, pred)
assert ret > 0.999
assert evals_result["valid_0"]["auc"][-1] == pytest.approx(ret)
@pytest.mark.parametrize(
"use_quantized_grad",
[
pytest.param(
True,
marks=pytest.mark.skipif(
getenv("TASK", "") == "cuda",
reason="Skip because quantized training with categorical features is not supported for cuda version",
),
),
False,
],
)
def test_categorical_handle_na(use_quantized_grad):
x = [0, np.nan, 0, np.nan, 0, np.nan]
y = [0, 1, 0, 1, 0, 1]
X_train = np.array(x).reshape(len(x), 1)
y_train = np.array(y)
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_train, y_train)
params = {
"objective": "regression",
"metric": "auc",
"verbose": -1,
"boost_from_average": False,
"min_data": 1,
"num_leaves": 2,
"learning_rate": 1,
"min_data_in_bin": 1,
"min_data_per_group": 1,
"cat_smooth": 1,
"cat_l2": 0,
"max_cat_to_onehot": 1,
"zero_as_missing": False,
"categorical_column": 0,
"use_quantized_grad": use_quantized_grad,
}
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=1, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
pred = gbm.predict(X_train)
np.testing.assert_allclose(pred, y)
ret = roc_auc_score(y_train, pred)
assert ret > 0.999
assert evals_result["valid_0"]["auc"][-1] == pytest.approx(ret)
@pytest.mark.parametrize(
"use_quantized_grad",
[
pytest.param(
True,
marks=pytest.mark.skipif(
getenv("TASK", "") == "cuda",
reason="Skip because quantized training with categorical features is not supported for cuda version",
),
),
False,
],
)
def test_categorical_non_zero_inputs(use_quantized_grad):
x = [1, 1, 1, 1, 1, 1, 2, 2]
y = [1, 1, 1, 1, 1, 1, 0, 0]
X_train = np.array(x).reshape(len(x), 1)
y_train = np.array(y)
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_train, y_train)
params = {
"objective": "regression",
"metric": "auc",
"verbose": -1,
"boost_from_average": False,
"min_data": 1,
"num_leaves": 2,
"learning_rate": 1,
"min_data_in_bin": 1,
"min_data_per_group": 1,
"cat_smooth": 1,
"cat_l2": 0,
"max_cat_to_onehot": 1,
"zero_as_missing": False,
"categorical_column": 0,
"use_quantized_grad": use_quantized_grad,
}
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=1, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
pred = gbm.predict(X_train)
np.testing.assert_allclose(pred, y)
ret = roc_auc_score(y_train, pred)
assert ret > 0.999
assert evals_result["valid_0"]["auc"][-1] == pytest.approx(ret)
def test_multiclass():
X, y = load_digits(n_class=10, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
params = {"objective": "multiclass", "metric": "multi_logloss", "num_class": 10, "verbose": -1}
lgb_train = lgb.Dataset(X_train, y_train, params=params)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train, params=params)
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=50, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
ret = multi_logloss(y_test, gbm.predict(X_test))
assert ret < 0.16
assert evals_result["valid_0"]["multi_logloss"][-1] == pytest.approx(ret)
def test_multiclass_rf():
X, y = load_digits(n_class=10, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
params = {
"boosting_type": "rf",
"objective": "multiclass",
"metric": "multi_logloss",
"bagging_freq": 1,
"bagging_fraction": 0.6,
"feature_fraction": 0.6,
"num_class": 10,
"num_leaves": 50,
"min_data": 1,
"verbose": -1,
"gpu_use_dp": True,
}
lgb_train = lgb.Dataset(X_train, y_train, params=params)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train, params=params)
evals_result = {}
gbm = lgb.train(
params, lgb_train, num_boost_round=50, valid_sets=lgb_eval, callbacks=[lgb.record_evaluation(evals_result)]
)
ret = multi_logloss(y_test, gbm.predict(X_test))
assert ret < 0.23
assert evals_result["valid_0"]["multi_logloss"][-1] == pytest.approx(ret)
def test_multiclass_prediction_early_stopping():
X, y = load_digits(n_class=10, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
params = {"objective": "multiclass", "metric": "multi_logloss", "num_class": 10, "verbose": -1}
lgb_train = lgb.Dataset(X_train, y_train, params=params)
gbm = lgb.train(params, lgb_train, num_boost_round=50)
pred_parameter = {"pred_early_stop": True, "pred_early_stop_freq": 5, "pred_early_stop_margin": 1.5}
ret = multi_logloss(y_test, gbm.predict(X_test, **pred_parameter))
assert ret < 0.8
assert ret > 0.6 # loss will be higher than when evaluating the full model
pred_parameter["pred_early_stop_margin"] = 5.5
ret = multi_logloss(y_test, gbm.predict(X_test, **pred_parameter))
assert ret < 0.2
def test_multi_class_error():
X, y = load_digits(n_class=10, return_X_y=True)
params = {"objective": "multiclass", "num_classes": 10, "metric": "multi_error", "num_leaves": 4, "verbose": -1}
lgb_data = lgb.Dataset(X, label=y)
est = lgb.train(params, lgb_data, num_boost_round=10)
predict_default = est.predict(X)
results = {}
est = lgb.train(
dict(params, multi_error_top_k=1),
lgb_data,
num_boost_round=10,
valid_sets=[lgb_data],
callbacks=[lgb.record_evaluation(results)],
)
predict_1 = est.predict(X)
# check that default gives same result as k = 1
np.testing.assert_allclose(predict_1, predict_default)
# check against independent calculation for k = 1
err = top_k_error(y, predict_1, 1)
assert results["training"]["multi_error"][-1] == pytest.approx(err)
# check against independent calculation for k = 2
results = {}
est = lgb.train(
dict(params, multi_error_top_k=2),
lgb_data,
num_boost_round=10,
valid_sets=[lgb_data],
callbacks=[lgb.record_evaluation(results)],
)
predict_2 = est.predict(X)
err = top_k_error(y, predict_2, 2)
assert results["training"]["multi_error@2"][-1] == pytest.approx(err)
# check against independent calculation for k = 10
results = {}
est = lgb.train(
dict(params, multi_error_top_k=10),
lgb_data,
num_boost_round=10,
valid_sets=[lgb_data],
callbacks=[lgb.record_evaluation(results)],
)
predict_3 = est.predict(X)
err = top_k_error(y, predict_3, 10)
assert results["training"]["multi_error@10"][-1] == pytest.approx(err)
# check cases where predictions are equal
X = np.array([[0, 0], [0, 0]])
y = np.array([0, 1])
lgb_data = lgb.Dataset(X, label=y)
params["num_classes"] = 2
results = {}
lgb.train(params, lgb_data, num_boost_round=10, valid_sets=[lgb_data], callbacks=[lgb.record_evaluation(results)])
assert results["training"]["multi_error"][-1] == pytest.approx(1)
results = {}
lgb.train(
dict(params, multi_error_top_k=2),
lgb_data,
num_boost_round=10,
valid_sets=[lgb_data],
callbacks=[lgb.record_evaluation(results)],
)
assert results["training"]["multi_error@2"][-1] == pytest.approx(0)
@pytest.mark.skipif(
getenv("TASK", "") == "cuda", reason="Skip due to differences in implementation details of CUDA version"
)
def test_auc_mu():
# should give same result as binary auc for 2 classes
X, y = load_digits(n_class=10, return_X_y=True)
y_new = np.zeros((len(y)))
y_new[y != 0] = 1
lgb_X = lgb.Dataset(X, label=y_new)
params = {"objective": "multiclass", "metric": "auc_mu", "verbose": -1, "num_classes": 2, "seed": 0}
results_auc_mu = {}
lgb.train(params, lgb_X, num_boost_round=10, valid_sets=[lgb_X], callbacks=[lgb.record_evaluation(results_auc_mu)])
params = {"objective": "binary", "metric": "auc", "verbose": -1, "seed": 0}
results_auc = {}
lgb.train(params, lgb_X, num_boost_round=10, valid_sets=[lgb_X], callbacks=[lgb.record_evaluation(results_auc)])
np.testing.assert_allclose(results_auc_mu["training"]["auc_mu"], results_auc["training"]["auc"])
# test the case where all predictions are equal
lgb_X = lgb.Dataset(X[:10], label=y_new[:10])
params = {
"objective": "multiclass",
"metric": "auc_mu",
"verbose": -1,
"num_classes": 2,
"min_data_in_leaf": 20,
"seed": 0,
}
results_auc_mu = {}
lgb.train(params, lgb_X, num_boost_round=10, valid_sets=[lgb_X], callbacks=[lgb.record_evaluation(results_auc_mu)])
assert results_auc_mu["training"]["auc_mu"][-1] == pytest.approx(0.5)
# test that weighted data gives different auc_mu
lgb_X = lgb.Dataset(X, label=y)
lgb_X_weighted = lgb.Dataset(X, label=y, weight=np.abs(np.random.normal(size=y.shape)))
results_unweighted = {}
results_weighted = {}
params = dict(params, num_classes=10, num_leaves=5)
lgb.train(
params, lgb_X, num_boost_round=10, valid_sets=[lgb_X], callbacks=[lgb.record_evaluation(results_unweighted)]
)
lgb.train(
params,
lgb_X_weighted,
num_boost_round=10,
valid_sets=[lgb_X_weighted],
callbacks=[lgb.record_evaluation(results_weighted)],
)
assert results_weighted["training"]["auc_mu"][-1] < 1
assert results_unweighted["training"]["auc_mu"][-1] != results_weighted["training"]["auc_mu"][-1]
# test that equal data weights give same auc_mu as unweighted data
lgb_X_weighted = lgb.Dataset(X, label=y, weight=np.ones(y.shape) * 0.5)
lgb.train(
params,
lgb_X_weighted,
num_boost_round=10,
valid_sets=[lgb_X_weighted],
callbacks=[lgb.record_evaluation(results_weighted)],
)
assert results_unweighted["training"]["auc_mu"][-1] == pytest.approx(
results_weighted["training"]["auc_mu"][-1], abs=1e-5
)
# should give 1 when accuracy = 1
X = X[:10, :]
y = y[:10]
lgb_X = lgb.Dataset(X, label=y)
params = {"objective": "multiclass", "metric": "auc_mu", "num_classes": 10, "min_data_in_leaf": 1, "verbose": -1}
results = {}
lgb.train(params, lgb_X, num_boost_round=100, valid_sets=[lgb_X], callbacks=[lgb.record_evaluation(results)])
assert results["training"]["auc_mu"][-1] == pytest.approx(1)
# test loading class weights
Xy = np.loadtxt(
str(Path(__file__).absolute().parents[2] / "examples" / "multiclass_classification" / "multiclass.train")
)
y = Xy[:, 0]
X = Xy[:, 1:]
lgb_X = lgb.Dataset(X, label=y)
params = {
"objective": "multiclass",
"metric": "auc_mu",
"auc_mu_weights": [0, 2, 2, 2, 2, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0],
"num_classes": 5,
"verbose": -1,
"seed": 0,
}
results_weight = {}
lgb.train(params, lgb_X, num_boost_round=5, valid_sets=[lgb_X], callbacks=[lgb.record_evaluation(results_weight)])
params["auc_mu_weights"] = []
results_no_weight = {}
lgb.train(
params, lgb_X, num_boost_round=5, valid_sets=[lgb_X], callbacks=[lgb.record_evaluation(results_no_weight)]
)
assert results_weight["training"]["auc_mu"][-1] != results_no_weight["training"]["auc_mu"][-1]
def test_ranking_prediction_early_stopping():
rank_example_dir = Path(__file__).absolute().parents[2] / "examples" / "lambdarank"
X_train, y_train = load_svmlight_file(str(rank_example_dir / "rank.train"))
q_train = np.loadtxt(str(rank_example_dir / "rank.train.query"))
X_test, _ = load_svmlight_file(str(rank_example_dir / "rank.test"))
params = {"objective": "rank_xendcg", "verbose": -1}
lgb_train = lgb.Dataset(X_train, y_train, group=q_train, params=params)
gbm = lgb.train(params, lgb_train, num_boost_round=50)
pred_parameter = {"pred_early_stop": True, "pred_early_stop_freq": 5, "pred_early_stop_margin": 1.5}
ret_early = gbm.predict(X_test, **pred_parameter)
pred_parameter["pred_early_stop_margin"] = 5.5
ret_early_more_strict = gbm.predict(X_test, **pred_parameter)
with pytest.raises(AssertionError):
np.testing.assert_allclose(ret_early, ret_early_more_strict)
# Simulates position bias for a given ranking dataset.
# The ouput dataset is identical to the input one with the exception for the relevance labels.
# The new labels are generated according to an instance of a cascade user model:
# for each query, the user is simulated to be traversing the list of documents ranked by a baseline ranker
# (in our example it is simply the ordering by some feature correlated with relevance, e.g., 34)
# and clicks on that document (new_label=1) with some probability 'pclick' depending on its true relevance;
# at each position the user may stop the traversal with some probability pstop. For the non-clicked documents,
# new_label=0. Thus the generated new labels are biased towards the baseline ranker.
# The positions of the documents in the ranked lists produced by the baseline, are returned.
def simulate_position_bias(file_dataset_in, file_query_in, file_dataset_out, baseline_feature):
# a mapping of a document's true relevance (defined on a 5-grade scale) into the probability of clicking it
def get_pclick(label):
if label == 0:
return 0.4
elif label == 1:
return 0.6
elif label == 2:
return 0.7
elif label == 3:
return 0.8
else:
return 0.9
# an instantiation of a cascade model where the user stops with probability 0.2 after observing each document
pstop = 0.2
f_dataset_in = open(file_dataset_in, "r")
f_dataset_out = open(file_dataset_out, "w")
random.seed(10)
positions_all = []
for line in open(file_query_in):
docs_num = int(line)
lines = []
index_values = []
positions = [0] * docs_num
for index in range(docs_num):
features = f_dataset_in.readline().split()
lines.append(features)
val = 0.0
for feature_val in features:
feature_val_split = feature_val.split(":")
if int(feature_val_split[0]) == baseline_feature:
val = float(feature_val_split[1])
index_values.append([index, val])
index_values.sort(key=lambda x: -x[1])
stop = False
for pos in range(docs_num):
index = index_values[pos][0]
new_label = 0
if not stop:
label = int(lines[index][0])
pclick = get_pclick(label)
if random.random() < pclick:
new_label = 1
stop = random.random() < pstop
lines[index][0] = str(new_label)
positions[index] = pos
for features in lines:
f_dataset_out.write(" ".join(features) + "\n")
positions_all.extend(positions)
f_dataset_out.close()
return positions_all
@pytest.mark.skipif(
getenv("TASK", "") == "cuda", reason="Positions in learning to rank is not supported in CUDA version yet"
)
def test_ranking_with_position_information_with_file(tmp_path):
rank_example_dir = Path(__file__).absolute().parents[2] / "examples" / "lambdarank"
params = {
"objective": "lambdarank",
"verbose": -1,
"eval_at": [3],
"metric": "ndcg",
"bagging_freq": 1,
"bagging_fraction": 0.9,
"min_data_in_leaf": 50,
"min_sum_hessian_in_leaf": 5.0,
}
# simulate position bias for the train dataset and put the train dataset with biased labels to temp directory
positions = simulate_position_bias(
str(rank_example_dir / "rank.train"),
str(rank_example_dir / "rank.train.query"),
str(tmp_path / "rank.train"),
baseline_feature=34,
)
copyfile(str(rank_example_dir / "rank.train.query"), str(tmp_path / "rank.train.query"))
copyfile(str(rank_example_dir / "rank.test"), str(tmp_path / "rank.test"))
copyfile(str(rank_example_dir / "rank.test.query"), str(tmp_path / "rank.test.query"))
lgb_train = lgb.Dataset(str(tmp_path / "rank.train"), params=params)
lgb_valid = [lgb_train.create_valid(str(tmp_path / "rank.test"))]
gbm_baseline = lgb.train(params, lgb_train, valid_sets=lgb_valid, num_boost_round=50)
f_positions_out = open(str(tmp_path / "rank.train.position"), "w")
for pos in positions:
f_positions_out.write(str(pos) + "\n")
f_positions_out.close()
lgb_train = lgb.Dataset(str(tmp_path / "rank.train"), params=params)
lgb_valid = [lgb_train.create_valid(str(tmp_path / "rank.test"))]
gbm_unbiased_with_file = lgb.train(params, lgb_train, valid_sets=lgb_valid, num_boost_round=50)
# the performance of the unbiased LambdaMART should outperform the plain LambdaMART on the dataset with position bias
assert gbm_baseline.best_score["valid_0"]["ndcg@3"] + 0.03 <= gbm_unbiased_with_file.best_score["valid_0"]["ndcg@3"]
# add extra row to position file
with open(str(tmp_path / "rank.train.position"), "a") as file:
file.write("pos_1000\n")
file.close()
lgb_train = lgb.Dataset(str(tmp_path / "rank.train"), params=params)
lgb_valid = [lgb_train.create_valid(str(tmp_path / "rank.test"))]
with pytest.raises(lgb.basic.LightGBMError, match=r"Positions size \(3006\) doesn't match data size"):
lgb.train(params, lgb_train, valid_sets=lgb_valid, num_boost_round=50)
@pytest.mark.skipif(
getenv("TASK", "") == "cuda", reason="Positions in learning to rank is not supported in CUDA version yet"
)
def test_ranking_with_position_information_with_dataset_constructor(tmp_path):
rank_example_dir = Path(__file__).absolute().parents[2] / "examples" / "lambdarank"
params = {
"objective": "lambdarank",
"verbose": -1,
"eval_at": [3],
"metric": "ndcg",
"bagging_freq": 1,
"bagging_fraction": 0.9,
"min_data_in_leaf": 50,
"min_sum_hessian_in_leaf": 5.0,
"num_threads": 1,
"deterministic": True,
"seed": 0,
}
# simulate position bias for the train dataset and put the train dataset with biased labels to temp directory
positions = simulate_position_bias(
str(rank_example_dir / "rank.train"),
str(rank_example_dir / "rank.train.query"),
str(tmp_path / "rank.train"),
baseline_feature=34,
)
copyfile(str(rank_example_dir / "rank.train.query"), str(tmp_path / "rank.train.query"))
copyfile(str(rank_example_dir / "rank.test"), str(tmp_path / "rank.test"))
copyfile(str(rank_example_dir / "rank.test.query"), str(tmp_path / "rank.test.query"))
lgb_train = lgb.Dataset(str(tmp_path / "rank.train"), params=params)
lgb_valid = [lgb_train.create_valid(str(tmp_path / "rank.test"))]
gbm_baseline = lgb.train(params, lgb_train, valid_sets=lgb_valid, num_boost_round=50)
positions = np.array(positions)
# test setting positions through Dataset constructor with numpy array
lgb_train = lgb.Dataset(str(tmp_path / "rank.train"), params=params, position=positions)
lgb_valid = [lgb_train.create_valid(str(tmp_path / "rank.test"))]
gbm_unbiased = lgb.train(params, lgb_train, valid_sets=lgb_valid, num_boost_round=50)
# the performance of the unbiased LambdaMART should outperform the plain LambdaMART on the dataset with position bias
assert gbm_baseline.best_score["valid_0"]["ndcg@3"] + 0.03 <= gbm_unbiased.best_score["valid_0"]["ndcg@3"]
if PANDAS_INSTALLED:
# test setting positions through Dataset constructor with pandas Series
lgb_train = lgb.Dataset(str(tmp_path / "rank.train"), params=params, position=pd_Series(positions))
lgb_valid = [lgb_train.create_valid(str(tmp_path / "rank.test"))]
gbm_unbiased_pandas_series = lgb.train(params, lgb_train, valid_sets=lgb_valid, num_boost_round=50)
assert (
gbm_unbiased.best_score["valid_0"]["ndcg@3"] == gbm_unbiased_pandas_series.best_score["valid_0"]["ndcg@3"]
)
# test setting positions through set_position
lgb_train = lgb.Dataset(str(tmp_path / "rank.train"), params=params)
lgb_valid = [lgb_train.create_valid(str(tmp_path / "rank.test"))]
lgb_train.set_position(positions)
gbm_unbiased_set_position = lgb.train(params, lgb_train, valid_sets=lgb_valid, num_boost_round=50)
assert gbm_unbiased.best_score["valid_0"]["ndcg@3"] == gbm_unbiased_set_position.best_score["valid_0"]["ndcg@3"]
# test get_position works
positions_from_get = lgb_train.get_position()
np.testing.assert_array_equal(positions_from_get, positions)
def test_early_stopping():
X, y = load_breast_cancer(return_X_y=True)
params = {"objective": "binary", "metric": "binary_logloss", "verbose": -1}
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
valid_set_name = "valid_set"
# no early stopping
gbm = lgb.train(
params,
lgb_train,
num_boost_round=10,
valid_sets=lgb_eval,
valid_names=valid_set_name,
callbacks=[lgb.early_stopping(stopping_rounds=5)],
)
assert gbm.best_iteration == 10
assert valid_set_name in gbm.best_score
assert "binary_logloss" in gbm.best_score[valid_set_name]
# early stopping occurs
gbm = lgb.train(
params,
lgb_train,
num_boost_round=40,
valid_sets=lgb_eval,
valid_names=valid_set_name,
callbacks=[lgb.early_stopping(stopping_rounds=5)],
)
assert gbm.best_iteration <= 39
assert valid_set_name in gbm.best_score
assert "binary_logloss" in gbm.best_score[valid_set_name]
@pytest.mark.parametrize("use_valid", [True, False])
def test_early_stopping_ignores_training_set(use_valid):
x = np.linspace(-1, 1, 100)
X = x.reshape(-1, 1)
y = x**2
X_train, X_valid = X[:80], X[80:]
y_train, y_valid = y[:80], y[80:]
train_ds = lgb.Dataset(X_train, y_train)
valid_ds = lgb.Dataset(X_valid, y_valid)
valid_sets = [train_ds]
valid_names = ["train"]
if use_valid:
valid_sets.append(valid_ds)
valid_names.append("valid")
eval_result = {}
def train_fn():
return lgb.train(
{"num_leaves": 5},
train_ds,
num_boost_round=2,
valid_sets=valid_sets,
valid_names=valid_names,
callbacks=[lgb.early_stopping(1), lgb.record_evaluation(eval_result)],
)
if use_valid:
bst = train_fn()
assert bst.best_iteration == 1
assert eval_result["train"]["l2"][1] < eval_result["train"]["l2"][0] # train improved
assert eval_result["valid"]["l2"][1] > eval_result["valid"]["l2"][0] # valid didn't
else:
with pytest.warns(UserWarning, match="Only training set found, disabling early stopping."):
bst = train_fn()
assert bst.current_iteration() == 2
assert bst.best_iteration == 0
@pytest.mark.parametrize("first_metric_only", [True, False])
def test_early_stopping_via_global_params(first_metric_only):
X, y = load_breast_cancer(return_X_y=True)
num_trees = 5
params = {
"num_trees": num_trees,
"objective": "binary",
"metric": "None",
"verbose": -1,
"early_stopping_round": 2,
"first_metric_only": first_metric_only,
}
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
valid_set_name = "valid_set"
gbm = lgb.train(
params, lgb_train, feval=[decreasing_metric, constant_metric], valid_sets=lgb_eval, valid_names=valid_set_name
)
if first_metric_only:
assert gbm.best_iteration == num_trees
else:
assert gbm.best_iteration == 1
assert valid_set_name in gbm.best_score
assert "decreasing_metric" in gbm.best_score[valid_set_name]
assert "error" in gbm.best_score[valid_set_name]
@pytest.mark.parametrize("first_only", [True, False])
@pytest.mark.parametrize("single_metric", [True, False])
@pytest.mark.parametrize("greater_is_better", [True, False])
def test_early_stopping_min_delta(first_only, single_metric, greater_is_better):
if single_metric and not first_only:
pytest.skip("first_metric_only doesn't affect single metric.")
metric2min_delta = {
"auc": 0.001,
"binary_logloss": 0.01,
"average_precision": 0.001,
"mape": 0.01,
}
if single_metric:
if greater_is_better:
metric = "auc"
else:
metric = "binary_logloss"
else:
if first_only:
if greater_is_better:
metric = ["auc", "binary_logloss"]
else:
metric = ["binary_logloss", "auc"]
else:
if greater_is_better:
metric = ["auc", "average_precision"]
else:
metric = ["binary_logloss", "mape"]
X, y = load_breast_cancer(return_X_y=True)
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2, random_state=0)
train_ds = lgb.Dataset(X_train, y_train)
valid_ds = lgb.Dataset(X_valid, y_valid, reference=train_ds)
params = {"objective": "binary", "metric": metric, "verbose": -1}
if isinstance(metric, str):
min_delta = metric2min_delta[metric]
elif first_only:
min_delta = metric2min_delta[metric[0]]
else:
min_delta = [metric2min_delta[m] for m in metric]
train_kwargs = {
"params": params,
"train_set": train_ds,
"num_boost_round": 50,
"valid_sets": [train_ds, valid_ds],
"valid_names": ["training", "valid"],
}
# regular early stopping
evals_result = {}
train_kwargs["callbacks"] = [
lgb.callback.early_stopping(10, first_only, verbose=False),
lgb.record_evaluation(evals_result),
]
bst = lgb.train(**train_kwargs)
scores = np.vstack(list(evals_result["valid"].values())).T
# positive min_delta
delta_result = {}