PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/sklearn/utils/tests/test_utils.py

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