_openml.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. import gzip
  2. import hashlib
  3. import json
  4. import os
  5. import shutil
  6. import time
  7. from contextlib import closing
  8. from functools import wraps
  9. from os.path import join
  10. from tempfile import TemporaryDirectory
  11. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  12. from urllib.error import HTTPError, URLError
  13. from urllib.request import Request, urlopen
  14. from warnings import warn
  15. import numpy as np
  16. from ..utils import (
  17. Bunch,
  18. check_pandas_support, # noqa # noqa
  19. )
  20. from ..utils._param_validation import (
  21. Hidden,
  22. Integral,
  23. Interval,
  24. Real,
  25. StrOptions,
  26. validate_params,
  27. )
  28. from . import get_data_home
  29. from ._arff_parser import load_arff_from_gzip_file
  30. __all__ = ["fetch_openml"]
  31. _OPENML_PREFIX = "https://api.openml.org/"
  32. _SEARCH_NAME = "api/v1/json/data/list/data_name/{}/limit/2"
  33. _DATA_INFO = "api/v1/json/data/{}"
  34. _DATA_FEATURES = "api/v1/json/data/features/{}"
  35. _DATA_QUALITIES = "api/v1/json/data/qualities/{}"
  36. _DATA_FILE = "data/v1/download/{}"
  37. OpenmlQualitiesType = List[Dict[str, str]]
  38. OpenmlFeaturesType = List[Dict[str, str]]
  39. def _get_local_path(openml_path: str, data_home: str) -> str:
  40. return os.path.join(data_home, "openml.org", openml_path + ".gz")
  41. def _retry_with_clean_cache(
  42. openml_path: str,
  43. data_home: Optional[str],
  44. no_retry_exception: Optional[Exception] = None,
  45. ) -> Callable:
  46. """If the first call to the decorated function fails, the local cached
  47. file is removed, and the function is called again. If ``data_home`` is
  48. ``None``, then the function is called once. We can provide a specific
  49. exception to not retry on using `no_retry_exception` parameter.
  50. """
  51. def decorator(f):
  52. @wraps(f)
  53. def wrapper(*args, **kw):
  54. if data_home is None:
  55. return f(*args, **kw)
  56. try:
  57. return f(*args, **kw)
  58. except URLError:
  59. raise
  60. except Exception as exc:
  61. if no_retry_exception is not None and isinstance(
  62. exc, no_retry_exception
  63. ):
  64. raise
  65. warn("Invalid cache, redownloading file", RuntimeWarning)
  66. local_path = _get_local_path(openml_path, data_home)
  67. if os.path.exists(local_path):
  68. os.unlink(local_path)
  69. return f(*args, **kw)
  70. return wrapper
  71. return decorator
  72. def _retry_on_network_error(
  73. n_retries: int = 3, delay: float = 1.0, url: str = ""
  74. ) -> Callable:
  75. """If the function call results in a network error, call the function again
  76. up to ``n_retries`` times with a ``delay`` between each call. If the error
  77. has a 412 status code, don't call the function again as this is a specific
  78. OpenML error.
  79. The url parameter is used to give more information to the user about the
  80. error.
  81. """
  82. def decorator(f):
  83. @wraps(f)
  84. def wrapper(*args, **kwargs):
  85. retry_counter = n_retries
  86. while True:
  87. try:
  88. return f(*args, **kwargs)
  89. except (URLError, TimeoutError) as e:
  90. # 412 is a specific OpenML error code.
  91. if isinstance(e, HTTPError) and e.code == 412:
  92. raise
  93. if retry_counter == 0:
  94. raise
  95. warn(
  96. f"A network error occurred while downloading {url}. Retrying..."
  97. )
  98. retry_counter -= 1
  99. time.sleep(delay)
  100. return wrapper
  101. return decorator
  102. def _open_openml_url(
  103. openml_path: str, data_home: Optional[str], n_retries: int = 3, delay: float = 1.0
  104. ):
  105. """
  106. Returns a resource from OpenML.org. Caches it to data_home if required.
  107. Parameters
  108. ----------
  109. openml_path : str
  110. OpenML URL that will be accessed. This will be prefixes with
  111. _OPENML_PREFIX.
  112. data_home : str
  113. Directory to which the files will be cached. If None, no caching will
  114. be applied.
  115. n_retries : int, default=3
  116. Number of retries when HTTP errors are encountered. Error with status
  117. code 412 won't be retried as they represent OpenML generic errors.
  118. delay : float, default=1.0
  119. Number of seconds between retries.
  120. Returns
  121. -------
  122. result : stream
  123. A stream to the OpenML resource.
  124. """
  125. def is_gzip_encoded(_fsrc):
  126. return _fsrc.info().get("Content-Encoding", "") == "gzip"
  127. req = Request(_OPENML_PREFIX + openml_path)
  128. req.add_header("Accept-encoding", "gzip")
  129. if data_home is None:
  130. fsrc = _retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(req)
  131. if is_gzip_encoded(fsrc):
  132. return gzip.GzipFile(fileobj=fsrc, mode="rb")
  133. return fsrc
  134. local_path = _get_local_path(openml_path, data_home)
  135. dir_name, file_name = os.path.split(local_path)
  136. if not os.path.exists(local_path):
  137. os.makedirs(dir_name, exist_ok=True)
  138. try:
  139. # Create a tmpdir as a subfolder of dir_name where the final file will
  140. # be moved to if the download is successful. This guarantees that the
  141. # renaming operation to the final location is atomic to ensure the
  142. # concurrence safety of the dataset caching mechanism.
  143. with TemporaryDirectory(dir=dir_name) as tmpdir:
  144. with closing(
  145. _retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(
  146. req
  147. )
  148. ) as fsrc:
  149. opener: Callable
  150. if is_gzip_encoded(fsrc):
  151. opener = open
  152. else:
  153. opener = gzip.GzipFile
  154. with opener(os.path.join(tmpdir, file_name), "wb") as fdst:
  155. shutil.copyfileobj(fsrc, fdst)
  156. shutil.move(fdst.name, local_path)
  157. except Exception:
  158. if os.path.exists(local_path):
  159. os.unlink(local_path)
  160. raise
  161. # XXX: First time, decompression will not be necessary (by using fsrc), but
  162. # it will happen nonetheless
  163. return gzip.GzipFile(local_path, "rb")
  164. class OpenMLError(ValueError):
  165. """HTTP 412 is a specific OpenML error code, indicating a generic error"""
  166. pass
  167. def _get_json_content_from_openml_api(
  168. url: str,
  169. error_message: Optional[str],
  170. data_home: Optional[str],
  171. n_retries: int = 3,
  172. delay: float = 1.0,
  173. ) -> Dict:
  174. """
  175. Loads json data from the openml api.
  176. Parameters
  177. ----------
  178. url : str
  179. The URL to load from. Should be an official OpenML endpoint.
  180. error_message : str or None
  181. The error message to raise if an acceptable OpenML error is thrown
  182. (acceptable error is, e.g., data id not found. Other errors, like 404's
  183. will throw the native error message).
  184. data_home : str or None
  185. Location to cache the response. None if no cache is required.
  186. n_retries : int, default=3
  187. Number of retries when HTTP errors are encountered. Error with status
  188. code 412 won't be retried as they represent OpenML generic errors.
  189. delay : float, default=1.0
  190. Number of seconds between retries.
  191. Returns
  192. -------
  193. json_data : json
  194. the json result from the OpenML server if the call was successful.
  195. An exception otherwise.
  196. """
  197. @_retry_with_clean_cache(url, data_home=data_home)
  198. def _load_json():
  199. with closing(
  200. _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
  201. ) as response:
  202. return json.loads(response.read().decode("utf-8"))
  203. try:
  204. return _load_json()
  205. except HTTPError as error:
  206. # 412 is an OpenML specific error code, indicating a generic error
  207. # (e.g., data not found)
  208. if error.code != 412:
  209. raise error
  210. # 412 error, not in except for nicer traceback
  211. raise OpenMLError(error_message)
  212. def _get_data_info_by_name(
  213. name: str,
  214. version: Union[int, str],
  215. data_home: Optional[str],
  216. n_retries: int = 3,
  217. delay: float = 1.0,
  218. ):
  219. """
  220. Utilizes the openml dataset listing api to find a dataset by
  221. name/version
  222. OpenML api function:
  223. https://www.openml.org/api_docs#!/data/get_data_list_data_name_data_name
  224. Parameters
  225. ----------
  226. name : str
  227. name of the dataset
  228. version : int or str
  229. If version is an integer, the exact name/version will be obtained from
  230. OpenML. If version is a string (value: "active") it will take the first
  231. version from OpenML that is annotated as active. Any other string
  232. values except "active" are treated as integer.
  233. data_home : str or None
  234. Location to cache the response. None if no cache is required.
  235. n_retries : int, default=3
  236. Number of retries when HTTP errors are encountered. Error with status
  237. code 412 won't be retried as they represent OpenML generic errors.
  238. delay : float, default=1.0
  239. Number of seconds between retries.
  240. Returns
  241. -------
  242. first_dataset : json
  243. json representation of the first dataset object that adhired to the
  244. search criteria
  245. """
  246. if version == "active":
  247. # situation in which we return the oldest active version
  248. url = _SEARCH_NAME.format(name) + "/status/active/"
  249. error_msg = "No active dataset {} found.".format(name)
  250. json_data = _get_json_content_from_openml_api(
  251. url,
  252. error_msg,
  253. data_home=data_home,
  254. n_retries=n_retries,
  255. delay=delay,
  256. )
  257. res = json_data["data"]["dataset"]
  258. if len(res) > 1:
  259. warn(
  260. "Multiple active versions of the dataset matching the name"
  261. " {name} exist. Versions may be fundamentally different, "
  262. "returning version"
  263. " {version}.".format(name=name, version=res[0]["version"])
  264. )
  265. return res[0]
  266. # an integer version has been provided
  267. url = (_SEARCH_NAME + "/data_version/{}").format(name, version)
  268. try:
  269. json_data = _get_json_content_from_openml_api(
  270. url,
  271. error_message=None,
  272. data_home=data_home,
  273. n_retries=n_retries,
  274. delay=delay,
  275. )
  276. except OpenMLError:
  277. # we can do this in 1 function call if OpenML does not require the
  278. # specification of the dataset status (i.e., return datasets with a
  279. # given name / version regardless of active, deactivated, etc. )
  280. # TODO: feature request OpenML.
  281. url += "/status/deactivated"
  282. error_msg = "Dataset {} with version {} not found.".format(name, version)
  283. json_data = _get_json_content_from_openml_api(
  284. url,
  285. error_msg,
  286. data_home=data_home,
  287. n_retries=n_retries,
  288. delay=delay,
  289. )
  290. return json_data["data"]["dataset"][0]
  291. def _get_data_description_by_id(
  292. data_id: int,
  293. data_home: Optional[str],
  294. n_retries: int = 3,
  295. delay: float = 1.0,
  296. ) -> Dict[str, Any]:
  297. # OpenML API function: https://www.openml.org/api_docs#!/data/get_data_id
  298. url = _DATA_INFO.format(data_id)
  299. error_message = "Dataset with data_id {} not found.".format(data_id)
  300. json_data = _get_json_content_from_openml_api(
  301. url,
  302. error_message,
  303. data_home=data_home,
  304. n_retries=n_retries,
  305. delay=delay,
  306. )
  307. return json_data["data_set_description"]
  308. def _get_data_features(
  309. data_id: int,
  310. data_home: Optional[str],
  311. n_retries: int = 3,
  312. delay: float = 1.0,
  313. ) -> OpenmlFeaturesType:
  314. # OpenML function:
  315. # https://www.openml.org/api_docs#!/data/get_data_features_id
  316. url = _DATA_FEATURES.format(data_id)
  317. error_message = "Dataset with data_id {} not found.".format(data_id)
  318. json_data = _get_json_content_from_openml_api(
  319. url,
  320. error_message,
  321. data_home=data_home,
  322. n_retries=n_retries,
  323. delay=delay,
  324. )
  325. return json_data["data_features"]["feature"]
  326. def _get_data_qualities(
  327. data_id: int,
  328. data_home: Optional[str],
  329. n_retries: int = 3,
  330. delay: float = 1.0,
  331. ) -> OpenmlQualitiesType:
  332. # OpenML API function:
  333. # https://www.openml.org/api_docs#!/data/get_data_qualities_id
  334. url = _DATA_QUALITIES.format(data_id)
  335. error_message = "Dataset with data_id {} not found.".format(data_id)
  336. json_data = _get_json_content_from_openml_api(
  337. url,
  338. error_message,
  339. data_home=data_home,
  340. n_retries=n_retries,
  341. delay=delay,
  342. )
  343. # the qualities might not be available, but we still try to process
  344. # the data
  345. return json_data.get("data_qualities", {}).get("quality", [])
  346. def _get_num_samples(data_qualities: OpenmlQualitiesType) -> int:
  347. """Get the number of samples from data qualities.
  348. Parameters
  349. ----------
  350. data_qualities : list of dict
  351. Used to retrieve the number of instances (samples) in the dataset.
  352. Returns
  353. -------
  354. n_samples : int
  355. The number of samples in the dataset or -1 if data qualities are
  356. unavailable.
  357. """
  358. # If the data qualities are unavailable, we return -1
  359. default_n_samples = -1
  360. qualities = {d["name"]: d["value"] for d in data_qualities}
  361. return int(float(qualities.get("NumberOfInstances", default_n_samples)))
  362. def _load_arff_response(
  363. url: str,
  364. data_home: Optional[str],
  365. parser: str,
  366. output_type: str,
  367. openml_columns_info: dict,
  368. feature_names_to_select: List[str],
  369. target_names_to_select: List[str],
  370. shape: Optional[Tuple[int, int]],
  371. md5_checksum: str,
  372. n_retries: int = 3,
  373. delay: float = 1.0,
  374. read_csv_kwargs: Optional[Dict] = None,
  375. ):
  376. """Load the ARFF data associated with the OpenML URL.
  377. In addition of loading the data, this function will also check the
  378. integrity of the downloaded file from OpenML using MD5 checksum.
  379. Parameters
  380. ----------
  381. url : str
  382. The URL of the ARFF file on OpenML.
  383. data_home : str
  384. The location where to cache the data.
  385. parser : {"liac-arff", "pandas"}
  386. The parser used to parse the ARFF file.
  387. output_type : {"numpy", "pandas", "sparse"}
  388. The type of the arrays that will be returned. The possibilities are:
  389. - `"numpy"`: both `X` and `y` will be NumPy arrays;
  390. - `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array;
  391. - `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a
  392. pandas Series or DataFrame.
  393. openml_columns_info : dict
  394. The information provided by OpenML regarding the columns of the ARFF
  395. file.
  396. feature_names_to_select : list of str
  397. The list of the features to be selected.
  398. target_names_to_select : list of str
  399. The list of the target variables to be selected.
  400. shape : tuple or None
  401. With `parser="liac-arff"`, when using a generator to load the data,
  402. one needs to provide the shape of the data beforehand.
  403. md5_checksum : str
  404. The MD5 checksum provided by OpenML to check the data integrity.
  405. n_retries : int, default=3
  406. The number of times to retry downloading the data if it fails.
  407. delay : float, default=1.0
  408. The delay between two consecutive downloads in seconds.
  409. read_csv_kwargs : dict, default=None
  410. Keyword arguments to pass to `pandas.read_csv` when using the pandas parser.
  411. It allows to overwrite the default options.
  412. .. versionadded:: 1.3
  413. Returns
  414. -------
  415. X : {ndarray, sparse matrix, dataframe}
  416. The data matrix.
  417. y : {ndarray, dataframe, series}
  418. The target.
  419. frame : dataframe or None
  420. A dataframe containing both `X` and `y`. `None` if
  421. `output_array_type != "pandas"`.
  422. categories : list of str or None
  423. The names of the features that are categorical. `None` if
  424. `output_array_type == "pandas"`.
  425. """
  426. gzip_file = _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
  427. with closing(gzip_file):
  428. md5 = hashlib.md5()
  429. for chunk in iter(lambda: gzip_file.read(4096), b""):
  430. md5.update(chunk)
  431. actual_md5_checksum = md5.hexdigest()
  432. if actual_md5_checksum != md5_checksum:
  433. raise ValueError(
  434. f"md5 checksum of local file for {url} does not match description: "
  435. f"expected: {md5_checksum} but got {actual_md5_checksum}. "
  436. "Downloaded file could have been modified / corrupted, clean cache "
  437. "and retry..."
  438. )
  439. def _open_url_and_load_gzip_file(url, data_home, n_retries, delay, arff_params):
  440. gzip_file = _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
  441. with closing(gzip_file):
  442. return load_arff_from_gzip_file(gzip_file, **arff_params)
  443. arff_params: Dict = dict(
  444. parser=parser,
  445. output_type=output_type,
  446. openml_columns_info=openml_columns_info,
  447. feature_names_to_select=feature_names_to_select,
  448. target_names_to_select=target_names_to_select,
  449. shape=shape,
  450. read_csv_kwargs=read_csv_kwargs or {},
  451. )
  452. try:
  453. X, y, frame, categories = _open_url_and_load_gzip_file(
  454. url, data_home, n_retries, delay, arff_params
  455. )
  456. except Exception as exc:
  457. if parser != "pandas":
  458. raise
  459. from pandas.errors import ParserError
  460. if not isinstance(exc, ParserError):
  461. raise
  462. # A parsing error could come from providing the wrong quotechar
  463. # to pandas. By default, we use a double quote. Thus, we retry
  464. # with a single quote before to raise the error.
  465. arff_params["read_csv_kwargs"].update(quotechar="'")
  466. X, y, frame, categories = _open_url_and_load_gzip_file(
  467. url, data_home, n_retries, delay, arff_params
  468. )
  469. return X, y, frame, categories
  470. def _download_data_to_bunch(
  471. url: str,
  472. sparse: bool,
  473. data_home: Optional[str],
  474. *,
  475. as_frame: bool,
  476. openml_columns_info: List[dict],
  477. data_columns: List[str],
  478. target_columns: List[str],
  479. shape: Optional[Tuple[int, int]],
  480. md5_checksum: str,
  481. n_retries: int = 3,
  482. delay: float = 1.0,
  483. parser: str,
  484. read_csv_kwargs: Optional[Dict] = None,
  485. ):
  486. """Download ARFF data, load it to a specific container and create to Bunch.
  487. This function has a mechanism to retry/cache/clean the data.
  488. Parameters
  489. ----------
  490. url : str
  491. The URL of the ARFF file on OpenML.
  492. sparse : bool
  493. Whether the dataset is expected to use the sparse ARFF format.
  494. data_home : str
  495. The location where to cache the data.
  496. as_frame : bool
  497. Whether or not to return the data into a pandas DataFrame.
  498. openml_columns_info : list of dict
  499. The information regarding the columns provided by OpenML for the
  500. ARFF dataset. The information is stored as a list of dictionaries.
  501. data_columns : list of str
  502. The list of the features to be selected.
  503. target_columns : list of str
  504. The list of the target variables to be selected.
  505. shape : tuple or None
  506. With `parser="liac-arff"`, when using a generator to load the data,
  507. one needs to provide the shape of the data beforehand.
  508. md5_checksum : str
  509. The MD5 checksum provided by OpenML to check the data integrity.
  510. n_retries : int, default=3
  511. Number of retries when HTTP errors are encountered. Error with status
  512. code 412 won't be retried as they represent OpenML generic errors.
  513. delay : float, default=1.0
  514. Number of seconds between retries.
  515. parser : {"liac-arff", "pandas"}
  516. The parser used to parse the ARFF file.
  517. read_csv_kwargs : dict, default=None
  518. Keyword arguments to pass to `pandas.read_csv` when using the pandas parser.
  519. It allows to overwrite the default options.
  520. .. versionadded:: 1.3
  521. Returns
  522. -------
  523. data : :class:`~sklearn.utils.Bunch`
  524. Dictionary-like object, with the following attributes.
  525. X : {ndarray, sparse matrix, dataframe}
  526. The data matrix.
  527. y : {ndarray, dataframe, series}
  528. The target.
  529. frame : dataframe or None
  530. A dataframe containing both `X` and `y`. `None` if
  531. `output_array_type != "pandas"`.
  532. categories : list of str or None
  533. The names of the features that are categorical. `None` if
  534. `output_array_type == "pandas"`.
  535. """
  536. # Prepare which columns and data types should be returned for the X and y
  537. features_dict = {feature["name"]: feature for feature in openml_columns_info}
  538. if sparse:
  539. output_type = "sparse"
  540. elif as_frame:
  541. output_type = "pandas"
  542. else:
  543. output_type = "numpy"
  544. # XXX: target columns should all be categorical or all numeric
  545. _verify_target_data_type(features_dict, target_columns)
  546. for name in target_columns:
  547. column_info = features_dict[name]
  548. n_missing_values = int(column_info["number_of_missing_values"])
  549. if n_missing_values > 0:
  550. raise ValueError(
  551. f"Target column '{column_info['name']}' has {n_missing_values} missing "
  552. "values. Missing values are not supported for target columns."
  553. )
  554. no_retry_exception = None
  555. if parser == "pandas":
  556. # If we get a ParserError with pandas, then we don't want to retry and we raise
  557. # early.
  558. from pandas.errors import ParserError
  559. no_retry_exception = ParserError
  560. X, y, frame, categories = _retry_with_clean_cache(
  561. url, data_home, no_retry_exception
  562. )(_load_arff_response)(
  563. url,
  564. data_home,
  565. parser=parser,
  566. output_type=output_type,
  567. openml_columns_info=features_dict,
  568. feature_names_to_select=data_columns,
  569. target_names_to_select=target_columns,
  570. shape=shape,
  571. md5_checksum=md5_checksum,
  572. n_retries=n_retries,
  573. delay=delay,
  574. read_csv_kwargs=read_csv_kwargs,
  575. )
  576. return Bunch(
  577. data=X,
  578. target=y,
  579. frame=frame,
  580. categories=categories,
  581. feature_names=data_columns,
  582. target_names=target_columns,
  583. )
  584. def _verify_target_data_type(features_dict, target_columns):
  585. # verifies the data type of the y array in case there are multiple targets
  586. # (throws an error if these targets do not comply with sklearn support)
  587. if not isinstance(target_columns, list):
  588. raise ValueError("target_column should be list, got: %s" % type(target_columns))
  589. found_types = set()
  590. for target_column in target_columns:
  591. if target_column not in features_dict:
  592. raise KeyError(f"Could not find target_column='{target_column}'")
  593. if features_dict[target_column]["data_type"] == "numeric":
  594. found_types.add(np.float64)
  595. else:
  596. found_types.add(object)
  597. # note: we compare to a string, not boolean
  598. if features_dict[target_column]["is_ignore"] == "true":
  599. warn(f"target_column='{target_column}' has flag is_ignore.")
  600. if features_dict[target_column]["is_row_identifier"] == "true":
  601. warn(f"target_column='{target_column}' has flag is_row_identifier.")
  602. if len(found_types) > 1:
  603. raise ValueError(
  604. "Can only handle homogeneous multi-target datasets, "
  605. "i.e., all targets are either numeric or "
  606. "categorical."
  607. )
  608. def _valid_data_column_names(features_list, target_columns):
  609. # logic for determining on which columns can be learned. Note that from the
  610. # OpenML guide follows that columns that have the `is_row_identifier` or
  611. # `is_ignore` flag, these can not be learned on. Also target columns are
  612. # excluded.
  613. valid_data_column_names = []
  614. for feature in features_list:
  615. if (
  616. feature["name"] not in target_columns
  617. and feature["is_ignore"] != "true"
  618. and feature["is_row_identifier"] != "true"
  619. ):
  620. valid_data_column_names.append(feature["name"])
  621. return valid_data_column_names
  622. @validate_params(
  623. {
  624. "name": [str, None],
  625. "version": [Interval(Integral, 1, None, closed="left"), StrOptions({"active"})],
  626. "data_id": [Interval(Integral, 1, None, closed="left"), None],
  627. "data_home": [str, os.PathLike, None],
  628. "target_column": [str, list, None],
  629. "cache": [bool],
  630. "return_X_y": [bool],
  631. "as_frame": [bool, StrOptions({"auto"})],
  632. "n_retries": [Interval(Integral, 1, None, closed="left")],
  633. "delay": [Interval(Real, 0, None, closed="right")],
  634. "parser": [
  635. StrOptions({"auto", "pandas", "liac-arff"}),
  636. Hidden(StrOptions({"warn"})),
  637. ],
  638. "read_csv_kwargs": [dict, None],
  639. },
  640. prefer_skip_nested_validation=True,
  641. )
  642. def fetch_openml(
  643. name: Optional[str] = None,
  644. *,
  645. version: Union[str, int] = "active",
  646. data_id: Optional[int] = None,
  647. data_home: Optional[Union[str, os.PathLike]] = None,
  648. target_column: Optional[Union[str, List]] = "default-target",
  649. cache: bool = True,
  650. return_X_y: bool = False,
  651. as_frame: Union[str, bool] = "auto",
  652. n_retries: int = 3,
  653. delay: float = 1.0,
  654. parser: str = "warn",
  655. read_csv_kwargs: Optional[Dict] = None,
  656. ):
  657. """Fetch dataset from openml by name or dataset id.
  658. Datasets are uniquely identified by either an integer ID or by a
  659. combination of name and version (i.e. there might be multiple
  660. versions of the 'iris' dataset). Please give either name or data_id
  661. (not both). In case a name is given, a version can also be
  662. provided.
  663. Read more in the :ref:`User Guide <openml>`.
  664. .. versionadded:: 0.20
  665. .. note:: EXPERIMENTAL
  666. The API is experimental (particularly the return value structure),
  667. and might have small backward-incompatible changes without notice
  668. or warning in future releases.
  669. Parameters
  670. ----------
  671. name : str, default=None
  672. String identifier of the dataset. Note that OpenML can have multiple
  673. datasets with the same name.
  674. version : int or 'active', default='active'
  675. Version of the dataset. Can only be provided if also ``name`` is given.
  676. If 'active' the oldest version that's still active is used. Since
  677. there may be more than one active version of a dataset, and those
  678. versions may fundamentally be different from one another, setting an
  679. exact version is highly recommended.
  680. data_id : int, default=None
  681. OpenML ID of the dataset. The most specific way of retrieving a
  682. dataset. If data_id is not given, name (and potential version) are
  683. used to obtain a dataset.
  684. data_home : str or path-like, default=None
  685. Specify another download and cache folder for the data sets. By default
  686. all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
  687. target_column : str, list or None, default='default-target'
  688. Specify the column name in the data to use as target. If
  689. 'default-target', the standard target column a stored on the server
  690. is used. If ``None``, all columns are returned as data and the
  691. target is ``None``. If list (of strings), all columns with these names
  692. are returned as multi-target (Note: not all scikit-learn classifiers
  693. can handle all types of multi-output combinations).
  694. cache : bool, default=True
  695. Whether to cache the downloaded datasets into `data_home`.
  696. return_X_y : bool, default=False
  697. If True, returns ``(data, target)`` instead of a Bunch object. See
  698. below for more information about the `data` and `target` objects.
  699. as_frame : bool or 'auto', default='auto'
  700. If True, the data is a pandas DataFrame including columns with
  701. appropriate dtypes (numeric, string or categorical). The target is
  702. a pandas DataFrame or Series depending on the number of target_columns.
  703. The Bunch will contain a ``frame`` attribute with the target and the
  704. data. If ``return_X_y`` is True, then ``(data, target)`` will be pandas
  705. DataFrames or Series as describe above.
  706. If `as_frame` is 'auto', the data and target will be converted to
  707. DataFrame or Series as if `as_frame` is set to True, unless the dataset
  708. is stored in sparse format.
  709. If `as_frame` is False, the data and target will be NumPy arrays and
  710. the `data` will only contain numerical values when `parser="liac-arff"`
  711. where the categories are provided in the attribute `categories` of the
  712. `Bunch` instance. When `parser="pandas"`, no ordinal encoding is made.
  713. .. versionchanged:: 0.24
  714. The default value of `as_frame` changed from `False` to `'auto'`
  715. in 0.24.
  716. n_retries : int, default=3
  717. Number of retries when HTTP errors or network timeouts are encountered.
  718. Error with status code 412 won't be retried as they represent OpenML
  719. generic errors.
  720. delay : float, default=1.0
  721. Number of seconds between retries.
  722. parser : {"auto", "pandas", "liac-arff"}, default="liac-arff"
  723. Parser used to load the ARFF file. Two parsers are implemented:
  724. - `"pandas"`: this is the most efficient parser. However, it requires
  725. pandas to be installed and can only open dense datasets.
  726. - `"liac-arff"`: this is a pure Python ARFF parser that is much less
  727. memory- and CPU-efficient. It deals with sparse ARFF datasets.
  728. If `"auto"` (future default), the parser is chosen automatically such that
  729. `"liac-arff"` is selected for sparse ARFF datasets, otherwise
  730. `"pandas"` is selected.
  731. .. versionadded:: 1.2
  732. .. versionchanged:: 1.4
  733. The default value of `parser` will change from `"liac-arff"` to
  734. `"auto"` in 1.4. You can set `parser="auto"` to silence this
  735. warning. Therefore, an `ImportError` will be raised from 1.4 if
  736. the dataset is dense and pandas is not installed.
  737. read_csv_kwargs : dict, default=None
  738. Keyword arguments passed to :func:`pandas.read_csv` when loading the data
  739. from a ARFF file and using the pandas parser. It can allow to
  740. overwrite some default parameters.
  741. .. versionadded:: 1.3
  742. Returns
  743. -------
  744. data : :class:`~sklearn.utils.Bunch`
  745. Dictionary-like object, with the following attributes.
  746. data : np.array, scipy.sparse.csr_matrix of floats, or pandas DataFrame
  747. The feature matrix. Categorical features are encoded as ordinals.
  748. target : np.array, pandas Series or DataFrame
  749. The regression target or classification labels, if applicable.
  750. Dtype is float if numeric, and object if categorical. If
  751. ``as_frame`` is True, ``target`` is a pandas object.
  752. DESCR : str
  753. The full description of the dataset.
  754. feature_names : list
  755. The names of the dataset columns.
  756. target_names: list
  757. The names of the target columns.
  758. .. versionadded:: 0.22
  759. categories : dict or None
  760. Maps each categorical feature name to a list of values, such
  761. that the value encoded as i is ith in the list. If ``as_frame``
  762. is True, this is None.
  763. details : dict
  764. More metadata from OpenML.
  765. frame : pandas DataFrame
  766. Only present when `as_frame=True`. DataFrame with ``data`` and
  767. ``target``.
  768. (data, target) : tuple if ``return_X_y`` is True
  769. .. note:: EXPERIMENTAL
  770. This interface is **experimental** and subsequent releases may
  771. change attributes without notice (although there should only be
  772. minor changes to ``data`` and ``target``).
  773. Missing values in the 'data' are represented as NaN's. Missing values
  774. in 'target' are represented as NaN's (numerical target) or None
  775. (categorical target).
  776. Notes
  777. -----
  778. The `"pandas"` and `"liac-arff"` parsers can lead to different data types
  779. in the output. The notable differences are the following:
  780. - The `"liac-arff"` parser always encodes categorical features as `str` objects.
  781. To the contrary, the `"pandas"` parser instead infers the type while
  782. reading and numerical categories will be casted into integers whenever
  783. possible.
  784. - The `"liac-arff"` parser uses float64 to encode numerical features
  785. tagged as 'REAL' and 'NUMERICAL' in the metadata. The `"pandas"`
  786. parser instead infers if these numerical features corresponds
  787. to integers and uses panda's Integer extension dtype.
  788. - In particular, classification datasets with integer categories are
  789. typically loaded as such `(0, 1, ...)` with the `"pandas"` parser while
  790. `"liac-arff"` will force the use of string encoded class labels such as
  791. `"0"`, `"1"` and so on.
  792. - The `"pandas"` parser will not strip single quotes - i.e. `'` - from
  793. string columns. For instance, a string `'my string'` will be kept as is
  794. while the `"liac-arff"` parser will strip the single quotes. For
  795. categorical columns, the single quotes are stripped from the values.
  796. In addition, when `as_frame=False` is used, the `"liac-arff"` parser
  797. returns ordinally encoded data where the categories are provided in the
  798. attribute `categories` of the `Bunch` instance. Instead, `"pandas"` returns
  799. a NumPy array were the categories are not encoded.
  800. """
  801. if cache is False:
  802. # no caching will be applied
  803. data_home = None
  804. else:
  805. data_home = get_data_home(data_home=data_home)
  806. data_home = join(str(data_home), "openml")
  807. # check valid function arguments. data_id XOR (name, version) should be
  808. # provided
  809. if name is not None:
  810. # OpenML is case-insensitive, but the caching mechanism is not
  811. # convert all data names (str) to lower case
  812. name = name.lower()
  813. if data_id is not None:
  814. raise ValueError(
  815. "Dataset data_id={} and name={} passed, but you can only "
  816. "specify a numeric data_id or a name, not "
  817. "both.".format(data_id, name)
  818. )
  819. data_info = _get_data_info_by_name(
  820. name, version, data_home, n_retries=n_retries, delay=delay
  821. )
  822. data_id = data_info["did"]
  823. elif data_id is not None:
  824. # from the previous if statement, it is given that name is None
  825. if version != "active":
  826. raise ValueError(
  827. "Dataset data_id={} and version={} passed, but you can only "
  828. "specify a numeric data_id or a version, not "
  829. "both.".format(data_id, version)
  830. )
  831. else:
  832. raise ValueError(
  833. "Neither name nor data_id are provided. Please provide name or data_id."
  834. )
  835. data_description = _get_data_description_by_id(data_id, data_home)
  836. if data_description["status"] != "active":
  837. warn(
  838. "Version {} of dataset {} is inactive, meaning that issues have "
  839. "been found in the dataset. Try using a newer version from "
  840. "this URL: {}".format(
  841. data_description["version"],
  842. data_description["name"],
  843. data_description["url"],
  844. )
  845. )
  846. if "error" in data_description:
  847. warn(
  848. "OpenML registered a problem with the dataset. It might be "
  849. "unusable. Error: {}".format(data_description["error"])
  850. )
  851. if "warning" in data_description:
  852. warn(
  853. "OpenML raised a warning on the dataset. It might be "
  854. "unusable. Warning: {}".format(data_description["warning"])
  855. )
  856. if parser == "warn":
  857. # TODO(1.4): remove this warning
  858. parser = "liac-arff"
  859. warn(
  860. (
  861. "The default value of `parser` will change from `'liac-arff'` to"
  862. " `'auto'` in 1.4. You can set `parser='auto'` to silence this warning."
  863. " Therefore, an `ImportError` will be raised from 1.4 if the dataset is"
  864. " dense and pandas is not installed. Note that the pandas parser may"
  865. " return different data types. See the Notes Section in fetch_openml's"
  866. " API doc for details."
  867. ),
  868. FutureWarning,
  869. )
  870. return_sparse = data_description["format"].lower() == "sparse_arff"
  871. as_frame = not return_sparse if as_frame == "auto" else as_frame
  872. if parser == "auto":
  873. parser_ = "liac-arff" if return_sparse else "pandas"
  874. else:
  875. parser_ = parser
  876. if as_frame or parser_ == "pandas":
  877. try:
  878. check_pandas_support("`fetch_openml`")
  879. except ImportError as exc:
  880. if as_frame:
  881. err_msg = (
  882. "Returning pandas objects requires pandas to be installed. "
  883. "Alternatively, explicitly set `as_frame=False` and "
  884. "`parser='liac-arff'`."
  885. )
  886. raise ImportError(err_msg) from exc
  887. else:
  888. err_msg = (
  889. f"Using `parser={parser_!r}` requires pandas to be installed. "
  890. "Alternatively, explicitly set `parser='liac-arff'`."
  891. )
  892. if parser == "auto":
  893. # TODO(1.4): In version 1.4, we will raise an error instead of
  894. # a warning.
  895. warn(
  896. (
  897. "From version 1.4, `parser='auto'` with `as_frame=False` "
  898. "will use pandas. Either install pandas or set explicitly "
  899. "`parser='liac-arff'` to preserve the current behavior."
  900. ),
  901. FutureWarning,
  902. )
  903. parser_ = "liac-arff"
  904. else:
  905. raise ImportError(err_msg) from exc
  906. if return_sparse:
  907. if as_frame:
  908. raise ValueError(
  909. "Sparse ARFF datasets cannot be loaded with as_frame=True. "
  910. "Use as_frame=False or as_frame='auto' instead."
  911. )
  912. if parser_ == "pandas":
  913. raise ValueError(
  914. f"Sparse ARFF datasets cannot be loaded with parser={parser!r}. "
  915. "Use parser='liac-arff' or parser='auto' instead."
  916. )
  917. # download data features, meta-info about column types
  918. features_list = _get_data_features(data_id, data_home)
  919. if not as_frame:
  920. for feature in features_list:
  921. if "true" in (feature["is_ignore"], feature["is_row_identifier"]):
  922. continue
  923. if feature["data_type"] == "string":
  924. raise ValueError(
  925. "STRING attributes are not supported for "
  926. "array representation. Try as_frame=True"
  927. )
  928. if target_column == "default-target":
  929. # determines the default target based on the data feature results
  930. # (which is currently more reliable than the data description;
  931. # see issue: https://github.com/openml/OpenML/issues/768)
  932. target_columns = [
  933. feature["name"]
  934. for feature in features_list
  935. if feature["is_target"] == "true"
  936. ]
  937. elif isinstance(target_column, str):
  938. # for code-simplicity, make target_column by default a list
  939. target_columns = [target_column]
  940. elif target_column is None:
  941. target_columns = []
  942. else:
  943. # target_column already is of type list
  944. target_columns = target_column
  945. data_columns = _valid_data_column_names(features_list, target_columns)
  946. shape: Optional[Tuple[int, int]]
  947. # determine arff encoding to return
  948. if not return_sparse:
  949. # The shape must include the ignored features to keep the right indexes
  950. # during the arff data conversion.
  951. data_qualities = _get_data_qualities(data_id, data_home)
  952. shape = _get_num_samples(data_qualities), len(features_list)
  953. else:
  954. shape = None
  955. # obtain the data
  956. url = _DATA_FILE.format(data_description["file_id"])
  957. bunch = _download_data_to_bunch(
  958. url,
  959. return_sparse,
  960. data_home,
  961. as_frame=bool(as_frame),
  962. openml_columns_info=features_list,
  963. shape=shape,
  964. target_columns=target_columns,
  965. data_columns=data_columns,
  966. md5_checksum=data_description["md5_checksum"],
  967. n_retries=n_retries,
  968. delay=delay,
  969. parser=parser_,
  970. read_csv_kwargs=read_csv_kwargs,
  971. )
  972. if return_X_y:
  973. return bunch.data, bunch.target
  974. description = "{}\n\nDownloaded from openml.org.".format(
  975. data_description.pop("description")
  976. )
  977. bunch.update(
  978. DESCR=description,
  979. details=data_description,
  980. url="https://www.openml.org/d/{}".format(data_id),
  981. )
  982. return bunch