PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/sklearn/utils/tests/test_utils.py

https://github.com/NelleV/scikit-learn
Python | 709 lines | 563 code | 118 blank | 28 comment | 56 complexity | c03964f44b0a14e33554423f21afee89 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from copy import copy
  2. from itertools import chain
  3. import warnings
  4. import string
  5. import timeit
  6. import pytest
  7. import numpy as np
  8. import scipy.sparse as sp
  9. from sklearn.utils._testing import (
  10. assert_array_equal,
  11. assert_allclose_dense_sparse,
  12. assert_no_warnings,
  13. _convert_container,
  14. )
  15. from sklearn.utils import check_random_state
  16. from sklearn.utils import _determine_key_type
  17. from sklearn.utils import deprecated
  18. from sklearn.utils import gen_batches
  19. from sklearn.utils import _get_column_indices
  20. from sklearn.utils import resample
  21. from sklearn.utils import safe_mask
  22. from sklearn.utils import column_or_1d
  23. from sklearn.utils import _safe_indexing
  24. from sklearn.utils import shuffle
  25. from sklearn.utils import gen_even_slices
  26. from sklearn.utils import _message_with_time, _print_elapsed_time
  27. from sklearn.utils import get_chunk_n_rows
  28. from sklearn.utils import is_scalar_nan
  29. from sklearn.utils import _to_object_array
  30. from sklearn.utils.fixes import parse_version
  31. from sklearn.utils._mocking import MockDataFrame
  32. from sklearn.utils._testing import SkipTest
  33. from sklearn import config_context
  34. # toy array
  35. X_toy = np.arange(9).reshape((3, 3))
  36. def test_make_rng():
  37. # Check the check_random_state utility function behavior
  38. assert check_random_state(None) is np.random.mtrand._rand
  39. assert check_random_state(np.random) is np.random.mtrand._rand
  40. rng_42 = np.random.RandomState(42)
  41. assert check_random_state(42).randint(100) == rng_42.randint(100)
  42. rng_42 = np.random.RandomState(42)
  43. assert check_random_state(rng_42) is rng_42
  44. rng_42 = np.random.RandomState(42)
  45. assert check_random_state(43).randint(100) != rng_42.randint(100)
  46. with pytest.raises(ValueError):
  47. check_random_state("some invalid seed")
  48. def test_gen_batches():
  49. # Make sure gen_batches errors on invalid batch_size
  50. assert_array_equal(list(gen_batches(4, 2)), [slice(0, 2, None), slice(2, 4, None)])
  51. msg_zero = "gen_batches got batch_size=0, must be positive"
  52. with pytest.raises(ValueError, match=msg_zero):
  53. next(gen_batches(4, 0))
  54. msg_float = "gen_batches got batch_size=0.5, must be an integer"
  55. with pytest.raises(TypeError, match=msg_float):
  56. next(gen_batches(4, 0.5))
  57. def test_deprecated():
  58. # Test whether the deprecated decorator issues appropriate warnings
  59. # Copied almost verbatim from https://docs.python.org/library/warnings.html
  60. # First a function...
  61. with warnings.catch_warnings(record=True) as w:
  62. warnings.simplefilter("always")
  63. @deprecated()
  64. def ham():
  65. return "spam"
  66. spam = ham()
  67. assert spam == "spam" # function must remain usable
  68. assert len(w) == 1
  69. assert issubclass(w[0].category, FutureWarning)
  70. assert "deprecated" in str(w[0].message).lower()
  71. # ... then a class.
  72. with warnings.catch_warnings(record=True) as w:
  73. warnings.simplefilter("always")
  74. @deprecated("don't use this")
  75. class Ham:
  76. SPAM = 1
  77. ham = Ham()
  78. assert hasattr(ham, "SPAM")
  79. assert len(w) == 1
  80. assert issubclass(w[0].category, FutureWarning)
  81. assert "deprecated" in str(w[0].message).lower()
  82. def test_resample():
  83. # Border case not worth mentioning in doctests
  84. assert resample() is None
  85. # Check that invalid arguments yield ValueError
  86. with pytest.raises(ValueError):
  87. resample([0], [0, 1])
  88. with pytest.raises(ValueError):
  89. resample([0, 1], [0, 1], replace=False, n_samples=3)
  90. # Issue:6581, n_samples can be more when replace is True (default).
  91. assert len(resample([1, 2], n_samples=5)) == 5
  92. def test_resample_stratified():
  93. # Make sure resample can stratify
  94. rng = np.random.RandomState(0)
  95. n_samples = 100
  96. p = 0.9
  97. X = rng.normal(size=(n_samples, 1))
  98. y = rng.binomial(1, p, size=n_samples)
  99. _, y_not_stratified = resample(X, y, n_samples=10, random_state=0, stratify=None)
  100. assert np.all(y_not_stratified == 1)
  101. _, y_stratified = resample(X, y, n_samples=10, random_state=0, stratify=y)
  102. assert not np.all(y_stratified == 1)
  103. assert np.sum(y_stratified) == 9 # all 1s, one 0
  104. def test_resample_stratified_replace():
  105. # Make sure stratified resampling supports the replace parameter
  106. rng = np.random.RandomState(0)
  107. n_samples = 100
  108. X = rng.normal(size=(n_samples, 1))
  109. y = rng.randint(0, 2, size=n_samples)
  110. X_replace, _ = resample(
  111. X, y, replace=True, n_samples=50, random_state=rng, stratify=y
  112. )
  113. X_no_replace, _ = resample(
  114. X, y, replace=False, n_samples=50, random_state=rng, stratify=y
  115. )
  116. assert np.unique(X_replace).shape[0] < 50
  117. assert np.unique(X_no_replace).shape[0] == 50
  118. # make sure n_samples can be greater than X.shape[0] if we sample with
  119. # replacement
  120. X_replace, _ = resample(
  121. X, y, replace=True, n_samples=1000, random_state=rng, stratify=y
  122. )
  123. assert X_replace.shape[0] == 1000
  124. assert np.unique(X_replace).shape[0] == 100
  125. def test_resample_stratify_2dy():
  126. # Make sure y can be 2d when stratifying
  127. rng = np.random.RandomState(0)
  128. n_samples = 100
  129. X = rng.normal(size=(n_samples, 1))
  130. y = rng.randint(0, 2, size=(n_samples, 2))
  131. X, y = resample(X, y, n_samples=50, random_state=rng, stratify=y)
  132. assert y.ndim == 2
  133. def test_resample_stratify_sparse_error():
  134. # resample must be ndarray
  135. rng = np.random.RandomState(0)
  136. n_samples = 100
  137. X = rng.normal(size=(n_samples, 2))
  138. y = rng.randint(0, 2, size=n_samples)
  139. stratify = sp.csr_matrix(y)
  140. with pytest.raises(TypeError, match="A sparse matrix was passed"):
  141. X, y = resample(X, y, n_samples=50, random_state=rng, stratify=stratify)
  142. def test_safe_mask():
  143. random_state = check_random_state(0)
  144. X = random_state.rand(5, 4)
  145. X_csr = sp.csr_matrix(X)
  146. mask = [False, False, True, True, True]
  147. mask = safe_mask(X, mask)
  148. assert X[mask].shape[0] == 3
  149. mask = safe_mask(X_csr, mask)
  150. assert X_csr[mask].shape[0] == 3
  151. def test_column_or_1d():
  152. EXAMPLES = [
  153. ("binary", ["spam", "egg", "spam"]),
  154. ("binary", [0, 1, 0, 1]),
  155. ("continuous", np.arange(10) / 20.0),
  156. ("multiclass", [1, 2, 3]),
  157. ("multiclass", [0, 1, 2, 2, 0]),
  158. ("multiclass", [[1], [2], [3]]),
  159. ("multilabel-indicator", [[0, 1, 0], [0, 0, 1]]),
  160. ("multiclass-multioutput", [[1, 2, 3]]),
  161. ("multiclass-multioutput", [[1, 1], [2, 2], [3, 1]]),
  162. ("multiclass-multioutput", [[5, 1], [4, 2], [3, 1]]),
  163. ("multiclass-multioutput", [[1, 2, 3]]),
  164. ("continuous-multioutput", np.arange(30).reshape((-1, 3))),
  165. ]
  166. for y_type, y in EXAMPLES:
  167. if y_type in ["binary", "multiclass", "continuous"]:
  168. assert_array_equal(column_or_1d(y), np.ravel(y))
  169. else:
  170. with pytest.raises(ValueError):
  171. column_or_1d(y)
  172. @pytest.mark.parametrize(
  173. "key, dtype",
  174. [
  175. (0, "int"),
  176. ("0", "str"),
  177. (True, "bool"),
  178. (np.bool_(True), "bool"),
  179. ([0, 1, 2], "int"),
  180. (["0", "1", "2"], "str"),
  181. ((0, 1, 2), "int"),
  182. (("0", "1", "2"), "str"),
  183. (slice(None, None), None),
  184. (slice(0, 2), "int"),
  185. (np.array([0, 1, 2], dtype=np.int32), "int"),
  186. (np.array([0, 1, 2], dtype=np.int64), "int"),
  187. (np.array([0, 1, 2], dtype=np.uint8), "int"),
  188. ([True, False], "bool"),
  189. ((True, False), "bool"),
  190. (np.array([True, False]), "bool"),
  191. ("col_0", "str"),
  192. (["col_0", "col_1", "col_2"], "str"),
  193. (("col_0", "col_1", "col_2"), "str"),
  194. (slice("begin", "end"), "str"),
  195. (np.array(["col_0", "col_1", "col_2"]), "str"),
  196. (np.array(["col_0", "col_1", "col_2"], dtype=object), "str"),
  197. ],
  198. )
  199. def test_determine_key_type(key, dtype):
  200. assert _determine_key_type(key) == dtype
  201. def test_determine_key_type_error():
  202. with pytest.raises(ValueError, match="No valid specification of the"):
  203. _determine_key_type(1.0)
  204. def test_determine_key_type_slice_error():
  205. with pytest.raises(TypeError, match="Only array-like or scalar are"):
  206. _determine_key_type(slice(0, 2, 1), accept_slice=False)
  207. @pytest.mark.parametrize("array_type", ["list", "array", "sparse", "dataframe"])
  208. @pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"])
  209. def test_safe_indexing_2d_container_axis_0(array_type, indices_type):
  210. indices = [1, 2]
  211. if indices_type == "slice" and isinstance(indices[1], int):
  212. indices[1] += 1
  213. array = _convert_container([[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type)
  214. indices = _convert_container(indices, indices_type)
  215. subset = _safe_indexing(array, indices, axis=0)
  216. assert_allclose_dense_sparse(
  217. subset, _convert_container([[4, 5, 6], [7, 8, 9]], array_type)
  218. )
  219. @pytest.mark.parametrize("array_type", ["list", "array", "series"])
  220. @pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"])
  221. def test_safe_indexing_1d_container(array_type, indices_type):
  222. indices = [1, 2]
  223. if indices_type == "slice" and isinstance(indices[1], int):
  224. indices[1] += 1
  225. array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type)
  226. indices = _convert_container(indices, indices_type)
  227. subset = _safe_indexing(array, indices, axis=0)
  228. assert_allclose_dense_sparse(subset, _convert_container([2, 3], array_type))
  229. @pytest.mark.parametrize("array_type", ["array", "sparse", "dataframe"])
  230. @pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"])
  231. @pytest.mark.parametrize("indices", [[1, 2], ["col_1", "col_2"]])
  232. def test_safe_indexing_2d_container_axis_1(array_type, indices_type, indices):
  233. # validation of the indices
  234. # we make a copy because indices is mutable and shared between tests
  235. indices_converted = copy(indices)
  236. if indices_type == "slice" and isinstance(indices[1], int):
  237. indices_converted[1] += 1
  238. columns_name = ["col_0", "col_1", "col_2"]
  239. array = _convert_container(
  240. [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name
  241. )
  242. indices_converted = _convert_container(indices_converted, indices_type)
  243. if isinstance(indices[0], str) and array_type != "dataframe":
  244. err_msg = (
  245. "Specifying the columns using strings is only supported "
  246. "for pandas DataFrames"
  247. )
  248. with pytest.raises(ValueError, match=err_msg):
  249. _safe_indexing(array, indices_converted, axis=1)
  250. else:
  251. subset = _safe_indexing(array, indices_converted, axis=1)
  252. assert_allclose_dense_sparse(
  253. subset, _convert_container([[2, 3], [5, 6], [8, 9]], array_type)
  254. )
  255. @pytest.mark.parametrize("array_read_only", [True, False])
  256. @pytest.mark.parametrize("indices_read_only", [True, False])
  257. @pytest.mark.parametrize("array_type", ["array", "sparse", "dataframe"])
  258. @pytest.mark.parametrize("indices_type", ["array", "series"])
  259. @pytest.mark.parametrize(
  260. "axis, expected_array", [(0, [[4, 5, 6], [7, 8, 9]]), (1, [[2, 3], [5, 6], [8, 9]])]
  261. )
  262. def test_safe_indexing_2d_read_only_axis_1(
  263. array_read_only, indices_read_only, array_type, indices_type, axis, expected_array
  264. ):
  265. array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  266. if array_read_only:
  267. array.setflags(write=False)
  268. array = _convert_container(array, array_type)
  269. indices = np.array([1, 2])
  270. if indices_read_only:
  271. indices.setflags(write=False)
  272. indices = _convert_container(indices, indices_type)
  273. subset = _safe_indexing(array, indices, axis=axis)
  274. assert_allclose_dense_sparse(subset, _convert_container(expected_array, array_type))
  275. @pytest.mark.parametrize("array_type", ["list", "array", "series"])
  276. @pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series"])
  277. def test_safe_indexing_1d_container_mask(array_type, indices_type):
  278. indices = [False] + [True] * 2 + [False] * 6
  279. array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type)
  280. indices = _convert_container(indices, indices_type)
  281. subset = _safe_indexing(array, indices, axis=0)
  282. assert_allclose_dense_sparse(subset, _convert_container([2, 3], array_type))
  283. @pytest.mark.parametrize("array_type", ["array", "sparse", "dataframe"])
  284. @pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series"])
  285. @pytest.mark.parametrize(
  286. "axis, expected_subset",
  287. [(0, [[4, 5, 6], [7, 8, 9]]), (1, [[2, 3], [5, 6], [8, 9]])],
  288. )
  289. def test_safe_indexing_2d_mask(array_type, indices_type, axis, expected_subset):
  290. columns_name = ["col_0", "col_1", "col_2"]
  291. array = _convert_container(
  292. [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name
  293. )
  294. indices = [False, True, True]
  295. indices = _convert_container(indices, indices_type)
  296. subset = _safe_indexing(array, indices, axis=axis)
  297. assert_allclose_dense_sparse(
  298. subset, _convert_container(expected_subset, array_type)
  299. )
  300. @pytest.mark.parametrize(
  301. "array_type, expected_output_type",
  302. [
  303. ("list", "list"),
  304. ("array", "array"),
  305. ("sparse", "sparse"),
  306. ("dataframe", "series"),
  307. ],
  308. )
  309. def test_safe_indexing_2d_scalar_axis_0(array_type, expected_output_type):
  310. array = _convert_container([[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type)
  311. indices = 2
  312. subset = _safe_indexing(array, indices, axis=0)
  313. expected_array = _convert_container([7, 8, 9], expected_output_type)
  314. assert_allclose_dense_sparse(subset, expected_array)
  315. @pytest.mark.parametrize("array_type", ["list", "array", "series"])
  316. def test_safe_indexing_1d_scalar(array_type):
  317. array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type)
  318. indices = 2
  319. subset = _safe_indexing(array, indices, axis=0)
  320. assert subset == 3
  321. @pytest.mark.parametrize(
  322. "array_type, expected_output_type",
  323. [("array", "array"), ("sparse", "sparse"), ("dataframe", "series")],
  324. )
  325. @pytest.mark.parametrize("indices", [2, "col_2"])
  326. def test_safe_indexing_2d_scalar_axis_1(array_type, expected_output_type, indices):
  327. columns_name = ["col_0", "col_1", "col_2"]
  328. array = _convert_container(
  329. [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name
  330. )
  331. if isinstance(indices, str) and array_type != "dataframe":
  332. err_msg = (
  333. "Specifying the columns using strings is only supported "
  334. "for pandas DataFrames"
  335. )
  336. with pytest.raises(ValueError, match=err_msg):
  337. _safe_indexing(array, indices, axis=1)
  338. else:
  339. subset = _safe_indexing(array, indices, axis=1)
  340. expected_output = [3, 6, 9]
  341. if expected_output_type == "sparse":
  342. # sparse matrix are keeping the 2D shape
  343. expected_output = [[3], [6], [9]]
  344. expected_array = _convert_container(expected_output, expected_output_type)
  345. assert_allclose_dense_sparse(subset, expected_array)
  346. @pytest.mark.parametrize("array_type", ["list", "array", "sparse"])
  347. def test_safe_indexing_None_axis_0(array_type):
  348. X = _convert_container([[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type)
  349. X_subset = _safe_indexing(X, None, axis=0)
  350. assert_allclose_dense_sparse(X_subset, X)
  351. def test_safe_indexing_pandas_no_matching_cols_error():
  352. pd = pytest.importorskip("pandas")
  353. err_msg = "No valid specification of the columns."
  354. X = pd.DataFrame(X_toy)
  355. with pytest.raises(ValueError, match=err_msg):
  356. _safe_indexing(X, [1.0], axis=1)
  357. @pytest.mark.parametrize("axis", [None, 3])
  358. def test_safe_indexing_error_axis(axis):
  359. with pytest.raises(ValueError, match="'axis' should be either 0"):
  360. _safe_indexing(X_toy, [0, 1], axis=axis)
  361. @pytest.mark.parametrize("X_constructor", ["array", "series"])
  362. def test_safe_indexing_1d_array_error(X_constructor):
  363. # check that we are raising an error if the array-like passed is 1D and
  364. # we try to index on the 2nd dimension
  365. X = list(range(5))
  366. if X_constructor == "array":
  367. X_constructor = np.asarray(X)
  368. elif X_constructor == "series":
  369. pd = pytest.importorskip("pandas")
  370. X_constructor = pd.Series(X)
  371. err_msg = "'X' should be a 2D NumPy array, 2D sparse matrix or pandas"
  372. with pytest.raises(ValueError, match=err_msg):
  373. _safe_indexing(X_constructor, [0, 1], axis=1)
  374. def test_safe_indexing_container_axis_0_unsupported_type():
  375. indices = ["col_1", "col_2"]
  376. array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  377. err_msg = "String indexing is not supported with 'axis=0'"
  378. with pytest.raises(ValueError, match=err_msg):
  379. _safe_indexing(array, indices, axis=0)
  380. def test_safe_indexing_pandas_no_settingwithcopy_warning():
  381. # Using safe_indexing with an array-like indexer gives a copy of the
  382. # DataFrame -> ensure it doesn't raise a warning if modified
  383. pd = pytest.importorskip("pandas")
  384. if parse_version(pd.__version__) < parse_version("0.25.0"):
  385. raise SkipTest(
  386. "Older pandas version still raise a SettingWithCopyWarning warning"
  387. )
  388. X = pd.DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]})
  389. subset = _safe_indexing(X, [0, 1], axis=0)
  390. with pytest.warns(None) as record:
  391. subset.iloc[0, 0] = 10
  392. assert len(record) == 0, f"{[str(rec.message) for rec in record]}"
  393. # The original dataframe is unaffected by the assignment on the subset:
  394. assert X.iloc[0, 0] == 1
  395. @pytest.mark.parametrize(
  396. "key, err_msg",
  397. [
  398. (10, r"all features must be in \[0, 2\]"),
  399. ("whatever", "A given column is not a column of the dataframe"),
  400. ],
  401. )
  402. def test_get_column_indices_error(key, err_msg):
  403. pd = pytest.importorskip("pandas")
  404. X_df = pd.DataFrame(X_toy, columns=["col_0", "col_1", "col_2"])
  405. with pytest.raises(ValueError, match=err_msg):
  406. _get_column_indices(X_df, key)
  407. @pytest.mark.parametrize(
  408. "key", [["col1"], ["col2"], ["col1", "col2"], ["col1", "col3"], ["col2", "col3"]]
  409. )
  410. def test_get_column_indices_pandas_nonunique_columns_error(key):
  411. pd = pytest.importorskip("pandas")
  412. toy = np.zeros((1, 5), dtype=int)
  413. columns = ["col1", "col1", "col2", "col3", "col2"]
  414. X = pd.DataFrame(toy, columns=columns)
  415. err_msg = "Selected columns, {}, are not unique in dataframe".format(key)
  416. with pytest.raises(ValueError) as exc_info:
  417. _get_column_indices(X, key)
  418. assert str(exc_info.value) == err_msg
  419. def test_shuffle_on_ndim_equals_three():
  420. def to_tuple(A): # to make the inner arrays hashable
  421. return tuple(tuple(tuple(C) for C in B) for B in A)
  422. A = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # A.shape = (2,2,2)
  423. S = set(to_tuple(A))
  424. shuffle(A) # shouldn't raise a ValueError for dim = 3
  425. assert set(to_tuple(A)) == S
  426. def test_shuffle_dont_convert_to_array():
  427. # Check that shuffle does not try to convert to numpy arrays with float
  428. # dtypes can let any indexable datastructure pass-through.
  429. a = ["a", "b", "c"]
  430. b = np.array(["a", "b", "c"], dtype=object)
  431. c = [1, 2, 3]
  432. d = MockDataFrame(np.array([["a", 0], ["b", 1], ["c", 2]], dtype=object))
  433. e = sp.csc_matrix(np.arange(6).reshape(3, 2))
  434. a_s, b_s, c_s, d_s, e_s = shuffle(a, b, c, d, e, random_state=0)
  435. assert a_s == ["c", "b", "a"]
  436. assert type(a_s) == list
  437. assert_array_equal(b_s, ["c", "b", "a"])
  438. assert b_s.dtype == object
  439. assert c_s == [3, 2, 1]
  440. assert type(c_s) == list
  441. assert_array_equal(d_s, np.array([["c", 2], ["b", 1], ["a", 0]], dtype=object))
  442. assert type(d_s) == MockDataFrame
  443. assert_array_equal(e_s.toarray(), np.array([[4, 5], [2, 3], [0, 1]]))
  444. def test_gen_even_slices():
  445. # check that gen_even_slices contains all samples
  446. some_range = range(10)
  447. joined_range = list(chain(*[some_range[slice] for slice in gen_even_slices(10, 3)]))
  448. assert_array_equal(some_range, joined_range)
  449. # check that passing negative n_chunks raises an error
  450. slices = gen_even_slices(10, -1)
  451. with pytest.raises(ValueError, match="gen_even_slices got n_packs=-1, must be >=1"):
  452. next(slices)
  453. @pytest.mark.parametrize(
  454. ("row_bytes", "max_n_rows", "working_memory", "expected", "warn_msg"),
  455. [
  456. (1024, None, 1, 1024, None),
  457. (1024, None, 0.99999999, 1023, None),
  458. (1023, None, 1, 1025, None),
  459. (1025, None, 1, 1023, None),
  460. (1024, None, 2, 2048, None),
  461. (1024, 7, 1, 7, None),
  462. (1024 * 1024, None, 1, 1, None),
  463. (
  464. 1024 * 1024 + 1,
  465. None,
  466. 1,
  467. 1,
  468. "Could not adhere to working_memory config. Currently 1MiB, 2MiB required.",
  469. ),
  470. ],
  471. )
  472. def test_get_chunk_n_rows(row_bytes, max_n_rows, working_memory, expected, warn_msg):
  473. warning = None if warn_msg is None else UserWarning
  474. with pytest.warns(warning, match=warn_msg) as w:
  475. actual = get_chunk_n_rows(
  476. row_bytes=row_bytes,
  477. max_n_rows=max_n_rows,
  478. working_memory=working_memory,
  479. )
  480. assert actual == expected
  481. assert type(actual) is type(expected)
  482. if warn_msg is None:
  483. assert len(w) == 0
  484. with config_context(working_memory=working_memory):
  485. with pytest.warns(warning, match=warn_msg) as w:
  486. actual = get_chunk_n_rows(row_bytes=row_bytes, max_n_rows=max_n_rows)
  487. assert actual == expected
  488. assert type(actual) is type(expected)
  489. if warn_msg is None:
  490. assert len(w) == 0
  491. @pytest.mark.parametrize(
  492. ["source", "message", "is_long"],
  493. [
  494. ("ABC", string.ascii_lowercase, False),
  495. ("ABCDEF", string.ascii_lowercase, False),
  496. ("ABC", string.ascii_lowercase * 3, True),
  497. ("ABC" * 10, string.ascii_lowercase, True),
  498. ("ABC", string.ascii_lowercase + "\u1048", False),
  499. ],
  500. )
  501. @pytest.mark.parametrize(
  502. ["time", "time_str"],
  503. [
  504. (0.2, " 0.2s"),
  505. (20, " 20.0s"),
  506. (2000, "33.3min"),
  507. (20000, "333.3min"),
  508. ],
  509. )
  510. def test_message_with_time(source, message, is_long, time, time_str):
  511. out = _message_with_time(source, message, time)
  512. if is_long:
  513. assert len(out) > 70
  514. else:
  515. assert len(out) == 70
  516. assert out.startswith("[" + source + "] ")
  517. out = out[len(source) + 3 :]
  518. assert out.endswith(time_str)
  519. out = out[: -len(time_str)]
  520. assert out.endswith(", total=")
  521. out = out[: -len(", total=")]
  522. assert out.endswith(message)
  523. out = out[: -len(message)]
  524. assert out.endswith(" ")
  525. out = out[:-1]
  526. if is_long:
  527. assert not out
  528. else:
  529. assert list(set(out)) == ["."]
  530. @pytest.mark.parametrize(
  531. ["message", "expected"],
  532. [
  533. ("hello", _message_with_time("ABC", "hello", 0.1) + "\n"),
  534. ("", _message_with_time("ABC", "", 0.1) + "\n"),
  535. (None, ""),
  536. ],
  537. )
  538. def test_print_elapsed_time(message, expected, capsys, monkeypatch):
  539. monkeypatch.setattr(timeit, "default_timer", lambda: 0)
  540. with _print_elapsed_time("ABC", message):
  541. monkeypatch.setattr(timeit, "default_timer", lambda: 0.1)
  542. assert capsys.readouterr().out == expected
  543. @pytest.mark.parametrize(
  544. "value, result",
  545. [
  546. (float("nan"), True),
  547. (np.nan, True),
  548. (float(np.nan), True),
  549. (np.float32(np.nan), True),
  550. (np.float64(np.nan), True),
  551. (0, False),
  552. (0.0, False),
  553. (None, False),
  554. ("", False),
  555. ("nan", False),
  556. ([np.nan], False),
  557. (9867966753463435747313673, False), # Python int that overflows with C type
  558. ],
  559. )
  560. def test_is_scalar_nan(value, result):
  561. assert is_scalar_nan(value) is result
  562. # make sure that we are returning a Python bool
  563. assert isinstance(is_scalar_nan(value), bool)
  564. def dummy_func():
  565. pass
  566. def test_deprecation_joblib_api(tmpdir):
  567. # Only parallel_backend and register_parallel_backend are not deprecated in
  568. # sklearn.utils
  569. from sklearn.utils import parallel_backend, register_parallel_backend
  570. assert_no_warnings(parallel_backend, "loky", None)
  571. assert_no_warnings(register_parallel_backend, "failing", None)
  572. from sklearn.utils._joblib import joblib
  573. del joblib.parallel.BACKENDS["failing"]
  574. @pytest.mark.parametrize("sequence", [[np.array(1), np.array(2)], [[1, 2], [3, 4]]])
  575. def test_to_object_array(sequence):
  576. out = _to_object_array(sequence)
  577. assert isinstance(out, np.ndarray)
  578. assert out.dtype.kind == "O"
  579. assert out.ndim == 1