-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
core.py
6937 lines (5912 loc) · 306 KB
/
core.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 contextlib import contextmanager # noqa E402
from copy import deepcopy
import logging
import sys
import os
if sys.version_info >= (3, 3):
from collections.abc import Iterable, Sequence, Mapping, MutableMapping
else:
from collections import Iterable, Sequence, Mapping, MutableMapping
from collections import OrderedDict, defaultdict
from six import iteritems, string_types, integer_types
import warnings
import numpy as np
import ctypes
import platform
import tempfile
import shutil
from enum import Enum
from operator import itemgetter
from threading import Lock
if platform.system() == 'Linux':
try:
ctypes.CDLL('librt.so')
except Exception:
pass
try:
from pandas import DataFrame, Series
except ImportError:
class DataFrame(object):
pass
class Series(object):
pass
import scipy.sparse
_typeof = type
from .plot_helpers import save_plot_file, try_plot_offline, OfflineMetricVisualizer
from . import _catboost
from .metrics import BuiltinMetric
_PoolBase = _catboost._PoolBase
_CatBoost = _catboost._CatBoost
_MetricCalcerBase = _catboost._MetricCalcerBase
_cv = _catboost._cv
_set_logger = _catboost._set_logger
_reset_logger = _catboost._reset_logger
_configure_malloc = _catboost._configure_malloc
CatBoostError = _catboost.CatBoostError
_metric_description_or_str_to_str = _catboost._metric_description_or_str_to_str
is_classification_objective = _catboost.is_classification_objective
is_cv_stratified_objective = _catboost.is_cv_stratified_objective
is_regression_objective = _catboost.is_regression_objective
is_multiregression_objective = _catboost.is_multiregression_objective
is_multitarget_objective = _catboost.is_multitarget_objective
is_survivalregression_objective = _catboost.is_survivalregression_objective
is_groupwise_metric = _catboost.is_groupwise_metric
is_ranking_metric = _catboost.is_ranking_metric
is_maximizable_metric = _catboost.is_maximizable_metric
is_minimizable_metric = _catboost.is_minimizable_metric
_PreprocessParams = _catboost._PreprocessParams
_check_train_params = _catboost._check_train_params
_MetadataHashProxy = _catboost._MetadataHashProxy
_NumpyAwareEncoder = _catboost._NumpyAwareEncoder
FeaturesData = _catboost.FeaturesData
_have_equal_features = _catboost._have_equal_features
SPARSE_MATRIX_TYPES = _catboost.SPARSE_MATRIX_TYPES
MultiTargetCustomMetric = _catboost.MultiTargetCustomMetric
MultiTargetCustomObjective = _catboost.MultiTargetCustomObjective
MultiRegressionCustomMetric = _catboost.MultiTargetCustomMetric # for compatibility
MultiRegressionCustomObjective = _catboost.MultiTargetCustomObjective # for compatibility
fspath = _catboost.fspath
_eval_metric_util = _catboost._eval_metric_util
logger = logging.getLogger(__name__)
_configure_malloc()
_catboost._library_init()
INTEGER_TYPES = (integer_types, np.integer)
FLOAT_TYPES = (float, np.floating)
STRING_TYPES = (string_types,)
ARRAY_TYPES = (list, np.ndarray, DataFrame, Series)
if sys.version_info >= (3, 6):
PATH_TYPES = STRING_TYPES + (os.PathLike,)
elif sys.version_info >= (3, 4):
from pathlib import Path
PATH_TYPES = STRING_TYPES + (Path,)
else:
PATH_TYPES = STRING_TYPES
class _StreamLikeWrapper:
def __init__(self, callable_object):
self.callable_object = callable_object
def write(self, message):
self.callable_object(message)
def _get_stream_like_object(obj):
if hasattr(obj, 'write'):
return obj
if hasattr(obj, '__call__'):
return _StreamLikeWrapper(obj)
raise CatBoostError(
'Expected callable object or stream-like object'
)
catboost_logger_lock = Lock()
@contextmanager
def log_fixup(log_cout=sys.stdout, log_cerr=sys.stderr):
if catboost_logger_lock.acquire(False):
try:
_set_logger(_get_stream_like_object(log_cout), _get_stream_like_object(log_cerr))
yield
finally:
_reset_logger()
catboost_logger_lock.release()
else:
if log_cout is not sys.stdout or log_cerr is not sys.stderr:
logger.warning(
'CatBoost custom logger function is already set in another thread, ' +
'will use it from this thread. If you are training CatBoost models from different threads, ' +
'consider using sys.stdout and sys.stderr default loggers'
)
yield
def _cast_to_base_types(value):
# NOTE: Special case, avoiding new list creation.
if isinstance(value, list):
for index, element in enumerate(value):
value[index] = _cast_to_base_types(element)
return value
if isinstance(value, ARRAY_TYPES[1:]):
new_value = []
for element in value:
new_value.append(_cast_to_base_types(element))
return new_value
if isinstance(value, (Mapping, MutableMapping)):
for key in list(value):
value[key] = _cast_to_base_types(value[key])
return value
if isinstance(value, bool):
return value
if isinstance(value, INTEGER_TYPES):
return int(value)
if isinstance(value, FLOAT_TYPES):
return float(value)
if isinstance(value, tuple(set(PATH_TYPES) - set(STRING_TYPES))):
return fspath(value)
return value
def metric_description_or_str_to_str(description):
return _metric_description_or_str_to_str(description)
def _check_param_type(value, name, types, or_none=True):
if not isinstance(value, types + ((type(None),) if or_none else ())):
raise CatBoostError('Parameter {} should have a type of {}, got {}'.format(name, types, type(value)))
def _process_verbose(metric_period=None, verbose=None, logging_level=None, verbose_eval=None, silent=None):
_check_param_type(metric_period, 'metric_period', (int,))
_check_param_type(verbose, 'verbose', (bool, int))
_check_param_type(logging_level, 'logging_level', (string_types,))
_check_param_type(verbose_eval, 'verbose_eval', (bool, int))
_check_param_type(silent, 'silent', (bool,))
params = locals()
exclusive_params = ['verbose', 'logging_level', 'verbose_eval', 'silent']
at_most_one = sum(params.get(exclusive) is not None for exclusive in exclusive_params)
if at_most_one > 1:
raise CatBoostError('Only one of parameters {} should be set'.format(exclusive_params))
if verbose is None:
if silent is not None:
verbose = not silent
elif verbose_eval is not None:
verbose = verbose_eval
if verbose is not None:
verbose = int(verbose)
return (metric_period, verbose, logging_level)
def enum_from_enum_or_str(enum_type, arg):
if isinstance(arg, enum_type):
return arg
elif isinstance(arg, str):
return enum_type[arg]
else:
raise Exception("can't create enum " + str(enum_type) + " from type " + str(type(arg)))
class EFstrType(Enum):
"""Calculate score for every feature by values change."""
PredictionValuesChange = 0
"""Calculate score for every feature by loss change"""
LossFunctionChange = 1
"""Use LossFunctionChange for ranking models and PredictionValuesChange otherwise"""
FeatureImportance = 2
"""Calculate pairwise score between every feature."""
Interaction = 3
"""Calculate SHAP Values for every object."""
ShapValues = 4
"""Calculate most important features explaining difference in predictions for a pair of documents"""
PredictionDiff = 5
"""Calculate SHAP Interaction Values pairwise between every feature for every object."""
ShapInteractionValues = 6
"""Calculate SAGE Values for every feature"""
SageValues = 7
class EShapCalcType(Enum):
"""Calculate regular SHAP values"""
Regular = "Regular"
"""Calculate approximate SHAP values"""
Approximate = "Approximate"
"""Calculate exact SHAP values"""
Exact = "Exact"
class EFeaturesSelectionAlgorithm(Enum):
"""Use prediction values change as feature strength, eliminate batch of features at once"""
RecursiveByPredictionValuesChange = "RecursiveByPredictionValuesChange"
"""Use loss function change as feature strength, eliminate batch of features at each step"""
RecursiveByLossFunctionChange = "RecursiveByLossFunctionChange"
"""Use shap values to estimate loss function change, eliminate features one by one"""
RecursiveByShapValues = "RecursiveByShapValues"
class EFeaturesSelectionGrouping(Enum):
"""Select individual features"""
Individual = "Individual"
"""Select feature groups (marked by tags)"""
ByTags = "ByTags"
def _get_features_indices(features, feature_names):
"""
Parameters
----------
features :
must be a sequence of either integers or strings
if it contains strings 'feature_names' parameter must be defined and string ids from 'features'
must represent a subset of in 'feature_names'
feature_names :
A sequence of string ids for features or None.
Used to get feature indices for string ids in 'features' parameter
"""
if (not isinstance(features, (Sequence, np.ndarray))) or isinstance(features, (str, bytes, bytearray)):
raise CatBoostError("feature names should be a sequence, but got " + repr(features))
if feature_names is not None:
return [
feature_names.index(f) if isinstance(f, STRING_TYPES) else f
for f in features
]
else:
for f in features:
if isinstance(f, STRING_TYPES):
raise CatBoostError("features parameter contains string value '{}' but feature names "
"for a dataset are not specified".format(f))
return features
def _update_params_quantize_part(params, ignored_features, per_float_feature_quantization, border_count,
feature_border_type, sparse_features_conflict_fraction, dev_efb_max_buckets,
nan_mode, input_borders, task_type, used_ram_limit, random_seed,
dev_max_subset_size_for_build_borders):
if ignored_features is not None:
params.update({
'ignored_features': ignored_features
})
if per_float_feature_quantization is not None:
params.update({
'per_float_feature_quantization': per_float_feature_quantization
})
if border_count is not None:
params.update({
'border_count': border_count
})
if feature_border_type is not None:
params.update({
'feature_border_type': feature_border_type
})
if sparse_features_conflict_fraction is not None:
params.update({
'sparse_features_conflict_fraction': sparse_features_conflict_fraction
})
if dev_efb_max_buckets is not None:
params.update({
'dev_efb_max_buckets': dev_efb_max_buckets
})
if nan_mode is not None:
params.update({
'nan_mode': nan_mode
})
if input_borders is not None:
params.update({
'input_borders': input_borders
})
if task_type is not None:
params.update({
'task_type': task_type
})
if used_ram_limit is not None:
params.update({
'used_ram_limit': used_ram_limit
})
if random_seed is not None:
params.update({
'random_seed': random_seed
})
if dev_max_subset_size_for_build_borders is not None:
params.update({
'dev_max_subset_size_for_build_borders': dev_max_subset_size_for_build_borders
})
return params
def plot_features_selection_loss_graph(
title,
entities_name,
entities_name_in_fields,
eliminated_entities_indices,
eliminated_entities_names,
loss_graph,
cost_graph=None
):
warn_msg = "To draw plots you should install plotly."
try:
import plotly.graph_objs as go
except ImportError as e:
warnings.warn(warn_msg)
raise ImportError(str(e))
indices_present = any(eliminated_entities_indices)
names_present = any(eliminated_entities_names)
names_or_indices = eliminated_entities_names if names_present else list(map(str, eliminated_entities_indices))
loss_values = loss_graph['loss_values']
removed_entities_cnt = loss_graph['removed_' + entities_name_in_fields + '_count']
main_indices = loss_graph['main_indices']
fig = go.Figure()
fig['layout']['title'] = go.layout.Title(text=title)
loss_graph_color = 'rgb(51,160,44)'
# line with all points
fig.add_trace(go.Scatter(
x=removed_entities_cnt,
y=loss_values,
line=go.scatter.Line(color=loss_graph_color),
mode='lines+markers',
text=[''] + names_or_indices,
name=''
))
if len(main_indices) > 0:
# red markers for main points
fig.add_trace(go.Scatter(
x=[removed_entities_cnt[idx] for idx in main_indices],
y=[loss_values[idx] for idx in main_indices],
mode='markers',
marker=go.scatter.Marker(size=10, symbol='square'),
text=[names_or_indices[idx - 1] if idx > 0 else '' for idx in main_indices],
name=''
))
if indices_present:
# labels with entities indices
fig.add_trace(go.Scatter(
x=removed_entities_cnt,
y=loss_values,
mode='text',
text=[''] + list(map(str, eliminated_entities_indices)),
textposition='bottom center',
textfont=dict(family='sans serif', size=18, color=loss_graph_color),
name='',
visible=False
))
if names_present:
# labels with entities names
fig.add_trace(go.Scatter(
x=removed_entities_cnt,
y=loss_values,
mode='text',
text=[''] + eliminated_entities_names,
textfont=dict(family='sans serif', size=18, color=loss_graph_color),
textposition='bottom center',
name='',
visible=False
))
cost_graph_color = 'rgb(160,44,44)'
if cost_graph is not None:
# line with all points
fig.add_trace(go.Scatter(
x=removed_entities_cnt,
y=cost_graph['loss_values'],
line=go.scatter.Line(color=cost_graph_color),
mode='lines+markers',
text=[''] + eliminated_entities_names,
name='',
yaxis="y2"
))
# labels with entities names
fig.add_trace(go.Scatter(
x=removed_entities_cnt,
y=cost_graph['loss_values'],
mode='text',
text=[''] + eliminated_entities_names,
textfont=dict(family='sans serif', size=18, color=cost_graph_color),
textposition='bottom center',
name='',
yaxis="y2",
visible=False
))
axis_options = dict(
gridcolor='rgb(255,255,255)', showgrid=True, showline=False,
showticklabels=True, tickcolor='rgb(127,127,127)', ticks='outside', zeroline=False
)
fig.update_layout(
xaxis=dict(title='number of removed ' + entities_name, **axis_options),
yaxis=dict(
title='loss value',
titlefont=dict(color=loss_graph_color),
tickfont=dict(color=loss_graph_color),
**axis_options
)
)
if cost_graph is not None:
fig.update_layout(
yaxis2=dict(
title='cost value',
side="right",
anchor="x",
overlaying="y",
titlefont=dict(color=cost_graph_color),
tickfont=dict(color=cost_graph_color),
**axis_options
)
)
buttons = []
def get_visible_arg(show_indices, show_names):
visible_arg = [True]
if len(main_indices) > 0:
visible_arg.append(True)
if indices_present:
visible_arg.append(show_indices)
if names_present:
visible_arg.append(show_names)
if cost_graph is not None:
visible_arg.append(True)
visible_arg.append(show_names)
return visible_arg
buttons.append(dict(
label='Hide ' + entities_name,
method='update',
args=[{"visible": get_visible_arg(show_indices=False, show_names=False)}]
))
if indices_present:
buttons.append(dict(
label='Show indices',
method='update',
args=[{"visible": get_visible_arg(show_indices=True, show_names=False)}]
))
if names_present:
buttons.append(dict(
label='Show names',
method='update',
args=[{"visible": get_visible_arg(show_indices=False, show_names=True)}]
))
fig.update_layout(
updatemenus=[dict(
active=0,
buttons=buttons,
pad={"r": 10, "t": 10},
showactive=True,
x=-0.25,
xanchor="left",
y=1.03,
yanchor="top"
)]
)
fig.update_layout(
showlegend=False
)
return fig
def plot_features_selection_loss_graphs(summary):
result = {}
result['features'] = plot_features_selection_loss_graph(
'Loss by eliminated features',
'features',
'features',
summary['eliminated_features'],
summary['eliminated_features_names'],
summary['loss_graph']
)
if 'eliminated_features_tags' in summary:
result['features_tags'] = plot_features_selection_loss_graph(
'Loss by eliminated features tags',
'features tags',
'features_tags',
[],
summary['eliminated_features_tags'],
summary['features_tags_loss_graph'],
cost_graph=summary['features_tags_cost_graph']
)
return result
class Pool(_PoolBase):
"""
Pool used in CatBoost as a data structure to train model from.
"""
def __init__(
self,
data,
label=None,
cat_features=None,
text_features=None,
embedding_features=None,
embedding_features_data=None,
column_description=None,
pairs=None,
delimiter='\t',
has_header=False,
ignore_csv_quoting=False,
weight=None,
group_id=None,
group_weight=None,
subgroup_id=None,
pairs_weight=None,
baseline=None,
timestamp=None,
feature_names=None,
feature_tags=None,
thread_count=-1,
log_cout=sys.stdout,
log_cerr=sys.stderr
):
"""
Pool is an internal data structure that is used by CatBoost.
You can construct Pool from list, numpy.ndarray, pandas.DataFrame, pandas.Series.
Parameters
----------
data : list or numpy.ndarray or pandas.DataFrame or pandas.Series or FeaturesData or string or pathlib.Path
Data source of Pool.
If list or numpy.ndarrays or pandas.DataFrame or pandas.Series, giving 2 dimensional array like data.
If FeaturesData - see FeaturesData description for details, 'cat_features' and 'feature_names'
parameters must be equal to None in this case
If string or pathlib.Path, giving the path to the file with data in catboost format.
If string starts with "quantized://", the file has to contain quantized dataset saved with Pool.save().
label : list or numpy.ndarrays or pandas.DataFrame or pandas.Series, optional (default=None)
Label of the training data.
If not None, giving 1 or 2 dimensional array like data with floats.
If data is a file, then label must be in the file, that is label must be equals to None
cat_features : list or numpy.ndarray, optional (default=None)
If not None, giving the list of Categ features indices or names.
If it contains feature names, Pool's feature names must be defined: either by passing 'feature_names'
parameter or if data is pandas.DataFrame (feature names are initialized from it's column names)
Must be None if 'data' parameter has FeaturesData type
text_features : list or numpy.ndarray, optional (default=None)
If not None, giving the list of Text features indices or names.
If it contains feature names, Pool's feature names must be defined: either by passing 'feature_names'
parameter or if data is pandas.DataFrame (feature names are initialized from it's column names)
Must be None if 'data' parameter has FeaturesData type
embedding_features : list or numpy.ndarray, optional (default=None)
If not None, giving the list of Embedding features indices or names.
If it contains feature names, Pool's feature names must be defined: either by passing 'feature_names'
parameter or if data is pandas.DataFrame (feature names are initialized from it's column names)
Must be None if 'data' parameter has FeaturesData type
embedding_features_data : list or dict, optional (default=None)
If not None, giving the data of Embedding features (instead of data in main 'data' parameter).
If list - list containing 2d arrays (lists or numpy.ndarrays or scipy.sparse.spmatrix) with [n_data_size x embedding_size] elements
If dict - dict containing 2d arrays (lists or numpy.ndarrays or scipy.sparse.spmatrix) with [n_data_size x embedding_size] elements
Dict keys must be the same as specified in 'embedding_features' parameter
column_description : string or pathlib.Path, optional (default=None)
ColumnsDescription parameter.
There are several columns description types: Label, Categ, Num, Auxiliary, DocId, Weight, Baseline, GroupId, Timestamp.
All columns are Num as default, it's not necessary to specify
this type of columns. Default Label column index is 0 (zero).
If None, Label column is 0 (zero) as default, all data columns are Num as default.
If string or pathlib.Path, giving the path to the file with ColumnsDescription in column_description format.
pairs : list or numpy.ndarray or pandas.DataFrame or string or pathlib.Path
The pairs description.
If list or numpy.ndarrays or pandas.DataFrame, giving 2 dimensional.
The shape should be Nx2, where N is the pairs' count. The first element of the pair is
the index of winner object in the training set. The second element of the pair is
the index of loser object in the training set.
If string or pathlib.Path, giving the path to the file with pairs description.
delimiter : string, optional (default='\t')
Delimiter to use for separate features in file.
Should be only one symbol, otherwise would be taken only the first character of the string.
has_header : bool optional (default=False)
If True, read column names from first line.
ignore_csv_quoting : bool optional (default=False)
If True ignore quoting '"'.
weight : list or numpy.ndarray, optional (default=None)
Weight for each instance.
If not None, giving 1 dimensional array like data.
group_id : list or numpy.ndarray, optional (default=None)
group id for each instance.
If not None, giving 1 dimensional array like data.
group_weight : list or numpy.ndarray, optional (default=None)
Group weight for each instance.
If not None, giving 1 dimensional array like data.
subgroup_id : list or numpy.ndarray, optional (default=None)
subgroup id for each instance.
If not None, giving 1 dimensional array like data.
pairs_weight : list or numpy.ndarray, optional (default=None)
Weight for each pair.
If not None, giving 1 dimensional array like pairs.
baseline : list or numpy.ndarray, optional (default=None)
Baseline for each instance.
If not None, giving 2 dimensional array like data.
timestamp: list or numpy.ndarray, optional (default=None)
Timestamp for each instance.
Should be a non-negative integer.
Useful for sorting a learning dataset by this field during training.
feature_names : list or string or pathlib.Path, optional (default=None)
If list - list of names for each given data_feature.
If string or pathlib.Path - path with scheme for feature names data to load.
If this parameter is None and 'data' is pandas.DataFrame feature names will be initialized
from DataFrame's column names.
Must be None if 'data' parameter has FeaturesData type
feature_tags : json, optional (default=None)
Format:
{'tag1':
{
'features': [<ids or names of features>],
'cost': <positive integer>
}
'tag2':
{
...
}
...
}
thread_count : int, optional (default=-1)
Thread count for data processing.
If -1, then the number of threads is set to the number of CPU cores.
log_cout: output stream or callback for logging
log_cerr: error stream or callback for logging
"""
if data is not None:
self._check_data_type(data)
self._check_data_empty(data)
if pairs is not None and isinstance(data, PATH_TYPES) != isinstance(pairs, PATH_TYPES):
raise CatBoostError("data and pairs parameters should be the same types.")
if column_description is not None and not isinstance(data, PATH_TYPES):
raise CatBoostError("data should be the string or pathlib.Path type if column_description parameter is specified.")
if isinstance(data, PATH_TYPES):
if any(v is not None for v in [cat_features, text_features, embedding_features, embedding_features_data, weight, group_id, group_weight,
subgroup_id, pairs_weight, baseline, label]):
raise CatBoostError(
"cat_features, text_features, embedding_features, embedding_features_data, weight, group_id, group_weight, subgroup_id, pairs_weight, "
"baseline, label should have the None type when the pool is read from the file."
)
if (feature_names is not None) and (not isinstance(feature_names, PATH_TYPES)):
raise CatBoostError(
"feature_names should have None or string or pathlib.Path type when the pool is read from the file."
)
self._read(data, column_description, pairs, feature_names, delimiter, has_header, ignore_csv_quoting, thread_count,
log_cout=log_cout, log_cerr=log_cerr)
else:
if isinstance(data, FeaturesData):
if any(v is not None for v in [cat_features, text_features, embedding_features, embedding_features_data, feature_names]):
raise CatBoostError(
"cat_features, text_features, embedding_features, embedding_features_data, feature_names should have the None type"
" when 'data' parameter has FeaturesData type"
)
elif isinstance(data, np.ndarray):
if (data.dtype.kind == 'f') and (cat_features is not None) and (len(cat_features) > 0):
raise CatBoostError(
"'data' is numpy array of floating point numerical type, it means no categorical features,"
" but 'cat_features' parameter specifies nonzero number of categorical features"
)
if (data.dtype.kind == 'f') and (text_features is not None) and (len(text_features) > 0):
raise CatBoostError(
"'data' is numpy array of floating point numerical type, it means no text features,"
" but 'text_features' parameter specifies nonzero number of text features"
)
if (data.dtype.kind != 'O') and (embedding_features is not None) and (len(embedding_features) > 0):
if embedding_features_data is None:
raise CatBoostError(
"'data' is numpy array of non-object type, it means no embedding features,"
" but 'embedding_features' parameter specifies nonzero number of embedding features"
)
elif isinstance(data, scipy.sparse.spmatrix):
if (data.dtype.kind == 'f') and (cat_features is not None) and (len(cat_features) > 0):
raise CatBoostError(
"'data' is scipy.sparse.spmatrix of floating point numerical type, it means no categorical features,"
" but 'cat_features' parameter specifies nonzero number of categorical features"
)
if (text_features is not None) and (len(text_features) > 0):
raise CatBoostError(
"'data' is scipy.sparse.spmatrix, it means no text features,"
" but 'text_features' parameter specifies nonzero number of text features"
)
if (embedding_features is not None) and (len(embedding_features) > 0) and (embedding_features_data is None):
raise CatBoostError(
"'data' is scipy.sparse.spmatrix and 'embedding_features_data' is None, it means no embedding features,"
" but 'embedding_features' parameter specifies nonzero number of embedding features"
)
if embedding_features_data is not None:
if embedding_features is None:
raise CatBoostError(
"'embedding_features_data' is not None, but 'embedding_features' parameter is not specified"
)
if isinstance(embedding_features_data, list):
if len(embedding_features) != len(embedding_features_data):
raise CatBoostError(
"'embedding_features_data' and 'embedding_features' contain different numbers of features"
)
elif isinstance(embedding_features_data, dict):
if set(embedding_features) != set(embedding_features_data.keys()):
raise CatBoostError(
"keys of 'embedding_features_data' dict do not correspond to 'embedding_features'"
)
else:
raise CatBoostError(
"'embedding_features_data' must have either 'list' or 'dict' type"
)
if isinstance(feature_names, PATH_TYPES):
raise CatBoostError(
"feature_names must be None or have non-string type when the pool is created from "
"python objects."
)
self._init(data, label, cat_features, text_features, embedding_features, embedding_features_data, pairs, weight,
group_id, group_weight, subgroup_id, pairs_weight, baseline, timestamp, feature_names, feature_tags, thread_count)
super(Pool, self).__init__()
def _check_files(self, data, column_description, pairs):
"""
Check files existence.
"""
data = fspath(data)
column_description = fspath(column_description)
pairs = fspath(pairs)
if data.find('://') == -1 and not os.path.isfile(data):
raise CatBoostError("Invalid data path='{}': file does not exist.".format(data))
if column_description is not None and column_description.find('://') == -1 and not os.path.isfile(column_description):
raise CatBoostError("Invalid column_description path='{}': file does not exist.".format(column_description))
if pairs is not None and pairs.find('://') == -1 and not os.path.isfile(pairs):
raise CatBoostError("Invalid pairs path='{}': file does not exist.".format(pairs))
def _check_delimiter(self, delimiter):
if not isinstance(delimiter, STRING_TYPES):
raise CatBoostError("Invalid delimiter type={} : must be str().".format(type(delimiter)))
if len(delimiter) < 1:
raise CatBoostError("Invalid delimiter length={} : must be > 0.".format(len(delimiter)))
def _check_column_description_type(self, column_description):
"""
Check type of column_description parameter.
"""
if not isinstance(column_description, PATH_TYPES):
raise CatBoostError("Invalid column_description type={}: must be str() or pathlib.Path().".format(type(column_description)))
def _check_string_feature_type(self, features, features_name):
"""
Check type of cat_feature parameter.
"""
if not isinstance(features, (list, np.ndarray)):
raise CatBoostError("Invalid {} type={}: must be list() or np.ndarray().".format(features_name, type(features)))
def _check_string_feature_value(self, features, features_count, features_name):
"""
Check values in cat_feature parameter. Must be int indices.
"""
for indx, feature in enumerate(features):
if not isinstance(feature, INTEGER_TYPES):
raise CatBoostError("Invalid {}[{}] = {} value type={}: must be int().".format(features_name, indx, feature, type(feature)))
if feature >= features_count:
raise CatBoostError("Invalid {}[{}] = {} value: index must be < {}.".format(features_name, indx, feature, features_count))
def _check_pairs_type(self, pairs):
"""
Check type of pairs parameter.
"""
if not isinstance(pairs, (list, np.ndarray, DataFrame)):
raise CatBoostError("Invalid pairs type={}: must be list(), np.ndarray() or pd.DataFrame.".format(type(pairs)))
def _check_pairs_value(self, pairs):
"""
Check values in pairs parameter. Must be int indices.
"""
for pair_id, pair in enumerate(pairs):
if (len(pair) != 2):
raise CatBoostError("Length of pairs[{}] isn't equal to 2.".format(pair_id))
for i, index in enumerate(pair):
if not isinstance(index, INTEGER_TYPES):
raise CatBoostError("Invalid pairs[{}][{}] = {} value type={}: must be int().".format(pair_id, i, index, type(index)))
def _check_data_type(self, data):
"""
Check type of data.
"""
if not isinstance(data, (PATH_TYPES, ARRAY_TYPES, SPARSE_MATRIX_TYPES, FeaturesData)):
raise CatBoostError(
"Invalid data type={}: data must be list(), np.ndarray(), DataFrame(), Series(), FeaturesData " +
" scipy.sparse matrix or filename str() or pathlib.Path().".format(type(data))
)
def _check_data_empty(self, data):
"""
Check that data is not empty (0 objects is ok).
note: already checked if data is FeatureType, so no need to check again
"""
if isinstance(data, PATH_TYPES):
if not data:
raise CatBoostError("Features filename is empty.")
elif isinstance(data, (ARRAY_TYPES, SPARSE_MATRIX_TYPES)):
data_shape = np.shape(data)
if len(data_shape) == 1 and data_shape[0] > 0:
if isinstance(data[0], Iterable):
data_shape = tuple(data_shape + tuple([len(data[0])]))
else:
data_shape = tuple(data_shape + tuple([1]))
if not len(data_shape) == 2:
raise CatBoostError("Input data has invalid shape: {}. Must be 2 dimensional".format(data_shape))
if data_shape[1] == 0:
raise CatBoostError("Input data must have at least one feature")
def _check_label_type(self, label):
"""
Check type of label.
"""
if not isinstance(label, ARRAY_TYPES):
raise CatBoostError("Invalid label type={}: must be array like.".format(type(label)))
def _check_label_empty(self, label):
"""
Check label is not empty.
"""
if len(label) == 0:
raise CatBoostError("Labels variable is empty.")
def _check_label_shape(self, label, samples_count):
"""
Check label length and dimension.
"""
if len(label) != samples_count:
raise CatBoostError("Length of label={} and length of data={} is different.".format(len(label), samples_count))
def _check_baseline_type(self, baseline):
"""
Check type of baseline parameter.
"""
if not isinstance(baseline, ARRAY_TYPES):
raise CatBoostError("Invalid baseline type={}: must be array like.".format(type(baseline)))
def _check_baseline_shape(self, baseline, samples_count):
"""
Check baseline length and dimension.
"""
if len(baseline) != samples_count:
raise CatBoostError("Length of baseline={} and length of data={} are different.".format(len(baseline), samples_count))
if not isinstance(baseline[0], Iterable) or isinstance(baseline[0], STRING_TYPES):
raise CatBoostError("Baseline must be 2 dimensional data, 1 column for each class.")
try:
if np.array(baseline).dtype not in (np.dtype('float'), np.dtype('float32'), np.dtype('int')):
raise CatBoostError()
except CatBoostError:
raise CatBoostError("Invalid baseline value type={}: must be float or int.".format(np.array(baseline).dtype))
def _check_weight_type(self, weight):
"""
Check type of weight parameter.
"""
if not isinstance(weight, ARRAY_TYPES):
raise CatBoostError("Invalid weight type={}: must be array like.".format(type(weight)))
def _check_weight_shape(self, weight, samples_count):
"""
Check weight length.
"""
if len(weight) != samples_count:
raise CatBoostError("Length of weight={} and length of data={} are different.".format(len(weight), samples_count))
if not isinstance(weight[0], (INTEGER_TYPES, FLOAT_TYPES)):
raise CatBoostError("Invalid weight value type={}: must be 1 dimensional data with int, float or long types.".format(type(weight[0])))
def _check_group_id_type(self, group_id):
"""
Check type of group_id parameter.
"""
if not isinstance(group_id, ARRAY_TYPES):
raise CatBoostError("Invalid group_id type={}: must be array like.".format(type(group_id)))
def _check_group_id_shape(self, group_id, samples_count):
"""
Check group_id length.
"""
if len(group_id) != samples_count:
raise CatBoostError("Length of group_id={} and length of data={} are different.".format(len(group_id), samples_count))
def _check_group_weight_type(self, group_weight):
"""
Check type of group_weight parameter.
"""
if not isinstance(group_weight, ARRAY_TYPES):
raise CatBoostError("Invalid group_weight type={}: must be array like.".format(type(group_weight)))
def _check_group_weight_shape(self, group_weight, samples_count):
"""
Check group_weight length.
"""
if len(group_weight) != samples_count:
raise CatBoostError("Length of group_weight={} and length of data={} are different.".format(len(group_weight), samples_count))
if not isinstance(group_weight[0], (FLOAT_TYPES)):
raise CatBoostError("Invalid group_weight value type={}: must be 1 dimensional data with float types.".format(type(group_weight[0])))
def _check_subgroup_id_type(self, subgroup_id):
"""
Check type of subgroup_id parameter.
"""
if not isinstance(subgroup_id, ARRAY_TYPES):
raise CatBoostError("Invalid subgroup_id type={}: must be array like.".format(type(subgroup_id)))
def _check_subgroup_id_shape(self, subgroup_id, samples_count):
"""
Check subgroup_id length.
"""
if len(subgroup_id) != samples_count:
raise CatBoostError("Length of subgroup_id={} and length of data={} are different.".format(len(subgroup_id), samples_count))
def _check_timestamp_type(self, timestamp):
"""
Check type of timestamp parameter.
"""
if not isinstance(timestamp, ARRAY_TYPES):
raise CatBoostError("Invalid timestamp type={}: must be array like.".format(type(timestamp)))
def _check_transform_tags(self, tags, feature_names):
if not isinstance(tags, dict):
raise CatBoostError("Invalid feature_tags type={}: must be dict like.".format(type(tags)))