-
-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathtest_dataset_functions.py
More file actions
2007 lines (1794 loc) · 75.5 KB
/
test_dataset_functions.py
File metadata and controls
2007 lines (1794 loc) · 75.5 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 itertools
import os
import random
import shutil
import time
import uuid
from itertools import product
from pathlib import Path
from typing import Iterable
from unittest import mock
import arff
import numpy as np
import pandas as pd
import pytest
import requests
import requests_mock
import scipy.sparse
from oslo_concurrency import lockutils
import openml
from openml import OpenMLDataset
from openml._api_calls import _download_minio_file
from openml.datasets import edit_dataset, fork_dataset
from openml.datasets.functions import (
DATASETS_CACHE_DIR_NAME,
_get_dataset_arff,
_get_dataset_description,
_get_dataset_features_file,
_get_dataset_parquet,
_get_dataset_qualities_file,
_get_online_dataset_arff,
_get_online_dataset_format,
_topic_add_dataset,
_topic_delete_dataset,
attributes_arff_from_df,
create_dataset,
)
from openml.exceptions import (
OpenMLHashException,
OpenMLNotAuthorizedError,
OpenMLPrivateDatasetError,
OpenMLServerException,
OpenMLServerNoResult,
)
from openml.tasks import TaskType, create_task
from openml.testing import TestBase, create_request_response
from openml.utils import _create_cache_directory_for_id, _tag_entity
class TestOpenMLDataset(TestBase):
_multiprocess_can_split_ = True
def tearDown(self):
self._remove_pickle_files()
super().tearDown()
def _remove_pickle_files(self):
self.lock_path = os.path.join(openml.config.get_cache_directory(), "locks")
for did in ["-1", "2"]:
with lockutils.external_lock(
name=f"datasets.functions.get_dataset:{did}",
lock_path=self.lock_path,
):
pickle_path = os.path.join(
openml.config.get_cache_directory(),
"datasets",
did,
"dataset.pkl.py3",
)
try:
os.remove(pickle_path)
except (OSError, FileNotFoundError):
# Replaced a bare except. Not sure why either of these would be acceptable.
pass
def _get_empty_param_for_dataset(self):
return {
"name": None,
"description": None,
"creator": None,
"contributor": None,
"collection_date": None,
"language": None,
"licence": None,
"default_target_attribute": None,
"row_id_attribute": None,
"ignore_attribute": None,
"citation": None,
"attributes": None,
"data": None,
}
def _check_dataset(self, dataset):
assert type(dataset) == dict
assert len(dataset) >= 2
assert "did" in dataset
assert isinstance(dataset["did"], int)
assert "status" in dataset
assert isinstance(dataset["status"], str)
assert dataset["status"] in ["in_preparation", "active", "deactivated"]
def _check_datasets(self, datasets):
for did in datasets:
self._check_dataset(datasets[did])
@pytest.mark.uses_test_server()
def test_tag_untag_dataset(self):
tag = "test_tag_%d" % random.randint(1, 1000000)
all_tags = _tag_entity("data", 1, tag)
assert tag in all_tags
all_tags = _tag_entity("data", 1, tag, untag=True)
assert tag not in all_tags
@pytest.mark.uses_test_server()
def test_list_datasets_length(self):
datasets = openml.datasets.list_datasets()
assert len(datasets) >= 100
@pytest.mark.uses_test_server()
def test_list_datasets_paginate(self):
size = 10
max = 100
for i in range(0, max, size):
datasets = openml.datasets.list_datasets(offset=i, size=size)
assert len(datasets) == size
assert len(datasets.columns) >= 2
assert "did" in datasets.columns
assert datasets["did"].dtype == int
assert "status" in datasets.columns
assert datasets["status"].dtype == pd.CategoricalDtype(
categories=["in_preparation", "active", "deactivated"],
)
@pytest.mark.uses_test_server()
def test_list_datasets_empty(self):
datasets = openml.datasets.list_datasets(tag="NoOneWouldUseThisTagAnyway")
assert datasets.empty
@pytest.mark.production()
def test_check_datasets_active(self):
# Have to test on live because there is no deactivated dataset on the test server.
self.use_production_server()
active = openml.datasets.check_datasets_active(
[2, 17, 79],
raise_error_if_not_exist=False,
)
assert active[2]
assert not active[17]
assert active.get(79) is None
self.assertRaisesRegex(
ValueError,
r"Could not find dataset\(s\) 79 in OpenML dataset list.",
openml.datasets.check_datasets_active,
[79],
)
openml.config.server = self.test_server
@pytest.mark.uses_test_server()
def test_illegal_character_tag(self):
dataset = openml.datasets.get_dataset(1)
tag = "illegal_tag&"
try:
dataset.push_tag(tag)
raise AssertionError()
except openml.exceptions.OpenMLServerException as e:
assert e.code == 477
@pytest.mark.uses_test_server()
def test_illegal_length_tag(self):
dataset = openml.datasets.get_dataset(1)
tag = "a" * 65
try:
dataset.push_tag(tag)
raise AssertionError()
except openml.exceptions.OpenMLServerException as e:
assert e.code == 477
@pytest.mark.production()
def test__name_to_id_with_deactivated(self):
"""Check that an activated dataset is returned if an earlier deactivated one exists."""
self.use_production_server()
# /d/1 was deactivated
assert openml.datasets.functions._name_to_id("anneal") == 2
openml.config.server = self.test_server
@pytest.mark.production()
def test__name_to_id_with_multiple_active(self):
"""With multiple active datasets, retrieve the least recent active."""
self.use_production_server()
assert openml.datasets.functions._name_to_id("iris") == 61
@pytest.mark.production()
def test__name_to_id_with_version(self):
"""With multiple active datasets, retrieve the least recent active."""
self.use_production_server()
assert openml.datasets.functions._name_to_id("iris", version=3) == 969
@pytest.mark.production()
def test__name_to_id_with_multiple_active_error(self):
"""With multiple active datasets, retrieve the least recent active."""
self.use_production_server()
self.assertRaisesRegex(
ValueError,
"Multiple active datasets exist with name 'iris'.",
openml.datasets.functions._name_to_id,
dataset_name="iris",
error_if_multiple=True,
)
@pytest.mark.uses_test_server()
def test__name_to_id_name_does_not_exist(self):
"""With multiple active datasets, retrieve the least recent active."""
self.assertRaisesRegex(
RuntimeError,
"No active datasets exist with name 'does_not_exist'.",
openml.datasets.functions._name_to_id,
dataset_name="does_not_exist",
)
@pytest.mark.uses_test_server()
def test__name_to_id_version_does_not_exist(self):
"""With multiple active datasets, retrieve the least recent active."""
self.assertRaisesRegex(
RuntimeError,
"No active datasets exist with name 'iris' and version '100000'.",
openml.datasets.functions._name_to_id,
dataset_name="iris",
version=100000,
)
@pytest.mark.uses_test_server()
def test_get_datasets_by_name(self):
# did 1 and 2 on the test server:
dids = ["anneal", "kr-vs-kp"]
datasets = openml.datasets.get_datasets(dids)
assert len(datasets) == 2
_assert_datasets_retrieved_successfully([1, 2])
@pytest.mark.uses_test_server()
def test_get_datasets_by_mixed(self):
# did 1 and 2 on the test server:
dids = ["anneal", 2]
datasets = openml.datasets.get_datasets(dids)
assert len(datasets) == 2
_assert_datasets_retrieved_successfully([1, 2])
@pytest.mark.uses_test_server()
def test_get_datasets(self):
dids = [1, 2]
datasets = openml.datasets.get_datasets(dids)
assert len(datasets) == 2
_assert_datasets_retrieved_successfully([1, 2])
@pytest.mark.uses_test_server()
def test_get_dataset_by_name(self):
dataset = openml.datasets.get_dataset("anneal")
assert type(dataset) == OpenMLDataset
assert dataset.dataset_id == 1
_assert_datasets_retrieved_successfully([1])
assert len(dataset.features) > 1
assert len(dataset.qualities) > 4
@pytest.mark.skip("Feature is experimental, can not test against stable server.")
def test_get_dataset_download_all_files(self):
# openml.datasets.get_dataset(id, download_all_files=True)
# check for expected files
# checking that no additional files are downloaded if
# the default (false) is used, seems covered by
# test_get_dataset_lazy
raise NotImplementedError
@pytest.mark.uses_test_server()
def test_get_dataset_uint8_dtype(self):
dataset = openml.datasets.get_dataset(1)
assert type(dataset) == OpenMLDataset
assert dataset.name == "anneal"
df, _, _, _ = dataset.get_data()
assert df["carbon"].dtype == "uint8"
@pytest.mark.production()
def test_get_dataset_cannot_access_private_data(self):
# Issue324 Properly handle private datasets when trying to access them
self.use_production_server()
self.assertRaises(OpenMLPrivateDatasetError, openml.datasets.get_dataset, 45)
@pytest.mark.skip("Need to find dataset name of private dataset")
def test_dataset_by_name_cannot_access_private_data(self):
self.use_production_server()
self.assertRaises(OpenMLPrivateDatasetError, openml.datasets.get_dataset, "NAME_GOES_HERE")
@pytest.mark.uses_test_server()
def test_get_dataset_lazy_all_functions(self):
"""Test that all expected functionality is available without downloading the dataset."""
dataset = openml.datasets.get_dataset(1)
# We only tests functions as general integrity is tested by test_get_dataset_lazy
def ensure_absence_of_real_data():
assert not os.path.exists(
os.path.join(openml.config.get_cache_directory(), "datasets", "1", "dataset.arff")
)
tag = "test_lazy_tag_%d" % random.randint(1, 1000000)
dataset.push_tag(tag)
ensure_absence_of_real_data()
dataset.remove_tag(tag)
ensure_absence_of_real_data()
nominal_indices = dataset.get_features_by_type("nominal")
# fmt: off
correct = [0, 1, 2, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 35, 36, 37, 38]
# fmt: on
assert nominal_indices == correct
ensure_absence_of_real_data()
classes = dataset.retrieve_class_labels()
assert classes == ["1", "2", "3", "4", "5", "U"]
ensure_absence_of_real_data()
@pytest.mark.uses_test_server()
def test_get_dataset_sparse(self):
dataset = openml.datasets.get_dataset(102)
X, *_ = dataset.get_data()
assert isinstance(X, pd.DataFrame)
assert all(isinstance(col, pd.SparseDtype) for col in X.dtypes)
@pytest.mark.uses_test_server()
def test_download_rowid(self):
# Smoke test which checks that the dataset has the row-id set correctly
did = 44
dataset = openml.datasets.get_dataset(did)
assert dataset.row_id_attribute == "Counter"
@pytest.mark.uses_test_server()
def test__get_dataset_description(self):
description = _get_dataset_description(self.workdir, 2)
assert isinstance(description, dict)
description_xml_path = os.path.join(self.workdir, "description.xml")
assert os.path.exists(description_xml_path)
@pytest.mark.uses_test_server()
def test__getarff_path_dataset_arff(self):
openml.config.set_root_cache_directory(self.static_cache_dir)
description = _get_dataset_description(self.workdir, 2)
arff_path = _get_dataset_arff(description, cache_directory=self.workdir)
assert isinstance(arff_path, Path)
assert arff_path.exists()
def test__download_minio_file_object_does_not_exist(self):
self.assertRaisesRegex(
FileNotFoundError,
r"Object at .* does not exist",
_download_minio_file,
source="http://data.openml.org/dataset20/i_do_not_exist.pq",
destination=self.workdir,
exists_ok=True,
)
def test__download_minio_file_to_directory(self):
_download_minio_file(
source="http://data.openml.org/dataset20/dataset_20.pq",
destination=self.workdir,
exists_ok=True,
)
assert os.path.isfile(
os.path.join(self.workdir, "dataset_20.pq")
), "_download_minio_file can save to a folder by copying the object name"
def test__download_minio_file_to_path(self):
file_destination = os.path.join(self.workdir, "custom.pq")
_download_minio_file(
source="http://data.openml.org/dataset20/dataset_20.pq",
destination=file_destination,
exists_ok=True,
)
assert os.path.isfile(
file_destination
), "_download_minio_file can save to a folder by copying the object name"
def test__download_minio_file_raises_FileExists_if_destination_in_use(self):
file_destination = Path(self.workdir, "custom.pq")
file_destination.touch()
self.assertRaises(
FileExistsError,
_download_minio_file,
source="http://data.openml.org/dataset20/dataset_20.pq",
destination=str(file_destination),
exists_ok=False,
)
def test__download_minio_file_works_with_bucket_subdirectory(self):
file_destination = Path(self.workdir, "custom.pq")
_download_minio_file(
source="http://data.openml.org/dataset61/dataset_61.pq",
destination=file_destination,
exists_ok=True,
)
assert os.path.isfile(
file_destination
), "_download_minio_file can download from subdirectories"
@mock.patch("openml._api_calls._download_minio_file")
@pytest.mark.uses_test_server()
def test__get_dataset_parquet_is_cached(self, patch):
openml.config.set_root_cache_directory(self.static_cache_dir)
patch.side_effect = RuntimeError(
"_download_parquet_url should not be called when loading from cache",
)
description = {
"oml:parquet_url": "http://data.openml.org/dataset30/dataset_30.pq",
"oml:id": "30",
}
path = _get_dataset_parquet(description, cache_directory=None)
assert isinstance(path, Path), "_get_dataset_parquet returns a path"
assert path.is_file(), "_get_dataset_parquet returns path to real file"
def test__get_dataset_parquet_file_does_not_exist(self):
description = {
"oml:parquet_url": "http://data.openml.org/dataset20/does_not_exist.pq",
"oml:id": "20",
}
path = _get_dataset_parquet(description, cache_directory=self.workdir)
assert path is None, "_get_dataset_parquet returns None if no file is found"
def test__getarff_md5_issue(self):
description = {
"oml:id": 5,
"oml:md5_checksum": "abc",
"oml:url": "https://www.openml.org/data/download/61",
}
n = openml.config.connection_n_retries
openml.config.connection_n_retries = 1
self.assertRaisesRegex(
OpenMLHashException,
"Checksum of downloaded file is unequal to the expected checksum abc when downloading "
"https://www.openml.org/data/download/61. Raised when downloading dataset 5.",
_get_dataset_arff,
description,
)
openml.config.connection_n_retries = n
@pytest.mark.uses_test_server()
def test__get_dataset_features(self):
features_file = _get_dataset_features_file(self.workdir, 2)
assert isinstance(features_file, Path)
features_xml_path = self.workdir / "features.xml"
assert features_xml_path.exists()
@pytest.mark.uses_test_server()
def test__get_dataset_qualities(self):
qualities = _get_dataset_qualities_file(self.workdir, 2)
assert isinstance(qualities, Path)
qualities_xml_path = self.workdir / "qualities.xml"
assert qualities_xml_path.exists()
@pytest.mark.uses_test_server()
def test_get_dataset_force_refresh_cache(self):
did_cache_dir = _create_cache_directory_for_id(
DATASETS_CACHE_DIR_NAME,
2,
)
openml.datasets.get_dataset(2)
change_time = os.stat(did_cache_dir).st_mtime
# Test default
openml.datasets.get_dataset(2)
assert change_time == os.stat(did_cache_dir).st_mtime
# Test refresh
openml.datasets.get_dataset(2, force_refresh_cache=True)
assert change_time != os.stat(did_cache_dir).st_mtime
# Final clean up
openml.utils._remove_cache_dir_for_id(
DATASETS_CACHE_DIR_NAME,
did_cache_dir,
)
@pytest.mark.uses_test_server()
def test_get_dataset_force_refresh_cache_clean_start(self):
did_cache_dir = _create_cache_directory_for_id(
DATASETS_CACHE_DIR_NAME,
2,
)
# Clean up
openml.utils._remove_cache_dir_for_id(
DATASETS_CACHE_DIR_NAME,
did_cache_dir,
)
# Test clean start
openml.datasets.get_dataset(2, force_refresh_cache=True)
assert os.path.exists(did_cache_dir)
# Final clean up
openml.utils._remove_cache_dir_for_id(
DATASETS_CACHE_DIR_NAME,
did_cache_dir,
)
def test_deletion_of_cache_dir(self):
# Simple removal
did_cache_dir = _create_cache_directory_for_id(
DATASETS_CACHE_DIR_NAME,
1,
)
assert os.path.exists(did_cache_dir)
openml.utils._remove_cache_dir_for_id(
DATASETS_CACHE_DIR_NAME,
did_cache_dir,
)
assert not os.path.exists(did_cache_dir)
# get_dataset_description is the only data guaranteed to be downloaded
@mock.patch("openml.datasets.functions._get_dataset_description")
@pytest.mark.uses_test_server()
def test_deletion_of_cache_dir_faulty_download(self, patch):
patch.side_effect = Exception("Boom!")
self.assertRaisesRegex(Exception, "Boom!", openml.datasets.get_dataset, dataset_id=1)
datasets_cache_dir = os.path.join(openml.config.get_cache_directory(), "datasets")
assert len(os.listdir(datasets_cache_dir)) == 0
@pytest.mark.uses_test_server()
def test_publish_dataset(self):
arff_file_path = self.static_cache_dir / "org" / "openml" / "test" / "datasets" / "2" / "dataset.arff"
dataset = OpenMLDataset(
"anneal",
"test",
data_format="arff",
version=1,
licence="public",
default_target_attribute="class",
data_file=arff_file_path,
)
dataset.publish()
TestBase._mark_entity_for_removal("data", dataset.dataset_id)
TestBase.logger.info(
f"collected from {__file__.split('/')[-1]}: {dataset.dataset_id}",
)
assert isinstance(dataset.dataset_id, int)
@pytest.mark.uses_test_server()
def test__retrieve_class_labels(self):
openml.config.set_root_cache_directory(self.static_cache_dir)
labels = openml.datasets.get_dataset(2).retrieve_class_labels()
assert labels == ["1", "2", "3", "4", "5", "U"]
labels = openml.datasets.get_dataset(2).retrieve_class_labels(
target_name="product-type",
)
assert labels == ["C", "H", "G"]
# Test workaround for string-typed class labels
custom_ds = openml.datasets.get_dataset(2)
custom_ds.features[31].data_type = "string"
labels = custom_ds.retrieve_class_labels(target_name=custom_ds.features[31].name)
assert labels == ["COIL", "SHEET"]
@pytest.mark.uses_test_server()
def test_upload_dataset_with_url(self):
dataset = OpenMLDataset(
f"{self._get_sentinel()}-UploadTestWithURL",
"test",
data_format="arff",
version=1,
url="https://www.openml.org/data/download/61/dataset_61_iris.arff",
)
dataset.publish()
TestBase._mark_entity_for_removal("data", dataset.dataset_id)
TestBase.logger.info(
f"collected from {__file__.split('/')[-1]}: {dataset.dataset_id}",
)
assert isinstance(dataset.dataset_id, int)
def _assert_status_of_dataset(self, *, did: int, status: str):
"""Asserts there is exactly one dataset with id `did` and its current status is `status`"""
# need to use listing fn, as this is immune to cache
result = openml.datasets.list_datasets(data_id=[did], status="all")
result = result.to_dict(orient="index")
# I think we should drop the test that one result is returned,
# the server should never return multiple results?
assert len(result) == 1
assert result[did]["status"] == status
@pytest.mark.flaky()
@pytest.mark.uses_test_server()
def test_data_status(self):
dataset = OpenMLDataset(
f"{self._get_sentinel()}-UploadTestWithURL",
"test",
"ARFF",
version=1,
url="https://www.openml.org/data/download/61/dataset_61_iris.arff",
)
dataset.publish()
TestBase._mark_entity_for_removal("data", dataset.id)
TestBase.logger.info(f"collected from {__file__.split('/')[-1]}: {dataset.id}")
did = dataset.id
# admin key for test server (only admins can activate datasets.
# all users can deactivate their own datasets)
openml.config.apikey = TestBase.admin_key
openml.datasets.status_update(did, "active")
self._assert_status_of_dataset(did=did, status="active")
openml.datasets.status_update(did, "deactivated")
self._assert_status_of_dataset(did=did, status="deactivated")
openml.datasets.status_update(did, "active")
self._assert_status_of_dataset(did=did, status="active")
with pytest.raises(ValueError):
openml.datasets.status_update(did, "in_preparation")
self._assert_status_of_dataset(did=did, status="active")
def test_attributes_arff_from_df(self):
# DataFrame case
df = pd.DataFrame(
[[1, 1.0, "xxx", "A", True], [2, 2.0, "yyy", "B", False]],
columns=["integer", "floating", "string", "category", "boolean"],
)
df["category"] = df["category"].astype("category")
attributes = attributes_arff_from_df(df)
assert attributes == [
("integer", "INTEGER"),
("floating", "REAL"),
("string", "STRING"),
("category", ["A", "B"]),
("boolean", ["True", "False"]),
]
# DataFrame with Sparse columns case
df = pd.DataFrame(
{
"integer": pd.arrays.SparseArray([1, 2, 0], fill_value=0),
"floating": pd.arrays.SparseArray([1.0, 2.0, 0], fill_value=0.0),
},
)
df["integer"] = df["integer"].astype(np.int64)
attributes = attributes_arff_from_df(df)
assert attributes == [("integer", "INTEGER"), ("floating", "REAL")]
def test_attributes_arff_from_df_numeric_column(self):
# Test column names are automatically converted to str if needed (#819)
df = pd.DataFrame({0: [1, 2, 3], 0.5: [4, 5, 6], "target": [0, 1, 1]})
attributes = attributes_arff_from_df(df)
assert attributes == [
("0", "INTEGER"),
("0.5", "INTEGER"),
("target", "INTEGER"),
]
def test_attributes_arff_from_df_mixed_dtype_categories(self):
# liac-arff imposed categorical attributes to be of sting dtype. We
# raise an error if this is not the case.
df = pd.DataFrame([[1], ["2"], [3.0]])
df[0] = df[0].astype("category")
err_msg = "The column '0' of the dataframe is of 'category' dtype."
with pytest.raises(ValueError, match=err_msg):
attributes_arff_from_df(df)
def test_attributes_arff_from_df_unknown_dtype(self):
# check that an error is raised when the dtype is not supptagorted by
# liac-arff
data = [
[[1], ["2"], [3.0]],
[pd.Timestamp("2012-05-01"), pd.Timestamp("2012-05-02")],
]
dtype = ["mixed-integer", "datetime64"]
for arr, dt in zip(data, dtype):
df = pd.DataFrame(arr)
err_msg = (
f"The dtype '{dt}' of the column '0' is not currently " "supported by liac-arff"
)
with pytest.raises(ValueError, match=err_msg):
attributes_arff_from_df(df)
@pytest.mark.uses_test_server()
def test_create_dataset_numpy(self):
data = np.array([[1, 2, 3], [1.2, 2.5, 3.8], [2, 5, 8], [0, 1, 0]]).T
attributes = [(f"col_{i}", "REAL") for i in range(data.shape[1])]
dataset = create_dataset(
name=f"{self._get_sentinel()}-NumPy_testing_dataset",
description="Synthetic dataset created from a NumPy array",
creator="OpenML tester",
contributor=None,
collection_date="01-01-2018",
language="English",
licence="MIT",
default_target_attribute=f"col_{data.shape[1] - 1}",
row_id_attribute=None,
ignore_attribute=None,
citation="None",
attributes=attributes,
data=data,
version_label="test",
original_data_url="http://openml.github.io/openml-python",
paper_url="http://openml.github.io/openml-python",
)
dataset.publish()
TestBase._mark_entity_for_removal("data", dataset.id)
TestBase.logger.info(f"collected from {__file__.split('/')[-1]}: {dataset.id}")
assert (
_get_online_dataset_arff(dataset.id) == dataset._dataset
), "Uploaded arff does not match original one"
assert _get_online_dataset_format(dataset.id) == "arff", "Wrong format for dataset"
@pytest.mark.uses_test_server()
def test_create_dataset_list(self):
data = [
["a", "sunny", 85.0, 85.0, "FALSE", "no"],
["b", "sunny", 80.0, 90.0, "TRUE", "no"],
["c", "overcast", 83.0, 86.0, "FALSE", "yes"],
["d", "rainy", 70.0, 96.0, "FALSE", "yes"],
["e", "rainy", 68.0, 80.0, "FALSE", "yes"],
["f", "rainy", 65.0, 70.0, "TRUE", "no"],
["g", "overcast", 64.0, 65.0, "TRUE", "yes"],
["h", "sunny", 72.0, 95.0, "FALSE", "no"],
["i", "sunny", 69.0, 70.0, "FALSE", "yes"],
["j", "rainy", 75.0, 80.0, "FALSE", "yes"],
["k", "sunny", 75.0, 70.0, "TRUE", "yes"],
["l", "overcast", 72.0, 90.0, "TRUE", "yes"],
["m", "overcast", 81.0, 75.0, "FALSE", "yes"],
["n", "rainy", 71.0, 91.0, "TRUE", "no"],
]
attributes = [
("rnd_str", "STRING"),
("outlook", ["sunny", "overcast", "rainy"]),
("temperature", "REAL"),
("humidity", "REAL"),
("windy", ["TRUE", "FALSE"]),
("play", ["yes", "no"]),
]
dataset = create_dataset(
name=f"{self._get_sentinel()}-ModifiedWeather",
description=("Testing dataset upload when the data is a list of lists"),
creator="OpenML test",
contributor=None,
collection_date="21-09-2018",
language="English",
licence="MIT",
default_target_attribute="play",
row_id_attribute=None,
ignore_attribute=None,
citation="None",
attributes=attributes,
data=data,
version_label="test",
original_data_url="http://openml.github.io/openml-python",
paper_url="http://openml.github.io/openml-python",
)
dataset.publish()
TestBase._mark_entity_for_removal("data", dataset.id)
TestBase.logger.info(f"collected from {__file__.split('/')[-1]}: {dataset.id}")
assert (
_get_online_dataset_arff(dataset.id) == dataset._dataset
), "Uploaded ARFF does not match original one"
assert _get_online_dataset_format(dataset.id) == "arff", "Wrong format for dataset"
@pytest.mark.uses_test_server()
def test_create_dataset_sparse(self):
# test the scipy.sparse.coo_matrix
sparse_data = scipy.sparse.coo_matrix(
(
[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
([0, 1, 1, 2, 2, 3, 3], [0, 1, 2, 0, 2, 0, 1]),
),
)
column_names = [
("input1", "REAL"),
("input2", "REAL"),
("y", "REAL"),
]
xor_dataset = create_dataset(
name=f"{self._get_sentinel()}-XOR",
description="Dataset representing the XOR operation",
creator=None,
contributor=None,
collection_date=None,
language="English",
licence=None,
default_target_attribute="y",
row_id_attribute=None,
ignore_attribute=None,
citation=None,
attributes=column_names,
data=sparse_data,
version_label="test",
)
xor_dataset.publish()
TestBase._mark_entity_for_removal("data", xor_dataset.id)
TestBase.logger.info(
f"collected from {__file__.split('/')[-1]}: {xor_dataset.id}",
)
assert (
_get_online_dataset_arff(xor_dataset.id) == xor_dataset._dataset
), "Uploaded ARFF does not match original one"
assert (
_get_online_dataset_format(xor_dataset.id) == "sparse_arff"
), "Wrong format for dataset"
# test the list of dicts sparse representation
sparse_data = [{0: 0.0}, {1: 1.0, 2: 1.0}, {0: 1.0, 2: 1.0}, {0: 1.0, 1: 1.0}]
xor_dataset = create_dataset(
name=f"{self._get_sentinel()}-XOR",
description="Dataset representing the XOR operation",
creator=None,
contributor=None,
collection_date=None,
language="English",
licence=None,
default_target_attribute="y",
row_id_attribute=None,
ignore_attribute=None,
citation=None,
attributes=column_names,
data=sparse_data,
version_label="test",
)
xor_dataset.publish()
TestBase._mark_entity_for_removal("data", xor_dataset.id)
TestBase.logger.info(
f"collected from {__file__.split('/')[-1]}: {xor_dataset.id}",
)
assert (
_get_online_dataset_arff(xor_dataset.id) == xor_dataset._dataset
), "Uploaded ARFF does not match original one"
assert (
_get_online_dataset_format(xor_dataset.id) == "sparse_arff"
), "Wrong format for dataset"
def test_create_invalid_dataset(self):
data = [
"sunny",
"overcast",
"overcast",
"rainy",
"rainy",
"rainy",
"overcast",
"sunny",
"sunny",
"rainy",
"sunny",
"overcast",
"overcast",
"rainy",
]
param = self._get_empty_param_for_dataset()
param["data"] = data
self.assertRaises(ValueError, create_dataset, **param)
param["data"] = data[0]
self.assertRaises(ValueError, create_dataset, **param)
@pytest.mark.uses_test_server()
def test_get_online_dataset_arff(self):
dataset_id = 128 # iris -- one of the few datasets without parquet file
# lazy loading not used as arff file is checked.
dataset = openml.datasets.get_dataset(dataset_id, download_data=True)
decoder = arff.ArffDecoder()
# check if the arff from the dataset is
# the same as the arff from _get_arff function
d_format = (dataset.format).lower()
assert dataset._get_arff(d_format) == decoder.decode(
_get_online_dataset_arff(dataset_id),
encode_nominal=True,
return_type=arff.DENSE if d_format == "arff" else arff.COO,
), "ARFF files are not equal"
@pytest.mark.uses_test_server()
def test_topic_api_error(self):
# Check server exception when non-admin accessses apis
self.assertRaisesRegex(
OpenMLServerException,
"Topic can only be added/removed by admin.",
_topic_add_dataset,
data_id=31,
topic="business",
)
# Check server exception when non-admin accessses apis
self.assertRaisesRegex(
OpenMLServerException,
"Topic can only be added/removed by admin.",
_topic_delete_dataset,
data_id=31,
topic="business",
)
@pytest.mark.uses_test_server()
def test_get_online_dataset_format(self):
# Phoneme dataset
dataset_id = 77
dataset = openml.datasets.get_dataset(dataset_id)
assert dataset.format.lower() == _get_online_dataset_format(
dataset_id
), "The format of the ARFF files is different"
@pytest.mark.uses_test_server()
def test_create_dataset_pandas(self):
data = [
["a", "sunny", 85.0, 85.0, "FALSE", "no"],
["b", "sunny", 80.0, 90.0, "TRUE", "no"],
["c", "overcast", 83.0, 86.0, "FALSE", "yes"],
["d", "rainy", 70.0, 96.0, "FALSE", "yes"],
["e", "rainy", 68.0, 80.0, "FALSE", "yes"],
]
column_names = [
"rnd_str",
"outlook",
"temperature",
"humidity",
"windy",
"play",
]
df = pd.DataFrame(data, columns=column_names)
# enforce the type of each column
df["outlook"] = df["outlook"].astype("category")
df["windy"] = df["windy"].astype("bool")
df["play"] = df["play"].astype("category")
# meta-information
name = f"{self._get_sentinel()}-pandas_testing_dataset"
description = "Synthetic dataset created from a Pandas DataFrame"
creator = "OpenML tester"
collection_date = "01-01-2018"
language = "English"
licence = "MIT"
citation = "None"
original_data_url = "http://openml.github.io/openml-python"
paper_url = "http://openml.github.io/openml-python"
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute="play",
row_id_attribute=None,
ignore_attribute=None,
citation=citation,
attributes="auto",
data=df,
version_label="test",
original_data_url=original_data_url,
paper_url=paper_url,
)
dataset.publish()
TestBase._mark_entity_for_removal("data", dataset.id)
TestBase.logger.info(f"collected from {__file__.split('/')[-1]}: {dataset.id}")
assert (
_get_online_dataset_arff(dataset.id) == dataset._dataset
), "Uploaded ARFF does not match original one"
# Check that DataFrame with Sparse columns are supported properly
sparse_data = scipy.sparse.coo_matrix(
(
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
([0, 1, 1, 2, 2, 3, 3], [0, 1, 2, 0, 2, 0, 1]),
),
)
column_names = ["input1", "input2", "y"]
df = pd.DataFrame.sparse.from_spmatrix(sparse_data, columns=column_names)
# meta-information
description = "Synthetic dataset created from a Pandas DataFrame with Sparse columns"
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,