-
-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathtest_run_functions.py
More file actions
2035 lines (1838 loc) · 77.9 KB
/
test_run_functions.py
File metadata and controls
2035 lines (1838 loc) · 77.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
# License: BSD 3-Clause
from __future__ import annotations
import ast
import os
import random
import time
import unittest
import warnings
from openml_sklearn import SklearnExtension, cat, cont
from packaging.version import Version
from unittest import mock
import arff
import joblib
import numpy as np
import pandas as pd
import pytest
import requests
import sklearn
from joblib import parallel_backend
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier
from sklearn.feature_selection import VarianceThreshold
from sklearn.linear_model import LinearRegression, LogisticRegression, SGDClassifier
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, StratifiedKFold
from sklearn.model_selection._search import BaseSearchCV
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.compose import ColumnTransformer
import openml
import openml._api_calls
import openml.exceptions
from openml.exceptions import (
OpenMLNotAuthorizedError,
OpenMLServerException,
)
#from openml.extensions.sklearn import cat, cont
from openml.runs.functions import (
_run_task_get_arffcontent,
delete_run,
format_prediction,
run_exists,
)
from openml.runs.trace import OpenMLRunTrace
from openml.tasks import TaskType
from openml.testing import (
CustomImputer,
SimpleImputer,
TestBase,
check_task_existence,
create_request_response,
)
class TestRun(TestBase):
_multiprocess_can_split_ = True
TEST_SERVER_TASK_MISSING_VALS = {
"task_id": 96,
"n_missing_vals": 67,
"n_test_obs": 227,
"nominal_indices": [0, 3, 4, 5, 6, 8, 9, 11, 12],
"numeric_indices": [1, 2, 7, 10, 13, 14],
"task_meta_data": {
"task_type": TaskType.SUPERVISED_CLASSIFICATION,
"dataset_id": 16, # credit-a
"estimation_procedure_id": 6,
"target_name": "class",
},
}
TEST_SERVER_TASK_SIMPLE = {
"task_id": 119,
"n_missing_vals": 0,
"n_test_obs": 253,
"nominal_indices": [],
"numeric_indices": [*range(8)],
"task_meta_data": {
"task_type": TaskType.SUPERVISED_CLASSIFICATION,
"dataset_id": 20, # diabetes
"estimation_procedure_id": 5,
"target_name": "class",
},
}
TEST_SERVER_TASK_REGRESSION = {
"task_id": 1605,
"n_missing_vals": 0,
"n_test_obs": 2178,
"nominal_indices": [],
"numeric_indices": [*range(8)],
"task_meta_data": {
"task_type": TaskType.SUPERVISED_REGRESSION,
"dataset_id": 123, # quake
"estimation_procedure_id": 7,
"target_name": "richter",
},
}
# Suppress warnings to facilitate testing
hide_warnings = True
if hide_warnings:
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
def setUp(self):
super().setUp()
self.extension = SklearnExtension()
def _wait_for_processed_run(self, run_id, max_waiting_time_seconds):
# it can take a while for a run to be processed on the OpenML (test)
# server however, sometimes it is good to wait (a bit) for this, to
# properly test a function. In this case, we wait for max_waiting_time_
# seconds on this to happen, probing the server every 10 seconds to
# speed up the process
# time.time() works in seconds
start_time = time.time()
while time.time() - start_time < max_waiting_time_seconds:
try:
openml.runs.get_run_trace(run_id)
except openml.exceptions.OpenMLServerException:
time.sleep(10)
continue
run = openml.runs.get_run(run_id, ignore_cache=True)
if run.evaluations is None:
time.sleep(10)
continue
assert len(run.evaluations) > 0, (
"Expect not-None evaluations to always contain elements."
)
return
raise RuntimeError(
f"Could not find any evaluations! Please check whether run {run_id} was "
"evaluated correctly on the server",
)
def _assert_predictions_equal(self, predictions, predictions_prime):
assert np.array(predictions_prime["data"]).shape == np.array(predictions["data"]).shape
# The original search model does not submit confidence
# bounds, so we can not compare the arff line
compare_slice = [0, 1, 2, -1, -2]
for idx in range(len(predictions["data"])):
# depends on the assumption "predictions are in same order"
# that does not necessarily hold.
# But with the current code base, it holds.
for col_idx in compare_slice:
val_1 = predictions["data"][idx][col_idx]
val_2 = predictions_prime["data"][idx][col_idx]
if isinstance(val_1, float) or isinstance(val_2, float):
self.assertAlmostEqual(
float(val_1),
float(val_2),
places=6,
)
else:
assert val_1 == val_2
def _rerun_model_and_compare_predictions(self, run_id, model_prime, seed, create_task_obj):
run = openml.runs.get_run(run_id)
# TODO: assert holdout task
# downloads the predictions of the old task
file_id = run.output_files["predictions"]
predictions_url = openml._api_calls._file_id_to_url(file_id)
response = openml._api_calls._download_text_file(predictions_url)
predictions = arff.loads(response)
# if create_task_obj=False, task argument in run_model_on_task is specified task_id
if create_task_obj:
task = openml.tasks.get_task(run.task_id)
run_prime = openml.runs.run_model_on_task(
model=model_prime,
task=task,
seed=seed,
)
else:
run_prime = openml.runs.run_model_on_task(
model=model_prime,
task=run.task_id,
seed=seed,
)
predictions_prime = run_prime._generate_arff_dict()
self._assert_predictions_equal(predictions, predictions_prime)
pd.testing.assert_frame_equal(
run.predictions,
run_prime.predictions,
check_dtype=False, # Loaded ARFF reads NUMERIC as float, even if integer.
)
def _perform_run(
self,
task_id,
num_instances,
n_missing_vals,
clf,
flow_expected_rsv=None,
seed=1,
check_setup=True,
sentinel=None,
):
"""
Runs a classifier on a task, and performs some basic checks.
Also uploads the run.
Parameters
----------
task_id : int
num_instances: int
The expected length of the prediction file (number of test
instances in original dataset)
n_missing_values: int
clf: sklearn.base.BaseEstimator
The classifier to run
flow_expected_rsv: str
The expected random state value for the flow (check by hand,
depends on seed parameter)
seed: int
The seed with which the RSV for runs will be initialized
check_setup: bool
If set to True, the flow will be downloaded again and
reinstantiated, for consistency with original flow.
sentinel: optional, str
in case the sentinel should be user specified
Returns
-------
run: OpenMLRun
The performed run (with run id)
"""
classes_without_random_state = [
"sklearn.model_selection._search.GridSearchCV",
"sklearn.pipeline.Pipeline",
]
if Version(sklearn.__version__) < Version("0.22"):
classes_without_random_state.append("sklearn.linear_model.base.LinearRegression")
else:
classes_without_random_state.append("sklearn.linear_model._base.LinearRegression")
def _remove_random_state(flow):
if "random_state" in flow.parameters:
del flow.parameters["random_state"]
for component in flow.components.values():
_remove_random_state(component)
flow = self.extension.model_to_flow(clf)
flow, _ = self._add_sentinel_to_flow_name(flow, sentinel)
if not openml.flows.flow_exists(flow.name, flow.external_version):
flow.publish()
TestBase._mark_entity_for_removal("flow", flow.flow_id, flow.name)
TestBase.logger.info(f"collected from test_run_functions: {flow.flow_id}")
task = openml.tasks.get_task(task_id)
X, y = task.get_X_and_y()
assert X.isna().sum().sum() == n_missing_vals
run = openml.runs.run_flow_on_task(
flow=flow,
task=task,
seed=seed,
)
run_ = run.publish()
TestBase._mark_entity_for_removal("run", run.run_id)
TestBase.logger.info(f"collected from test_run_functions: {run.run_id}")
assert run_ == run
assert isinstance(run.dataset_id, int)
# This is only a smoke check right now
# TODO add a few asserts here
run._to_xml()
if run.trace is not None:
# This is only a smoke check right now
# TODO add a few asserts here
run.trace.trace_to_arff()
# check arff output
assert len(run.data_content) == num_instances
if check_setup:
# test the initialize setup function
run_id = run_.run_id
run_server = openml.runs.get_run(run_id)
clf_server = openml.setups.initialize_model(
setup_id=run_server.setup_id,
)
flow_local = self.extension.model_to_flow(clf)
flow_server = self.extension.model_to_flow(clf_server)
if flow.class_name not in classes_without_random_state:
error_msg = "Flow class %s (id=%d) does not have a random state parameter" % (
flow.class_name,
flow.flow_id,
)
assert "random_state" in flow.parameters, error_msg
# If the flow is initialized from a model without a random
# state, the flow is on the server without any random state
assert flow.parameters["random_state"] == "null"
# As soon as a flow is run, a random state is set in the model.
# If a flow is re-instantiated
assert flow_local.parameters["random_state"] == flow_expected_rsv
assert flow_server.parameters["random_state"] == flow_expected_rsv
_remove_random_state(flow_local)
_remove_random_state(flow_server)
openml.flows.assert_flows_equal(flow_local, flow_server)
# and test the initialize setup from run function
clf_server2 = openml.runs.initialize_model_from_run(
run_id=run_server.run_id,
)
flow_server2 = self.extension.model_to_flow(clf_server2)
if flow.class_name not in classes_without_random_state:
assert flow_server2.parameters["random_state"] == flow_expected_rsv
_remove_random_state(flow_server2)
openml.flows.assert_flows_equal(flow_local, flow_server2)
# self.assertEqual(clf.get_params(), clf_prime.get_params())
# self.assertEqual(clf, clf_prime)
downloaded = openml.runs.get_run(run_.run_id)
assert "openml-python" in downloaded.tags
# TODO make sure that these attributes are instantiated when
# downloading a run? Or make sure that the trace object is created when
# running a flow on a task (and not only the arff object is created,
# so that the two objects can actually be compared):
# downloaded_run_trace = downloaded._generate_trace_arff_dict()
# self.assertEqual(run_trace, downloaded_run_trace)
return run
def _check_sample_evaluations(
self,
sample_evaluations,
num_repeats,
num_folds,
num_samples,
max_time_allowed=60000,
):
"""
Checks whether the right timing measures are attached to the run
(before upload). Test is only performed for versions >= Python3.3
In case of check_n_jobs(clf) == false, please do not perform this
check (check this condition outside of this function. )
default max_time_allowed (per fold, in milli seconds) = 1 minute,
quite pessimistic
"""
# a dict mapping from openml measure to a tuple with the minimum and
# maximum allowed value
check_measures = {
# should take at least one millisecond (?)
"usercpu_time_millis_testing": (0, max_time_allowed),
"usercpu_time_millis_training": (0, max_time_allowed),
"usercpu_time_millis": (0, max_time_allowed),
"wall_clock_time_millis_training": (0, max_time_allowed),
"wall_clock_time_millis_testing": (0, max_time_allowed),
"wall_clock_time_millis": (0, max_time_allowed),
"predictive_accuracy": (0, 1),
}
assert isinstance(sample_evaluations, dict)
assert set(sample_evaluations.keys()) == set(check_measures.keys())
for measure in check_measures:
if measure in sample_evaluations:
num_rep_entrees = len(sample_evaluations[measure])
assert num_rep_entrees == num_repeats
for rep in range(num_rep_entrees):
num_fold_entrees = len(sample_evaluations[measure][rep])
assert num_fold_entrees == num_folds
for fold in range(num_fold_entrees):
num_sample_entrees = len(sample_evaluations[measure][rep][fold])
assert num_sample_entrees == num_samples
for sample in range(num_sample_entrees):
evaluation = sample_evaluations[measure][rep][fold][sample]
assert isinstance(evaluation, float)
if not (os.environ.get("CI_WINDOWS") or os.name == "nt"):
# Windows seems to get an eval-time of 0 sometimes.
assert evaluation > 0
assert evaluation < max_time_allowed
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_run_regression_on_classif_task(self):
task_id = 259 # collins; crossvalidation; has numeric targets
clf = LinearRegression()
task = openml.tasks.get_task(task_id)
# internally dataframe is loaded and targets are categorical
# which LinearRegression() cannot handle
with pytest.raises(
AttributeError, match="'LinearRegression' object has no attribute 'classes_'"
):
openml.runs.run_model_on_task(
model=clf,
task=task,
)
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_check_erronous_sklearn_flow_fails(self):
task_id = 115 # diabetes; crossvalidation
task = openml.tasks.get_task(task_id)
# Invalid parameter values
clf = LogisticRegression(C="abc", solver="lbfgs")
# The exact error message depends on scikit-learn version.
# Because the sklearn-extension module is to be separated,
# I will simply relax specifics of the raised Error.
# old: r"Penalty term must be positive; got \(C=u?'abc'\)"
# new: sklearn.utils._param_validation.InvalidParameterError:
# The 'C' parameter of LogisticRegression must be a float in the range (0, inf]. Got 'abc' instead. # noqa: E501
try:
from sklearn.utils._param_validation import InvalidParameterError
exceptions = (ValueError, InvalidParameterError)
except ImportError:
exceptions = (ValueError,)
with pytest.raises(exceptions):
openml.runs.run_model_on_task(
task=task,
model=clf,
)
###########################################################################
# These unit tests are meant to test the following functions, using a
# variety of flows:
# - openml.runs.run_task()
# - openml.runs.OpenMLRun.publish()
# - openml.runs.initialize_model()
# - [implicitly] openml.setups.initialize_model()
# - openml.runs.initialize_model_from_trace()
# They're split among several actual functions to allow for parallel
# execution of the unit tests without the need to add an additional module
# like unittest2
def _run_and_upload(
self,
clf,
task_id,
n_missing_vals,
n_test_obs,
flow_expected_rsv,
num_folds=1,
num_iterations=5,
seed=1,
metric=sklearn.metrics.accuracy_score,
metric_name="predictive_accuracy",
task_type=TaskType.SUPERVISED_CLASSIFICATION,
sentinel=None,
):
def determine_grid_size(param_grid):
if isinstance(param_grid, dict):
grid_iterations = 1
for param in param_grid:
grid_iterations *= len(param_grid[param])
return grid_iterations
elif isinstance(param_grid, list):
grid_iterations = 0
for sub_grid in param_grid:
grid_iterations += determine_grid_size(sub_grid)
return grid_iterations
else:
raise TypeError("Param Grid should be of type list (GridSearch only) or dict")
run = self._perform_run(
task_id,
n_test_obs,
n_missing_vals,
clf,
flow_expected_rsv=flow_expected_rsv,
seed=seed,
sentinel=sentinel,
)
# obtain scores using get_metric_score:
scores = run.get_metric_fn(metric)
# compare with the scores in user defined measures
scores_provided = []
for rep in run.fold_evaluations[metric_name]:
for fold in run.fold_evaluations[metric_name][rep]:
scores_provided.append(run.fold_evaluations[metric_name][rep][fold])
assert sum(scores_provided) == sum(scores)
if isinstance(clf, BaseSearchCV):
trace_content = run.trace.trace_to_arff()["data"]
if isinstance(clf, GridSearchCV):
grid_iterations = determine_grid_size(clf.param_grid)
assert len(trace_content) == grid_iterations * num_folds
else:
assert len(trace_content) == num_iterations * num_folds
# downloads the best model based on the optimization trace
# suboptimal (slow), and not guaranteed to work if evaluation
# engine is behind.
# TODO: mock this? We have the arff already on the server
self._wait_for_processed_run(run.run_id, 600)
try:
model_prime = openml.runs.initialize_model_from_trace(
run_id=run.run_id,
repeat=0,
fold=0,
)
except openml.exceptions.OpenMLServerException as e:
e.message = "%s; run_id %d" % (e.message, run.run_id)
raise e
self._rerun_model_and_compare_predictions(
run.run_id,
model_prime,
seed,
create_task_obj=True,
)
self._rerun_model_and_compare_predictions(
run.run_id,
model_prime,
seed,
create_task_obj=False,
)
else:
run_downloaded = openml.runs.get_run(run.run_id)
sid = run_downloaded.setup_id
model_prime = openml.setups.initialize_model(sid)
self._rerun_model_and_compare_predictions(
run.run_id,
model_prime,
seed,
create_task_obj=True,
)
self._rerun_model_and_compare_predictions(
run.run_id,
model_prime,
seed,
create_task_obj=False,
)
# todo: check if runtime is present
self._check_fold_timing_evaluations(
fold_evaluations=run.fold_evaluations,
num_repeats=1,
num_folds=num_folds,
task_type=task_type,
)
# Check if run string and print representation do not run into an error
# The above check already verifies that all columns needed for supported
# representations are present.
# Supported: SUPERVISED_CLASSIFICATION, LEARNING_CURVE, SUPERVISED_REGRESSION
str(run)
self.logger.info(run)
return run
def _run_and_upload_classification(
self,
clf,
task_id,
n_missing_vals,
n_test_obs,
flow_expected_rsv,
sentinel=None,
):
num_folds = 1 # because of holdout
num_iterations = 5 # for base search algorithms
metric = sklearn.metrics.accuracy_score # metric class
metric_name = "predictive_accuracy" # openml metric name
task_type = TaskType.SUPERVISED_CLASSIFICATION # task type
return self._run_and_upload(
clf=clf,
task_id=task_id,
n_missing_vals=n_missing_vals,
n_test_obs=n_test_obs,
flow_expected_rsv=flow_expected_rsv,
num_folds=num_folds,
num_iterations=num_iterations,
metric=metric,
metric_name=metric_name,
task_type=task_type,
sentinel=sentinel,
)
def _run_and_upload_regression(
self,
clf,
task_id,
n_missing_vals,
n_test_obs,
flow_expected_rsv,
sentinel=None,
):
num_folds = 10 # because of cross-validation
num_iterations = 5 # for base search algorithms
metric = sklearn.metrics.mean_absolute_error # metric class
metric_name = "mean_absolute_error" # openml metric name
task_type = TaskType.SUPERVISED_REGRESSION # task type
return self._run_and_upload(
clf=clf,
task_id=task_id,
n_missing_vals=n_missing_vals,
n_test_obs=n_test_obs,
flow_expected_rsv=flow_expected_rsv,
num_folds=num_folds,
num_iterations=num_iterations,
metric=metric,
metric_name=metric_name,
task_type=task_type,
sentinel=sentinel,
)
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_run_and_upload_logistic_regression(self):
lr = LogisticRegression(solver="lbfgs", max_iter=1000)
task_id = self.TEST_SERVER_TASK_SIMPLE["task_id"]
n_missing_vals = self.TEST_SERVER_TASK_SIMPLE["n_missing_vals"]
n_test_obs = self.TEST_SERVER_TASK_SIMPLE["n_test_obs"]
self._run_and_upload_classification(lr, task_id, n_missing_vals, n_test_obs, "62501")
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_run_and_upload_linear_regression(self):
lr = LinearRegression()
task_id = self.TEST_SERVER_TASK_REGRESSION["task_id"]
task_meta_data = self.TEST_SERVER_TASK_REGRESSION["task_meta_data"]
_task_id = check_task_existence(**task_meta_data)
if _task_id is not None:
task_id = _task_id
else:
new_task = openml.tasks.create_task(**task_meta_data)
# publishes the new task
try:
new_task = new_task.publish()
task_id = new_task.task_id
except OpenMLServerException as e:
if e.code == 614: # Task already exists
# the exception message contains the task_id that was matched in the format
# 'Task already exists. - matched id(s): [xxxx]'
task_id = ast.literal_eval(e.message.split("matched id(s):")[-1].strip())[0]
else:
raise Exception(repr(e))
# mark to remove the uploaded task
TestBase._mark_entity_for_removal("task", task_id)
TestBase.logger.info(f"collected from test_run_functions: {task_id}")
n_missing_vals = self.TEST_SERVER_TASK_REGRESSION["n_missing_vals"]
n_test_obs = self.TEST_SERVER_TASK_REGRESSION["n_test_obs"]
self._run_and_upload_regression(lr, task_id, n_missing_vals, n_test_obs, "62501")
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_run_and_upload_pipeline_dummy_pipeline(self):
pipeline1 = Pipeline(
steps=[
("scaler", StandardScaler(with_mean=False)),
("dummy", DummyClassifier(strategy="prior")),
],
)
task_id = self.TEST_SERVER_TASK_SIMPLE["task_id"]
n_missing_vals = self.TEST_SERVER_TASK_SIMPLE["n_missing_vals"]
n_test_obs = self.TEST_SERVER_TASK_SIMPLE["n_test_obs"]
self._run_and_upload_classification(pipeline1, task_id, n_missing_vals, n_test_obs, "62501")
@pytest.mark.sklearn()
@unittest.skipIf(
Version(sklearn.__version__) < Version("0.20"),
reason="columntransformer introduction in 0.20.0",
)
@pytest.mark.test_server()
def test_run_and_upload_column_transformer_pipeline(self):
import sklearn.compose
import sklearn.impute
def get_ct_cf(nominal_indices, numeric_indices):
inner = sklearn.compose.ColumnTransformer(
transformers=[
(
"numeric",
make_pipeline(
SimpleImputer(strategy="mean"),
sklearn.preprocessing.StandardScaler(),
),
numeric_indices,
),
(
"nominal",
make_pipeline(
CustomImputer(strategy="most_frequent"),
sklearn.preprocessing.OneHotEncoder(handle_unknown="ignore"),
),
nominal_indices,
),
],
remainder="passthrough",
)
return sklearn.pipeline.Pipeline(
steps=[
("transformer", inner),
("classifier", sklearn.tree.DecisionTreeClassifier()),
],
)
sentinel = self._get_sentinel()
self._run_and_upload_classification(
get_ct_cf(
self.TEST_SERVER_TASK_SIMPLE["nominal_indices"],
self.TEST_SERVER_TASK_SIMPLE["numeric_indices"],
),
self.TEST_SERVER_TASK_SIMPLE["task_id"],
self.TEST_SERVER_TASK_SIMPLE["n_missing_vals"],
self.TEST_SERVER_TASK_SIMPLE["n_test_obs"],
"62501",
sentinel=sentinel,
)
# Due to #602, it is important to test this model on two tasks
# with different column specifications
self._run_and_upload_classification(
get_ct_cf(
self.TEST_SERVER_TASK_MISSING_VALS["nominal_indices"],
self.TEST_SERVER_TASK_MISSING_VALS["numeric_indices"],
),
self.TEST_SERVER_TASK_MISSING_VALS["task_id"],
self.TEST_SERVER_TASK_MISSING_VALS["n_missing_vals"],
self.TEST_SERVER_TASK_MISSING_VALS["n_test_obs"],
"62501",
sentinel=sentinel,
)
@pytest.mark.sklearn()
@unittest.skip("https://github.com/openml/OpenML/issues/1180")
@unittest.skipIf(
Version(sklearn.__version__) < Version("0.20"),
reason="columntransformer introduction in 0.20.0",
)
@mock.patch("warnings.warn")
def test_run_and_upload_knn_pipeline(self, warnings_mock):
cat_imp = make_pipeline(
SimpleImputer(strategy="most_frequent"),
OneHotEncoder(handle_unknown="ignore"),
)
cont_imp = make_pipeline(CustomImputer(), StandardScaler())
from sklearn.compose import ColumnTransformer
from sklearn.neighbors import KNeighborsClassifier
ct = ColumnTransformer([("cat", cat_imp, cat), ("cont", cont_imp, cont)])
pipeline2 = Pipeline(
steps=[
("Imputer", ct),
("VarianceThreshold", VarianceThreshold()),
(
"Estimator",
RandomizedSearchCV(
KNeighborsClassifier(),
{"n_neighbors": list(range(2, 10))},
cv=3,
n_iter=10,
),
),
],
)
task_id = self.TEST_SERVER_TASK_MISSING_VALS["task_id"]
n_missing_vals = self.TEST_SERVER_TASK_MISSING_VALS["n_missing_vals"]
n_test_obs = self.TEST_SERVER_TASK_MISSING_VALS["n_test_obs"]
self._run_and_upload_classification(pipeline2, task_id, n_missing_vals, n_test_obs, "62501")
# The warning raised is:
# "The total space of parameters 8 is smaller than n_iter=10.
# Running 8 iterations. For exhaustive searches, use GridSearchCV."
# It is raised three times because we once run the model to upload something and then run
# it again twice to compare that the predictions are reproducible.
warning_msg = (
"The total space of parameters 8 is smaller than n_iter=10. "
"Running 8 iterations. For exhaustive searches, use GridSearchCV."
)
call_count = 0
for _warnings in warnings_mock.call_args_list:
if _warnings[0][0] == warning_msg:
call_count += 1
assert call_count == 3
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_run_and_upload_gridsearch(self):
estimator_name = (
"base_estimator" if Version(sklearn.__version__) < Version("1.4") else "estimator"
)
gridsearch = GridSearchCV(
BaggingClassifier(**{estimator_name: SVC()}),
{f"{estimator_name}__C": [0.01, 0.1, 10], f"{estimator_name}__gamma": [0.01, 0.1, 10]},
cv=3,
)
task_id = self.TEST_SERVER_TASK_SIMPLE["task_id"]
n_missing_vals = self.TEST_SERVER_TASK_SIMPLE["n_missing_vals"]
n_test_obs = self.TEST_SERVER_TASK_SIMPLE["n_test_obs"]
run = self._run_and_upload_classification(
clf=gridsearch,
task_id=task_id,
n_missing_vals=n_missing_vals,
n_test_obs=n_test_obs,
flow_expected_rsv="62501",
)
assert len(run.trace.trace_iterations) == 9
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_run_and_upload_randomsearch(self):
randomsearch = RandomizedSearchCV(
RandomForestClassifier(n_estimators=5),
{
"max_depth": [3, None],
"max_features": [1, 2, 3, 4],
"min_samples_split": [2, 3, 4, 5, 6, 7, 8, 9, 10],
"min_samples_leaf": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"bootstrap": [True, False],
"criterion": ["gini", "entropy"],
},
cv=StratifiedKFold(n_splits=2, shuffle=True),
n_iter=5,
)
# The random states for the RandomizedSearchCV is set after the
# random state of the RandomForestClassifier is set, therefore,
# it has a different value than the other examples before
task_id = self.TEST_SERVER_TASK_SIMPLE["task_id"]
n_missing_vals = self.TEST_SERVER_TASK_SIMPLE["n_missing_vals"]
n_test_obs = self.TEST_SERVER_TASK_SIMPLE["n_test_obs"]
run = self._run_and_upload_classification(
clf=randomsearch,
task_id=task_id,
n_missing_vals=n_missing_vals,
n_test_obs=n_test_obs,
flow_expected_rsv="12172",
)
assert len(run.trace.trace_iterations) == 5
trace = openml.runs.get_run_trace(run.run_id)
assert len(trace.trace_iterations) == 5
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_run_and_upload_maskedarrays(self):
# This testcase is important for 2 reasons:
# 1) it verifies the correct handling of masked arrays (not all
# parameters are active)
# 2) it verifies the correct handling of a 2-layered grid search
gridsearch = GridSearchCV(
RandomForestClassifier(n_estimators=5),
[{"max_features": [2, 4]}, {"min_samples_leaf": [1, 10]}],
cv=StratifiedKFold(n_splits=2, shuffle=True),
)
# The random states for the GridSearchCV is set after the
# random state of the RandomForestClassifier is set, therefore,
# it has a different value than the other examples before
task_id = self.TEST_SERVER_TASK_SIMPLE["task_id"]
n_missing_vals = self.TEST_SERVER_TASK_SIMPLE["n_missing_vals"]
n_test_obs = self.TEST_SERVER_TASK_SIMPLE["n_test_obs"]
self._run_and_upload_classification(
gridsearch,
task_id,
n_missing_vals,
n_test_obs,
"12172",
)
##########################################################################
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_learning_curve_task_1(self):
task_id = 801 # diabates dataset
num_test_instances = 6144 # for learning curve
num_missing_vals = 0
num_repeats = 1
num_folds = 10
num_samples = 8
pipeline1 = Pipeline(
steps=[
("scaler", StandardScaler(with_mean=False)),
("dummy", DummyClassifier(strategy="prior")),
],
)
run = self._perform_run(
task_id,
num_test_instances,
num_missing_vals,
pipeline1,
flow_expected_rsv="62501",
)
self._check_sample_evaluations(run.sample_evaluations, num_repeats, num_folds, num_samples)
@pytest.mark.sklearn()
@pytest.mark.test_server()
def test_learning_curve_task_2(self):
task_id = 801 # diabates dataset
num_test_instances = 6144 # for learning curve
num_missing_vals = 0
num_repeats = 1
num_folds = 10
num_samples = 8
pipeline2 = Pipeline(
steps=[
("Imputer", SimpleImputer(strategy="median")),
("VarianceThreshold", VarianceThreshold()),
(
"Estimator",
RandomizedSearchCV(
DecisionTreeClassifier(),
{
"min_samples_split": [2**x for x in range(1, 8)],
"min_samples_leaf": [2**x for x in range(7)],
},
cv=3,
n_iter=10,
),
),
],
)
run = self._perform_run(
task_id,
num_test_instances,
num_missing_vals,
pipeline2,
flow_expected_rsv="62501",
)
self._check_sample_evaluations(run.sample_evaluations, num_repeats, num_folds, num_samples)
@pytest.mark.sklearn()
@unittest.skipIf(
Version(sklearn.__version__) < Version("0.21"),
reason="Pipelines don't support indexing (used for the assert check)",
)
@pytest.mark.test_server()
def test_initialize_cv_from_run(self):
randomsearch = Pipeline(
[
("enc", OneHotEncoder(handle_unknown="ignore")),
(
"rs",
RandomizedSearchCV(
RandomForestClassifier(n_estimators=5),
{
"max_depth": [3, None],
"max_features": [1, 2, 3, 4],
"min_samples_split": [2, 3, 4, 5, 6, 7, 8, 9, 10],
"min_samples_leaf": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"bootstrap": [True, False],
"criterion": ["gini", "entropy"],
},
cv=StratifiedKFold(n_splits=2, shuffle=True),
n_iter=2,
),
),
],
)
task = openml.tasks.get_task(11) # kr-vs-kp; holdout
run = openml.runs.run_model_on_task(
model=randomsearch,
task=task,
seed=1,
)
run_ = run.publish()
TestBase._mark_entity_for_removal("run", run.run_id)
TestBase.logger.info(f"collected from test_run_functions: {run.run_id}")
run = openml.runs.get_run(run_.run_id)
modelR = openml.runs.initialize_model_from_run(run_id=run.run_id)
modelS = openml.setups.initialize_model(setup_id=run.setup_id)
assert modelS[-1].cv.random_state == 62501
assert modelR[-1].cv.random_state == 62501
def _test_local_evaluations(self, run):
# compare with the scores in user defined measures
accuracy_scores_provided = []
for rep in run.fold_evaluations["predictive_accuracy"]:
for fold in run.fold_evaluations["predictive_accuracy"][rep]:
accuracy_scores_provided.append(
run.fold_evaluations["predictive_accuracy"][rep][fold],
)