-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
test.py
5805 lines (4755 loc) · 213 KB
/
test.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
from collections import OrderedDict
import hashlib
import math
import numpy as np
import pprint
import pytest
import random
import re
import subprocess
import sys
import tempfile
import json
from catboost import (
CatBoost,
CatBoostClassifier,
CatBoostRegressor,
CatBoostError,
EFstrType,
FeaturesData,
Pool,
cv,
sum_models,
train,
_have_equal_features,)
from catboost.eval.catboost_evaluation import CatboostEvaluation, EvalType
from catboost.utils import eval_metric, create_cd, read_cd, get_roc_curve, select_threshold
from catboost.utils import DataMetaInfo, TargetStats, compute_training_options
import os.path
import os
from pandas import read_csv, DataFrame, Series, Categorical, SparseArray
from six import PY3
from six.moves import xrange
import scipy.sparse
from catboost_pytest_lib import (
DelayedTee,
binary_path,
data_file,
local_canonical_file,
permute_dataset_columns,
remove_time_from_json,
test_output_path,
generate_random_labeled_set,
load_dataset_as_dataframe,
load_pool_features_as_df
)
if sys.version_info.major == 2:
import cPickle as pickle
else:
import _pickle as pickle
pytest_plugins = "list_plugin",
fails_on_gpu = pytest.mark.fails_on_gpu
EPS = 1e-5
BOOSTING_TYPE = ['Ordered', 'Plain']
OVERFITTING_DETECTOR_TYPE = ['IncToDec', 'Iter']
NONSYMMETRIC = ['Lossguide', 'Depthwise']
TRAIN_FILE = data_file('adult', 'train_small')
TEST_FILE = data_file('adult', 'test_small')
CD_FILE = data_file('adult', 'train.cd')
NAN_TRAIN_FILE = data_file('adult_nan', 'train_small')
NAN_TEST_FILE = data_file('adult_nan', 'test_small')
NAN_CD_FILE = data_file('adult_nan', 'train.cd')
CLOUDNESS_TRAIN_FILE = data_file('cloudness_small', 'train_small')
CLOUDNESS_TEST_FILE = data_file('cloudness_small', 'test_small')
CLOUDNESS_CD_FILE = data_file('cloudness_small', 'train.cd')
QUERYWISE_TRAIN_FILE = data_file('querywise', 'train')
QUERYWISE_TEST_FILE = data_file('querywise', 'test')
QUERYWISE_CD_FILE = data_file('querywise', 'train.cd')
QUERYWISE_CD_FILE_WITH_GROUP_WEIGHT = data_file('querywise', 'train.cd.group_weight')
QUERYWISE_CD_FILE_WITH_GROUP_ID = data_file('querywise', 'train.cd.query_id')
QUERYWISE_CD_FILE_WITH_SUBGROUP_ID = data_file('querywise', 'train.cd.subgroup_id')
QUERYWISE_TRAIN_PAIRS_FILE = data_file('querywise', 'train.pairs')
QUERYWISE_TRAIN_PAIRS_FILE_WITH_PAIR_WEIGHT = data_file('querywise', 'train.pairs.weighted')
QUERYWISE_TEST_PAIRS_FILE = data_file('querywise', 'test.pairs')
QUANTIZED_TRAIN_FILE = data_file('quantized_adult', 'train.qbin')
QUANTIZED_TEST_FILE = data_file('quantized_adult', 'test.qbin')
QUANTIZED_CD_FILE = data_file('quantized_adult', 'pool.cd')
AIRLINES_5K_TRAIN_FILE = data_file('airlines_5K', 'train')
AIRLINES_5K_TEST_FILE = data_file('airlines_5K', 'test')
AIRLINES_5K_CD_FILE = data_file('airlines_5K', 'cd')
SMALL_CATEGORIAL_FILE = data_file('small_categorial', 'train')
SMALL_CATEGORIAL_CD_FILE = data_file('small_categorial', 'train.cd')
BLACK_FRIDAY_TRAIN_FILE = data_file('black_friday', 'train')
BLACK_FRIDAY_TEST_FILE = data_file('black_friday', 'test')
BLACK_FRIDAY_CD_FILE = data_file('black_friday', 'cd')
HIGGS_TRAIN_FILE = data_file('higgs', 'train_small')
HIGGS_TEST_FILE = data_file('higgs', 'test_small')
HIGGS_CD_FILE = data_file('higgs', 'train.cd')
AIRLINES_ONEHOT_TRAIN_FILE = data_file('airlines_onehot_250', 'train_small')
AIRLINES_ONEHOT_TEST_FILE = data_file('airlines_onehot_250', 'test_small')
AIRLINES_ONEHOT_CD_FILE = data_file('airlines_onehot_250', 'train.cd')
CONVERT_LIGHT_GBM_PREDICTIONS = data_file('convertions_models', 'predict')
CONVERT_RANDOM_GENERATED_TEST = data_file('convertions_models', 'test')
CONVERT_MODEL_ONNX = data_file('convertions_models', 'model_gbm.onnx')
OUTPUT_MODEL_PATH = 'model.bin'
OUTPUT_COREML_MODEL_PATH = 'model.mlmodel'
OUTPUT_CPP_MODEL_PATH = 'model.cpp'
OUTPUT_PYTHON_MODEL_PATH = 'model.py'
OUTPUT_JSON_MODEL_PATH = 'model.json'
OUTPUT_ONNX_MODEL_PATH = 'model.onnx'
OUTPUT_PMML_MODEL_PATH = 'model.pmml'
PREDS_PATH = 'predictions.npy'
PREDS_TXT_PATH = 'predictions.txt'
FIMP_NPY_PATH = 'feature_importance.npy'
FIMP_TXT_PATH = 'feature_importance.txt'
OIMP_PATH = 'object_importances.txt'
JSON_LOG_PATH = 'catboost_info/catboost_training.json'
OUTPUT_QUANTIZED_POOL_PATH = 'quantized_pool.bin'
TARGET_IDX = 1
CAT_FEATURES = [0, 1, 2, 4, 6, 8, 9, 10, 11, 12, 16]
CAT_COLUMNS = [0, 2, 3, 5, 7, 9, 10, 11, 12, 13, 17]
model_diff_tool = binary_path("catboost/tools/model_comparator/model_comparator")
np.set_printoptions(legacy='1.13')
class LogStdout:
def __init__(self, file):
self.log_file = file
def __enter__(self):
self.saved_stdout = sys.stdout
sys.stdout = self.log_file
return self.saved_stdout
def __exit__(self, exc_type, exc_value, exc_traceback):
sys.stdout = self.saved_stdout
self.log_file.close()
def compare_canonical_models(model, diff_limit=0):
return local_canonical_file(model, diff_tool=[model_diff_tool, '--diff-limit', str(diff_limit)])
def _check_shape(pool, object_count, features_count):
return pool.shape == (object_count, features_count)
def _check_data(data1, data2):
return np.all(np.isclose(data1, data2, rtol=0.001, equal_nan=True))
def _count_lines(afile):
with open(afile, 'r') as f:
num_lines = sum(1 for line in f)
return num_lines
def _generate_nontrivial_binary_target(num, seed=20181219, prng=None):
'''
Generate binary vector with non zero variance
:param num:
:return:
'''
if prng is None:
prng = np.random.RandomState(seed=seed)
def gen():
return prng.randint(0, 2, size=num)
if num <= 1:
return gen()
y = gen() # 0/1 labels
while y.min() == y.max():
y = gen()
return y
def _generate_random_target(num, seed=20181219, prng=None):
if prng is None:
prng = np.random.RandomState(seed=seed)
return prng.random_sample((num,))
def set_random_weight(pool, seed=20181219, prng=None):
if prng is None:
prng = np.random.RandomState(seed=seed)
pool.set_weight(prng.random_sample(pool.num_row()))
if pool.num_pairs() > 0:
pool.set_pairs_weight(prng.random_sample(pool.num_pairs()))
def verify_finite(result):
inf = float('inf')
for r in result:
assert(r == r)
assert(abs(r) < inf)
def append_param(metric_name, param):
return metric_name + (':' if ':' not in metric_name else ';') + param
# returns (features_data, labels)
def load_simple_dataset_as_lists(is_test):
features_data = []
labels = []
with open(TEST_FILE if is_test else TRAIN_FILE) as data_file:
for l in data_file:
elements = l[:-1].split('\t')
features_data.append([])
for column_idx, element in enumerate(elements):
if column_idx == TARGET_IDX:
labels.append(element)
else:
features_data[-1].append(element if column_idx in CAT_COLUMNS else float(element))
return features_data, labels
# Test cases begin here ########################################################
def test_load_file():
assert _check_shape(Pool(TRAIN_FILE, column_description=CD_FILE), 101, 17)
def test_load_list():
features_data, labels = load_simple_dataset_as_lists(is_test=False)
assert _check_shape(Pool(features_data, labels, CAT_FEATURES), 101, 17)
@pytest.mark.parametrize(
'dtype',
[np.float32, np.float64, object],
ids=['dtype=np.float32', 'dtype=np.float64', 'dtype=object']
)
@pytest.mark.parametrize('order', ['C', 'F'], ids=['order=C', 'order=F'])
def test_load_ndarray_vs_load_from_file(dtype, order):
if dtype is object: # mixed numeric and categorical features data
n_features = 17
n_objects = 101
train_file = TRAIN_FILE
cd_file = CD_FILE
target_column_idx = TARGET_IDX
cat_column_indices = CAT_COLUMNS
cat_feature_indices = CAT_FEATURES
else:
n_features = 28
n_objects = 101
train_file = HIGGS_TRAIN_FILE
cd_file = HIGGS_CD_FILE
target_column_idx = 0
cat_column_indices = []
cat_feature_indices = []
pool_from_file = Pool(train_file, column_description=cd_file)
features_data = np.empty((n_objects, n_features), dtype=dtype, order=order)
labels = np.empty(n_objects, dtype=float)
with open(train_file) as train_input:
for line_idx, l in enumerate(train_input.readlines()):
elements = l[:-1].split('\t')
feature_idx = 0
for column_idx, element in enumerate(elements):
if column_idx == target_column_idx:
labels[line_idx] = float(element)
else:
features_data[line_idx, feature_idx] = (
element if (dtype is object) or (column_idx in cat_column_indices) else dtype(element)
)
feature_idx += 1
pool_from_ndarray = Pool(features_data, labels, cat_features=cat_feature_indices)
assert _have_equal_features(pool_from_file, pool_from_ndarray)
assert _check_data([float(label) for label in pool_from_file.get_label()], pool_from_ndarray.get_label())
@pytest.mark.parametrize('dataset', ['adult', 'adult_nan', 'querywise'])
def test_load_df_vs_load_from_file(dataset):
train_file, cd_file, target_idx, group_id_idx, other_non_feature_columns = {
'adult': (TRAIN_FILE, CD_FILE, TARGET_IDX, None, []),
'adult_nan': (NAN_TRAIN_FILE, NAN_CD_FILE, TARGET_IDX, None, []),
'querywise': (QUERYWISE_TRAIN_FILE, QUERYWISE_CD_FILE, 2, 1, [0, 3, 4])
}[dataset]
pool1 = Pool(train_file, column_description=cd_file)
data = read_csv(train_file, header=None, delimiter='\t')
labels = data.iloc[:, target_idx]
group_ids = None
if group_id_idx:
group_ids = [int(group_id) for group_id in data.iloc[:, group_id_idx]]
data.drop(
[target_idx] + ([group_id_idx] if group_id_idx else []) + other_non_feature_columns,
axis=1,
inplace=True
)
cat_features = pool1.get_cat_feature_indices()
pool1.set_feature_names(list(data.columns))
pool2 = Pool(data, labels, cat_features, group_id=group_ids)
assert _have_equal_features(pool1, pool2)
assert _check_data([float(label) for label in pool1.get_label()], pool2.get_label())
def test_load_series():
pool = Pool(TRAIN_FILE, column_description=CD_FILE)
data = read_csv(TRAIN_FILE, header=None, delimiter='\t')
labels = Series(data.iloc[:, TARGET_IDX])
data.drop([TARGET_IDX], axis=1, inplace=True)
data = Series(list(data.values))
cat_features = pool.get_cat_feature_indices()
pool2 = Pool(data, labels, cat_features)
assert _have_equal_features(pool, pool2)
assert [int(label) for label in pool.get_label()] == pool2.get_label()
def test_pool_cat_features():
pool = Pool(TRAIN_FILE, column_description=CD_FILE)
assert np.all(pool.get_cat_feature_indices() == CAT_FEATURES)
def test_pool_cat_features_as_strings():
df = DataFrame(data=[[1, 2], [3, 4]], columns=['col1', 'col2'])
pool = Pool(df, cat_features=['col2'])
assert np.all(pool.get_cat_feature_indices() == [1])
data = [[1, 2, 3], [4, 5, 6]]
pool = Pool(data, feature_names=['col1', 'col2', 'col3'], cat_features=['col2', 'col3'])
assert np.all(pool.get_cat_feature_indices() == [1, 2])
data = [[1, 2, 3], [4, 5, 6]]
with pytest.raises(CatBoostError):
Pool(data, cat_features=['col2', 'col3'])
def test_load_generated():
pool_size = (100, 10)
prng = np.random.RandomState(seed=20181219)
data = np.round(prng.normal(size=pool_size), decimals=3)
label = _generate_nontrivial_binary_target(pool_size[0], prng=prng)
pool = Pool(data, label)
assert _check_data(pool.get_features(), data)
assert _check_data(pool.get_label(), label)
def test_load_dumps():
pool_size = (100, 10)
prng = np.random.RandomState(seed=20181219)
data = prng.randint(10, size=pool_size)
labels = _generate_nontrivial_binary_target(pool_size[0], prng=prng)
pool1 = Pool(data, labels)
lines = []
for i in range(len(data)):
line = [str(labels[i])] + [str(x) for x in data[i]]
lines.append('\t'.join(line))
text = '\n'.join(lines)
with open('test_data_dumps', 'w') as f:
f.write(text)
pool2 = Pool('test_data_dumps')
assert _check_data(pool1.get_features(), pool2.get_features())
assert pool1.get_label() == [int(label) for label in pool2.get_label()]
@pytest.mark.parametrize(
'cat_features_specified',
[False, True],
ids=['cat_features_specified=False', 'cat_features_specified=True']
)
def test_dataframe_with_pandas_categorical_columns(cat_features_specified):
df = DataFrame()
df['num_feat_0'] = [0, 1, 0, 2, 3, 1, 2]
df['num_feat_1'] = [0.12, 0.8, 0.33, 0.11, 0.0, 1.0, 0.0]
df['cat_feat_2'] = Series(['A', 'B', 'A', 'C', 'A', 'A', 'A'], dtype='category')
df['cat_feat_3'] = Series(['x', 'x', 'y', 'y', 'y', 'x', 'x'])
df['cat_feat_4'] = Categorical(
['large', 'small', 'medium', 'large', 'small', 'small', 'medium'],
categories=['small', 'medium', 'large'],
ordered=True
)
df['cat_feat_5'] = [0, 1, 0, 2, 3, 1, 2]
labels = [0, 1, 1, 0, 1, 0, 1]
model = CatBoostClassifier(iterations=2)
if cat_features_specified:
model.fit(X=df, y=labels, cat_features=[2, 3, 4, 5])
pred = model.predict(df)
preds_path = test_output_path(PREDS_TXT_PATH)
np.savetxt(preds_path, np.array(pred), fmt='%.8f')
return local_canonical_file(preds_path)
else:
with pytest.raises(CatBoostError):
model.fit(X=df, y=labels)
def test_equivalence_of_pools_from_pandas_dataframe_with_different_cat_features_column_types():
df = DataFrame()
df['num_feat_0'] = [0, 1, 0, 2, 3, 1, 2]
df['num_feat_1'] = [0.12, 0.8, 0.33, 0.11, 0.0, 1.0, 0.0]
df['cat_feat_2'] = ['A', 'B', 'A', 'C', 'A', 'A', 'A']
df['cat_feat_3'] = ['x', 'x', 'y', 'y', 'y', 'x', 'x']
df['cat_feat_4'] = ['large', 'small', 'medium', 'large', 'small', 'small', 'medium']
df['cat_feat_5'] = [0, 1, 0, 2, 3, 1, 2]
labels = [0, 1, 1, 0, 1, 0, 1]
cat_features = ['cat_feat_%i' % i for i in range(2, 6)]
pool_from_df = Pool(df, labels, cat_features=cat_features)
for cat_features_dtype in ['object', 'category']:
columns_for_new_df = OrderedDict()
for column_name, column_data in df.iteritems():
if column_name in cat_features:
column_data = column_data.astype(cat_features_dtype)
columns_for_new_df.setdefault(column_name, column_data)
new_df = DataFrame(columns_for_new_df)
pool_from_new_df = Pool(new_df, labels, cat_features=cat_features)
assert _have_equal_features(pool_from_df, pool_from_new_df)
# feature_matrix is (doc_count x feature_count)
def get_features_data_from_matrix(feature_matrix, cat_feature_indices, order='C'):
object_count = len(feature_matrix)
feature_count = len(feature_matrix[0])
cat_feature_count = len(cat_feature_indices)
num_feature_count = feature_count - cat_feature_count
result_num = np.empty((object_count, num_feature_count), dtype=np.float32, order=order)
result_cat = np.empty((object_count, cat_feature_count), dtype=object, order=order)
for object_idx in xrange(object_count):
num_feature_idx = 0
cat_feature_idx = 0
for feature_idx in xrange(len(feature_matrix[object_idx])):
if (cat_feature_idx < cat_feature_count) and (cat_feature_indices[cat_feature_idx] == feature_idx):
# simplified handling of transformation to bytes for tests
result_cat[object_idx, cat_feature_idx] = (
feature_matrix[object_idx, feature_idx]
if isinstance(feature_matrix[object_idx, feature_idx], bytes)
else str(feature_matrix[object_idx, feature_idx]).encode('utf-8')
)
cat_feature_idx += 1
else:
result_num[object_idx, num_feature_idx] = float(feature_matrix[object_idx, feature_idx])
num_feature_idx += 1
return FeaturesData(num_feature_data=result_num, cat_feature_data=result_cat)
def get_features_data_from_file(data_file, drop_columns, cat_feature_indices, order='C'):
data_matrix_from_file = read_csv(data_file, header=None, dtype=str, delimiter='\t')
data_matrix_from_file.drop(drop_columns, axis=1, inplace=True)
return get_features_data_from_matrix(np.array(data_matrix_from_file), cat_feature_indices, order)
def test_features_data_with_empty_objects():
fd = FeaturesData(
cat_feature_data=np.empty((0, 4), dtype=object)
)
assert fd.get_object_count() == 0
assert fd.get_feature_count() == 4
assert fd.get_num_feature_count() == 0
assert fd.get_cat_feature_count() == 4
assert fd.get_feature_names() == [''] * 4
fd = FeaturesData(
num_feature_data=np.empty((0, 2), dtype=np.float32),
num_feature_names=['f0', 'f1']
)
assert fd.get_object_count() == 0
assert fd.get_feature_count() == 2
assert fd.get_num_feature_count() == 2
assert fd.get_cat_feature_count() == 0
assert fd.get_feature_names() == ['f0', 'f1']
fd = FeaturesData(
cat_feature_data=np.empty((0, 2), dtype=object),
num_feature_data=np.empty((0, 3), dtype=np.float32)
)
assert fd.get_object_count() == 0
assert fd.get_feature_count() == 5
assert fd.get_num_feature_count() == 3
assert fd.get_cat_feature_count() == 2
assert fd.get_feature_names() == [''] * 5
def test_features_data_names():
# empty specification of names
fd = FeaturesData(
cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object),
num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32),
)
assert fd.get_feature_names() == [''] * 5
# full specification of names
fd = FeaturesData(
cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object),
cat_feature_names=['shop', 'search'],
num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32),
num_feature_names=['weight', 'price', 'volume']
)
assert fd.get_feature_names() == ['weight', 'price', 'volume', 'shop', 'search']
# partial specification of names
fd = FeaturesData(
cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object),
num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32),
num_feature_names=['weight', 'price', 'volume']
)
assert fd.get_feature_names() == ['weight', 'price', 'volume', '', '']
# partial specification of names
fd = FeaturesData(
cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object),
cat_feature_names=['shop', 'search'],
num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32),
)
assert fd.get_feature_names() == ['', '', '', 'shop', 'search']
def compare_pools_from_features_data_and_generic_matrix(
features_data,
generic_matrix,
cat_features_indices,
feature_names=None
):
pool1 = Pool(data=features_data)
pool2 = Pool(data=generic_matrix, cat_features=cat_features_indices, feature_names=feature_names)
assert _have_equal_features(pool1, pool2)
@pytest.mark.parametrize('order', ['C', 'F'], ids=['order=C', 'order=F'])
def test_features_data_good(order):
# 0 objects
compare_pools_from_features_data_and_generic_matrix(
FeaturesData(cat_feature_data=np.empty((0, 4), dtype=object, order=order)),
np.empty((0, 4), dtype=object),
cat_features_indices=[0, 1, 2, 3]
)
# 0 objects
compare_pools_from_features_data_and_generic_matrix(
FeaturesData(
cat_feature_data=np.empty((0, 2), dtype=object, order=order),
cat_feature_names=['cat0', 'cat1'],
num_feature_data=np.empty((0, 3), dtype=np.float32, order=order),
),
np.empty((0, 5), dtype=object),
cat_features_indices=[3, 4],
feature_names=['', '', '', 'cat0', 'cat1']
)
compare_pools_from_features_data_and_generic_matrix(
FeaturesData(
cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object, order=order)
),
[[b'amazon', b'bing'], [b'ebay', b'google']],
cat_features_indices=[0, 1]
)
compare_pools_from_features_data_and_generic_matrix(
FeaturesData(
num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32, order=order)
),
[[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]],
cat_features_indices=[]
)
compare_pools_from_features_data_and_generic_matrix(
FeaturesData(
cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object, order=order),
num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32, order=order)
),
[[1.0, 2.0, 3.0, b'amazon', b'bing'], [22.0, 7.1, 10.2, b'ebay', b'google']],
cat_features_indices=[3, 4]
)
compare_pools_from_features_data_and_generic_matrix(
FeaturesData(
cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object, order=order),
cat_feature_names=['shop', 'search']
),
[[b'amazon', b'bing'], [b'ebay', b'google']],
cat_features_indices=[0, 1],
feature_names=['shop', 'search']
)
compare_pools_from_features_data_and_generic_matrix(
FeaturesData(
num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32, order=order),
num_feature_names=['weight', 'price', 'volume']
),
[[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]],
cat_features_indices=[],
feature_names=['weight', 'price', 'volume']
)
compare_pools_from_features_data_and_generic_matrix(
FeaturesData(
cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object, order=order),
cat_feature_names=['shop', 'search'],
num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32, order=order),
num_feature_names=['weight', 'price', 'volume']
),
[[1.0, 2.0, 3.0, b'amazon', b'bing'], [22.0, 7.1, 10.2, b'ebay', b'google']],
cat_features_indices=[3, 4],
feature_names=['weight', 'price', 'volume', 'shop', 'search']
)
def test_features_data_bad():
# empty
with pytest.raises(CatBoostError):
FeaturesData()
# names w/o data
with pytest.raises(CatBoostError):
FeaturesData(cat_feature_data=[[b'amazon', b'bing']], num_feature_names=['price'])
# bad matrix type
with pytest.raises(CatBoostError):
FeaturesData(
cat_feature_data=[[b'amazon', b'bing']],
num_feature_data=np.array([1.0, 2.0, 3.0], dtype=np.float32)
)
# bad matrix shape
with pytest.raises(CatBoostError):
FeaturesData(num_feature_data=np.array([[[1.0], [2.0], [3.0]]], dtype=np.float32))
# bad element type
with pytest.raises(CatBoostError):
FeaturesData(
cat_feature_data=np.array([b'amazon', b'bing'], dtype=object),
num_feature_data=np.array([1.0, 2.0, 3.0], dtype=np.float64)
)
# bad element type
with pytest.raises(CatBoostError):
FeaturesData(cat_feature_data=np.array(['amazon', 'bing']))
# bad names type
with pytest.raises(CatBoostError):
FeaturesData(
cat_feature_data=np.array([[b'google'], [b'reddit']], dtype=object),
cat_feature_names=[None, 'news_aggregator']
)
# bad names length
with pytest.raises(CatBoostError):
FeaturesData(
cat_feature_data=np.array([[b'google'], [b'bing']], dtype=object),
cat_feature_names=['search_engine', 'news_aggregator']
)
# no features
with pytest.raises(CatBoostError):
FeaturesData(
cat_feature_data=np.array([[], [], []], dtype=object),
num_feature_data=np.array([[], [], []], dtype=np.float32)
)
# number of objects is different
with pytest.raises(CatBoostError):
FeaturesData(
cat_feature_data=np.array([[b'google'], [b'bing']], dtype=object),
num_feature_data=np.array([1.0, 2.0, 3.0], dtype=np.float32)
)
def test_predict_regress(task_type):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
model = CatBoost({'iterations': 2, 'loss_function': 'RMSE', 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
assert(model.is_fitted())
output_model_path = test_output_path(OUTPUT_MODEL_PATH)
model.save_model(output_model_path)
return compare_canonical_models(output_model_path)
def test_predict_sklearn_regress(task_type):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
model = CatBoostRegressor(iterations=2, learning_rate=0.03, task_type=task_type, devices='0')
model.fit(train_pool)
assert(model.is_fitted())
output_model_path = test_output_path(OUTPUT_MODEL_PATH)
model.save_model(output_model_path)
return compare_canonical_models(output_model_path)
def test_predict_sklearn_class(task_type):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
model = CatBoostClassifier(iterations=2, learning_rate=0.03, loss_function='Logloss', task_type=task_type, devices='0')
model.fit(train_pool)
assert(model.is_fitted())
output_model_path = test_output_path(OUTPUT_MODEL_PATH)
model.save_model(output_model_path)
return compare_canonical_models(output_model_path)
def test_predict_class_raw(task_type):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
test_pool = Pool(TEST_FILE, column_description=CD_FILE)
model = CatBoostClassifier(iterations=2, task_type=task_type, devices='0')
model.fit(train_pool)
pred = model.predict(test_pool)
preds_path = test_output_path(PREDS_PATH)
np.save(preds_path, np.array(pred))
return local_canonical_file(preds_path)
def test_raw_predict_equals_to_model_predict(task_type):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
test_pool = Pool(TEST_FILE, column_description=CD_FILE)
model = CatBoostClassifier(iterations=10, task_type=task_type, devices='0')
model.fit(train_pool, eval_set=test_pool)
assert(model.is_fitted())
pred = model.predict(test_pool, prediction_type='RawFormulaVal')
assert np.all(np.isclose(model.get_test_eval(), pred, rtol=1.e-6))
@pytest.mark.parametrize('problem', ['Classifier', 'Regressor'])
def test_predict_and_predict_proba_on_single_object(problem):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
if problem == 'Classifier':
model = CatBoostClassifier(iterations=2)
else:
model = CatBoostRegressor(iterations=2)
model.fit(train_pool)
test_data = read_csv(TEST_FILE, header=None, delimiter='\t')
test_data.drop([TARGET_IDX], axis=1, inplace=True)
pred = model.predict(test_data)
if problem == 'Classifier':
pred_probabilities = model.predict_proba(test_data)
random.seed(0)
for i in xrange(3): # just some indices
test_object_idx = random.randrange(test_data.shape[0])
assert pred[test_object_idx] == model.predict(test_data.values[test_object_idx])
if problem == 'Classifier':
assert np.array_equal(pred_probabilities[test_object_idx], model.predict_proba(test_data.values[test_object_idx]))
def test_model_pickling(task_type):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
test_pool = Pool(TEST_FILE, column_description=CD_FILE)
model = CatBoostClassifier(iterations=10, task_type=task_type, devices='0')
model.fit(train_pool, eval_set=test_pool)
pred = model.predict(test_pool, prediction_type='RawFormulaVal')
model_unpickled = pickle.loads(pickle.dumps(model))
pred_new = model_unpickled.predict(test_pool, prediction_type='RawFormulaVal')
assert all(pred_new == pred)
def test_fit_from_file(task_type):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
model = CatBoost({'iterations': 2, 'loss_function': 'RMSE', 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
predictions1 = model.predict(train_pool)
model.fit(TRAIN_FILE, column_description=CD_FILE)
predictions2 = model.predict(train_pool)
assert all(predictions1 == predictions2)
assert 'train_finish_time' in model.get_metadata()
def test_fit_from_empty_features_data(task_type):
model = CatBoost({'iterations': 2, 'loss_function': 'RMSE', 'task_type': task_type, 'devices': '0'})
with pytest.raises(CatBoostError):
model.fit(
X=FeaturesData(num_feature_data=np.empty((0, 2), dtype=np.float32)),
y=np.empty((0), dtype=np.int32)
)
def test_coreml_import_export(task_type):
train_pool = Pool(QUERYWISE_TRAIN_FILE, column_description=QUERYWISE_CD_FILE)
test_pool = Pool(QUERYWISE_TEST_FILE, column_description=QUERYWISE_CD_FILE)
model = CatBoost(params={'loss_function': 'RMSE', 'iterations': 20, 'thread_count': 8, 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
output_coreml_model_path = test_output_path(OUTPUT_COREML_MODEL_PATH)
model.save_model(output_coreml_model_path, format="coreml")
canon_pred = model.predict(test_pool)
coreml_loaded_model = CatBoostRegressor()
coreml_loaded_model.load_model(output_coreml_model_path, format="coreml")
assert all(canon_pred == coreml_loaded_model.predict(test_pool))
return compare_canonical_models(output_coreml_model_path)
def test_coreml_import_export_one_hot_features(task_type):
train_pool = Pool(SMALL_CATEGORIAL_FILE, column_description=SMALL_CATEGORIAL_CD_FILE)
model = CatBoost(params={'loss_function': 'RMSE', 'iterations': 2, 'task_type': task_type, 'devices': '0', 'one_hot_max_size': 4})
model.fit(train_pool)
output_coreml_model_path = test_output_path(OUTPUT_COREML_MODEL_PATH)
model.save_model(output_coreml_model_path, format="coreml", pool=train_pool)
pred = model.predict(train_pool)
coreml_loaded_model = CatBoostRegressor()
coreml_loaded_model.load_model(output_coreml_model_path, format="coreml")
assert all(pred == coreml_loaded_model.predict(train_pool))
return compare_canonical_models(output_coreml_model_path)
@pytest.mark.parametrize('pool', ['adult', 'higgs'])
def test_convert_model_to_json(task_type, pool):
train_pool = Pool(data_file(pool, 'train_small'), column_description=data_file(pool, 'train.cd'))
test_pool = Pool(data_file(pool, 'test_small'), column_description=data_file(pool, 'train.cd'))
converted_model_path = test_output_path("converted_model.bin")
model = CatBoost({'iterations': 20, 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
output_model_path = test_output_path(OUTPUT_MODEL_PATH)
output_json_model_path = test_output_path(OUTPUT_JSON_MODEL_PATH)
model.save_model(output_model_path)
model.save_model(output_json_model_path, format="json")
model2 = CatBoost()
model2.load_model(output_json_model_path, format="json")
model2.save_model(converted_model_path)
pred1 = model.predict(test_pool)
pred2 = model2.predict(test_pool)
assert _check_data(pred1, pred2)
subprocess.check_call((model_diff_tool, output_model_path, converted_model_path, '--diff-limit', '0.000001'))
return compare_canonical_models(converted_model_path)
def test_coreml_cbm_import_export(task_type):
train_pool = Pool(QUERYWISE_TRAIN_FILE, column_description=QUERYWISE_CD_FILE)
test_pool = Pool(QUERYWISE_TEST_FILE, column_description=QUERYWISE_CD_FILE)
model = CatBoost(params={'loss_function': 'RMSE', 'iterations': 20, 'thread_count': 8, 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
canon_pred = model.predict(test_pool)
output_coreml_model_path = test_output_path(OUTPUT_COREML_MODEL_PATH)
model.save_model(output_coreml_model_path, format="coreml")
coreml_loaded_model = CatBoost()
coreml_loaded_model.load_model(output_coreml_model_path, format="coreml")
output_model_path = test_output_path(OUTPUT_MODEL_PATH)
coreml_loaded_model.save_model(output_model_path)
cbm_loaded_model = CatBoost()
cbm_loaded_model.load_model(output_model_path)
assert all(canon_pred == cbm_loaded_model.predict(test_pool))
return compare_canonical_models(output_coreml_model_path)
def test_cpp_export_no_cat_features(task_type):
train_pool = Pool(QUERYWISE_TRAIN_FILE, column_description=QUERYWISE_CD_FILE)
model = CatBoost({'iterations': 2, 'loss_function': 'RMSE', 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
output_cpp_model_path = test_output_path(OUTPUT_CPP_MODEL_PATH)
model.save_model(output_cpp_model_path, format="cpp")
return local_canonical_file(output_cpp_model_path)
def test_cpp_export_with_cat_features(task_type):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
model = CatBoost({'iterations': 20, 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
output_cpp_model_path = test_output_path(OUTPUT_CPP_MODEL_PATH)
model.save_model(output_cpp_model_path, format="cpp")
return local_canonical_file(output_cpp_model_path)
@pytest.mark.parametrize('iterations', [2, 40])
def test_export_to_python_no_cat_features(task_type, iterations):
train_pool = Pool(QUERYWISE_TRAIN_FILE, column_description=QUERYWISE_CD_FILE)
model = CatBoost({'iterations': iterations, 'loss_function': 'RMSE', 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
output_python_model_path = test_output_path(OUTPUT_PYTHON_MODEL_PATH)
model.save_model(output_python_model_path, format="python")
return local_canonical_file(output_python_model_path)
@pytest.mark.parametrize('iterations', [2, 40])
def test_export_to_python_with_cat_features(task_type, iterations):
train_pool = Pool(TRAIN_FILE, column_description=CD_FILE)
model = CatBoost({'iterations': iterations, 'task_type': task_type, 'devices': '0'})
model.fit(train_pool)
output_python_model_path = test_output_path(OUTPUT_PYTHON_MODEL_PATH)
model.save_model(output_python_model_path, format="python", pool=train_pool)
return local_canonical_file(output_python_model_path)
def test_export_to_python_with_cat_features_from_pandas(task_type):
model = CatBoost({'iterations': 5, 'task_type': task_type, 'devices': '0'})
X = DataFrame([[1, 2], [3, 4]], columns=['Num', 'Categ'])
y = [1, 0]
cat_features = [1]
model.fit(X, y, cat_features)
output_python_model_path = test_output_path(OUTPUT_PYTHON_MODEL_PATH)
model.save_model(output_python_model_path, format="python", pool=X)
return local_canonical_file(output_python_model_path)
@pytest.mark.parametrize('problem_type', ['binclass', 'multiclass', 'regression'])
def test_onnx_export(problem_type):
if problem_type == 'binclass':
loss_function = 'Logloss'
train_path = TRAIN_FILE
cd_path = CD_FILE
elif problem_type == 'multiclass':
loss_function = 'MultiClass'
train_path = CLOUDNESS_TRAIN_FILE
cd_path = CLOUDNESS_CD_FILE
elif problem_type == 'regression':
loss_function = 'RMSE'
train_path = TRAIN_FILE
cd_path = CD_FILE
else:
raise Exception('Unsupported problem_type: %s' % problem_type)
train_pool = Pool(train_path, column_description=cd_path)
model = CatBoost(
{
'task_type': 'CPU', # TODO(akhropov): GPU results are unstable, difficult to compare models
'loss_function': loss_function,
'iterations': 5,
'depth': 4,
# onnx format export does not yet support categorical features so ignore them
'ignored_features': train_pool.get_cat_feature_indices()
}
)
model.fit(train_pool)
output_onnx_model_path = test_output_path(OUTPUT_ONNX_MODEL_PATH)
model.save_model(
output_onnx_model_path,
format="onnx",
export_parameters={
'onnx_domain': 'ai.catboost',
'onnx_model_version': 1,
'onnx_doc_string': 'test model for problem_type %s' % problem_type,
'onnx_graph_name': 'CatBoostModel_for_%s' % problem_type
}
)
return compare_canonical_models(output_onnx_model_path)
@pytest.mark.parametrize('problem_type', ['binclass', 'multiclass', 'regression'])
def test_onnx_import(problem_type):
if problem_type == 'binclass':
loss_function = 'Logloss'
train_path = TRAIN_FILE
test_path = TEST_FILE
cd_path = CD_FILE
elif problem_type == 'multiclass':
loss_function = 'MultiClass'
train_path = CLOUDNESS_TRAIN_FILE
test_path = CLOUDNESS_TEST_FILE
cd_path = CLOUDNESS_CD_FILE
elif problem_type == 'regression':
loss_function = 'RMSE'
train_path = TRAIN_FILE
test_path = TEST_FILE
cd_path = CD_FILE
else:
raise Exception('Unsupported problem_type: %s' % problem_type)
train_pool = Pool(train_path, column_description=cd_path)
test_pool = Pool(test_path, column_description=cd_path)
model = CatBoost(
{
'task_type': 'CPU',
'loss_function': loss_function,
'iterations': 5,
'depth': 4,
'ignored_features': train_pool.get_cat_feature_indices()
}
)
model.fit(train_pool)
output_onnx_model_path = test_output_path(OUTPUT_ONNX_MODEL_PATH)
model.save_model(
output_onnx_model_path,