-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathtest_classification.py
1375 lines (1156 loc) · 51.3 KB
/
test_classification.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 typing import Any, Dict, Optional, Union
import copy
import itertools
import os
import resource
import tempfile
import numpy as np
import sklearn.datasets
import sklearn.decomposition
import sklearn.ensemble
import sklearn.model_selection
import sklearn.svm
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import CategoricalHyperparameter
from joblib import Memory
from sklearn.base import clone
from sklearn.utils.validation import check_is_fitted
import autosklearn.pipeline.components.classification as classification_components
import autosklearn.pipeline.components.feature_preprocessing as preprocessing_components
from autosklearn.askl_typing import FEAT_TYPE_TYPE
from autosklearn.pipeline.classification import SimpleClassificationPipeline
from autosklearn.pipeline.components.base import (
AutoSklearnChoice,
AutoSklearnClassificationAlgorithm,
AutoSklearnComponent,
AutoSklearnPreprocessingAlgorithm,
_addons,
)
from autosklearn.pipeline.constants import (
DENSE,
INPUT,
PREDICTIONS,
SIGNED_DATA,
SPARSE,
UNSIGNED_DATA,
)
from autosklearn.pipeline.util import get_dataset
import unittest
import unittest.mock
from test.test_pipeline.ignored_warnings import classifier_warnings, ignore_warnings
class DummyClassifier(AutoSklearnClassificationAlgorithm):
@staticmethod
def get_properties(dataset_properties=None):
return {
"shortname": "AB",
"name": "AdaBoost Classifier",
"handles_regression": False,
"handles_classification": True,
"handles_multiclass": True,
"handles_multilabel": True,
"handles_multioutput": False,
"is_deterministic": True,
"input": (DENSE, SPARSE, UNSIGNED_DATA),
"output": (PREDICTIONS,),
}
@staticmethod
def get_hyperparameter_search_space(feat_type=None, dataset_properties=None):
cs = ConfigurationSpace()
return cs
class DummyPreprocessor(AutoSklearnPreprocessingAlgorithm):
@staticmethod
def get_properties(dataset_properties=None):
return {
"shortname": "AB",
"name": "AdaBoost Classifier",
"handles_regression": False,
"handles_classification": True,
"handles_multiclass": True,
"handles_multilabel": True,
"handles_multioutput": False,
"is_deterministic": True,
"input": (DENSE, SPARSE, UNSIGNED_DATA),
"output": (INPUT,),
}
@staticmethod
def get_hyperparameter_search_space(dataset_properties=None):
cs = ConfigurationSpace()
return cs
class CrashPreprocessor(AutoSklearnPreprocessingAlgorithm):
def __init__(*args, **kwargs):
pass
@staticmethod
def get_properties(dataset_properties=None):
return {
"shortname": "AB",
"name": "AdaBoost Classifier",
"handles_regression": False,
"handles_classification": True,
"handles_multiclass": True,
"handles_multilabel": True,
"handles_multioutput": False,
"is_deterministic": True,
"input": (DENSE, SPARSE, UNSIGNED_DATA),
"output": (INPUT,),
}
def fit(self, X, y):
raise ValueError("Make sure fit is called")
@staticmethod
def get_hyperparameter_search_space(dataset_properties=None):
cs = ConfigurationSpace()
return cs
class SimpleClassificationPipelineTest(unittest.TestCase):
_multiprocess_can_split_ = True
def test_io_dict(self):
"""Test for the properties of classifier components
Expects
-------
* All required properties are stated in class `get_properties()`
"""
classifiers = classification_components._classifiers
for c in classifiers:
if classifiers[c] == classification_components.ClassifierChoice:
continue
props = classifiers[c].get_properties()
self.assertIn("input", props)
self.assertIn("output", props)
inp = props["input"]
output = props["output"]
self.assertIsInstance(inp, tuple)
self.assertIsInstance(output, tuple)
for i in inp:
self.assertIn(i, (SPARSE, DENSE, SIGNED_DATA, UNSIGNED_DATA))
self.assertEqual(output, (PREDICTIONS,))
self.assertIn("handles_regression", props)
self.assertFalse(props["handles_regression"])
self.assertIn("handles_classification", props)
self.assertIn("handles_multiclass", props)
self.assertIn("handles_multilabel", props)
def test_find_classifiers(self):
"""Test that the classifier components can be found
Expects
-------
* At least two classifier components can be found
* They inherit from AutoSklearnClassificationAlgorithm
"""
classifiers = classification_components._classifiers
self.assertGreaterEqual(len(classifiers), 2)
for key in classifiers:
if hasattr(classifiers[key], "get_components"):
continue
self.assertIn(
AutoSklearnClassificationAlgorithm, classifiers[key].__bases__
)
def test_find_preprocessors(self):
"""Test that preproccesor components can be found
Expects
-------
* At least 1 preprocessor component can be found
* The inherit from AutoSklearnPreprocessingAlgorithm
"""
preprocessors = preprocessing_components._preprocessors
self.assertGreaterEqual(len(preprocessors), 1)
for key in preprocessors:
if hasattr(preprocessors[key], "get_components"):
continue
self.assertIn(
AutoSklearnPreprocessingAlgorithm, preprocessors[key].__bases__
)
def test_default_configuration(self):
"""Test that seeded SimpleClassificaitonPipeline returns good results on iris
Expects
-------
* The performance of configuration with fixed seed gets above 96% accuracy
on iris
"""
X_train, Y_train, X_test, Y_test = get_dataset(dataset="iris")
auto = SimpleClassificationPipeline(random_state=1)
with ignore_warnings(classifier_warnings):
auto = auto.fit(X_train, Y_train)
predictions = auto.predict(X_test)
acc = sklearn.metrics.accuracy_score(predictions, Y_test)
self.assertAlmostEqual(0.96, acc)
def test_default_configuration_multilabel(self):
"""Test that SimpleClassificationPipeline default config returns good results on
a multilabel version of iris.
Expects
-------
* The performance of a random configuratino gets above 96% on a multilabel
version of iris
"""
X_train, Y_train, X_test, Y_test = get_dataset(
dataset="iris", make_multilabel=True
)
classifier = SimpleClassificationPipeline(
dataset_properties={"multilabel": True}, random_state=0
)
cs = classifier.get_hyperparameter_search_space()
default = cs.get_default_configuration()
classifier.set_hyperparameters(default)
with ignore_warnings(classifier_warnings):
classifier = classifier.fit(X_train, Y_train)
predictions = classifier.predict(X_test)
acc = sklearn.metrics.accuracy_score(predictions, Y_test)
self.assertAlmostEqual(0.96, acc)
def test_default_configuration_iterative_fit(self):
"""Test that the SimpleClassificationPipeline default config for random forest
with no preprocessing can be iteratively fit on iris.
Expects
-------
* Random forest pipeline can be fit iteratively
* Test that its number of estimators is equal to the iteration count
"""
X_train, Y_train, X_test, Y_test = get_dataset(dataset="iris")
classifier = SimpleClassificationPipeline(
include={
"classifier": ["random_forest"],
"feature_preprocessor": ["no_preprocessing"],
},
random_state=0,
)
classifier.fit_transformer(X_train, Y_train)
with ignore_warnings(classifier_warnings):
for i in range(1, 11):
classifier.iterative_fit(X_train, Y_train)
n_estimators = classifier.steps[-1][-1].choice.estimator.n_estimators
self.assertEqual(n_estimators, i)
def test_repr(self):
"""Test that the default pipeline can be converted to its representation and
converted back.
Expects
-------
* The the SimpleClassificationPipeline has a repr
* This repr can be evaluated back to an instance of SimpleClassificationPipeline
"""
representation = repr(SimpleClassificationPipeline())
cls = eval(representation)
self.assertIsInstance(cls, SimpleClassificationPipeline)
def test_multilabel(self):
"""Test non-seeded configurations for multi-label data
Expects
-------
* All configurations should fit, predict and predict_proba successfully
"""
cache = Memory(location=tempfile.gettempdir())
cached_func = cache.cache(sklearn.datasets.make_multilabel_classification)
X, Y = cached_func(
n_samples=150,
n_features=20,
n_classes=5,
n_labels=2,
length=50,
allow_unlabeled=True,
sparse=False,
return_indicator=True,
return_distributions=False,
random_state=1,
)
data = {
"X_train": X[:100, :],
"Y_train": Y[:100, :],
"X_test": X[101:, :],
"Y_test": Y[
101:,
],
}
pipeline = SimpleClassificationPipeline(dataset_properties={"multilabel": True})
cs = pipeline.get_hyperparameter_search_space()
self._test_configurations(configurations_space=cs, dataset=data)
def test_configurations(self):
"""Test non-seeded random sets of configurations with default dataset properties
Expects
-------
* All configurations should fit, predict and predict_proba successfully
"""
cls = SimpleClassificationPipeline()
cs = cls.get_hyperparameter_search_space()
self._test_configurations(configurations_space=cs)
def test_configurations_signed_data(self):
"""Tests a non-seeded random set of configurations with signed data
Expects
-------
* All configurations should fit, predict and predict_proba successfully
"""
dataset_properties = {"signed": True}
cls = SimpleClassificationPipeline(dataset_properties=dataset_properties)
cs = cls.get_hyperparameter_search_space()
self._test_configurations(
configurations_space=cs, dataset_properties=dataset_properties
)
def test_configurations_sparse(self):
"""Tests a non-seeded random set of configurations with sparse data
Expects
-------
* All configurations should fit, predict and predict_proba successfully
"""
pipeline = SimpleClassificationPipeline(dataset_properties={"sparse": True})
cs = pipeline.get_hyperparameter_search_space()
self._test_configurations(configurations_space=cs, make_sparse=True)
def test_configurations_categorical_data(self):
"""Tests a non-seeded random set of configurations with sparse, mixed data
Loads specific data from <here>/components/data_preprocessing/dataset.pkl
Expects
-------
* All configurations should fit, predict and predict_proba successfully
"""
categorical_columns = [
True,
True,
True,
False,
False,
True,
True,
True,
False,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
False,
False,
False,
True,
True,
True,
]
categorical = {
i: "categorical" if is_categorical else "numerical"
for i, is_categorical in enumerate(categorical_columns)
}
pipeline = SimpleClassificationPipeline(
feat_type=categorical,
dataset_properties={"sparse": False},
include={
"feature_preprocessor": ["no_preprocessing"],
"classifier": ["sgd", "adaboost"],
},
)
cs = pipeline.get_hyperparameter_search_space(feat_type=categorical)
here = os.path.dirname(__file__)
dataset_path = os.path.join(
here, "components", "data_preprocessing", "dataset.pkl"
)
X = np.loadtxt(dataset_path)
y = X[:, -1].copy()
X = X[:, :-1]
X_train, X_test, Y_train, Y_test = sklearn.model_selection.train_test_split(
X, y
)
data = {
"X_train": X_train,
"Y_train": Y_train,
"X_test": X_test,
"Y_test": Y_test,
}
init_params = {"data_preprocessor:feat_type": categorical}
self._test_configurations(
configurations_space=cs,
dataset=data,
init_params=init_params,
feat_type=categorical,
)
@unittest.mock.patch(
"autosklearn.pipeline.components.data_preprocessing"
".DataPreprocessorChoice.set_hyperparameters"
)
def test_categorical_passed_to_one_hot_encoder(self, ohe_mock):
"""Test that the feat_types arg is passed to the OneHotEncoder
Expects
-------
* Construction of SimpleClassificationPipeline to pass init_params correctly
to the OneHotEncoder
* Setting the pipeline's hyperparameters after construction also correctly
sets the init params of the OneHotEncoder
"""
# Mock the _check_init_params_honored as there is no object created,
# _check_init_params_honored will fail as a datapreprocessor was never created
with unittest.mock.patch(
"autosklearn.pipeline.classification.SimpleClassificationPipeline"
"._check_init_params_honored"
):
# Check through construction
feat_types = {0: "categorical", 1: "numerical"}
cls = SimpleClassificationPipeline(
feat_type=feat_types,
init_params={"data_preprocessor:feat_type": feat_types},
)
init_args = ohe_mock.call_args[1]["init_params"]
self.assertEqual(init_args, {"feat_type": feat_types})
# Check through `set_hyperparameters`
feat_types = {0: "categorical", 1: "categorical", 2: "numerical"}
default = cls.get_hyperparameter_search_space(
feat_type=feat_types
).get_default_configuration()
cls.set_hyperparameters(
feat_type=feat_types,
configuration=default,
init_params={"data_preprocessor:feat_type": feat_types},
)
init_args = ohe_mock.call_args[1]["init_params"]
self.assertEqual(init_args, {"feat_type": feat_types})
def _test_configurations(
self,
configurations_space: ConfigurationSpace,
make_sparse: bool = False,
dataset: Union[str, Dict[str, Any]] = "digits",
init_params: Dict[str, Any] = None,
dataset_properties: Dict[str, Any] = None,
n_samples: int = 10,
feat_type: Optional[FEAT_TYPE_TYPE] = None,
):
"""Tests a configuration space by taking multiple samples and fiting each
before calling predict and predict_proba.
Parameters
----------
configurations_space: ConfigurationSpace
The configuration space to sample from
make_sparse: bool = False
Whether to make the dataset sparse or not
dataset: Union[str, Dict[str, Any]] = 'digits'
Either a dataset name or a dictionary as below. If given a str, it will
use `make_sparse` and add NaNs to the dataset.
{'X_train': ..., 'Y_train': ..., 'X_test': ..., 'y_test': ...}
init_params: Dict[str, Any] = None
A dictionary of initial parameters to give to the pipeline.
dataset_properties: Dict[str, Any]
A dictionary of properties describing the dataset
n_samples: int = 10
How many configurations to sample
"""
# Use a limit of ~3GiB
limit = 3072 * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
for i in range(n_samples):
config = configurations_space.sample_configuration()
config._populate_values()
# Restrict configurations which could take too long on travis-ci
restrictions = {
"classifier:passive_aggressive:n_iter": 5,
"classifier:sgd:n_iter": 5,
"classifier:adaboost:n_estimators": 50,
"classifier:adaboost:max_depth": 1,
"feature_preprocessor:kernel_pca:n_components": 10,
"feature_preprocessor:kitchen_sinks:n_components": 50,
"classifier:proj_logit:max_epochs": 1,
"classifier:libsvm_svc:degree": 2,
"regressor:libsvm_svr:degree": 2,
"feature_preprocessor:truncatedSVD:target_dim": 10,
"feature_preprocessor:polynomial:degree": 2,
"classifier:lda:n_components": 10,
"feature_preprocessor:nystroem_sampler:n_components": 50,
"feature_preprocessor:feature_agglomeration:n_clusters": 2,
"classifier:gradient_boosting:max_leaf_nodes": 64,
}
config._values.update(
{
param: value
for param, value in restrictions.items()
if param in config and config[param] is not None
}
)
if isinstance(dataset, str):
X_train, Y_train, X_test, Y_test = get_dataset(
dataset=dataset, make_sparse=make_sparse, add_NaNs=True
)
else:
X_train = dataset["X_train"].copy()
Y_train = dataset["Y_train"].copy()
X_test = dataset["X_test"].copy()
dataset["Y_test"].copy()
init_params_ = copy.deepcopy(init_params)
cls = SimpleClassificationPipeline(
feat_type=feat_type,
dataset_properties=dataset_properties,
init_params=init_params_,
)
cls.set_hyperparameters(
config, init_params=init_params_, feat_type=feat_type
)
# First make sure that for this configuration, setting the parameters
# does not mistakenly set the estimator as fitted
for name, step in cls.named_steps.items():
with self.assertRaisesRegex(
sklearn.exceptions.NotFittedError, "instance is not fitted yet"
):
check_is_fitted(step)
try:
with ignore_warnings(classifier_warnings):
cls.fit(X_train, Y_train)
# After fit, all components should be tagged as fitted
# by sklearn. Check is fitted raises an exception if that
# is not the case
try:
for name, step in cls.named_steps.items():
check_is_fitted(step)
except sklearn.exceptions.NotFittedError:
self.fail(f"config={config} raised NotFittedError unexpectedly!")
cls.predict(X_test.copy())
cls.predict_proba(X_test)
except MemoryError:
continue
except np.linalg.LinAlgError:
continue
except ValueError as e:
if "Floating-point under-/overflow occurred at epoch" in e.args[0]:
continue
elif "removed all features" in e.args[0]:
continue
elif "all features are discarded" in e.args[0]:
continue
elif "Numerical problems in QDA" in e.args[0]:
continue
elif "Bug in scikit-learn" in e.args[0]:
continue
elif (
"The condensed distance matrix must contain only finite "
"values." in e.args[0]
):
continue
elif "Internal work array size computation failed" in e.args[0]:
continue
# Assumed to be caused by knn with preprocessor fast_ica with whiten
elif "Input contains NaN, infinity or a value too large" in e.args[0]:
continue
elif (
"zero-size array to reduction operation maximum which has no "
"identity" in e.args[0]
):
continue
else:
e.args += (f"config={config}",)
raise e
except RuntimeWarning as e:
if "invalid value encountered in sqrt" in e.args[0]:
continue
elif "invalid value encountered in multiply" in e.args[0]:
continue
elif "divide by zero encountered in" in e.args[0]:
continue
elif "invalid value encountered in divide" in e.args[0]:
continue
elif "invalid value encountered in true_divide" in e.args[0]:
continue
elif "invalid value encountered in multiply" in e.args[0]:
continue
else:
e.args += (f"config={config}",)
raise e
except UserWarning as e:
if "FastICA did not converge" in e.args[0]:
continue
else:
e.args += (f"config={config}",)
raise e
def test_get_hyperparameter_search_space(self):
"""Test the configuration space returned by a SimpleClassificationPipeline
Expects
-------
* pipeline returns a configurations space
* 7 rescaling choices
* 16 classifier choices
* 13 features preprocessor choices
* 176 total hyperparameters
* (n_hyperparameters - 4) different conditionals for the pipeline
* 53 forbidden combinations
"""
pipeline = SimpleClassificationPipeline(
feat_type={"A": "numerical", "B": "categorical", "C": "string"}
)
cs = pipeline.get_hyperparameter_search_space()
self.assertIsInstance(cs, ConfigurationSpace)
rescale_param = (
"data_preprocessor:feature_type:numerical_transformer:rescaling:__choice__"
)
n_choices = len(cs.get_hyperparameter(rescale_param).choices)
self.assertEqual(n_choices, 7)
n_classifiers = len(cs.get_hyperparameter("classifier:__choice__").choices)
self.assertEqual(n_classifiers, 16)
n_preprocessors = len(
cs.get_hyperparameter("feature_preprocessor:__choice__").choices
)
self.assertEqual(n_preprocessors, 13)
hyperparameters = cs.get_hyperparameters()
self.assertEqual(len(hyperparameters), 179)
# for hp in sorted([str(h) for h in hyperparameters]):
# print hp
# The four components which are always active are classifier,
# feature preprocessor, balancing and data preprocessing pipeline.
conditions = cs.get_conditions()
self.assertEqual(len(hyperparameters) - 4, len(conditions))
forbiddens = cs.get_forbiddens()
self.assertEqual(len(forbiddens), 53)
def test_get_hyperparameter_search_space_include_exclude_models(self):
"""Test the configuration space when using include and exclude
Expects
-------
* Including a classifier has pipeline give back matching choice
* Excluding a classifier means it won't show up in the hyperparameter space
* Including a feature preprocessor has pipeline give back matching choice
* Excluding a feature preprocessor means it won't show up in the
hyperparameter space
"""
# include a classifier choice
pipeline = SimpleClassificationPipeline(include={"classifier": ["libsvm_svc"]})
cs = pipeline.get_hyperparameter_search_space()
expected = CategoricalHyperparameter("classifier:__choice__", ["libsvm_svc"])
returned = cs.get_hyperparameter("classifier:__choice__")
self.assertEqual(returned, expected)
# exclude a classifier choice
pipeline = SimpleClassificationPipeline(exclude={"classifier": ["libsvm_svc"]})
cs = pipeline.get_hyperparameter_search_space()
self.assertNotIn("libsvm_svc", str(cs))
# include a feature preprocessor
pipeline = SimpleClassificationPipeline(
include={"feature_preprocessor": ["select_percentile_classification"]}
)
cs = pipeline.get_hyperparameter_search_space()
returned = cs.get_hyperparameter("feature_preprocessor:__choice__")
expected = CategoricalHyperparameter(
"feature_preprocessor:__choice__", ["select_percentile_classification"]
)
self.assertEqual(returned, expected)
# exclude a feature preprocessor
pipeline = SimpleClassificationPipeline(
exclude={"feature_preprocessor": ["select_percentile_classification"]}
)
cs = pipeline.get_hyperparameter_search_space()
self.assertNotIn("select_percentile_classification", str(cs))
def test_get_hyperparameter_search_space_preprocessor_contradicts_default(
self,
):
"""Test that the default classifier gets updated based on the legal feature
preprocessors that come before.
Expects
-------
* With 'densifier' as only legal feature_preprocessor, 'qda' is default
* With 'nystroem_sampler' as only legal feature_preprocessor, 'sgd' is default
"""
pipeline = SimpleClassificationPipeline(
include={"feature_preprocessor": ["densifier"]},
dataset_properties={"sparse": True},
)
cs = pipeline.get_hyperparameter_search_space()
default_choice = cs.get_hyperparameter("classifier:__choice__").default_value
self.assertEqual(default_choice, "qda")
pipeline = SimpleClassificationPipeline(
include={"feature_preprocessor": ["nystroem_sampler"]}
)
cs = pipeline.get_hyperparameter_search_space()
default_choice = cs.get_hyperparameter("classifier:__choice__").default_value
self.assertEqual(default_choice, "sgd")
def test_get_hyperparameter_search_space_only_forbidden_combinations(self):
"""Test that invalid pipeline configurations raise errors
Expects
-------
* 0 combinations are found with 'multinomial_nb' and 'pca' with 'sparse' data
* Classifiers that can handle sparse but located behind a 'densifier' should
raise that no legal default configuration can be found
"""
with self.assertRaisesRegex(AssertionError, "No valid pipeline found."):
SimpleClassificationPipeline(
include={
"classifier": ["multinomial_nb"],
"feature_preprocessor": ["pca"],
},
dataset_properties={"sparse": True},
)
with self.assertRaisesRegex(
ValueError, "Cannot find a legal default configuration."
):
SimpleClassificationPipeline(
include={
"classifier": ["liblinear_svc"],
"feature_preprocessor": ["densifier"],
},
dataset_properties={"sparse": True},
)
@unittest.skip("Wait until ConfigSpace is fixed.")
def test_get_hyperparameter_search_space_dataset_properties(self):
cs_mc = SimpleClassificationPipeline.get_hyperparameter_search_space(
dataset_properties={"multiclass": True}
)
self.assertNotIn("bernoulli_nb", str(cs_mc))
cs_ml = SimpleClassificationPipeline.get_hyperparameter_search_space(
dataset_properties={"multilabel": True}
)
self.assertNotIn("k_nearest_neighbors", str(cs_ml))
self.assertNotIn("liblinear", str(cs_ml))
self.assertNotIn("libsvm_svc", str(cs_ml))
self.assertNotIn("sgd", str(cs_ml))
cs_sp = SimpleClassificationPipeline.get_hyperparameter_search_space(
dataset_properties={"sparse": True}
)
self.assertIn("extra_trees", str(cs_sp))
self.assertIn("gradient_boosting", str(cs_sp))
self.assertIn("random_forest", str(cs_sp))
cs_mc_ml = SimpleClassificationPipeline.get_hyperparameter_search_space(
dataset_properties={"multilabel": True, "multiclass": True}
)
self.assertEqual(cs_ml, cs_mc_ml)
def test_predict_batched(self):
"""Test that predict_proba predicts the same as the underlying classifier with
predict_proba argument `batches`.
Expects
-------
* Should expect the output shape to match that of the digits dataset
* Should expect a fixed call count each test run
* Should expect predict_proba with `batches` and predict_proba
perform near identically
"""
cls = SimpleClassificationPipeline(include={"classifier": ["sgd"]})
# Multiclass
X_train, Y_train, X_test, Y_test = get_dataset(dataset="digits")
with ignore_warnings(classifier_warnings):
cls.fit(X_train, Y_train)
X_test_ = X_test.copy()
prediction_ = cls.predict_proba(X_test_)
# The object behind the last step in the pipeline
cls_predict = unittest.mock.Mock(wraps=cls.steps[-1][1].predict_proba)
cls.steps[-1][-1].predict_proba = cls_predict
prediction = cls.predict_proba(X_test, batch_size=20)
self.assertEqual((1647, 10), prediction.shape)
self.assertEqual(84, cls_predict.call_count)
np.testing.assert_array_almost_equal(prediction_, prediction)
def test_predict_batched_sparse(self):
"""Test that predict_proba predicts the same as the underlying classifier with
predict_proba argument `batches`, with a sparse dataset
Expects
-------
* Should expect the output shape to match that of the digits dataset
* Should expect a fixed call count each test run
* Should expect predict_proba with `batches` and predict_proba
perform near identically
"""
cls = SimpleClassificationPipeline(
dataset_properties={"sparse": True}, include={"classifier": ["sgd"]}
)
# Multiclass
X_train, Y_train, X_test, Y_test = get_dataset(
dataset="digits", make_sparse=True
)
with ignore_warnings(classifier_warnings):
cls.fit(X_train, Y_train)
X_test_ = X_test.copy()
prediction_ = cls.predict_proba(X_test_)
# The object behind the last step in the pipeline
cls_predict = unittest.mock.Mock(wraps=cls.steps[-1][1].predict_proba)
cls.steps[-1][-1].predict_proba = cls_predict
prediction = cls.predict_proba(X_test, batch_size=20)
self.assertEqual((1647, 10), prediction.shape)
self.assertEqual(84, cls_predict.call_count)
np.testing.assert_array_almost_equal(prediction_, prediction)
def test_predict_proba_batched(self):
"""Test that predict_proba predicts the same as the underlying classifier with
predict_proba argument `batches`, for multiclass and multilabel data.
Expects
-------
* Should expect the output shape to match that of the digits dataset
* Should expect a fixed call count each test run
* Should expect predict_proba with `batches` and predict_proba
perform near identically
"""
# Multiclass
cls = SimpleClassificationPipeline(
feat_type={i: "numerical" for i in range(0, 64)},
include={"classifier": ["sgd"]},
)
X_train, Y_train, X_test, Y_test = get_dataset(dataset="digits")
with ignore_warnings(classifier_warnings):
cls.fit(X_train, Y_train)
X_test_ = X_test.copy()
prediction_ = cls.predict_proba(X_test_)
# The object behind the last step in the pipeline
cls_predict = unittest.mock.Mock(wraps=cls.steps[-1][1].predict_proba)
cls.steps[-1][-1].predict_proba = cls_predict
prediction = cls.predict_proba(X_test, batch_size=20)
self.assertEqual((1647, 10), prediction.shape)
self.assertEqual(84, cls_predict.call_count)
np.testing.assert_array_almost_equal(prediction_, prediction)
# Multilabel
cls = SimpleClassificationPipeline(include={"classifier": ["lda"]})
X_train, Y_train, X_test, Y_test = get_dataset(dataset="digits")
Y_train = np.array(
list([(list([1 if i != y else 0 for i in range(10)])) for y in Y_train])
)
with ignore_warnings(classifier_warnings):
cls.fit(X_train, Y_train)
X_test_ = X_test.copy()
prediction_ = cls.predict_proba(X_test_)
# The object behind the last step in the pipeline
cls_predict = unittest.mock.Mock(wraps=cls.steps[-1][1].predict_proba)
cls.steps[-1][-1].predict_proba = cls_predict
prediction = cls.predict_proba(X_test, batch_size=20)
self.assertEqual((1647, 10), prediction.shape)
self.assertEqual(84, cls_predict.call_count)
np.testing.assert_array_almost_equal(prediction_, prediction)
def test_predict_proba_batched_sparse(self):
"""Test that predict_proba predicts the same as the underlying classifier with
predict_proba argument `batches`, for multiclass and multilabel data.
Expects
-------
* Should expect the output shape to match that of the digits dataset
* Should expect a fixed call count each test run
* Should expect predict_proba with `batches` and predict_proba
perform near identically
"""
cls = SimpleClassificationPipeline(
feat_type={i: "numerical" for i in range(0, 64)},
dataset_properties={"sparse": True, "multiclass": True},
include={"classifier": ["sgd"]},
)
# Multiclass
X_train, Y_train, X_test, Y_test = get_dataset(
dataset="digits", make_sparse=True
)
X_test_ = X_test.copy()
with ignore_warnings(classifier_warnings):
cls.fit(X_train, Y_train)
prediction_ = cls.predict_proba(X_test_)
# The object behind the last step in the pipeline
cls_predict = unittest.mock.Mock(wraps=cls.steps[-1][1].predict_proba)
cls.steps[-1][-1].predict_proba = cls_predict
prediction = cls.predict_proba(X_test, batch_size=20)
self.assertEqual((1647, 10), prediction.shape)
self.assertEqual(84, cls_predict.call_count)
np.testing.assert_array_almost_equal(prediction_, prediction)
# Multilabel
cls = SimpleClassificationPipeline(