forked from scikit-learn/scikit-learn
-
Notifications
You must be signed in to change notification settings - Fork 2
/
test_openml.py
1647 lines (1442 loc) · 54.1 KB
/
test_openml.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
"""Test the openml loader."""
import gzip
import json
import os
import re
from functools import partial
from io import BytesIO
from urllib.error import HTTPError
import numpy as np
import scipy.sparse
import pytest
import sklearn
from sklearn import config_context
from sklearn.utils import Bunch, check_pandas_support
from sklearn.utils.fixes import _open_binary
from sklearn.utils._testing import (
SkipTest,
assert_allclose,
assert_array_equal,
fails_if_pypy,
)
from sklearn.datasets import fetch_openml as fetch_openml_orig
from sklearn.datasets._openml import (
_OPENML_PREFIX,
_open_openml_url,
_get_local_path,
_retry_with_clean_cache,
)
OPENML_TEST_DATA_MODULE = "sklearn.datasets.tests.data.openml"
# if True, urlopen will be monkey patched to only use local files
test_offline = True
class _MockHTTPResponse:
def __init__(self, data, is_gzip):
self.data = data
self.is_gzip = is_gzip
def read(self, amt=-1):
return self.data.read(amt)
def close(self):
self.data.close()
def info(self):
if self.is_gzip:
return {"Content-Encoding": "gzip"}
return {}
def __iter__(self):
return iter(self.data)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return False
# Disable the disk-based cache when testing `fetch_openml`:
# the mock data in sklearn/datasets/tests/data/openml/ is not always consistent
# with the version on openml.org. If one were to load the dataset outside of
# the tests, it may result in data that does not represent openml.org.
fetch_openml = partial(fetch_openml_orig, data_home=None)
def _monkey_patch_webbased_functions(context, data_id, gzip_response):
# monkey patches the urlopen function. Important note: Do NOT use this
# in combination with a regular cache directory, as the files that are
# stored as cache should not be mixed up with real openml datasets
url_prefix_data_description = "https://openml.org/api/v1/json/data/"
url_prefix_data_features = "https://openml.org/api/v1/json/data/features/"
url_prefix_download_data = "https://openml.org/data/v1/"
url_prefix_data_list = "https://openml.org/api/v1/json/data/list/"
path_suffix = ".gz"
read_fn = gzip.open
data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}"
def _file_name(url, suffix):
output = (
re.sub(r"\W", "-", url[len("https://openml.org/") :]) + suffix + path_suffix
)
# Shorten the filenames to have better compatibility with windows 10
# and filenames > 260 characters
return (
output.replace("-json-data-list", "-jdl")
.replace("-json-data-features", "-jdf")
.replace("-json-data-qualities", "-jdq")
.replace("-json-data", "-jd")
.replace("-data_name", "-dn")
.replace("-download", "-dl")
.replace("-limit", "-l")
.replace("-data_version", "-dv")
.replace("-status", "-s")
.replace("-deactivated", "-dact")
.replace("-active", "-act")
)
def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix):
assert url.startswith(expected_prefix)
data_file_name = _file_name(url, suffix)
with _open_binary(data_module, data_file_name) as f:
if has_gzip_header and gzip_response:
fp = BytesIO(f.read())
return _MockHTTPResponse(fp, True)
else:
decompressed_f = read_fn(f, "rb")
fp = BytesIO(decompressed_f.read())
return _MockHTTPResponse(fp, False)
def _mock_urlopen_data_description(url, has_gzip_header):
return _mock_urlopen_shared(
url=url,
has_gzip_header=has_gzip_header,
expected_prefix=url_prefix_data_description,
suffix=".json",
)
def _mock_urlopen_data_features(url, has_gzip_header):
return _mock_urlopen_shared(
url=url,
has_gzip_header=has_gzip_header,
expected_prefix=url_prefix_data_features,
suffix=".json",
)
def _mock_urlopen_download_data(url, has_gzip_header):
return _mock_urlopen_shared(
url=url,
has_gzip_header=has_gzip_header,
expected_prefix=url_prefix_download_data,
suffix=".arff",
)
def _mock_urlopen_data_list(url, has_gzip_header):
assert url.startswith(url_prefix_data_list)
data_file_name = _file_name(url, ".json")
# load the file itself, to simulate a http error
with _open_binary(data_module, data_file_name) as f:
decompressed_f = read_fn(f, "rb")
decoded_s = decompressed_f.read().decode("utf-8")
json_data = json.loads(decoded_s)
if "error" in json_data:
raise HTTPError(
url=None, code=412, msg="Simulated mock error", hdrs=None, fp=None
)
with _open_binary(data_module, data_file_name) as f:
if has_gzip_header:
fp = BytesIO(f.read())
return _MockHTTPResponse(fp, True)
else:
decompressed_f = read_fn(f, "rb")
fp = BytesIO(decompressed_f.read())
return _MockHTTPResponse(fp, False)
def _mock_urlopen(request, *args, **kwargs):
url = request.get_full_url()
has_gzip_header = request.get_header("Accept-encoding") == "gzip"
if url.startswith(url_prefix_data_list):
return _mock_urlopen_data_list(url, has_gzip_header)
elif url.startswith(url_prefix_data_features):
return _mock_urlopen_data_features(url, has_gzip_header)
elif url.startswith(url_prefix_download_data):
return _mock_urlopen_download_data(url, has_gzip_header)
elif url.startswith(url_prefix_data_description):
return _mock_urlopen_data_description(url, has_gzip_header)
else:
raise ValueError("Unknown mocking URL pattern: %s" % url)
# XXX: Global variable
if test_offline:
context.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen)
###############################################################################
# Test the behaviour of `fetch_openml` depending of the input parameters.
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize(
"data_id, dataset_params, n_samples, n_features, n_targets",
[
# iris
(61, {"data_id": 61}, 150, 4, 1),
(61, {"name": "iris", "version": 1}, 150, 4, 1),
# anneal
(2, {"data_id": 2}, 11, 38, 1),
(2, {"name": "anneal", "version": 1}, 11, 38, 1),
# cpu
(561, {"data_id": 561}, 209, 7, 1),
(561, {"name": "cpu", "version": 1}, 209, 7, 1),
# emotions
(40589, {"data_id": 40589}, 13, 72, 6),
# adult-census
(1119, {"data_id": 1119}, 10, 14, 1),
(1119, {"name": "adult-census"}, 10, 14, 1),
# miceprotein
(40966, {"data_id": 40966}, 7, 77, 1),
(40966, {"name": "MiceProtein"}, 7, 77, 1),
# titanic
(40945, {"data_id": 40945}, 1309, 13, 1),
],
)
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
@pytest.mark.parametrize("gzip_response", [True, False])
def test_fetch_openml_as_frame_true(
monkeypatch,
data_id,
dataset_params,
n_samples,
n_features,
n_targets,
parser,
gzip_response,
):
"""Check the behaviour of `fetch_openml` with `as_frame=True`.
Fetch by ID and/or name (depending if the file was previously cached).
"""
pd = pytest.importorskip("pandas")
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response)
bunch = fetch_openml(
as_frame=True,
cache=False,
parser=parser,
**dataset_params,
)
assert int(bunch.details["id"]) == data_id
assert isinstance(bunch, Bunch)
assert isinstance(bunch.frame, pd.DataFrame)
assert bunch.frame.shape == (n_samples, n_features + n_targets)
assert isinstance(bunch.data, pd.DataFrame)
assert bunch.data.shape == (n_samples, n_features)
if n_targets == 1:
assert isinstance(bunch.target, pd.Series)
assert bunch.target.shape == (n_samples,)
else:
assert isinstance(bunch.target, pd.DataFrame)
assert bunch.target.shape == (n_samples, n_targets)
assert bunch.categories is None
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize(
"data_id, dataset_params, n_samples, n_features, n_targets",
[
# iris
(61, {"data_id": 61}, 150, 4, 1),
(61, {"name": "iris", "version": 1}, 150, 4, 1),
# anneal
(2, {"data_id": 2}, 11, 38, 1),
(2, {"name": "anneal", "version": 1}, 11, 38, 1),
# cpu
(561, {"data_id": 561}, 209, 7, 1),
(561, {"name": "cpu", "version": 1}, 209, 7, 1),
# emotions
(40589, {"data_id": 40589}, 13, 72, 6),
# adult-census
(1119, {"data_id": 1119}, 10, 14, 1),
(1119, {"name": "adult-census"}, 10, 14, 1),
# miceprotein
(40966, {"data_id": 40966}, 7, 77, 1),
(40966, {"name": "MiceProtein"}, 7, 77, 1),
],
)
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
def test_fetch_openml_as_frame_false(
monkeypatch,
data_id,
dataset_params,
n_samples,
n_features,
n_targets,
parser,
):
"""Check the behaviour of `fetch_openml` with `as_frame=False`.
Fetch both by ID and/or name + version.
"""
pytest.importorskip("pandas")
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
bunch = fetch_openml(
as_frame=False,
cache=False,
parser=parser,
**dataset_params,
)
assert int(bunch.details["id"]) == data_id
assert isinstance(bunch, Bunch)
assert bunch.frame is None
assert isinstance(bunch.data, np.ndarray)
assert bunch.data.shape == (n_samples, n_features)
assert isinstance(bunch.target, np.ndarray)
if n_targets == 1:
assert bunch.target.shape == (n_samples,)
else:
assert bunch.target.shape == (n_samples, n_targets)
assert isinstance(bunch.categories, dict)
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize("data_id", [61, 1119, 40945])
def test_fetch_openml_consistency_parser(monkeypatch, data_id):
"""Check the consistency of the LIAC-ARFF and pandas parsers."""
pd = pytest.importorskip("pandas")
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
bunch_liac = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
parser="liac-arff",
)
bunch_pandas = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
parser="pandas",
)
# The data frames for the input features should match up to some numerical
# dtype conversions (e.g. float64 <=> Int64) due to limitations of the
# LIAC-ARFF parser.
data_liac, data_pandas = bunch_liac.data, bunch_pandas.data
def convert_numerical_dtypes(series):
pandas_series = data_pandas[series.name]
if pd.api.types.is_numeric_dtype(pandas_series):
return series.astype(pandas_series.dtype)
else:
return series
data_liac_with_fixed_dtypes = data_liac.apply(convert_numerical_dtypes)
pd.testing.assert_frame_equal(data_liac_with_fixed_dtypes, data_pandas)
# Let's also check that the .frame attributes also match
frame_liac, frame_pandas = bunch_liac.frame, bunch_pandas.frame
# Note that the .frame attribute is a superset of the .data attribute:
pd.testing.assert_frame_equal(frame_pandas[bunch_pandas.feature_names], data_pandas)
# However the remaining columns, typically the target(s), are not necessarily
# dtyped similarly by both parsers due to limitations of the LIAC-ARFF parser.
# Therefore, extra dtype conversions are required for those columns:
def convert_numerical_and_categorical_dtypes(series):
pandas_series = frame_pandas[series.name]
if pd.api.types.is_numeric_dtype(pandas_series):
return series.astype(pandas_series.dtype)
elif pd.api.types.is_categorical_dtype(pandas_series):
# Compare categorical features by converting categorical liac uses
# strings to denote the categories, we rename the categories to make
# them comparable to the pandas parser. Fixing this behavior in
# LIAC-ARFF would allow to check the consistency in the future but
# we do not plan to maintain the LIAC-ARFF on the long term.
return series.cat.rename_categories(pandas_series.cat.categories)
else:
return series
frame_liac_with_fixed_dtypes = frame_liac.apply(
convert_numerical_and_categorical_dtypes
)
pd.testing.assert_frame_equal(frame_liac_with_fixed_dtypes, frame_pandas)
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser):
"""Check the equivalence of the dataset when using `as_frame=False` and
`as_frame=True`.
"""
pytest.importorskip("pandas")
data_id = 61
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
bunch_as_frame_true = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
parser=parser,
)
bunch_as_frame_false = fetch_openml(
data_id=data_id,
as_frame=False,
cache=False,
parser=parser,
)
assert_allclose(bunch_as_frame_false.data, bunch_as_frame_true.data)
assert_array_equal(bunch_as_frame_false.target, bunch_as_frame_true.target)
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
def test_fetch_openml_iris_pandas(monkeypatch, parser):
"""Check fetching on a numerical only dataset with string labels."""
pd = pytest.importorskip("pandas")
CategoricalDtype = pd.api.types.CategoricalDtype
data_id = 61
data_shape = (150, 4)
target_shape = (150,)
frame_shape = (150, 5)
target_dtype = CategoricalDtype(
["Iris-setosa", "Iris-versicolor", "Iris-virginica"]
)
data_dtypes = [np.float64] * 4
data_names = ["sepallength", "sepalwidth", "petallength", "petalwidth"]
target_name = "class"
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
bunch = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
parser=parser,
)
data = bunch.data
target = bunch.target
frame = bunch.frame
assert isinstance(data, pd.DataFrame)
assert np.all(data.dtypes == data_dtypes)
assert data.shape == data_shape
assert np.all(data.columns == data_names)
assert np.all(bunch.feature_names == data_names)
assert bunch.target_names == [target_name]
assert isinstance(target, pd.Series)
assert target.dtype == target_dtype
assert target.shape == target_shape
assert target.name == target_name
assert target.index.is_unique
assert isinstance(frame, pd.DataFrame)
assert frame.shape == frame_shape
assert np.all(frame.dtypes == data_dtypes + [target_dtype])
assert frame.index.is_unique
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
@pytest.mark.parametrize("target_column", ["petalwidth", ["petalwidth", "petallength"]])
def test_fetch_openml_forcing_targets(monkeypatch, parser, target_column):
"""Check that we can force the target to not be the default target."""
pd = pytest.importorskip("pandas")
data_id = 61
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
bunch_forcing_target = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
target_column=target_column,
parser=parser,
)
bunch_default = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
parser=parser,
)
pd.testing.assert_frame_equal(bunch_forcing_target.frame, bunch_default.frame)
if isinstance(target_column, list):
pd.testing.assert_index_equal(
bunch_forcing_target.target.columns, pd.Index(target_column)
)
assert bunch_forcing_target.data.shape == (150, 3)
else:
assert bunch_forcing_target.target.name == target_column
assert bunch_forcing_target.data.shape == (150, 4)
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize("data_id", [61, 2, 561, 40589, 1119])
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
def test_fetch_openml_equivalence_frame_return_X_y(monkeypatch, data_id, parser):
"""Check the behaviour of `return_X_y=True` when `as_frame=True`."""
pd = pytest.importorskip("pandas")
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
bunch = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
return_X_y=False,
parser=parser,
)
X, y = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
return_X_y=True,
parser=parser,
)
pd.testing.assert_frame_equal(bunch.data, X)
if isinstance(y, pd.Series):
pd.testing.assert_series_equal(bunch.target, y)
else:
pd.testing.assert_frame_equal(bunch.target, y)
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize("data_id", [61, 561, 40589, 1119])
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
def test_fetch_openml_equivalence_array_return_X_y(monkeypatch, data_id, parser):
"""Check the behaviour of `return_X_y=True` when `as_frame=False`."""
pytest.importorskip("pandas")
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
bunch = fetch_openml(
data_id=data_id,
as_frame=False,
cache=False,
return_X_y=False,
parser=parser,
)
X, y = fetch_openml(
data_id=data_id,
as_frame=False,
cache=False,
return_X_y=True,
parser=parser,
)
assert_array_equal(bunch.data, X)
assert_array_equal(bunch.target, y)
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
def test_fetch_openml_difference_parsers(monkeypatch):
"""Check the difference between liac-arff and pandas parser."""
pytest.importorskip("pandas")
data_id = 1119
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
# When `as_frame=False`, the categories will be ordinally encoded with
# liac-arff parser while this is not the case with pandas parser.
as_frame = False
bunch_liac_arff = fetch_openml(
data_id=data_id,
as_frame=as_frame,
cache=False,
parser="liac-arff",
)
bunch_pandas = fetch_openml(
data_id=data_id,
as_frame=as_frame,
cache=False,
parser="pandas",
)
assert bunch_liac_arff.data.dtype.kind == "f"
assert bunch_pandas.data.dtype == "O"
###############################################################################
# Test the ARFF parsing on several dataset to check if detect the correct
# types (categories, intgers, floats).
@pytest.fixture(scope="module")
def datasets_column_names():
"""Returns the columns names for each dataset."""
return {
61: ["sepallength", "sepalwidth", "petallength", "petalwidth", "class"],
2: [
"family",
"product-type",
"steel",
"carbon",
"hardness",
"temper_rolling",
"condition",
"formability",
"strength",
"non-ageing",
"surface-finish",
"surface-quality",
"enamelability",
"bc",
"bf",
"bt",
"bw%2Fme",
"bl",
"m",
"chrom",
"phos",
"cbond",
"marvi",
"exptl",
"ferro",
"corr",
"blue%2Fbright%2Fvarn%2Fclean",
"lustre",
"jurofm",
"s",
"p",
"shape",
"thick",
"width",
"len",
"oil",
"bore",
"packing",
"class",
],
561: ["vendor", "MYCT", "MMIN", "MMAX", "CACH", "CHMIN", "CHMAX", "class"],
40589: [
"Mean_Acc1298_Mean_Mem40_Centroid",
"Mean_Acc1298_Mean_Mem40_Rolloff",
"Mean_Acc1298_Mean_Mem40_Flux",
"Mean_Acc1298_Mean_Mem40_MFCC_0",
"Mean_Acc1298_Mean_Mem40_MFCC_1",
"Mean_Acc1298_Mean_Mem40_MFCC_2",
"Mean_Acc1298_Mean_Mem40_MFCC_3",
"Mean_Acc1298_Mean_Mem40_MFCC_4",
"Mean_Acc1298_Mean_Mem40_MFCC_5",
"Mean_Acc1298_Mean_Mem40_MFCC_6",
"Mean_Acc1298_Mean_Mem40_MFCC_7",
"Mean_Acc1298_Mean_Mem40_MFCC_8",
"Mean_Acc1298_Mean_Mem40_MFCC_9",
"Mean_Acc1298_Mean_Mem40_MFCC_10",
"Mean_Acc1298_Mean_Mem40_MFCC_11",
"Mean_Acc1298_Mean_Mem40_MFCC_12",
"Mean_Acc1298_Std_Mem40_Centroid",
"Mean_Acc1298_Std_Mem40_Rolloff",
"Mean_Acc1298_Std_Mem40_Flux",
"Mean_Acc1298_Std_Mem40_MFCC_0",
"Mean_Acc1298_Std_Mem40_MFCC_1",
"Mean_Acc1298_Std_Mem40_MFCC_2",
"Mean_Acc1298_Std_Mem40_MFCC_3",
"Mean_Acc1298_Std_Mem40_MFCC_4",
"Mean_Acc1298_Std_Mem40_MFCC_5",
"Mean_Acc1298_Std_Mem40_MFCC_6",
"Mean_Acc1298_Std_Mem40_MFCC_7",
"Mean_Acc1298_Std_Mem40_MFCC_8",
"Mean_Acc1298_Std_Mem40_MFCC_9",
"Mean_Acc1298_Std_Mem40_MFCC_10",
"Mean_Acc1298_Std_Mem40_MFCC_11",
"Mean_Acc1298_Std_Mem40_MFCC_12",
"Std_Acc1298_Mean_Mem40_Centroid",
"Std_Acc1298_Mean_Mem40_Rolloff",
"Std_Acc1298_Mean_Mem40_Flux",
"Std_Acc1298_Mean_Mem40_MFCC_0",
"Std_Acc1298_Mean_Mem40_MFCC_1",
"Std_Acc1298_Mean_Mem40_MFCC_2",
"Std_Acc1298_Mean_Mem40_MFCC_3",
"Std_Acc1298_Mean_Mem40_MFCC_4",
"Std_Acc1298_Mean_Mem40_MFCC_5",
"Std_Acc1298_Mean_Mem40_MFCC_6",
"Std_Acc1298_Mean_Mem40_MFCC_7",
"Std_Acc1298_Mean_Mem40_MFCC_8",
"Std_Acc1298_Mean_Mem40_MFCC_9",
"Std_Acc1298_Mean_Mem40_MFCC_10",
"Std_Acc1298_Mean_Mem40_MFCC_11",
"Std_Acc1298_Mean_Mem40_MFCC_12",
"Std_Acc1298_Std_Mem40_Centroid",
"Std_Acc1298_Std_Mem40_Rolloff",
"Std_Acc1298_Std_Mem40_Flux",
"Std_Acc1298_Std_Mem40_MFCC_0",
"Std_Acc1298_Std_Mem40_MFCC_1",
"Std_Acc1298_Std_Mem40_MFCC_2",
"Std_Acc1298_Std_Mem40_MFCC_3",
"Std_Acc1298_Std_Mem40_MFCC_4",
"Std_Acc1298_Std_Mem40_MFCC_5",
"Std_Acc1298_Std_Mem40_MFCC_6",
"Std_Acc1298_Std_Mem40_MFCC_7",
"Std_Acc1298_Std_Mem40_MFCC_8",
"Std_Acc1298_Std_Mem40_MFCC_9",
"Std_Acc1298_Std_Mem40_MFCC_10",
"Std_Acc1298_Std_Mem40_MFCC_11",
"Std_Acc1298_Std_Mem40_MFCC_12",
"BH_LowPeakAmp",
"BH_LowPeakBPM",
"BH_HighPeakAmp",
"BH_HighPeakBPM",
"BH_HighLowRatio",
"BHSUM1",
"BHSUM2",
"BHSUM3",
"amazed.suprised",
"happy.pleased",
"relaxing.calm",
"quiet.still",
"sad.lonely",
"angry.aggresive",
],
1119: [
"age",
"workclass",
"fnlwgt:",
"education:",
"education-num:",
"marital-status:",
"occupation:",
"relationship:",
"race:",
"sex:",
"capital-gain:",
"capital-loss:",
"hours-per-week:",
"native-country:",
"class",
],
40966: [
"DYRK1A_N",
"ITSN1_N",
"BDNF_N",
"NR1_N",
"NR2A_N",
"pAKT_N",
"pBRAF_N",
"pCAMKII_N",
"pCREB_N",
"pELK_N",
"pERK_N",
"pJNK_N",
"PKCA_N",
"pMEK_N",
"pNR1_N",
"pNR2A_N",
"pNR2B_N",
"pPKCAB_N",
"pRSK_N",
"AKT_N",
"BRAF_N",
"CAMKII_N",
"CREB_N",
"ELK_N",
"ERK_N",
"GSK3B_N",
"JNK_N",
"MEK_N",
"TRKA_N",
"RSK_N",
"APP_N",
"Bcatenin_N",
"SOD1_N",
"MTOR_N",
"P38_N",
"pMTOR_N",
"DSCR1_N",
"AMPKA_N",
"NR2B_N",
"pNUMB_N",
"RAPTOR_N",
"TIAM1_N",
"pP70S6_N",
"NUMB_N",
"P70S6_N",
"pGSK3B_N",
"pPKCG_N",
"CDK5_N",
"S6_N",
"ADARB1_N",
"AcetylH3K9_N",
"RRP1_N",
"BAX_N",
"ARC_N",
"ERBB4_N",
"nNOS_N",
"Tau_N",
"GFAP_N",
"GluR3_N",
"GluR4_N",
"IL1B_N",
"P3525_N",
"pCASP9_N",
"PSD95_N",
"SNCA_N",
"Ubiquitin_N",
"pGSK3B_Tyr216_N",
"SHH_N",
"BAD_N",
"BCL2_N",
"pS6_N",
"pCFOS_N",
"SYP_N",
"H3AcK18_N",
"EGR1_N",
"H3MeK4_N",
"CaNA_N",
"class",
],
40945: [
"pclass",
"survived",
"name",
"sex",
"age",
"sibsp",
"parch",
"ticket",
"fare",
"cabin",
"embarked",
"boat",
"body",
"home.dest",
],
}
@pytest.fixture(scope="module")
def datasets_missing_values():
return {
61: {},
2: {
"family": 11,
"temper_rolling": 9,
"condition": 2,
"formability": 4,
"non-ageing": 10,
"surface-finish": 11,
"enamelability": 11,
"bc": 11,
"bf": 10,
"bt": 11,
"bw%2Fme": 8,
"bl": 9,
"m": 11,
"chrom": 11,
"phos": 11,
"cbond": 10,
"marvi": 11,
"exptl": 11,
"ferro": 11,
"corr": 11,
"blue%2Fbright%2Fvarn%2Fclean": 11,
"lustre": 8,
"jurofm": 11,
"s": 11,
"p": 11,
"oil": 10,
"packing": 11,
},
561: {},
40589: {},
1119: {},
40966: {"BCL2_N": 7},
40945: {
"age": 263,
"fare": 1,
"cabin": 1014,
"embarked": 2,
"boat": 823,
"body": 1188,
"home.dest": 564,
},
}
# Known failure of PyPy for OpenML. See the following issue:
# https://github.com/scikit-learn/scikit-learn/issues/18906
@fails_if_pypy
@pytest.mark.parametrize(
"data_id, parser, expected_n_categories, expected_n_floats, expected_n_ints",
[
# iris dataset
(61, "liac-arff", 1, 4, 0),
(61, "pandas", 1, 4, 0),
# anneal dataset
(2, "liac-arff", 33, 6, 0),
(2, "pandas", 33, 2, 4),
# cpu dataset
(561, "liac-arff", 1, 7, 0),
(561, "pandas", 1, 0, 7),
# emotions dataset
(40589, "liac-arff", 6, 72, 0),
(40589, "pandas", 6, 69, 3),
# adult-census dataset
(1119, "liac-arff", 9, 6, 0),
(1119, "pandas", 9, 0, 6),
# miceprotein
# 1 column has only missing values with object dtype
(40966, "liac-arff", 1, 76, 0),
# with casting it will be transformed to either float or Int64
(40966, "pandas", 1, 77, 0),
# titanic
(40945, "liac-arff", 3, 5, 0),
(40945, "pandas", 3, 3, 3),
],
)
@pytest.mark.parametrize("gzip_response", [True, False])
def test_fetch_openml_types_inference(
monkeypatch,
data_id,
parser,
expected_n_categories,
expected_n_floats,
expected_n_ints,
gzip_response,
datasets_column_names,
datasets_missing_values,
):
"""Check that `fetch_openml` infer the right number of categories, integers, and
floats."""
pd = pytest.importorskip("pandas")
CategoricalDtype = pd.api.types.CategoricalDtype
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response)
bunch = fetch_openml(
data_id=data_id,
as_frame=True,
cache=False,
parser=parser,
)
frame = bunch.frame
n_categories = len(
[dtype for dtype in frame.dtypes if isinstance(dtype, CategoricalDtype)]
)
n_floats = len([dtype for dtype in frame.dtypes if dtype.kind == "f"])
n_ints = len([dtype for dtype in frame.dtypes if dtype.kind == "i"])
assert n_categories == expected_n_categories
assert n_floats == expected_n_floats
assert n_ints == expected_n_ints
assert frame.columns.tolist() == datasets_column_names[data_id]
frame_feature_to_n_nan = frame.isna().sum().to_dict()
for name, n_missing in frame_feature_to_n_nan.items():
expected_missing = datasets_missing_values[data_id].get(name, 0)
assert n_missing == expected_missing
###############################################################################
# Test some more specific behaviour
# TODO(1.4): remove this filterwarning decorator
@pytest.mark.filterwarnings("ignore:The default value of `parser` will change")
@pytest.mark.parametrize(
"params, err_msg",
[
({"parser": "unknown"}, "`parser` must be one of"),
({"as_frame": "unknown"}, "`as_frame` must be one of"),
],
)
def test_fetch_openml_validation_parameter(monkeypatch, params, err_msg):
data_id = 1119
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
with pytest.raises(ValueError, match=err_msg):
fetch_openml(data_id=data_id, **params)
@pytest.mark.parametrize(
"params",
[
{"as_frame": True, "parser": "auto"},
{"as_frame": "auto", "parser": "auto"},
{"as_frame": False, "parser": "pandas"},
],
)