_array_api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. """Tools to support array_api."""
  2. import math
  3. from functools import wraps
  4. import numpy
  5. import scipy.special as special
  6. from .._config import get_config
  7. from .fixes import parse_version
  8. def _check_array_api_dispatch(array_api_dispatch):
  9. """Check that array_api_compat is installed and NumPy version is compatible.
  10. array_api_compat follows NEP29, which has a higher minimum NumPy version than
  11. scikit-learn.
  12. """
  13. if array_api_dispatch:
  14. try:
  15. import array_api_compat # noqa
  16. except ImportError:
  17. raise ImportError(
  18. "array_api_compat is required to dispatch arrays using the API"
  19. " specification"
  20. )
  21. numpy_version = parse_version(numpy.__version__)
  22. min_numpy_version = "1.21"
  23. if numpy_version < parse_version(min_numpy_version):
  24. raise ImportError(
  25. f"NumPy must be {min_numpy_version} or newer to dispatch array using"
  26. " the API specification"
  27. )
  28. def device(x):
  29. """Hardware device the array data resides on.
  30. Parameters
  31. ----------
  32. x : array
  33. Array instance from NumPy or an array API compatible library.
  34. Returns
  35. -------
  36. out : device
  37. `device` object (see the "Device Support" section of the array API spec).
  38. """
  39. if isinstance(x, (numpy.ndarray, numpy.generic)):
  40. return "cpu"
  41. return x.device
  42. def size(x):
  43. """Return the total number of elements of x.
  44. Parameters
  45. ----------
  46. x : array
  47. Array instance from NumPy or an array API compatible library.
  48. Returns
  49. -------
  50. out : int
  51. Total number of elements.
  52. """
  53. return math.prod(x.shape)
  54. def _is_numpy_namespace(xp):
  55. """Return True if xp is backed by NumPy."""
  56. return xp.__name__ in {"numpy", "array_api_compat.numpy", "numpy.array_api"}
  57. def isdtype(dtype, kind, *, xp):
  58. """Returns a boolean indicating whether a provided dtype is of type "kind".
  59. Included in the v2022.12 of the Array API spec.
  60. https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
  61. """
  62. if isinstance(kind, tuple):
  63. return any(_isdtype_single(dtype, k, xp=xp) for k in kind)
  64. else:
  65. return _isdtype_single(dtype, kind, xp=xp)
  66. def _isdtype_single(dtype, kind, *, xp):
  67. if isinstance(kind, str):
  68. if kind == "bool":
  69. return dtype == xp.bool
  70. elif kind == "signed integer":
  71. return dtype in {xp.int8, xp.int16, xp.int32, xp.int64}
  72. elif kind == "unsigned integer":
  73. return dtype in {xp.uint8, xp.uint16, xp.uint32, xp.uint64}
  74. elif kind == "integral":
  75. return any(
  76. _isdtype_single(dtype, k, xp=xp)
  77. for k in ("signed integer", "unsigned integer")
  78. )
  79. elif kind == "real floating":
  80. return dtype in {xp.float32, xp.float64}
  81. elif kind == "complex floating":
  82. # Some name spaces do not have complex, such as cupy.array_api
  83. # and numpy.array_api
  84. complex_dtypes = set()
  85. if hasattr(xp, "complex64"):
  86. complex_dtypes.add(xp.complex64)
  87. if hasattr(xp, "complex128"):
  88. complex_dtypes.add(xp.complex128)
  89. return dtype in complex_dtypes
  90. elif kind == "numeric":
  91. return any(
  92. _isdtype_single(dtype, k, xp=xp)
  93. for k in ("integral", "real floating", "complex floating")
  94. )
  95. else:
  96. raise ValueError(f"Unrecognized data type kind: {kind!r}")
  97. else:
  98. return dtype == kind
  99. class _ArrayAPIWrapper:
  100. """sklearn specific Array API compatibility wrapper
  101. This wrapper makes it possible for scikit-learn maintainers to
  102. deal with discrepancies between different implementations of the
  103. Python array API standard and its evolution over time.
  104. The Python array API standard specification:
  105. https://data-apis.org/array-api/latest/
  106. Documentation of the NumPy implementation:
  107. https://numpy.org/neps/nep-0047-array-api-standard.html
  108. """
  109. def __init__(self, array_namespace):
  110. self._namespace = array_namespace
  111. def __getattr__(self, name):
  112. return getattr(self._namespace, name)
  113. def take(self, X, indices, *, axis=0):
  114. # When array_api supports `take` we can use this directly
  115. # https://github.com/data-apis/array-api/issues/177
  116. if self._namespace.__name__ == "numpy.array_api":
  117. X_np = numpy.take(X, indices, axis=axis)
  118. return self._namespace.asarray(X_np)
  119. # We only support axis in (0, 1) and ndim in (1, 2) because that is all we need
  120. # in scikit-learn
  121. if axis not in {0, 1}:
  122. raise ValueError(f"Only axis in (0, 1) is supported. Got {axis}")
  123. if X.ndim not in {1, 2}:
  124. raise ValueError(f"Only X.ndim in (1, 2) is supported. Got {X.ndim}")
  125. if axis == 0:
  126. if X.ndim == 1:
  127. selected = [X[i] for i in indices]
  128. else: # X.ndim == 2
  129. selected = [X[i, :] for i in indices]
  130. else: # axis == 1
  131. selected = [X[:, i] for i in indices]
  132. return self._namespace.stack(selected, axis=axis)
  133. def isdtype(self, dtype, kind):
  134. return isdtype(dtype, kind, xp=self._namespace)
  135. def _check_device_cpu(device): # noqa
  136. if device not in {"cpu", None}:
  137. raise ValueError(f"Unsupported device for NumPy: {device!r}")
  138. def _accept_device_cpu(func):
  139. @wraps(func)
  140. def wrapped_func(*args, **kwargs):
  141. _check_device_cpu(kwargs.pop("device", None))
  142. return func(*args, **kwargs)
  143. return wrapped_func
  144. class _NumPyAPIWrapper:
  145. """Array API compat wrapper for any numpy version
  146. NumPy < 1.22 does not expose the numpy.array_api namespace. This
  147. wrapper makes it possible to write code that uses the standard
  148. Array API while working with any version of NumPy supported by
  149. scikit-learn.
  150. See the `get_namespace()` public function for more details.
  151. """
  152. # Creation functions in spec:
  153. # https://data-apis.org/array-api/latest/API_specification/creation_functions.html
  154. _CREATION_FUNCS = {
  155. "arange",
  156. "empty",
  157. "empty_like",
  158. "eye",
  159. "full",
  160. "full_like",
  161. "linspace",
  162. "ones",
  163. "ones_like",
  164. "zeros",
  165. "zeros_like",
  166. }
  167. # Data types in spec
  168. # https://data-apis.org/array-api/latest/API_specification/data_types.html
  169. _DTYPES = {
  170. "int8",
  171. "int16",
  172. "int32",
  173. "int64",
  174. "uint8",
  175. "uint16",
  176. "uint32",
  177. "uint64",
  178. "float32",
  179. "float64",
  180. "complex64",
  181. "complex128",
  182. }
  183. def __getattr__(self, name):
  184. attr = getattr(numpy, name)
  185. # Support device kwargs and make sure they are on the CPU
  186. if name in self._CREATION_FUNCS:
  187. return _accept_device_cpu(attr)
  188. # Convert to dtype objects
  189. if name in self._DTYPES:
  190. return numpy.dtype(attr)
  191. return attr
  192. @property
  193. def bool(self):
  194. return numpy.bool_
  195. def astype(self, x, dtype, *, copy=True, casting="unsafe"):
  196. # astype is not defined in the top level NumPy namespace
  197. return x.astype(dtype, copy=copy, casting=casting)
  198. def asarray(self, x, *, dtype=None, device=None, copy=None): # noqa
  199. _check_device_cpu(device)
  200. # Support copy in NumPy namespace
  201. if copy is True:
  202. return numpy.array(x, copy=True, dtype=dtype)
  203. else:
  204. return numpy.asarray(x, dtype=dtype)
  205. def unique_inverse(self, x):
  206. return numpy.unique(x, return_inverse=True)
  207. def unique_counts(self, x):
  208. return numpy.unique(x, return_counts=True)
  209. def unique_values(self, x):
  210. return numpy.unique(x)
  211. def concat(self, arrays, *, axis=None):
  212. return numpy.concatenate(arrays, axis=axis)
  213. def reshape(self, x, shape, *, copy=None):
  214. """Gives a new shape to an array without changing its data.
  215. The Array API specification requires shape to be a tuple.
  216. https://data-apis.org/array-api/latest/API_specification/generated/array_api.reshape.html
  217. """
  218. if not isinstance(shape, tuple):
  219. raise TypeError(
  220. f"shape must be a tuple, got {shape!r} of type {type(shape)}"
  221. )
  222. if copy is True:
  223. x = x.copy()
  224. return numpy.reshape(x, shape)
  225. def isdtype(self, dtype, kind):
  226. return isdtype(dtype, kind, xp=self)
  227. _NUMPY_API_WRAPPER_INSTANCE = _NumPyAPIWrapper()
  228. def get_namespace(*arrays):
  229. """Get namespace of arrays.
  230. Introspect `arrays` arguments and return their common Array API
  231. compatible namespace object, if any. NumPy 1.22 and later can
  232. construct such containers using the `numpy.array_api` namespace
  233. for instance.
  234. See: https://numpy.org/neps/nep-0047-array-api-standard.html
  235. If `arrays` are regular numpy arrays, an instance of the
  236. `_NumPyAPIWrapper` compatibility wrapper is returned instead.
  237. Namespace support is not enabled by default. To enabled it
  238. call:
  239. sklearn.set_config(array_api_dispatch=True)
  240. or:
  241. with sklearn.config_context(array_api_dispatch=True):
  242. # your code here
  243. Otherwise an instance of the `_NumPyAPIWrapper`
  244. compatibility wrapper is always returned irrespective of
  245. the fact that arrays implement the `__array_namespace__`
  246. protocol or not.
  247. Parameters
  248. ----------
  249. *arrays : array objects
  250. Array objects.
  251. Returns
  252. -------
  253. namespace : module
  254. Namespace shared by array objects. If any of the `arrays` are not arrays,
  255. the namespace defaults to NumPy.
  256. is_array_api_compliant : bool
  257. True if the arrays are containers that implement the Array API spec.
  258. Always False when array_api_dispatch=False.
  259. """
  260. array_api_dispatch = get_config()["array_api_dispatch"]
  261. if not array_api_dispatch:
  262. return _NUMPY_API_WRAPPER_INSTANCE, False
  263. _check_array_api_dispatch(array_api_dispatch)
  264. # array-api-compat is a required dependency of scikit-learn only when
  265. # configuring `array_api_dispatch=True`. Its import should therefore be
  266. # protected by _check_array_api_dispatch to display an informative error
  267. # message in case it is missing.
  268. import array_api_compat
  269. namespace, is_array_api_compliant = array_api_compat.get_namespace(*arrays), True
  270. if namespace.__name__ in {"numpy.array_api", "cupy.array_api"}:
  271. namespace = _ArrayAPIWrapper(namespace)
  272. return namespace, is_array_api_compliant
  273. def _expit(X):
  274. xp, _ = get_namespace(X)
  275. if _is_numpy_namespace(xp):
  276. return xp.asarray(special.expit(numpy.asarray(X)))
  277. return 1.0 / (1.0 + xp.exp(-X))
  278. def _asarray_with_order(array, dtype=None, order=None, copy=None, *, xp=None):
  279. """Helper to support the order kwarg only for NumPy-backed arrays
  280. Memory layout parameter `order` is not exposed in the Array API standard,
  281. however some input validation code in scikit-learn needs to work both
  282. for classes and functions that will leverage Array API only operations
  283. and for code that inherently relies on NumPy backed data containers with
  284. specific memory layout constraints (e.g. our own Cython code). The
  285. purpose of this helper is to make it possible to share code for data
  286. container validation without memory copies for both downstream use cases:
  287. the `order` parameter is only enforced if the input array implementation
  288. is NumPy based, otherwise `order` is just silently ignored.
  289. """
  290. if xp is None:
  291. xp, _ = get_namespace(array)
  292. if _is_numpy_namespace(xp):
  293. # Use NumPy API to support order
  294. if copy is True:
  295. array = numpy.array(array, order=order, dtype=dtype)
  296. else:
  297. array = numpy.asarray(array, order=order, dtype=dtype)
  298. # At this point array is a NumPy ndarray. We convert it to an array
  299. # container that is consistent with the input's namespace.
  300. return xp.asarray(array)
  301. else:
  302. return xp.asarray(array, dtype=dtype, copy=copy)
  303. def _convert_to_numpy(array, xp):
  304. """Convert X into a NumPy ndarray on the CPU."""
  305. xp_name = xp.__name__
  306. if xp_name in {"array_api_compat.torch", "torch"}:
  307. return array.cpu().numpy()
  308. elif xp_name == "cupy.array_api":
  309. return array._array.get()
  310. elif xp_name in {"array_api_compat.cupy", "cupy"}: # pragma: nocover
  311. return array.get()
  312. return numpy.asarray(array)
  313. def _estimator_with_converted_arrays(estimator, converter):
  314. """Create new estimator which converting all attributes that are arrays.
  315. The converter is called on all NumPy arrays and arrays that support the
  316. `DLPack interface <https://dmlc.github.io/dlpack/latest/>`__.
  317. Parameters
  318. ----------
  319. estimator : Estimator
  320. Estimator to convert
  321. converter : callable
  322. Callable that takes an array attribute and returns the converted array.
  323. Returns
  324. -------
  325. new_estimator : Estimator
  326. Convert estimator
  327. """
  328. from sklearn.base import clone
  329. new_estimator = clone(estimator)
  330. for key, attribute in vars(estimator).items():
  331. if hasattr(attribute, "__dlpack__") or isinstance(attribute, numpy.ndarray):
  332. attribute = converter(attribute)
  333. setattr(new_estimator, key, attribute)
  334. return new_estimator