-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathml.py
More file actions
2214 lines (1799 loc) · 90.9 KB
/
ml.py
File metadata and controls
2214 lines (1799 loc) · 90.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
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
import re
from ..utils import DataikuException
from ..utils import DataikuUTF8CSVReader
from ..utils import DataikuStreamedHttpUTF8CSVReader
import json, warnings
import time
from .metrics import ComputedMetrics
from .utils import DSSDatasetSelectionBuilder, DSSFilterBuilder
from .future import DSSFuture
class PredictionSplitParamsHandler(object):
"""Object to modify the train/test splitting params."""
SPLIT_PARAMS_KEY = 'splitParams'
def __init__(self, mltask_settings):
"""Do not call directly, use :meth:`DSSMLTaskSettings.get_split_params`"""
self.mltask_settings = mltask_settings
def get_raw(self):
"""Gets the raw settings of the prediction split configuration. This returns a reference to the raw settings, not a copy,
so changes made to the returned object will be reflected when saving.
:rtype: dict
"""
return self.mltask_settings[PredictionSplitParamsHandler.SPLIT_PARAMS_KEY]
def set_split_random(self, train_ratio = 0.8, selection = None, dataset_name=None):
"""
Sets the train/test split to random splitting of an extract of a single dataset
:param float train_ratio: Ratio of rows to use for train set. Must be between 0 and 1
:param object selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the dataset. May be None (won't be changed)
:param str dataset_name: Name of dataset to split. If None, the main dataset used to create the visual analysis will be used.
"""
sp = self.mltask_settings[PredictionSplitParamsHandler.SPLIT_PARAMS_KEY]
sp["ttPolicy"] = "SPLIT_SINGLE_DATASET"
if selection is not None:
if isinstance(selection, DSSDatasetSelectionBuilder):
sp["ssdSelection"] = selection.build()
else:
sp["ssdSelection"] = selection
sp["ssdTrainingRatio"] = train_ratio
sp["kfold"] = False
if dataset_name is not None:
sp["ssdDatasetSmartName"] = dataset_name
return self
def set_split_kfold(self, n_folds = 5, selection = None, dataset_name=None):
"""
Sets the train/test split to k-fold splitting of an extract of a single dataset
:param int n_folds: number of folds. Must be greater than 0
:param object selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the dataset. May be None (won't be changed)
:param str dataset_name: Name of dataset to split. If None, the main dataset used to create the visual analysis will be used.
"""
sp = self.mltask_settings[PredictionSplitParamsHandler.SPLIT_PARAMS_KEY]
sp["ttPolicy"] = "SPLIT_SINGLE_DATASET"
if selection is not None:
if isinstance(selection, DSSDatasetSelectionBuilder):
sp["ssdSelection"] = selection.build()
else:
sp["ssdSelection"] = selection
sp["kfold"] = True
sp["nFolds"] = n_folds
if dataset_name is not None:
sp["ssdDatasetSmartName"] = dataset_name
return self
def set_split_explicit(self, train_selection, test_selection, dataset_name=None, test_dataset_name=None, train_filter=None, test_filter=None):
"""
Sets the train/test split to explicit extract of one or two dataset(s)
:param object train_selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the train dataset. May be None (won't be changed)
:param object test_selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the test dataset. May be None (won't be changed)
:param str dataset_name: Name of dataset to use for the extracts. If None, the main dataset used to create the ML Task will be used.
:param str test_dataset_name: Name of a second dataset to use for the test data extract. If None, both extracts are done from dataset_name
:param object train_filter: A :class:`~dataikuapi.dss.utils.DSSFilterBuilder` to build the settings of the filter of the train dataset. May be None (won't be changed)
:param object test_filter: A :class:`~dataikuapi.dss.utils.DSSFilterBuilder` to build the settings of the filter of the test dataset. May be None (won't be changed)
"""
sp = self.mltask_settings[PredictionSplitParamsHandler.SPLIT_PARAMS_KEY]
if dataset_name is None:
raise Exception("For explicit splitting a dataset_name is mandatory")
if test_dataset_name is None or test_dataset_name == dataset_name:
sp["ttPolicy"] = "EXPLICIT_FILTERING_SINGLE_DATASET"
train_split ={}
test_split = {}
sp['efsdDatasetSmartName'] = dataset_name
sp['efsdTrain'] = train_split
sp['efsdTest'] = test_split
else:
sp["ttPolicy"] = "EXPLICIT_FILTERING_TWO_DATASETS"
train_split ={'datasetSmartName' : dataset_name}
test_split = {'datasetSmartName' : test_dataset_name}
sp['eftdTrain'] = train_split
sp['eftdTest'] = test_split
if train_selection is not None:
if isinstance(train_selection, DSSDatasetSelectionBuilder):
train_split["selection"] = train_selection.build()
else:
train_split["selection"] = train_selection
if test_selection is not None:
if isinstance(test_selection, DSSDatasetSelectionBuilder):
test_split["selection"] = test_selection.build()
else:
test_split["selection"] = test_selection
if train_filter is not None:
if isinstance(train_filter, DSSFilterBuilder):
train_split["filter"] = train_filter.build()
else:
train_split["filter"] = train_filter
if test_filter is not None:
if isinstance(test_filter, DSSFilterBuilder):
test_split["filter"] = test_filter.build()
else:
test_split["filter"] = test_filter
return self
def set_time_ordering(self, feature_name, ascending=True):
"""
Uses a variable to sort the data for train/test split and hyperparameter optimization by time
:param str feature_name: Name of the variable to use
:param bool ascending: True iff the test set is expected to have larger time values than the train set
"""
self.unset_time_ordering()
if not feature_name in self.mltask_settings["preprocessing"]["per_feature"]:
raise ValueError("Feature %s doesn't exist in this ML task, can't use as time" % feature_name)
self.mltask_settings['time']['enabled'] = True
self.mltask_settings['time']['timeVariable'] = feature_name
self.mltask_settings['time']['ascending'] = ascending
self.mltask_settings['preprocessing']['per_feature'][feature_name]['missing_handling'] = "DROP_ROW"
if self.mltask_settings['splitParams']['ttPolicy'] == "SPLIT_SINGLE_DATASET":
self.mltask_settings['splitParams']['ssdSplitMode'] = "SORTED"
self.mltask_settings['splitParams']['ssdColumn'] = feature_name
if self.mltask_settings['modeling']['gridSearchParams']['mode'] == "KFOLD":
self.mltask_settings['modeling']['gridSearchParams']['mode'] = "TIME_SERIES_KFOLD"
elif self.mltask_settings['modeling']['gridSearchParams']['mode'] == "SHUFFLE":
self.mltask_settings['modeling']['gridSearchParams']['mode'] = "TIME_SERIES_SINGLE_SPLIT"
return self
def unset_time_ordering(self):
"""
Remove time-based ordering for train/test split and hyperparameter optimization
"""
self.mltask_settings['time']['enabled'] = False
self.mltask_settings['time']['timeVariable'] = None
if self.mltask_settings['splitParams']['ttPolicy'] == "SPLIT_SINGLE_DATASET":
self.mltask_settings['splitParams']['ssdSplitMode'] = "RANDOM"
self.mltask_settings['splitParams']['ssdColumn'] = None
if self.mltask_settings['modeling']['gridSearchParams']['mode'] == "TIME_SERIES_KFOLD":
self.mltask_settings['modeling']['gridSearchParams']['mode'] = "KFOLD"
elif self.mltask_settings['modeling']['gridSearchParams']['mode'] == "TIME_SERIES_SINGLE_SPLIT":
self.mltask_settings['modeling']['gridSearchParams']['mode'] = "SHUFFLE"
return self
class DSSMLTaskSettings(object):
"""
Object to read and modify the settings of a ML task.
Do not create this object directly, use :meth:`DSSMLTask.get_settings()` instead
"""
def __init__(self, client, project_key, analysis_id, mltask_id, mltask_settings):
self.client = client
self.project_key = project_key
self.analysis_id = analysis_id
self.mltask_id = mltask_id
self.mltask_settings = mltask_settings
def get_raw(self):
"""
Gets the raw settings of this ML Task. This returns a reference to the raw settings, not a copy,
so changes made to the returned object will be reflected when saving.
:rtype: dict
"""
return self.mltask_settings
def get_feature_preprocessing(self, feature_name):
"""
Gets the feature preprocessing params for a particular feature. This returns a reference to the
feature's settings, not a copy, so changes made to the returned object will be reflected when saving
:return: A dict of the preprocessing settings for a feature
:rtype: dict
"""
return self.mltask_settings["preprocessing"]["per_feature"][feature_name]
def foreach_feature(self, fn, only_of_type = None):
"""
Applies a function to all features (except target)
:param function fn: Function that takes 2 parameters: feature_name and feature_params and returns modified feature_params
:param str only_of_type: if not None, only applies to feature of the given type. Can be one of ``CATEGORY``, ``NUMERIC``, ``TEXT`` or ``VECTOR``
"""
import copy
new_per_feature = {}
for (k, v) in self.mltask_settings["preprocessing"]["per_feature"].items():
if v["role"] == "TARGET" or (only_of_type is not None and v["type"] != only_of_type):
new_per_feature[k] = v
else:
new_per_feature[k] = fn(k, copy.deepcopy(v))
self.mltask_settings["preprocessing"]["per_feature"] = new_per_feature
def reject_feature(self, feature_name):
"""
Marks a feature as rejected and not used for training
:param str feature_name: Name of the feature to reject
"""
self.get_feature_preprocessing(feature_name)["role"] = "REJECT"
def use_feature(self, feature_name):
"""
Marks a feature as input for training
:param str feature_name: Name of the feature to reject
"""
self.get_feature_preprocessing(feature_name)["role"] = "INPUT"
def get_algorithm_settings(self, algorithm_name):
"""
Gets the training settings for a particular algorithm. This returns a reference to the
algorithm's settings, not a copy, so changes made to the returned object will be reflected when saving.
This method returns a dictionary of the settings for this algorithm.
All algorithm dicts have at least an "enabled" key in the dictionary.
The 'enabled' key indicates whether this algorithm will be trained
Other settings are algorithm-dependent and are the various hyperparameters of the
algorithm. The precise keys for each algorithm are not all documented. You can print
the returned dictionary to learn more about the settings of each particular algorithm
Please refer to the documentation for details on available algorithms.
:param str algorithm_name: Name (in capitals) of the algorithm.
:return: A dict of the settings for an algorithm
:rtype: dict
"""
if algorithm_name in self.__class__.algorithm_remap:
algorithm_name = self.__class__.algorithm_remap[algorithm_name]
return self.mltask_settings["modeling"][algorithm_name.lower()]
def get_diagnostics_settings(self):
"""
Gets the diagnostics settings for a mltask. This returns a reference to the
diagnostics' settings, not a copy, so changes made to the returned object will be reflected when saving.
This method returns a dictionary of the settings with:
- 'enabled': indicates if the diagnostics are enabled globally, if False, all diagnostics will be disabled
- 'settings': a list of dict comprised of:
- 'type': the diagnostic type
- 'enabled': indicates if the diagnostic type is enabled, if False, all diagnostics of that type will be disabled
Please refer to the documentation for details on available diagnostics.
:return: A dict of diagnostics settings
:rtype: dict
"""
return self.mltask_settings["diagnosticsSettings"]
def set_diagnostics_enabled(self, enabled):
"""
Globally enables or disables all diagnostics.
:param bool enabled: if the diagnostics should be enabled or not
"""
settings = self.get_diagnostics_settings()
settings["enabled"] = enabled
def set_diagnostic_type_enabled(self, diagnostic_type, enabled):
"""
Enables or disables a diagnostic based on its type.
Please refer to the documentation for details on available diagnostics.
:param str diagnostic_type: Name (in capitals) of the diagnostic type.
:param bool enabled: if the diagnostic should be enabled or not
"""
settings = self.get_diagnostics_settings()["settings"]
diagnostic = [h for h in settings if h["type"] == diagnostic_type]
if len(diagnostic) == 0:
raise ValueError("Diagnostic type '{}' not found in settings".format(diagnostic_type))
if len(diagnostic) > 1:
raise ValueError("Should not happen: multiple diagnostic types '{}' found in settings".format(diagnostic_type))
diagnostic[0]["enabled"] = enabled
def set_algorithm_enabled(self, algorithm_name, enabled):
"""
Enables or disables an algorithm based on its name.
Please refer to the documentation for details on available algorithms.
:param str algorithm_name: Name (in capitals) of the algorithm.
"""
self.get_algorithm_settings(algorithm_name)["enabled"] = enabled
def disable_all_algorithms(self):
"""Disables all algorithms"""
for algorithm_name in self.__class__.algorithm_remap.keys():
key = self.__class__.algorithm_remap[algorithm_name]
if key in self.mltask_settings["modeling"]:
self.mltask_settings["modeling"][key]["enabled"] = False
for custom_mllib in self.mltask_settings["modeling"]["custom_mllib"]:
custom_mllib["enabled"] = False
for custom_python in self.mltask_settings["modeling"]["custom_python"]:
custom_python["enabled"] = False
for plugin in self.mltask_settings["modeling"]["plugin_python"].values():
plugin["enabled"] = False
def get_all_possible_algorithm_names(self):
"""
Returns the list of possible algorithm names, i.e. the list of valid
identifiers for :meth:`set_algorithm_enabled` and :meth:`get_algorithm_settings`
This does not include Custom Python models, Custom MLLib models, plugin models.
This includes all possible algorithms, regardless of the prediction kind (regression/classification)
or engine, so some algorithms may be irrelevant
:returns: the list of algorithm names as a list of strings
:rtype: list of string
"""
return self.__class__.algorithm_remap.keys()
def set_metric(self, metric=None, custom_metric=None, custom_metric_greater_is_better=True, custom_metric_use_probas=False):
"""
Sets the score metric to optimize for a prediction ML Task
:param str metric: metric to use. Leave empty to use a custom metric. You need to set the ``custom_metric`` value in that case
:param str custom_metric: code of the custom metric
:param bool custom_metric_greater_is_better: whether the custom metric is a score or a loss
:param bool custom_metric_use_probas: whether to use the classes' probas or the predicted value (for classification)
"""
if custom_metric is None and metric is None:
raise ValueError("Either metric or custom_metric must be defined")
self.mltask_settings["modeling"]["metrics"]["evaluationMetric"] = metric if custom_metric is None else 'CUSTOM'
self.mltask_settings["modeling"]["metrics"]["customEvaluationMetricCode"] = custom_metric
self.mltask_settings["modeling"]["metrics"]["customEvaluationMetricGIB"] = custom_metric_greater_is_better
self.mltask_settings["modeling"]["metrics"]["customEvaluationMetricNeedsProba"] = custom_metric_use_probas
def save(self):
"""Saves back these settings to the ML Task"""
self.client._perform_empty(
"POST", "/projects/%s/models/lab/%s/%s/settings" % (self.project_key, self.analysis_id, self.mltask_id),
body = self.mltask_settings)
class DSSPredictionMLTaskSettings(DSSMLTaskSettings):
__doc__ = []
algorithm_remap = {
"RANDOM_FOREST_CLASSIFICATION": "random_forest_classification",
"RANDOM_FOREST_REGRESSION" : "random_forest_regression",
"EXTRA_TREES": "extra_trees",
"GBT_CLASSIFICATION" : "gbt_classification",
"GBT_REGRESSION" : "gbt_regression",
"DECISION_TREE_CLASSIFICATION" : "decision_tree_classification",
"DECISION_TREE_REGRESSION" : "decision_tree_regression",
"RIDGE_REGRESSION": "ridge_regression",
"LASSO_REGRESSION" : "lasso_regression",
"LEASTSQUARE_REGRESSION": "leastsquare_regression",
"SGD_REGRESSION" : "sgd_regression",
"KNN": "knn",
"LOGISTIC_REGRESSION" : "logistic_regression",
"NEURAL_NETWORK" :"neural_network",
"SVC_CLASSIFICATION" : "svc_classifier",
"SVM_REGRESSION" : "svm_regression",
"SGD_CLASSIFICATION" : "sgd_classifier",
"LARS" : "lars_params",
"XGBOOST_CLASSIFICATION" : "xgboost",
"XGBOOST_REGRESSION" : "xgboost",
"SPARKLING_DEEP_LEARNING" : "deep_learning_sparkling",
"SPARKLING_GBM" : "gbm_sparkling",
"SPARKLING_RF" : "rf_sparkling",
"SPARKLING_GLM" : "glm_sparkling",
"SPARKLING_NB" : "nb_sparkling",
"MLLIB_LOGISTIC_REGRESSION" : "mllib_logit",
"MLLIB_NAIVE_BAYES" : "mllib_naive_bayes",
"MLLIB_LINEAR_REGRESSION" : "mllib_linreg",
"MLLIB_RANDOM_FOREST" : "mllib_rf",
"MLLIB_GBT": "mllib_gbt",
"MLLIB_DECISION_TREE" : "mllib_dt",
"VERTICA_LINEAR_REGRESSION" : "vertica_linear_regression",
"VERTICA_LOGISTIC_REGRESSION" : "vertica_logistic_regression",
"KERAS_CODE" : "keras"
}
class PredictionTypes:
BINARY = "BINARY_CLASSIFICATION"
REGRESSION = "REGRESSION"
MULTICLASS = "MULTICLASS"
def __init__(self, client, project_key, analysis_id, mltask_id, mltask_settings):
DSSMLTaskSettings.__init__(self, client, project_key, analysis_id, mltask_id, mltask_settings)
if self.get_prediction_type() not in [self.PredictionTypes.BINARY, self.PredictionTypes.REGRESSION, self.PredictionTypes.MULTICLASS]:
raise ValueError("Unknown prediction type: {}".format(self.prediction_type))
self.classification_prediction_types = [self.PredictionTypes.BINARY, self.PredictionTypes.MULTICLASS]
def get_prediction_type(self):
return self.mltask_settings['predictionType']
@property
def split_params(self):
"""
Gets a handle to modify train/test splitting params.
:rtype: :class:`PredictionSplitParamsHandler`
"""
return self.get_split_params()
def get_split_params(self):
"""
Gets a handle to modify train/test splitting params.
:rtype: :class:`PredictionSplitParamsHandler`
"""
return PredictionSplitParamsHandler(self.mltask_settings)
def get_assertions_params(self):
"""
Retrieves the assertions parameters for this ml task
:rtype: :class:`dataikuapi.dss.ml.DSSMLAssertionsParams`
"""
return DSSMLAssertionsParams(self.mltask_settings["assertionParams"])
def split_ordered_by(self, feature_name, ascending=True):
"""
Deprecated. Use split_params.set_time_ordering()
"""
warnings.warn("split_ordered_by() is deprecated, please use split_params.set_time_ordering() instead", DeprecationWarning)
self.split_params.set_time_ordering(feature_name, ascending=ascending)
return self
def remove_ordered_split(self):
"""
Deprecated. Use split_params.unset_time_ordering()
"""
warnings.warn("remove_ordered_split() is deprecated, please use split_params.unset_time_ordering() instead", DeprecationWarning)
self.split_params.unset_time_ordering()
return self
def use_sample_weighting(self, feature_name):
"""
Deprecated. use set_weighting()
"""
warnings.warn("use_sample_weighting() is deprecated, please use set_weighting() instead", DeprecationWarning)
return self.set_weighting(method='SAMPLE_WEIGHT', feature_name=feature_name, )
def set_weighting(self, method, feature_name=None):
"""
Sets the method to weight samples.
If there was a WEIGHT feature declared previously, it will be set back as an INPUT feature first.
:param str method: Method to use. One of NO_WEIGHTING, SAMPLE_WEIGHT (must give a feature name),
CLASS_WEIGHT or CLASS_AND_SAMPLE_WEIGHT (must give a feature name)
:param str feature_name: Name of the feature to use as sample weight
"""
# First, if there was a WEIGHT feature, restore it as INPUT
for other_feature_name in self.mltask_settings['preprocessing']['per_feature']:
if self.mltask_settings['preprocessing']['per_feature'][other_feature_name]['role'] == 'WEIGHT':
self.mltask_settings['preprocessing']['per_feature'][other_feature_name]['role'] = 'INPUT'
if method == "NO_WEIGHTING":
self.mltask_settings['weight']['weightMethod'] = method
elif method == "SAMPLE_WEIGHT":
if not feature_name in self.mltask_settings["preprocessing"]["per_feature"]:
raise ValueError("Feature %s doesn't exist in this ML task, can't use as weight" % feature_name)
self.mltask_settings['weight']['weightMethod'] = method
self.mltask_settings['weight']['sampleWeightVariable'] = feature_name
self.mltask_settings['preprocessing']['per_feature'][feature_name]['role'] = 'WEIGHT'
elif method == "CLASS_WEIGHT":
if self.get_prediction_type() not in self.classification_prediction_types:
raise ValueError("Weighting method: {} not compatible with prediction type: {}, should be in {}".format(method, self.get_prediction_type(), self.classification_prediction_types))
self.mltask_settings['weight']['weightMethod'] = method
elif method == "CLASS_AND_SAMPLE_WEIGHT":
if self.get_prediction_type() not in self.classification_prediction_types:
raise ValueError("Weighting method: {} not compatible with prediction type: {}, should be in {}".format(method, self.get_prediction_type(), self.classification_prediction_types))
if not feature_name in self.mltask_settings["preprocessing"]["per_feature"]:
raise ValueError("Feature %s doesn't exist in this ML task, can't use as weight" % feature_name)
self.mltask_settings['weight']['weightMethod'] = method
self.mltask_settings['weight']['sampleWeightVariable'] = feature_name
self.mltask_settings['preprocessing']['per_feature'][feature_name]['role'] = 'WEIGHT'
else:
raise ValueError("Unknown weighting method: {}".format(method))
return self
def remove_sample_weighting(self):
"""
Deprecated. Use set_weighting(method=\"NO_WEIGHTING\") instead
"""
warnings.warn("remove_sample_weighting() is deprecated, please use set_weighting(method=\"NO_WEIGHTING\") instead", DeprecationWarning)
return self.set_weighting(method="NO_WEIGHTING")
class DSSClusteringMLTaskSettings(DSSMLTaskSettings):
__doc__ = []
algorithm_remap = {
"DBSCAN" : "db_scan_clustering",
}
class DSSTrainedModelDetails(object):
def __init__(self, details, snippet, saved_model=None, saved_model_version=None, mltask=None, mltask_model_id=None):
self.details = details
self.snippet = snippet
self.saved_model = saved_model
self.saved_model_version = saved_model_version
self.mltask = mltask
self.mltask_model_id = mltask_model_id
def get_raw(self):
"""
Gets the raw dictionary of trained model details
"""
return self.details
def get_raw_snippet(self):
"""
Gets the raw dictionary of trained model snippet.
The snippet is a lighter version than the details.
"""
return self.snippet
def get_train_info(self):
"""
Returns various information about the train process (size of the train set, quick description, timing information)
:rtype: dict
"""
return self.details["trainInfo"]
def get_user_meta(self):
"""
Gets the user-accessible metadata (name, description, cluster labels, classification threshold)
Returns the original object, not a copy. Changes to the returned object are persisted to DSS by calling
:meth:`save_user_meta`
"""
return self.details["userMeta"]
def save_user_meta(self):
um = self.details["userMeta"]
if self.mltask is not None:
self.mltask.client._perform_empty(
"PUT", "/projects/%s/models/lab/%s/%s/models/%s/user-meta" % (self.mltask.project_key,
self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id), body = um)
else:
self.saved_model.client._perform_empty(
"PUT", "/projects/%s/savedmodels/%s/versions/%s/user-meta" % (self.saved_model.project_key,
self.saved_model.sm_id, self.saved_model_version), body = um)
def get_origin_analysis_trained_model(self):
"""
Fetch details about the model in an analysis, this model has been exported from. Returns None if the
deployed trained model does not have an origin analysis trained model.
:rtype: DSSTrainedModelDetails | None
"""
if self.saved_model is None:
return self
else:
fmi = self.get_raw().get("smOrigin", {}).get("fullModelId")
if fmi is not None:
origin_ml_task = DSSMLTask.from_full_model_id(self.saved_model.client, fmi,
project_key=self.saved_model.project_key)
return origin_ml_task.get_trained_model_details(fmi)
def get_diagnostics(self):
"""
Retrieves diagnostics computed for this trained model
:returns: list of diagnostics
:rtype: list of type `dataikuapi.dss.ml.DSSMLDiagnostic`
"""
diagnostics = self.details.get("trainDiagnostics", {})
return [DSSMLDiagnostic(d) for d in diagnostics.get("diagnostics", [])]
class DSSMLDiagnostic(object):
"""
Object that represents a computed Diagnostic on a trained model
Do not create this object directly, use :meth:`DSSTrainedModelDetails.get_diagnostics()` instead
"""
def __init__(self, data):
self._internal_dict = data
def get_raw(self):
"""
Gets the raw dictionary of the diagnostic
:rtype: dict
"""
return self._internal_dict
def get_type(self):
"""
Returns the base Diagnostic type
:rtype: str
"""
return self._internal_dict["type"]
def get_type_pretty(self):
"""
Returns the Diagnostic type as displayed in the UI
:rtype: str
"""
return self._internal_dict["displayableType"]
def get_message(self):
"""
Returns the message as displayed in the UI
:rtype: str
"""
return self._internal_dict["message"]
def __repr__(self):
return "{cls}(type={type}, message={msg})".format(cls=self.__class__.__name__,
type=self._internal_dict["type"],
msg=self._internal_dict["message"])
class DSSMLAssertionsParams(object):
"""
Object that represents parameters for all assertions of a ml task
Do not create this object directly, use :meth:`DSSPredictionMLTaskSettings.get_assertions_params()` instead
"""
def __init__(self, data):
self._internal_dict = data
def get_raw(self):
"""
Gets the raw dictionary of the assertions parameters
:rtype: dict
"""
return self._internal_dict
def get_assertion(self, assertion_name):
"""
Gets a :class:`dataikuapi.dss.ml.DSSMLAssertionParams` representing the parameters of the assertion with the
provided name (or None if no assertion has that name)
:param str assertion_name: Name of the assertion
:rtype: :class:`dataikuapi.dss.ml.DSSMLAssertionParams` or None
"""
for assertion_dict in self._internal_dict["assertions"]:
if assertion_dict["name"] == assertion_name:
return DSSMLAssertionParams(assertion_dict)
return None
def add_assertion(self, assertion_params):
"""
Adds parameters of an assertion to the assertions parameters of the ml task.
Raises a ValueError if an assertion with the same name already exists
:param object assertion_params: A :class:`~dataikuapi.dss.utils.DSSMLAssertionParams` representing parameters of the assertion
"""
if not isinstance(assertion_params, DSSMLAssertionParams):
raise ValueError('Wrong type for assertion parameters: {}'.format(type(assertion_params)))
self._internal_dict["assertions"].append(assertion_params._internal_dict)
def delete_assertion(self, assertion_name):
"""
Deletes the assertion parameters of the assertion with the provided name from the `dataikuapi.dss.ml.DSSMLAssertionsParams`
Raises a ValueError if no assertion with the provided name was found
:param str assertion_name: Name of the assertion
"""
for idx, assertion_dict in enumerate(self._internal_dict["assertions"]):
if assertion_dict["name"] == assertion_name:
del self._internal_dict["assertions"][idx]
return
raise ValueError('No assertion found with name: {}'.format(assertion_name))
class DSSMLAssertionParams(object):
"""
Object that represents parameters for one assertion
Do not create this object directly, use :meth:`dataikuapi.dss.ml.DSSMLAssertionsParams.get_assertion(assertion_name)` or
`from_parts(name, a_filter, condition)` instead
"""
def __init__(self, data):
self._internal_dict = data
@staticmethod
def from_parts(name, a_filter, condition):
"""
Creates assertion parameters from name, filter and condition
:param str name: Name of the assertion
:param object a_filter: A :class:`~dataikuapi.dss.utils.DSSFilter` to select assertion population
:param object condition: A :class:`~dataikuapi.dss.ml.DSSMLAssertionCondition` for the assertion to be successful
:rtype: :class:`dataikuapi.dss.ml.DSSMLAssertionParams`
"""
assertion_params = DSSMLAssertionParams({})
assertion_params.name = name
assertion_params.filter = a_filter
assertion_params.condition = condition
return assertion_params
def get_raw(self):
"""
Gets the raw dictionary of the assertion parameters
:rtype: dict
"""
return self._internal_dict
@property
def name(self):
"""
Returns the assertion name
:rtype: str
"""
return self._internal_dict["name"]
@name.setter
def name(self, name):
self._internal_dict["name"] = name
@property
def filter(self):
"""
Returns the assertion filter
:rtype: :class:`dataikuapi.dss.utils.DSSFilter`
"""
return self._internal_dict["filter"]
@filter.setter
def filter(self, filter):
self._internal_dict["filter"] = filter
@property
def condition(self):
"""
Returns the assertion condition
:rtype: :class:`dataikuapi.dss.ml.DSSMLAssertionCondition`
"""
return DSSMLAssertionCondition(self._internal_dict["assertionCondition"])
@condition.setter
def condition(self, condition):
if not isinstance(condition, DSSMLAssertionCondition):
raise ValueError('Wrong type for assertion condition: {}'.format(type(condition)))
self._internal_dict["assertionCondition"] = condition._internal_dict
class DSSMLAssertionCondition(object):
"""
Object that represents an assertion condition
Do not create this object directly, use :meth:`dataikuapi.dss.ml.DSSMLAssertionParams.condition`, :meth:`dataikuapi.dss.ml.DSSMLAssertionCondition.from_expected_class(expected_valid_ratio, expected_class)`
or :meth:`dataikuapi.dss.ml.DSSMLAssertionCondition.from_expected_range(expected_valid_ratio, expected_min, expected_max)` instead
"""
def __init__(self, data):
self._internal_dict = data
@staticmethod
def from_expected_class(expected_valid_ratio, expected_class):
"""
Creates an assertion condition from the expected valid ratio and class
:param float expected_valid_ratio: Assertion passes if this ratio of rows predicted as expected_class is attained
:param str expected_class: Assertion passes if the ratio of rows predicted as expected_class is attained
:rtype: :class:`dataikuapi.dss.ml.DSSMLAssertionCondition`
"""
assertion_condition = DSSMLAssertionCondition({})
assertion_condition.expected_valid_ratio = expected_valid_ratio
assertion_condition.expected_class = expected_class
return assertion_condition
@staticmethod
def from_expected_range(expected_valid_ratio, expected_min, expected_max):
"""
Creates an assertion condition from expected valid ratio and range. The expected range is the
interval between expected_min and expected_max where the predictions and therefore the rows will be considered
valid.
:param float expected_valid_ratio: Assertion passes if this ratio of rows predicted between expected_min and expected_max is attained
:param float expected_min: Min value of the expected range
:param float expected_max: Max value of the expected range
:rtype: :class:`dataikuapi.dss.ml.DSSMLAssertionCondition`
"""
assertion_condition = DSSMLAssertionCondition({})
assertion_condition.expected_valid_ratio = expected_valid_ratio
assertion_condition.expected_min = expected_min
assertion_condition.expected_max = expected_max
return assertion_condition
def get_raw(self):
"""
Gets the raw dictionary of the condition
:rtype: dict
"""
return self._internal_dict
@property
def expected_class(self):
"""
Returns the expected class or None if it is not defined. Assertion passes if the ratio of rows predicted
as expected_class is attained
:rtype: str
"""
if "expectedClass" in self._internal_dict:
return self._internal_dict["expectedClass"]
else:
return None
@expected_class.setter
def expected_class(self, expected_class):
self._internal_dict["expectedClass"] = expected_class
@property
def expected_valid_ratio(self):
"""
Returns the ratio of valid rows to exceed for the assertion to pass. A row is considered valid if the prediction
is equal to the `expected_class` for classification or in the expected range for regresion
:rtype: str
"""
return self._internal_dict["successRatio"]
@expected_valid_ratio.setter
def expected_valid_ratio(self, expected_valid_ratio):
self._internal_dict["successRatio"] = expected_valid_ratio
@property
def expected_min(self):
"""
Returns the min (included) of the expected range or None if it is not defined. Assertion passes if the ratio of rows predicted
between expected_min and expected_max is attained
:rtype: float
"""
if "expectedMinValue" in self._internal_dict:
return self._internal_dict["expectedMinValue"]
else:
return None
@expected_min.setter
def expected_min(self, expected_min):
self._internal_dict["expectedMinValue"] = expected_min
@property
def expected_max(self):
"""
Returns the max (included) of the expected range or None if it is not defined. Assertion passes if the ratio of rows predicted
between expected_min and expected_max is attained
:rtype: float
"""
if "expectedMaxValue" in self._internal_dict:
return self._internal_dict["expectedMaxValue"]
else:
return None
@expected_max.setter
def expected_max(self, expected_max):
self._internal_dict["expectedMaxValue"] = expected_max
class DSSMLAssertionsMetrics(object):
"""
Object that represents the per assertion metrics for all assertions on a trained model
Do not create this object directly, use :meth:`dataikuapi.dss.ml.DSSTrainedPredictionModelDetails.get_assertions_metrics()` instead
"""
def __init__(self, data):
self._internal_dict = data
def get_raw(self):
"""
Gets the raw dictionary of the assertions metrics
:rtype: dict
"""
return self._internal_dict
def get_metric(self, assertion_name):
"""
Retrieves the metric computed for this trained model for the assertion with the provided name (or None if no
assertion with that name exists)
:param str assertion_name: Name of the assertion
:returns: an object representing assertion metrics or None if if no assertion with that name exists
:rtype: :class:`dataikuapi.dss.ml.DSSMLAssertionMetric`
"""
for assertion_metric_dict in self._internal_dict["perAssertion"]:
if assertion_name == assertion_metric_dict["name"]:
return DSSMLAssertionMetric(assertion_metric_dict)
return None
@property
def positive_assertion_ratio(self):
"""
Returns the ratio of passing assertions
:rtype: float
"""
return self._internal_dict['positiveAssertionsRatio']
class DSSMLAssertionMetric(object):
"""
Object that represents the result of an assertion on a trained model
Do not create this object directly, use :meth:`dataikuapi.dss.ml.DSSMLAssertionMetrics.get_metric(self, assertion_name)` instead
"""
def __init__(self, data):
self._internal_dict = data
def get_raw(self):
"""
Gets the raw dictionary of metrics of one assertion
:rtype: dict
"""
return self._internal_dict
@property
def name(self):
"""
Returns the assertion name
:rtype: str
"""
return self._internal_dict["name"]
@property
def result(self):
"""
Returns whether the assertion pass
:rtype: bool
"""
return self._internal_dict["result"]
@property
def valid_ratio(self):
"""
Returns the ratio of rows in the assertion population with prediction equals to the expected class
for classification or in the expected range for regression
:rtype: float
"""
return self._internal_dict["validRatio"]
@property
def nb_matching_rows(self):
"""
Returns the number of rows matching filter
:rtype: int
"""
return self._internal_dict["nbMatchingRows"]
@property
def nb_dropped_rows(self):
"""
Returns the number of rows dropped by the model's preprocessing
:rtype: int
"""
return self._internal_dict["nbDroppedRows"]
class DSSTreeNode(object):
def __init__(self, tree, i):
self.tree = tree
self.i = i
def get_left_child(self):
"""Gets a :class:`dataikuapi.dss.ml.DSSTreeNode` representing the left side of the tree node (or None)"""
left = self.tree.tree['leftChild'][self.i]
if left < 0:
return None
else:
return DSSTreeNode(self.tree, left)
def get_right_child(self):
"""Gets a :class:`dataikuapi.dss.ml.DSSTreeNode` representing the right side of the tree node (or None)"""