Aluode/PerceptionLabPortable
0
1import numpy as np
2from numpy.testing import assert_array_equal
3
4from sklearn.utils._unique import attach_unique, cached_unique
5from sklearn.utils.validation import check_array
6
7
8def test_attach_unique_attaches_unique_to_array():
9 arr = np.array([1, 2, 2, 3, 4, 4, 5])
10 arr_ = attach_unique(arr)
11 assert_array_equal(arr_.dtype.metadata["unique"], np.array([1, 2, 3, 4, 5]))
12 assert_array_equal(arr_, arr)
13
14
15def test_cached_unique_returns_cached_unique():
16 my_dtype = np.dtype(np.float64, metadata={"unique": np.array([1, 2])})
17 arr = np.array([1, 2, 2, 3, 4, 4, 5], dtype=my_dtype)
18 assert_array_equal(cached_unique(arr), np.array([1, 2]))
19
20
21def test_attach_unique_not_ndarray():
22 """Test that when not np.ndarray, we don't touch the array."""
23 arr = [1, 2, 2, 3, 4, 4, 5]
24 arr_ = attach_unique(arr)
25 assert arr_ is arr
26
27
28def test_attach_unique_returns_view():
29 """Test that attach_unique returns a view of the array."""
30 arr = np.array([1, 2, 2, 3, 4, 4, 5])
31 arr_ = attach_unique(arr)
32 assert arr_.base is arr
33
34
35def test_attach_unique_return_tuple():
36 """Test return_tuple argument of the function."""
37 arr = np.array([1, 2, 2, 3, 4, 4, 5])
38 arr_tuple = attach_unique(arr, return_tuple=True)
39 assert isinstance(arr_tuple, tuple)
40 assert len(arr_tuple) == 1
41 assert_array_equal(arr_tuple[0], arr)
42
43 arr_single = attach_unique(arr, return_tuple=False)
44 assert isinstance(arr_single, np.ndarray)
45 assert_array_equal(arr_single, arr)
46
47
48def test_check_array_keeps_unique():
49 """Test that check_array keeps the unique metadata."""
50 arr = np.array([[1, 2, 2, 3, 4, 4, 5]])
51 arr_ = attach_unique(arr)
52 arr_ = check_array(arr_)
53 assert_array_equal(arr_.dtype.metadata["unique"], np.array([1, 2, 3, 4, 5]))
54 assert_array_equal(arr_, arr)
55 