|
5 | 5 |
|
6 | 6 | import math
|
7 | 7 | import pickle
|
| 8 | +from unittest.mock import MagicMock |
8 | 9 |
|
9 | 10 | import numpy as np
|
10 | 11 | import pytest
|
|
16 | 17 | from sklearn.utils.fixes import _joblib_parallel_args
|
17 | 18 | from sklearn.utils.fixes import _object_dtype_isnan
|
18 | 19 | from sklearn.utils.fixes import loguniform
|
| 20 | +from sklearn.utils.fixes import empty_like |
| 21 | +from sklearn.utils.fixes import np_version |
19 | 22 |
|
20 | 23 |
|
21 | 24 | def test_masked_array_obj_dtype_pickleable():
|
@@ -95,3 +98,51 @@ def test_loguniform(low, high, base):
|
95 | 98 | loguniform(base ** low, base ** high).rvs(random_state=0)
|
96 | 99 | == loguniform(base ** low, base ** high).rvs(random_state=0)
|
97 | 100 | )
|
| 101 | + |
| 102 | + |
| 103 | +@pytest.mark.skipif(np_version < (1, 17), |
| 104 | + reason="NEP18 not supported before 1.17") |
| 105 | +def test_empty_like_nep18(): |
| 106 | + class ArrayLike: |
| 107 | + __array_function__ = MagicMock(return_value=42) |
| 108 | + |
| 109 | + # if NEP18 is supported, empty_like should be forwarded to us |
| 110 | + array_like = ArrayLike() |
| 111 | + value = empty_like(array_like, dtype=np.float32, shape=(4, 2)) |
| 112 | + assert value == 42 |
| 113 | + |
| 114 | + |
| 115 | +def test_empty_like(): |
| 116 | + # Normaly arrays should just work with all versions of numpy |
| 117 | + X = np.arange(8) |
| 118 | + Y = empty_like(X.reshape((4, 2))) |
| 119 | + assert isinstance(Y, np.ndarray) |
| 120 | + assert Y.shape == (4, 2) |
| 121 | + |
| 122 | + |
| 123 | +@pytest.mark.skipif(np_version >= (1, 17), |
| 124 | + reason="NEP18 not supported before 1.17") |
| 125 | +def test_empty_like_no_nep18(): |
| 126 | + class NotAnArray: |
| 127 | + def __array__(self): |
| 128 | + return np.arange(8, dtype=np.float64).reshape((4, 2)) |
| 129 | + |
| 130 | + # for numpy < 1.17, we should give an error msg, if we provide shape |
| 131 | + no_array = NotAnArray() |
| 132 | + with pytest.raises(ValueError): |
| 133 | + empty_like(no_array, dtype=np.float32, shape=(4, 2)) |
| 134 | + |
| 135 | + # we can pass a non-ndarray object, but without shape |
| 136 | + no_array = NotAnArray() |
| 137 | + an_array = empty_like(no_array, dtype=np.float32) |
| 138 | + assert an_array.shape == (4, 2) |
| 139 | + assert an_array.dtype == np.float32 |
| 140 | + |
| 141 | + # but with a ndarray, we can pass with shape |
| 142 | + second_array = empty_like(an_array, dtype=np.float64, shape=(3,5)) |
| 143 | + assert second_array.shape == (3, 5) |
| 144 | + assert second_array.dtype == np.float64 |
| 145 | + |
| 146 | + second_array_same_type = empty_like(an_array, shape=(3,5)) |
| 147 | + assert second_array_same_type.shape == (3, 5) |
| 148 | + assert second_array_same_type.dtype == np.float32 |
0 commit comments