Add loan-advisor-agent (part 5)
Browse files- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_fixes.py +160 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_graph.py +80 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_indexing.py +703 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_mask.py +19 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_metaestimators.py +63 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_missing.py +27 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_mocking.py +205 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_multiclass.py +634 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_murmurhash.py +73 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_optimize.py +220 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_parallel.py +197 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_param_validation.py +786 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_plotting.py +543 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_pprint.py +693 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_random.py +192 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_response.py +396 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_seq_dataset.py +185 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_set_output.py +471 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_shortest_path.py +65 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_show_versions.py +40 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_sparsefuncs.py +1054 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_stats.py +487 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_tags.py +142 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_testing.py +1143 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_typedefs.py +25 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_unique.py +54 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_user_interface.py +65 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_validation.py +2357 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_weight_vector.py +25 -0
- loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/validation.py +0 -0
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_fixes.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: The scikit-learn developers
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from sklearn.utils._testing import assert_array_equal
|
| 8 |
+
from sklearn.utils.fixes import _object_dtype_isnan, _smallest_admissible_index_dtype
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@pytest.mark.parametrize("dtype, val", ([object, 1], [object, "a"], [float, 1]))
|
| 12 |
+
def test_object_dtype_isnan(dtype, val):
|
| 13 |
+
X = np.array([[val, np.nan], [np.nan, val]], dtype=dtype)
|
| 14 |
+
|
| 15 |
+
expected_mask = np.array([[False, True], [True, False]])
|
| 16 |
+
|
| 17 |
+
mask = _object_dtype_isnan(X)
|
| 18 |
+
|
| 19 |
+
assert_array_equal(mask, expected_mask)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.mark.parametrize(
|
| 23 |
+
"params, expected_dtype",
|
| 24 |
+
[
|
| 25 |
+
({}, np.int32), # default behaviour
|
| 26 |
+
({"maxval": np.iinfo(np.int32).max}, np.int32),
|
| 27 |
+
({"maxval": np.iinfo(np.int32).max + 1}, np.int64),
|
| 28 |
+
],
|
| 29 |
+
)
|
| 30 |
+
def test_smallest_admissible_index_dtype_max_val(params, expected_dtype):
|
| 31 |
+
"""Check the behaviour of `smallest_admissible_index_dtype` depending only on the
|
| 32 |
+
`max_val` parameter.
|
| 33 |
+
"""
|
| 34 |
+
assert _smallest_admissible_index_dtype(**params) == expected_dtype
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize(
|
| 38 |
+
"params, expected_dtype",
|
| 39 |
+
[
|
| 40 |
+
# Arrays dtype is int64 and thus should not be downcasted to int32 without
|
| 41 |
+
# checking the content of providing maxval.
|
| 42 |
+
({"arrays": np.array([1, 2], dtype=np.int64)}, np.int64),
|
| 43 |
+
# One of the array is int64 and should not be downcasted to int32
|
| 44 |
+
# for the same reasons.
|
| 45 |
+
(
|
| 46 |
+
{
|
| 47 |
+
"arrays": (
|
| 48 |
+
np.array([1, 2], dtype=np.int32),
|
| 49 |
+
np.array([1, 2], dtype=np.int64),
|
| 50 |
+
)
|
| 51 |
+
},
|
| 52 |
+
np.int64,
|
| 53 |
+
),
|
| 54 |
+
# Both arrays are already int32: we can just keep this dtype.
|
| 55 |
+
(
|
| 56 |
+
{
|
| 57 |
+
"arrays": (
|
| 58 |
+
np.array([1, 2], dtype=np.int32),
|
| 59 |
+
np.array([1, 2], dtype=np.int32),
|
| 60 |
+
)
|
| 61 |
+
},
|
| 62 |
+
np.int32,
|
| 63 |
+
),
|
| 64 |
+
# Arrays should be upcasted to at least int32 precision.
|
| 65 |
+
({"arrays": np.array([1, 2], dtype=np.int8)}, np.int32),
|
| 66 |
+
# Check that `maxval` takes precedence over the arrays and thus upcast to
|
| 67 |
+
# int64.
|
| 68 |
+
(
|
| 69 |
+
{
|
| 70 |
+
"arrays": np.array([1, 2], dtype=np.int32),
|
| 71 |
+
"maxval": np.iinfo(np.int32).max + 1,
|
| 72 |
+
},
|
| 73 |
+
np.int64,
|
| 74 |
+
),
|
| 75 |
+
],
|
| 76 |
+
)
|
| 77 |
+
def test_smallest_admissible_index_dtype_without_checking_contents(
|
| 78 |
+
params, expected_dtype
|
| 79 |
+
):
|
| 80 |
+
"""Check the behaviour of `smallest_admissible_index_dtype` using the passed
|
| 81 |
+
arrays but without checking the contents of the arrays.
|
| 82 |
+
"""
|
| 83 |
+
assert _smallest_admissible_index_dtype(**params) == expected_dtype
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@pytest.mark.parametrize(
|
| 87 |
+
"params, expected_dtype",
|
| 88 |
+
[
|
| 89 |
+
# empty arrays should always be converted to int32 indices
|
| 90 |
+
(
|
| 91 |
+
{
|
| 92 |
+
"arrays": (np.array([], dtype=np.int64), np.array([], dtype=np.int64)),
|
| 93 |
+
"check_contents": True,
|
| 94 |
+
},
|
| 95 |
+
np.int32,
|
| 96 |
+
),
|
| 97 |
+
# arrays respecting np.iinfo(np.int32).min < x < np.iinfo(np.int32).max should
|
| 98 |
+
# be converted to int32,
|
| 99 |
+
(
|
| 100 |
+
{"arrays": np.array([1], dtype=np.int64), "check_contents": True},
|
| 101 |
+
np.int32,
|
| 102 |
+
),
|
| 103 |
+
# otherwise, it should be converted to int64. We need to create a uint32
|
| 104 |
+
# arrays to accommodate a value > np.iinfo(np.int32).max
|
| 105 |
+
(
|
| 106 |
+
{
|
| 107 |
+
"arrays": np.array([np.iinfo(np.int32).max + 1], dtype=np.uint32),
|
| 108 |
+
"check_contents": True,
|
| 109 |
+
},
|
| 110 |
+
np.int64,
|
| 111 |
+
),
|
| 112 |
+
# maxval should take precedence over the arrays contents and thus upcast to
|
| 113 |
+
# int64.
|
| 114 |
+
(
|
| 115 |
+
{
|
| 116 |
+
"arrays": np.array([1], dtype=np.int32),
|
| 117 |
+
"check_contents": True,
|
| 118 |
+
"maxval": np.iinfo(np.int32).max + 1,
|
| 119 |
+
},
|
| 120 |
+
np.int64,
|
| 121 |
+
),
|
| 122 |
+
# when maxval is small, but check_contents is True and the contents
|
| 123 |
+
# require np.int64, we still require np.int64 indexing in the end.
|
| 124 |
+
(
|
| 125 |
+
{
|
| 126 |
+
"arrays": np.array([np.iinfo(np.int32).max + 1], dtype=np.uint32),
|
| 127 |
+
"check_contents": True,
|
| 128 |
+
"maxval": 1,
|
| 129 |
+
},
|
| 130 |
+
np.int64,
|
| 131 |
+
),
|
| 132 |
+
],
|
| 133 |
+
)
|
| 134 |
+
def test_smallest_admissible_index_dtype_by_checking_contents(params, expected_dtype):
|
| 135 |
+
"""Check the behaviour of `smallest_admissible_index_dtype` using the dtype of the
|
| 136 |
+
arrays but as well the contents.
|
| 137 |
+
"""
|
| 138 |
+
assert _smallest_admissible_index_dtype(**params) == expected_dtype
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@pytest.mark.parametrize(
|
| 142 |
+
"params, err_type, err_msg",
|
| 143 |
+
[
|
| 144 |
+
(
|
| 145 |
+
{"maxval": np.iinfo(np.int64).max + 1},
|
| 146 |
+
ValueError,
|
| 147 |
+
"is to large to be represented as np.int64",
|
| 148 |
+
),
|
| 149 |
+
(
|
| 150 |
+
{"arrays": np.array([1, 2], dtype=np.float64)},
|
| 151 |
+
ValueError,
|
| 152 |
+
"Array dtype float64 is not supported",
|
| 153 |
+
),
|
| 154 |
+
({"arrays": [1, 2]}, TypeError, "Arrays should be of type np.ndarray"),
|
| 155 |
+
],
|
| 156 |
+
)
|
| 157 |
+
def test_smallest_admissible_index_dtype_error(params, err_type, err_msg):
|
| 158 |
+
"""Check that we raise the proper error message."""
|
| 159 |
+
with pytest.raises(err_type, match=err_msg):
|
| 160 |
+
_smallest_admissible_index_dtype(**params)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_graph.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
from scipy.sparse.csgraph import connected_components
|
| 4 |
+
|
| 5 |
+
from sklearn.metrics.pairwise import pairwise_distances
|
| 6 |
+
from sklearn.neighbors import kneighbors_graph
|
| 7 |
+
from sklearn.utils.graph import _fix_connected_components
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_fix_connected_components():
|
| 11 |
+
# Test that _fix_connected_components reduces the number of component to 1.
|
| 12 |
+
X = np.array([0, 1, 2, 5, 6, 7])[:, None]
|
| 13 |
+
graph = kneighbors_graph(X, n_neighbors=2, mode="distance")
|
| 14 |
+
|
| 15 |
+
n_connected_components, labels = connected_components(graph)
|
| 16 |
+
assert n_connected_components > 1
|
| 17 |
+
|
| 18 |
+
graph = _fix_connected_components(X, graph, n_connected_components, labels)
|
| 19 |
+
|
| 20 |
+
n_connected_components, labels = connected_components(graph)
|
| 21 |
+
assert n_connected_components == 1
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_fix_connected_components_precomputed():
|
| 25 |
+
# Test that _fix_connected_components accepts precomputed distance matrix.
|
| 26 |
+
X = np.array([0, 1, 2, 5, 6, 7])[:, None]
|
| 27 |
+
graph = kneighbors_graph(X, n_neighbors=2, mode="distance")
|
| 28 |
+
|
| 29 |
+
n_connected_components, labels = connected_components(graph)
|
| 30 |
+
assert n_connected_components > 1
|
| 31 |
+
|
| 32 |
+
distances = pairwise_distances(X)
|
| 33 |
+
graph = _fix_connected_components(
|
| 34 |
+
distances, graph, n_connected_components, labels, metric="precomputed"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
n_connected_components, labels = connected_components(graph)
|
| 38 |
+
assert n_connected_components == 1
|
| 39 |
+
|
| 40 |
+
# but it does not work with precomputed neighbors graph
|
| 41 |
+
with pytest.raises(RuntimeError, match="does not work with a sparse"):
|
| 42 |
+
_fix_connected_components(
|
| 43 |
+
graph, graph, n_connected_components, labels, metric="precomputed"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_fix_connected_components_wrong_mode():
|
| 48 |
+
# Test that the an error is raised if the mode string is incorrect.
|
| 49 |
+
X = np.array([0, 1, 2, 5, 6, 7])[:, None]
|
| 50 |
+
graph = kneighbors_graph(X, n_neighbors=2, mode="distance")
|
| 51 |
+
n_connected_components, labels = connected_components(graph)
|
| 52 |
+
|
| 53 |
+
with pytest.raises(ValueError, match="Unknown mode"):
|
| 54 |
+
graph = _fix_connected_components(
|
| 55 |
+
X, graph, n_connected_components, labels, mode="foo"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_fix_connected_components_connectivity_mode():
|
| 60 |
+
# Test that the connectivity mode fill new connections with ones.
|
| 61 |
+
X = np.array([0, 1, 6, 7])[:, None]
|
| 62 |
+
graph = kneighbors_graph(X, n_neighbors=1, mode="connectivity")
|
| 63 |
+
n_connected_components, labels = connected_components(graph)
|
| 64 |
+
graph = _fix_connected_components(
|
| 65 |
+
X, graph, n_connected_components, labels, mode="connectivity"
|
| 66 |
+
)
|
| 67 |
+
assert np.all(graph.data == 1)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_fix_connected_components_distance_mode():
|
| 71 |
+
# Test that the distance mode does not fill new connections with ones.
|
| 72 |
+
X = np.array([0, 1, 6, 7])[:, None]
|
| 73 |
+
graph = kneighbors_graph(X, n_neighbors=1, mode="distance")
|
| 74 |
+
assert np.all(graph.data == 1)
|
| 75 |
+
|
| 76 |
+
n_connected_components, labels = connected_components(graph)
|
| 77 |
+
graph = _fix_connected_components(
|
| 78 |
+
X, graph, n_connected_components, labels, mode="distance"
|
| 79 |
+
)
|
| 80 |
+
assert not np.all(graph.data == 1)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_indexing.py
ADDED
|
@@ -0,0 +1,703 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from copy import copy
|
| 3 |
+
from unittest import SkipTest
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
from scipy.stats import kstest
|
| 8 |
+
|
| 9 |
+
import sklearn
|
| 10 |
+
from sklearn.externals._packaging.version import parse as parse_version
|
| 11 |
+
from sklearn.utils import _safe_indexing, resample, shuffle
|
| 12 |
+
from sklearn.utils._array_api import (
|
| 13 |
+
_convert_to_numpy,
|
| 14 |
+
_get_namespace_device_dtype_ids,
|
| 15 |
+
device,
|
| 16 |
+
move_to,
|
| 17 |
+
yield_namespace_device_dtype_combinations,
|
| 18 |
+
)
|
| 19 |
+
from sklearn.utils._indexing import (
|
| 20 |
+
_determine_key_type,
|
| 21 |
+
_get_column_indices,
|
| 22 |
+
_safe_assign,
|
| 23 |
+
)
|
| 24 |
+
from sklearn.utils._mocking import MockDataFrame
|
| 25 |
+
from sklearn.utils._testing import (
|
| 26 |
+
_array_api_for_tests,
|
| 27 |
+
_convert_container,
|
| 28 |
+
assert_allclose,
|
| 29 |
+
assert_allclose_dense_sparse,
|
| 30 |
+
assert_array_equal,
|
| 31 |
+
skip_if_array_api_compat_not_configured,
|
| 32 |
+
)
|
| 33 |
+
from sklearn.utils.fixes import CSC_CONTAINERS, CSR_CONTAINERS
|
| 34 |
+
|
| 35 |
+
# toy array
|
| 36 |
+
X_toy = np.arange(9).reshape((3, 3))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_polars_indexing():
|
| 40 |
+
"""Check _safe_indexing for polars as expected."""
|
| 41 |
+
pl = pytest.importorskip("polars", minversion="0.18.2")
|
| 42 |
+
df = pl.DataFrame(
|
| 43 |
+
{"a": [1, 2, 3, 4], "b": [4, 5, 6, 8], "c": [1, 4, 1, 10]}, orient="row"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
from polars.testing import assert_frame_equal
|
| 47 |
+
|
| 48 |
+
str_keys = [["b"], ["a", "b"], ["b", "a", "c"], ["c"], ["a"]]
|
| 49 |
+
|
| 50 |
+
for key in str_keys:
|
| 51 |
+
out = _safe_indexing(df, key, axis=1)
|
| 52 |
+
assert_frame_equal(df[key], out)
|
| 53 |
+
|
| 54 |
+
bool_keys = [([True, False, True], ["a", "c"]), ([False, False, True], ["c"])]
|
| 55 |
+
|
| 56 |
+
for bool_key, str_key in bool_keys:
|
| 57 |
+
out = _safe_indexing(df, bool_key, axis=1)
|
| 58 |
+
assert_frame_equal(df[:, str_key], out)
|
| 59 |
+
|
| 60 |
+
int_keys = [([0, 1], ["a", "b"]), ([2], ["c"])]
|
| 61 |
+
|
| 62 |
+
for int_key, str_key in int_keys:
|
| 63 |
+
out = _safe_indexing(df, int_key, axis=1)
|
| 64 |
+
assert_frame_equal(df[:, str_key], out)
|
| 65 |
+
|
| 66 |
+
axis_0_keys = [[0, 1], [1, 3], [3, 2]]
|
| 67 |
+
for key in axis_0_keys:
|
| 68 |
+
out = _safe_indexing(df, key, axis=0)
|
| 69 |
+
assert_frame_equal(df[key], out)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@pytest.mark.parametrize(
|
| 73 |
+
"key, dtype",
|
| 74 |
+
[
|
| 75 |
+
(0, "int"),
|
| 76 |
+
("0", "str"),
|
| 77 |
+
(True, "bool"),
|
| 78 |
+
(np.bool_(True), "bool"),
|
| 79 |
+
([0, 1, 2], "int"),
|
| 80 |
+
(["0", "1", "2"], "str"),
|
| 81 |
+
((0, 1, 2), "int"),
|
| 82 |
+
(("0", "1", "2"), "str"),
|
| 83 |
+
(slice(None, None), None),
|
| 84 |
+
(slice(0, 2), "int"),
|
| 85 |
+
(np.array([0, 1, 2], dtype=np.int32), "int"),
|
| 86 |
+
(np.array([0, 1, 2], dtype=np.int64), "int"),
|
| 87 |
+
(np.array([0, 1, 2], dtype=np.uint8), "int"),
|
| 88 |
+
([True, False], "bool"),
|
| 89 |
+
((True, False), "bool"),
|
| 90 |
+
(np.array([True, False]), "bool"),
|
| 91 |
+
("col_0", "str"),
|
| 92 |
+
(["col_0", "col_1", "col_2"], "str"),
|
| 93 |
+
(("col_0", "col_1", "col_2"), "str"),
|
| 94 |
+
(slice("begin", "end"), "str"),
|
| 95 |
+
(np.array(["col_0", "col_1", "col_2"]), "str"),
|
| 96 |
+
(np.array(["col_0", "col_1", "col_2"], dtype=object), "str"),
|
| 97 |
+
],
|
| 98 |
+
)
|
| 99 |
+
def test_determine_key_type(key, dtype):
|
| 100 |
+
assert _determine_key_type(key) == dtype
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_determine_key_type_error():
|
| 104 |
+
with pytest.raises(ValueError, match="No valid specification of the"):
|
| 105 |
+
_determine_key_type(1.0)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_determine_key_type_slice_error():
|
| 109 |
+
with pytest.raises(TypeError, match="Only array-like or scalar are"):
|
| 110 |
+
_determine_key_type(slice(0, 2, 1), accept_slice=False)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@skip_if_array_api_compat_not_configured
|
| 114 |
+
@pytest.mark.parametrize(
|
| 115 |
+
"array_namespace, device_, dtype_name",
|
| 116 |
+
yield_namespace_device_dtype_combinations(),
|
| 117 |
+
ids=_get_namespace_device_dtype_ids,
|
| 118 |
+
)
|
| 119 |
+
def test_determine_key_type_array_api(array_namespace, device_, dtype_name):
|
| 120 |
+
xp = _array_api_for_tests(array_namespace, device_)
|
| 121 |
+
|
| 122 |
+
with sklearn.config_context(array_api_dispatch=True):
|
| 123 |
+
int_array_key = xp.asarray([1, 2, 3], device=device_)
|
| 124 |
+
assert _determine_key_type(int_array_key) == "int"
|
| 125 |
+
|
| 126 |
+
bool_array_key = xp.asarray([True, False, True], device=device_)
|
| 127 |
+
assert _determine_key_type(bool_array_key) == "bool"
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
complex_array_key = xp.asarray([1 + 1j, 2 + 2j, 3 + 3j], device=device_)
|
| 131 |
+
except TypeError:
|
| 132 |
+
# Complex numbers are not supported by all Array API libraries.
|
| 133 |
+
complex_array_key = None
|
| 134 |
+
|
| 135 |
+
if complex_array_key is not None:
|
| 136 |
+
with pytest.raises(ValueError, match="No valid specification of the"):
|
| 137 |
+
_determine_key_type(complex_array_key)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@skip_if_array_api_compat_not_configured
|
| 141 |
+
@pytest.mark.parametrize(
|
| 142 |
+
"array_namespace, device_, dtype_name",
|
| 143 |
+
yield_namespace_device_dtype_combinations(),
|
| 144 |
+
ids=_get_namespace_device_dtype_ids,
|
| 145 |
+
)
|
| 146 |
+
@pytest.mark.parametrize(
|
| 147 |
+
"indexing_key",
|
| 148 |
+
(
|
| 149 |
+
0,
|
| 150 |
+
-1,
|
| 151 |
+
[1, 3],
|
| 152 |
+
np.array([1, 3]),
|
| 153 |
+
slice(1, 2),
|
| 154 |
+
[True, False, True, True],
|
| 155 |
+
np.asarray([False, False, False, False]),
|
| 156 |
+
),
|
| 157 |
+
)
|
| 158 |
+
@pytest.mark.parametrize("axis", [0, 1])
|
| 159 |
+
def test_safe_indexing_array_api_support(
|
| 160 |
+
array_namespace, device_, dtype_name, indexing_key, axis
|
| 161 |
+
):
|
| 162 |
+
xp = _array_api_for_tests(array_namespace, device_)
|
| 163 |
+
|
| 164 |
+
array_to_index_np = np.arange(16).reshape(4, 4)
|
| 165 |
+
expected_result = _safe_indexing(array_to_index_np, indexing_key, axis=axis)
|
| 166 |
+
array_to_index_xp = move_to(array_to_index_np, xp=xp, device=device_)
|
| 167 |
+
|
| 168 |
+
with sklearn.config_context(array_api_dispatch=True):
|
| 169 |
+
indexed_array_xp = _safe_indexing(array_to_index_xp, indexing_key, axis=axis)
|
| 170 |
+
assert device(indexed_array_xp) == device(array_to_index_xp)
|
| 171 |
+
assert indexed_array_xp.dtype == array_to_index_xp.dtype
|
| 172 |
+
|
| 173 |
+
assert_allclose(_convert_to_numpy(indexed_array_xp, xp=xp), expected_result)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@pytest.mark.parametrize(
|
| 177 |
+
"array_type", ["list", "array", "sparse", "dataframe", "polars", "pyarrow"]
|
| 178 |
+
)
|
| 179 |
+
@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"])
|
| 180 |
+
def test_safe_indexing_2d_container_axis_0(array_type, indices_type):
|
| 181 |
+
indices = [1, 2]
|
| 182 |
+
if indices_type == "slice" and isinstance(indices[1], int):
|
| 183 |
+
indices[1] += 1
|
| 184 |
+
array = _convert_container([[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type)
|
| 185 |
+
indices = _convert_container(indices, indices_type)
|
| 186 |
+
subset = _safe_indexing(array, indices, axis=0)
|
| 187 |
+
assert_allclose_dense_sparse(
|
| 188 |
+
subset, _convert_container([[4, 5, 6], [7, 8, 9]], array_type)
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
@pytest.mark.parametrize(
|
| 193 |
+
"array_type", ["list", "array", "series", "polars_series", "pyarrow_array"]
|
| 194 |
+
)
|
| 195 |
+
@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"])
|
| 196 |
+
def test_safe_indexing_1d_container(array_type, indices_type):
|
| 197 |
+
indices = [1, 2]
|
| 198 |
+
if indices_type == "slice" and isinstance(indices[1], int):
|
| 199 |
+
indices[1] += 1
|
| 200 |
+
array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type)
|
| 201 |
+
indices = _convert_container(indices, indices_type)
|
| 202 |
+
subset = _safe_indexing(array, indices, axis=0)
|
| 203 |
+
assert_allclose_dense_sparse(subset, _convert_container([2, 3], array_type))
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@pytest.mark.parametrize(
|
| 207 |
+
"array_type", ["array", "sparse", "dataframe", "polars", "pyarrow"]
|
| 208 |
+
)
|
| 209 |
+
@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"])
|
| 210 |
+
@pytest.mark.parametrize("indices", [[1, 2], ["col_1", "col_2"]])
|
| 211 |
+
def test_safe_indexing_2d_container_axis_1(array_type, indices_type, indices):
|
| 212 |
+
# validation of the indices
|
| 213 |
+
# we make a copy because indices is mutable and shared between tests
|
| 214 |
+
indices_converted = copy(indices)
|
| 215 |
+
if indices_type == "slice" and isinstance(indices[1], int):
|
| 216 |
+
indices_converted[1] += 1
|
| 217 |
+
|
| 218 |
+
columns_name = ["col_0", "col_1", "col_2"]
|
| 219 |
+
array = _convert_container(
|
| 220 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name
|
| 221 |
+
)
|
| 222 |
+
indices_converted = _convert_container(indices_converted, indices_type)
|
| 223 |
+
|
| 224 |
+
if isinstance(indices[0], str) and array_type in ("array", "sparse"):
|
| 225 |
+
err_msg = (
|
| 226 |
+
"Specifying the columns using strings is only supported for dataframes"
|
| 227 |
+
)
|
| 228 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 229 |
+
_safe_indexing(array, indices_converted, axis=1)
|
| 230 |
+
else:
|
| 231 |
+
subset = _safe_indexing(array, indices_converted, axis=1)
|
| 232 |
+
assert_allclose_dense_sparse(
|
| 233 |
+
subset, _convert_container([[2, 3], [5, 6], [8, 9]], array_type)
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@pytest.mark.parametrize("array_read_only", [True, False])
|
| 238 |
+
@pytest.mark.parametrize("indices_read_only", [True, False])
|
| 239 |
+
@pytest.mark.parametrize(
|
| 240 |
+
"array_type", ["array", "sparse", "dataframe", "polars", "pyarrow"]
|
| 241 |
+
)
|
| 242 |
+
@pytest.mark.parametrize("indices_type", ["array", "series"])
|
| 243 |
+
@pytest.mark.parametrize(
|
| 244 |
+
"axis, expected_array", [(0, [[4, 5, 6], [7, 8, 9]]), (1, [[2, 3], [5, 6], [8, 9]])]
|
| 245 |
+
)
|
| 246 |
+
def test_safe_indexing_2d_read_only_axis_1(
|
| 247 |
+
array_read_only, indices_read_only, array_type, indices_type, axis, expected_array
|
| 248 |
+
):
|
| 249 |
+
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 250 |
+
if array_read_only:
|
| 251 |
+
array.setflags(write=False)
|
| 252 |
+
array = _convert_container(array, array_type)
|
| 253 |
+
indices = np.array([1, 2])
|
| 254 |
+
if indices_read_only:
|
| 255 |
+
indices.setflags(write=False)
|
| 256 |
+
indices = _convert_container(indices, indices_type)
|
| 257 |
+
subset = _safe_indexing(array, indices, axis=axis)
|
| 258 |
+
assert_allclose_dense_sparse(subset, _convert_container(expected_array, array_type))
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
@pytest.mark.parametrize(
|
| 262 |
+
"array_type", ["list", "array", "series", "polars_series", "pyarrow_array"]
|
| 263 |
+
)
|
| 264 |
+
@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series"])
|
| 265 |
+
def test_safe_indexing_1d_container_mask(array_type, indices_type):
|
| 266 |
+
indices = [False] + [True] * 2 + [False] * 6
|
| 267 |
+
array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type)
|
| 268 |
+
indices = _convert_container(indices, indices_type)
|
| 269 |
+
subset = _safe_indexing(array, indices, axis=0)
|
| 270 |
+
assert_allclose_dense_sparse(subset, _convert_container([2, 3], array_type))
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@pytest.mark.parametrize(
|
| 274 |
+
"array_type", ["array", "sparse", "dataframe", "polars", "pyarrow"]
|
| 275 |
+
)
|
| 276 |
+
@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series"])
|
| 277 |
+
@pytest.mark.parametrize(
|
| 278 |
+
"axis, expected_subset",
|
| 279 |
+
[(0, [[4, 5, 6], [7, 8, 9]]), (1, [[2, 3], [5, 6], [8, 9]])],
|
| 280 |
+
)
|
| 281 |
+
def test_safe_indexing_2d_mask(array_type, indices_type, axis, expected_subset):
|
| 282 |
+
columns_name = ["col_0", "col_1", "col_2"]
|
| 283 |
+
array = _convert_container(
|
| 284 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name
|
| 285 |
+
)
|
| 286 |
+
indices = [False, True, True]
|
| 287 |
+
indices = _convert_container(indices, indices_type)
|
| 288 |
+
|
| 289 |
+
subset = _safe_indexing(array, indices, axis=axis)
|
| 290 |
+
assert_allclose_dense_sparse(
|
| 291 |
+
subset, _convert_container(expected_subset, array_type)
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
@pytest.mark.parametrize(
|
| 296 |
+
"array_type, expected_output_type",
|
| 297 |
+
[
|
| 298 |
+
("list", "list"),
|
| 299 |
+
("array", "array"),
|
| 300 |
+
("sparse", "sparse"),
|
| 301 |
+
("dataframe", "series"),
|
| 302 |
+
("polars", "polars_series"),
|
| 303 |
+
("pyarrow", "pyarrow_array"),
|
| 304 |
+
],
|
| 305 |
+
)
|
| 306 |
+
def test_safe_indexing_2d_scalar_axis_0(array_type, expected_output_type):
|
| 307 |
+
array = _convert_container([[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type)
|
| 308 |
+
indices = 2
|
| 309 |
+
subset = _safe_indexing(array, indices, axis=0)
|
| 310 |
+
expected_array = _convert_container([7, 8, 9], expected_output_type)
|
| 311 |
+
assert_allclose_dense_sparse(subset, expected_array)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
@pytest.mark.parametrize(
|
| 315 |
+
"array_type", ["list", "array", "series", "polars_series", "pyarrow_array"]
|
| 316 |
+
)
|
| 317 |
+
def test_safe_indexing_1d_scalar(array_type):
|
| 318 |
+
array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type)
|
| 319 |
+
indices = 2
|
| 320 |
+
subset = _safe_indexing(array, indices, axis=0)
|
| 321 |
+
assert subset == 3
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@pytest.mark.parametrize(
|
| 325 |
+
"array_type, expected_output_type",
|
| 326 |
+
[
|
| 327 |
+
("array", "array"),
|
| 328 |
+
("sparse", "sparse"),
|
| 329 |
+
("dataframe", "series"),
|
| 330 |
+
("polars", "polars_series"),
|
| 331 |
+
("pyarrow", "pyarrow_array"),
|
| 332 |
+
],
|
| 333 |
+
)
|
| 334 |
+
@pytest.mark.parametrize("indices", [2, "col_2"])
|
| 335 |
+
def test_safe_indexing_2d_scalar_axis_1(array_type, expected_output_type, indices):
|
| 336 |
+
columns_name = ["col_0", "col_1", "col_2"]
|
| 337 |
+
array = _convert_container(
|
| 338 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
if isinstance(indices, str) and array_type in ("array", "sparse"):
|
| 342 |
+
err_msg = (
|
| 343 |
+
"Specifying the columns using strings is only supported for dataframes"
|
| 344 |
+
)
|
| 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(expected_output, expected_output_type)
|
| 354 |
+
assert_allclose_dense_sparse(subset, expected_array)
|
| 355 |
+
|
| 356 |
+
|
| 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 |
+
|
| 363 |
+
|
| 364 |
+
def test_safe_indexing_pandas_no_matching_cols_error():
|
| 365 |
+
pd = pytest.importorskip("pandas")
|
| 366 |
+
err_msg = "No valid specification of the columns."
|
| 367 |
+
X = pd.DataFrame(X_toy)
|
| 368 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 369 |
+
_safe_indexing(X, [1.0], axis=1)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@pytest.mark.parametrize("axis", [None, 3])
|
| 373 |
+
def test_safe_indexing_error_axis(axis):
|
| 374 |
+
with pytest.raises(ValueError, match="'axis' should be either 0"):
|
| 375 |
+
_safe_indexing(X_toy, [0, 1], axis=axis)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
@pytest.mark.parametrize(
|
| 379 |
+
"X_constructor", ["array", "series", "polars_series", "pyarrow_array"]
|
| 380 |
+
)
|
| 381 |
+
def test_safe_indexing_1d_array_error(X_constructor):
|
| 382 |
+
# check that we are raising an error if the array-like passed is 1D and
|
| 383 |
+
# we try to index on the 2nd dimension
|
| 384 |
+
X = list(range(5))
|
| 385 |
+
if X_constructor == "array":
|
| 386 |
+
X_constructor = np.asarray(X)
|
| 387 |
+
elif X_constructor == "series":
|
| 388 |
+
pd = pytest.importorskip("pandas")
|
| 389 |
+
X_constructor = pd.Series(X)
|
| 390 |
+
elif X_constructor == "polars_series":
|
| 391 |
+
pl = pytest.importorskip("polars")
|
| 392 |
+
X_constructor = pl.Series(values=X)
|
| 393 |
+
elif X_constructor == "pyarrow_array":
|
| 394 |
+
pa = pytest.importorskip("pyarrow")
|
| 395 |
+
X_constructor = pa.array(X)
|
| 396 |
+
|
| 397 |
+
err_msg = "'X' should be a 2D NumPy array, 2D sparse matrix or dataframe"
|
| 398 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 399 |
+
_safe_indexing(X_constructor, [0, 1], axis=1)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def test_safe_indexing_container_axis_0_unsupported_type():
|
| 403 |
+
indices = ["col_1", "col_2"]
|
| 404 |
+
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
|
| 405 |
+
err_msg = r"String indexing.*is not supported with 'axis=0'"
|
| 406 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 407 |
+
_safe_indexing(array, indices, axis=0)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def test_safe_indexing_pandas_no_settingwithcopy_warning():
|
| 411 |
+
# Using safe_indexing with an array-like indexer gives a copy of the
|
| 412 |
+
# DataFrame -> ensure it doesn't raise a warning if modified
|
| 413 |
+
pd = pytest.importorskip("pandas")
|
| 414 |
+
|
| 415 |
+
pd_version = parse_version(pd.__version__)
|
| 416 |
+
pd_base_version = parse_version(pd_version.base_version)
|
| 417 |
+
|
| 418 |
+
if pd_base_version >= parse_version("3"):
|
| 419 |
+
raise SkipTest("SettingWithCopyWarning has been removed in pandas 3.0.0.dev")
|
| 420 |
+
|
| 421 |
+
X = pd.DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]})
|
| 422 |
+
subset = _safe_indexing(X, [0, 1], axis=0)
|
| 423 |
+
if hasattr(pd.errors, "SettingWithCopyWarning"):
|
| 424 |
+
SettingWithCopyWarning = pd.errors.SettingWithCopyWarning
|
| 425 |
+
else:
|
| 426 |
+
# backward compatibility for pandas < 1.5
|
| 427 |
+
SettingWithCopyWarning = pd.core.common.SettingWithCopyWarning
|
| 428 |
+
with warnings.catch_warnings():
|
| 429 |
+
warnings.simplefilter("error", SettingWithCopyWarning)
|
| 430 |
+
subset.iloc[0, 0] = 10
|
| 431 |
+
# The original dataframe is unaffected by the assignment on the subset:
|
| 432 |
+
assert X.iloc[0, 0] == 1
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
@pytest.mark.parametrize("indices", [0, [0, 1], slice(0, 2), np.array([0, 1])])
|
| 436 |
+
def test_safe_indexing_list_axis_1_unsupported(indices):
|
| 437 |
+
"""Check that we raise a ValueError when axis=1 with input as list."""
|
| 438 |
+
X = [[1, 2], [4, 5], [7, 8]]
|
| 439 |
+
err_msg = "axis=1 is not supported for lists"
|
| 440 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 441 |
+
_safe_indexing(X, indices, axis=1)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@pytest.mark.parametrize("array_type", ["array", "sparse", "dataframe"])
|
| 445 |
+
def test_safe_assign(array_type):
|
| 446 |
+
"""Check that `_safe_assign` works as expected."""
|
| 447 |
+
rng = np.random.RandomState(0)
|
| 448 |
+
X_array = rng.randn(10, 5)
|
| 449 |
+
|
| 450 |
+
row_indexer = [1, 2]
|
| 451 |
+
values = rng.randn(len(row_indexer), X_array.shape[1])
|
| 452 |
+
X = _convert_container(X_array, array_type)
|
| 453 |
+
_safe_assign(X, values, row_indexer=row_indexer)
|
| 454 |
+
|
| 455 |
+
assigned_portion = _safe_indexing(X, row_indexer, axis=0)
|
| 456 |
+
assert_allclose_dense_sparse(
|
| 457 |
+
assigned_portion, _convert_container(values, array_type)
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
column_indexer = [1, 2]
|
| 461 |
+
values = rng.randn(X_array.shape[0], len(column_indexer))
|
| 462 |
+
X = _convert_container(X_array, array_type)
|
| 463 |
+
_safe_assign(X, values, column_indexer=column_indexer)
|
| 464 |
+
|
| 465 |
+
assigned_portion = _safe_indexing(X, column_indexer, axis=1)
|
| 466 |
+
assert_allclose_dense_sparse(
|
| 467 |
+
assigned_portion, _convert_container(values, array_type)
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
row_indexer, column_indexer = None, None
|
| 471 |
+
values = rng.randn(*X.shape)
|
| 472 |
+
X = _convert_container(X_array, array_type)
|
| 473 |
+
_safe_assign(X, values, column_indexer=column_indexer)
|
| 474 |
+
|
| 475 |
+
assert_allclose_dense_sparse(X, _convert_container(values, array_type))
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
@pytest.mark.parametrize(
|
| 479 |
+
"key, err_msg",
|
| 480 |
+
[
|
| 481 |
+
(10, r"all features must be in \[0, 2\]"),
|
| 482 |
+
("whatever", "A given column is not a column of the dataframe"),
|
| 483 |
+
(object(), "No valid specification of the columns"),
|
| 484 |
+
],
|
| 485 |
+
)
|
| 486 |
+
def test_get_column_indices_error(key, err_msg):
|
| 487 |
+
pd = pytest.importorskip("pandas")
|
| 488 |
+
X_df = pd.DataFrame(X_toy, columns=["col_0", "col_1", "col_2"])
|
| 489 |
+
|
| 490 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 491 |
+
_get_column_indices(X_df, key)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
@pytest.mark.parametrize(
|
| 495 |
+
"key", [["col1"], ["col2"], ["col1", "col2"], ["col1", "col3"], ["col2", "col3"]]
|
| 496 |
+
)
|
| 497 |
+
def test_get_column_indices_pandas_nonunique_columns_error(key):
|
| 498 |
+
pd = pytest.importorskip("pandas")
|
| 499 |
+
toy = np.zeros((1, 5), dtype=int)
|
| 500 |
+
columns = ["col1", "col1", "col2", "col3", "col2"]
|
| 501 |
+
X = pd.DataFrame(toy, columns=columns)
|
| 502 |
+
|
| 503 |
+
err_msg = "Selected columns, {}, are not unique in dataframe".format(key)
|
| 504 |
+
with pytest.raises(ValueError) as exc_info:
|
| 505 |
+
_get_column_indices(X, key)
|
| 506 |
+
assert str(exc_info.value) == err_msg
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def test_get_column_indices_interchange():
|
| 510 |
+
"""Check _get_column_indices for edge cases with the interchange"""
|
| 511 |
+
pl = pytest.importorskip("polars")
|
| 512 |
+
|
| 513 |
+
# Polars dataframes go down the interchange path.
|
| 514 |
+
df = pl.DataFrame([[1, 2, 3], [4, 5, 6]], schema=["a", "b", "c"])
|
| 515 |
+
|
| 516 |
+
key_results = [
|
| 517 |
+
(slice(1, None), [1, 2]),
|
| 518 |
+
(slice(None, 2), [0, 1]),
|
| 519 |
+
(slice(1, 2), [1]),
|
| 520 |
+
(["b", "c"], [1, 2]),
|
| 521 |
+
(slice("a", "b"), [0, 1]),
|
| 522 |
+
(slice("a", None), [0, 1, 2]),
|
| 523 |
+
(slice(None, "a"), [0]),
|
| 524 |
+
(["c", "a"], [2, 0]),
|
| 525 |
+
([], []),
|
| 526 |
+
]
|
| 527 |
+
for key, result in key_results:
|
| 528 |
+
assert _get_column_indices(df, key) == result
|
| 529 |
+
|
| 530 |
+
msg = "A given column is not a column of the dataframe"
|
| 531 |
+
with pytest.raises(ValueError, match=msg):
|
| 532 |
+
_get_column_indices(df, ["not_a_column"])
|
| 533 |
+
|
| 534 |
+
msg = "key.step must be 1 or None"
|
| 535 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 536 |
+
_get_column_indices(df, slice("a", None, 2))
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def test_resample():
|
| 540 |
+
# Border case not worth mentioning in doctests
|
| 541 |
+
assert resample() is None
|
| 542 |
+
|
| 543 |
+
# Check that invalid arguments yield ValueError
|
| 544 |
+
with pytest.raises(ValueError):
|
| 545 |
+
resample([0], [0, 1])
|
| 546 |
+
with pytest.raises(ValueError):
|
| 547 |
+
resample([0, 1], [0, 1], replace=False, n_samples=3)
|
| 548 |
+
|
| 549 |
+
# Issue:6581, n_samples can be more when replace is True (default).
|
| 550 |
+
assert len(resample([1, 2], n_samples=5)) == 5
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def test_resample_weighted():
|
| 554 |
+
# Check that sampling with replacement with integer weights yields the
|
| 555 |
+
# samples from the same distribution as sampling uniformly with
|
| 556 |
+
# repeated data points.
|
| 557 |
+
data = np.array([-1, 0, 1])
|
| 558 |
+
sample_weight = np.asarray([0, 100, 1])
|
| 559 |
+
|
| 560 |
+
mean_repeated = []
|
| 561 |
+
mean_reweighted = []
|
| 562 |
+
|
| 563 |
+
for seed in range(100):
|
| 564 |
+
mean_repeated.append(
|
| 565 |
+
resample(
|
| 566 |
+
data.repeat(sample_weight),
|
| 567 |
+
replace=True,
|
| 568 |
+
random_state=seed,
|
| 569 |
+
n_samples=data.shape[0],
|
| 570 |
+
).mean()
|
| 571 |
+
)
|
| 572 |
+
mean_reweighted.append(
|
| 573 |
+
resample(
|
| 574 |
+
data,
|
| 575 |
+
sample_weight=sample_weight,
|
| 576 |
+
replace=True,
|
| 577 |
+
random_state=seed,
|
| 578 |
+
n_samples=data.shape[0],
|
| 579 |
+
).mean()
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
mean_repeated = np.asarray(mean_repeated)
|
| 583 |
+
mean_reweighted = np.asarray(mean_reweighted)
|
| 584 |
+
|
| 585 |
+
test_result = kstest(mean_repeated, mean_reweighted)
|
| 586 |
+
# Should never be negative because -1 has a 0 weight.
|
| 587 |
+
assert np.all(mean_reweighted >= 0)
|
| 588 |
+
# The null-hypothesis (the computed means are identically distributed)
|
| 589 |
+
# cannot be rejected.
|
| 590 |
+
assert test_result.pvalue > 0.05
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def test_resample_stratified():
|
| 594 |
+
# Make sure resample can stratify
|
| 595 |
+
rng = np.random.RandomState(0)
|
| 596 |
+
n_samples = 100
|
| 597 |
+
p = 0.9
|
| 598 |
+
X = rng.normal(size=(n_samples, 1))
|
| 599 |
+
y = rng.binomial(1, p, size=n_samples)
|
| 600 |
+
|
| 601 |
+
_, y_not_stratified = resample(X, y, n_samples=10, random_state=0, stratify=None)
|
| 602 |
+
assert np.all(y_not_stratified == 1)
|
| 603 |
+
|
| 604 |
+
_, y_stratified = resample(X, y, n_samples=10, random_state=0, stratify=y)
|
| 605 |
+
assert not np.all(y_stratified == 1)
|
| 606 |
+
assert np.sum(y_stratified) == 9 # all 1s, one 0
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def test_resample_stratified_replace():
|
| 610 |
+
# Make sure stratified resampling supports the replace parameter
|
| 611 |
+
rng = np.random.RandomState(0)
|
| 612 |
+
n_samples = 100
|
| 613 |
+
X = rng.normal(size=(n_samples, 1))
|
| 614 |
+
y = rng.randint(0, 2, size=n_samples)
|
| 615 |
+
|
| 616 |
+
X_replace, _ = resample(
|
| 617 |
+
X, y, replace=True, n_samples=50, random_state=rng, stratify=y
|
| 618 |
+
)
|
| 619 |
+
X_no_replace, _ = resample(
|
| 620 |
+
X, y, replace=False, n_samples=50, random_state=rng, stratify=y
|
| 621 |
+
)
|
| 622 |
+
assert np.unique(X_replace).shape[0] < 50
|
| 623 |
+
assert np.unique(X_no_replace).shape[0] == 50
|
| 624 |
+
|
| 625 |
+
# make sure n_samples can be greater than X.shape[0] if we sample with
|
| 626 |
+
# replacement
|
| 627 |
+
X_replace, _ = resample(
|
| 628 |
+
X, y, replace=True, n_samples=1000, random_state=rng, stratify=y
|
| 629 |
+
)
|
| 630 |
+
assert X_replace.shape[0] == 1000
|
| 631 |
+
assert np.unique(X_replace).shape[0] == 100
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def test_resample_stratify_2dy():
|
| 635 |
+
# Make sure y can be 2d when stratifying
|
| 636 |
+
rng = np.random.RandomState(0)
|
| 637 |
+
n_samples = 100
|
| 638 |
+
X = rng.normal(size=(n_samples, 1))
|
| 639 |
+
y = rng.randint(0, 2, size=(n_samples, 2))
|
| 640 |
+
X, y = resample(X, y, n_samples=50, random_state=rng, stratify=y)
|
| 641 |
+
assert y.ndim == 2
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def test_notimplementederror():
|
| 645 |
+
with pytest.raises(
|
| 646 |
+
NotImplementedError,
|
| 647 |
+
match="Resampling with sample_weight is only implemented for replace=True.",
|
| 648 |
+
):
|
| 649 |
+
resample([0, 1], [0, 1], sample_weight=[1, 1], replace=False)
|
| 650 |
+
|
| 651 |
+
with pytest.raises(
|
| 652 |
+
NotImplementedError,
|
| 653 |
+
match="Resampling with sample_weight is only implemented for stratify=None",
|
| 654 |
+
):
|
| 655 |
+
resample([0, 1], [0, 1], sample_weight=[1, 1], stratify=[0, 1])
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 659 |
+
def test_resample_stratify_sparse_error(csr_container):
|
| 660 |
+
# resample must be ndarray
|
| 661 |
+
rng = np.random.RandomState(0)
|
| 662 |
+
n_samples = 100
|
| 663 |
+
X = rng.normal(size=(n_samples, 2))
|
| 664 |
+
y = rng.randint(0, 2, size=n_samples)
|
| 665 |
+
stratify = csr_container(y.reshape(-1, 1))
|
| 666 |
+
with pytest.raises(TypeError, match="Sparse data was passed"):
|
| 667 |
+
X, y = resample(X, y, n_samples=50, random_state=rng, stratify=stratify)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def test_shuffle_on_ndim_equals_three():
|
| 671 |
+
def to_tuple(A): # to make the inner arrays hashable
|
| 672 |
+
return tuple(tuple(tuple(C) for C in B) for B in A)
|
| 673 |
+
|
| 674 |
+
A = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # A.shape = (2,2,2)
|
| 675 |
+
S = set(to_tuple(A))
|
| 676 |
+
shuffle(A) # shouldn't raise a ValueError for dim = 3
|
| 677 |
+
assert set(to_tuple(A)) == S
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 681 |
+
def test_shuffle_dont_convert_to_array(csc_container):
|
| 682 |
+
# Check that shuffle does not try to convert to numpy arrays with float
|
| 683 |
+
# dtypes can let any indexable datastructure pass-through.
|
| 684 |
+
a = ["a", "b", "c"]
|
| 685 |
+
b = np.array(["a", "b", "c"], dtype=object)
|
| 686 |
+
c = [1, 2, 3]
|
| 687 |
+
d = MockDataFrame(np.array([["a", 0], ["b", 1], ["c", 2]], dtype=object))
|
| 688 |
+
e = csc_container(np.arange(6).reshape(3, 2))
|
| 689 |
+
a_s, b_s, c_s, d_s, e_s = shuffle(a, b, c, d, e, random_state=0)
|
| 690 |
+
|
| 691 |
+
assert a_s == ["c", "b", "a"]
|
| 692 |
+
assert type(a_s) == list
|
| 693 |
+
|
| 694 |
+
assert_array_equal(b_s, ["c", "b", "a"])
|
| 695 |
+
assert b_s.dtype == object
|
| 696 |
+
|
| 697 |
+
assert c_s == [3, 2, 1]
|
| 698 |
+
assert type(c_s) == list
|
| 699 |
+
|
| 700 |
+
assert_array_equal(d_s, np.array([["c", 2], ["b", 1], ["a", 0]], dtype=object))
|
| 701 |
+
assert type(d_s) == MockDataFrame
|
| 702 |
+
|
| 703 |
+
assert_array_equal(e_s.toarray(), np.array([[4, 5], [2, 3], [0, 1]]))
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_mask.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from sklearn.utils._mask import safe_mask
|
| 4 |
+
from sklearn.utils.fixes import CSR_CONTAINERS
|
| 5 |
+
from sklearn.utils.validation import check_random_state
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 9 |
+
def test_safe_mask(csr_container):
|
| 10 |
+
random_state = check_random_state(0)
|
| 11 |
+
X = random_state.rand(5, 4)
|
| 12 |
+
X_csr = csr_container(X)
|
| 13 |
+
mask = [False, False, True, True, True]
|
| 14 |
+
|
| 15 |
+
mask = safe_mask(X, mask)
|
| 16 |
+
assert X[mask].shape[0] == 3
|
| 17 |
+
|
| 18 |
+
mask = safe_mask(X_csr, mask)
|
| 19 |
+
assert X_csr[mask].shape[0] == 3
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_metaestimators.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from sklearn.utils.metaestimators import available_if
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class AvailableParameterEstimator:
|
| 9 |
+
"""This estimator's `available` parameter toggles the presence of a method"""
|
| 10 |
+
|
| 11 |
+
def __init__(self, available=True, return_value=1):
|
| 12 |
+
self.available = available
|
| 13 |
+
self.return_value = return_value
|
| 14 |
+
|
| 15 |
+
@available_if(lambda est: est.available)
|
| 16 |
+
def available_func(self):
|
| 17 |
+
"""This is a mock available_if function"""
|
| 18 |
+
return self.return_value
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_available_if_docstring():
|
| 22 |
+
assert "This is a mock available_if function" in str(
|
| 23 |
+
AvailableParameterEstimator.__dict__["available_func"].__doc__
|
| 24 |
+
)
|
| 25 |
+
assert "This is a mock available_if function" in str(
|
| 26 |
+
AvailableParameterEstimator.available_func.__doc__
|
| 27 |
+
)
|
| 28 |
+
assert "This is a mock available_if function" in str(
|
| 29 |
+
AvailableParameterEstimator().available_func.__doc__
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_available_if():
|
| 34 |
+
assert hasattr(AvailableParameterEstimator(), "available_func")
|
| 35 |
+
assert not hasattr(AvailableParameterEstimator(available=False), "available_func")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_available_if_unbound_method():
|
| 39 |
+
# This is a non regression test for:
|
| 40 |
+
# https://github.com/scikit-learn/scikit-learn/issues/20614
|
| 41 |
+
# to make sure that decorated functions can be used as an unbound method,
|
| 42 |
+
# for instance when monkeypatching.
|
| 43 |
+
est = AvailableParameterEstimator()
|
| 44 |
+
AvailableParameterEstimator.available_func(est)
|
| 45 |
+
|
| 46 |
+
est = AvailableParameterEstimator(available=False)
|
| 47 |
+
with pytest.raises(
|
| 48 |
+
AttributeError,
|
| 49 |
+
match="This 'AvailableParameterEstimator' has no attribute 'available_func'",
|
| 50 |
+
):
|
| 51 |
+
AvailableParameterEstimator.available_func(est)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_available_if_methods_can_be_pickled():
|
| 55 |
+
"""Check that available_if methods can be pickled.
|
| 56 |
+
|
| 57 |
+
Non-regression test for #21344.
|
| 58 |
+
"""
|
| 59 |
+
return_value = 10
|
| 60 |
+
est = AvailableParameterEstimator(available=True, return_value=return_value)
|
| 61 |
+
pickled_bytes = pickle.dumps(est.available_func)
|
| 62 |
+
unpickled_func = pickle.loads(pickled_bytes)
|
| 63 |
+
assert unpickled_func() == return_value
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_missing.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from sklearn.utils._missing import is_scalar_nan
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.parametrize(
|
| 8 |
+
"value, result",
|
| 9 |
+
[
|
| 10 |
+
(float("nan"), True),
|
| 11 |
+
(np.nan, True),
|
| 12 |
+
(float(np.nan), True),
|
| 13 |
+
(np.float32(np.nan), True),
|
| 14 |
+
(np.float64(np.nan), True),
|
| 15 |
+
(0, False),
|
| 16 |
+
(0.0, False),
|
| 17 |
+
(None, False),
|
| 18 |
+
("", False),
|
| 19 |
+
("nan", False),
|
| 20 |
+
([np.nan], False),
|
| 21 |
+
(9867966753463435747313673, False), # Python int that overflows with C type
|
| 22 |
+
],
|
| 23 |
+
)
|
| 24 |
+
def test_is_scalar_nan(value, result):
|
| 25 |
+
assert is_scalar_nan(value) is result
|
| 26 |
+
# make sure that we are returning a Python bool
|
| 27 |
+
assert isinstance(is_scalar_nan(value), bool)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_mocking.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
from numpy.testing import assert_array_equal
|
| 4 |
+
from scipy import sparse
|
| 5 |
+
|
| 6 |
+
from sklearn.datasets import load_iris
|
| 7 |
+
from sklearn.utils import _safe_indexing, check_array
|
| 8 |
+
from sklearn.utils._mocking import (
|
| 9 |
+
CheckingClassifier,
|
| 10 |
+
_MockEstimatorOnOffPrediction,
|
| 11 |
+
)
|
| 12 |
+
from sklearn.utils._testing import _convert_container
|
| 13 |
+
from sklearn.utils.fixes import CSR_CONTAINERS
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture
|
| 17 |
+
def iris():
|
| 18 |
+
return load_iris(return_X_y=True)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _success(x):
|
| 22 |
+
return True
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _fail(x):
|
| 26 |
+
return False
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@pytest.mark.parametrize(
|
| 30 |
+
"kwargs",
|
| 31 |
+
[
|
| 32 |
+
{},
|
| 33 |
+
{"check_X": _success},
|
| 34 |
+
{"check_y": _success},
|
| 35 |
+
{"check_X": _success, "check_y": _success},
|
| 36 |
+
],
|
| 37 |
+
)
|
| 38 |
+
def test_check_on_fit_success(iris, kwargs):
|
| 39 |
+
X, y = iris
|
| 40 |
+
CheckingClassifier(**kwargs).fit(X, y)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@pytest.mark.parametrize(
|
| 44 |
+
"kwargs",
|
| 45 |
+
[
|
| 46 |
+
{"check_X": _fail},
|
| 47 |
+
{"check_y": _fail},
|
| 48 |
+
{"check_X": _success, "check_y": _fail},
|
| 49 |
+
{"check_X": _fail, "check_y": _success},
|
| 50 |
+
{"check_X": _fail, "check_y": _fail},
|
| 51 |
+
],
|
| 52 |
+
)
|
| 53 |
+
def test_check_on_fit_fail(iris, kwargs):
|
| 54 |
+
X, y = iris
|
| 55 |
+
clf = CheckingClassifier(**kwargs)
|
| 56 |
+
with pytest.raises(AssertionError):
|
| 57 |
+
clf.fit(X, y)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@pytest.mark.parametrize(
|
| 61 |
+
"pred_func", ["predict", "predict_proba", "decision_function", "score"]
|
| 62 |
+
)
|
| 63 |
+
def test_check_X_on_predict_success(iris, pred_func):
|
| 64 |
+
X, y = iris
|
| 65 |
+
clf = CheckingClassifier(check_X=_success).fit(X, y)
|
| 66 |
+
getattr(clf, pred_func)(X)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@pytest.mark.parametrize(
|
| 70 |
+
"pred_func", ["predict", "predict_proba", "decision_function", "score"]
|
| 71 |
+
)
|
| 72 |
+
def test_check_X_on_predict_fail(iris, pred_func):
|
| 73 |
+
X, y = iris
|
| 74 |
+
clf = CheckingClassifier(check_X=_success).fit(X, y)
|
| 75 |
+
clf.set_params(check_X=_fail)
|
| 76 |
+
with pytest.raises(AssertionError):
|
| 77 |
+
getattr(clf, pred_func)(X)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize("input_type", ["list", "array", "sparse", "dataframe"])
|
| 81 |
+
def test_checking_classifier(iris, input_type):
|
| 82 |
+
# Check that the CheckingClassifier outputs what we expect
|
| 83 |
+
X, y = iris
|
| 84 |
+
X = _convert_container(X, input_type)
|
| 85 |
+
clf = CheckingClassifier()
|
| 86 |
+
clf.fit(X, y)
|
| 87 |
+
|
| 88 |
+
assert_array_equal(clf.classes_, np.unique(y))
|
| 89 |
+
assert len(clf.classes_) == 3
|
| 90 |
+
assert clf.n_features_in_ == 4
|
| 91 |
+
|
| 92 |
+
y_pred = clf.predict(X)
|
| 93 |
+
assert all(pred in clf.classes_ for pred in y_pred)
|
| 94 |
+
|
| 95 |
+
assert clf.score(X) == pytest.approx(0)
|
| 96 |
+
clf.set_params(foo_param=10)
|
| 97 |
+
assert clf.fit(X, y).score(X) == pytest.approx(1)
|
| 98 |
+
|
| 99 |
+
y_proba = clf.predict_proba(X)
|
| 100 |
+
assert y_proba.shape == (150, 3)
|
| 101 |
+
assert np.logical_and(y_proba >= 0, y_proba <= 1).all()
|
| 102 |
+
|
| 103 |
+
y_decision = clf.decision_function(X)
|
| 104 |
+
assert y_decision.shape == (150, 3)
|
| 105 |
+
|
| 106 |
+
# check the shape in case of binary classification
|
| 107 |
+
first_2_classes = np.logical_or(y == 0, y == 1)
|
| 108 |
+
X = _safe_indexing(X, first_2_classes)
|
| 109 |
+
y = _safe_indexing(y, first_2_classes)
|
| 110 |
+
clf.fit(X, y)
|
| 111 |
+
|
| 112 |
+
y_proba = clf.predict_proba(X)
|
| 113 |
+
assert y_proba.shape == (100, 2)
|
| 114 |
+
assert np.logical_and(y_proba >= 0, y_proba <= 1).all()
|
| 115 |
+
|
| 116 |
+
y_decision = clf.decision_function(X)
|
| 117 |
+
assert y_decision.shape == (100,)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 121 |
+
def test_checking_classifier_with_params(iris, csr_container):
|
| 122 |
+
X, y = iris
|
| 123 |
+
X_sparse = csr_container(X)
|
| 124 |
+
|
| 125 |
+
clf = CheckingClassifier(check_X=sparse.issparse)
|
| 126 |
+
with pytest.raises(AssertionError):
|
| 127 |
+
clf.fit(X, y)
|
| 128 |
+
clf.fit(X_sparse, y)
|
| 129 |
+
|
| 130 |
+
clf = CheckingClassifier(
|
| 131 |
+
check_X=check_array, check_X_params={"accept_sparse": False}
|
| 132 |
+
)
|
| 133 |
+
clf.fit(X, y)
|
| 134 |
+
with pytest.raises(TypeError, match="Sparse data was passed"):
|
| 135 |
+
clf.fit(X_sparse, y)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def test_checking_classifier_fit_params(iris):
|
| 139 |
+
# check the error raised when the number of samples is not the one expected
|
| 140 |
+
X, y = iris
|
| 141 |
+
clf = CheckingClassifier(expected_sample_weight=True)
|
| 142 |
+
sample_weight = np.ones(len(X) // 2)
|
| 143 |
+
|
| 144 |
+
msg = f"sample_weight.shape == ({len(X) // 2},), expected ({len(X)},)!"
|
| 145 |
+
with pytest.raises(ValueError) as exc:
|
| 146 |
+
clf.fit(X, y, sample_weight=sample_weight)
|
| 147 |
+
assert exc.value.args[0] == msg
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_checking_classifier_missing_fit_params(iris):
|
| 151 |
+
X, y = iris
|
| 152 |
+
clf = CheckingClassifier(expected_sample_weight=True)
|
| 153 |
+
err_msg = "Expected sample_weight to be passed"
|
| 154 |
+
with pytest.raises(AssertionError, match=err_msg):
|
| 155 |
+
clf.fit(X, y)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@pytest.mark.parametrize(
|
| 159 |
+
"methods_to_check",
|
| 160 |
+
[["predict"], ["predict", "predict_proba"]],
|
| 161 |
+
)
|
| 162 |
+
@pytest.mark.parametrize(
|
| 163 |
+
"predict_method", ["predict", "predict_proba", "decision_function", "score"]
|
| 164 |
+
)
|
| 165 |
+
def test_checking_classifier_methods_to_check(iris, methods_to_check, predict_method):
|
| 166 |
+
# check that methods_to_check allows to bypass checks
|
| 167 |
+
X, y = iris
|
| 168 |
+
|
| 169 |
+
clf = CheckingClassifier(
|
| 170 |
+
check_X=sparse.issparse,
|
| 171 |
+
methods_to_check=methods_to_check,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
clf.fit(X, y)
|
| 175 |
+
if predict_method in methods_to_check:
|
| 176 |
+
with pytest.raises(AssertionError):
|
| 177 |
+
getattr(clf, predict_method)(X)
|
| 178 |
+
else:
|
| 179 |
+
getattr(clf, predict_method)(X)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@pytest.mark.parametrize(
|
| 183 |
+
"response_methods",
|
| 184 |
+
[
|
| 185 |
+
["predict"],
|
| 186 |
+
["predict", "predict_proba"],
|
| 187 |
+
["predict", "decision_function"],
|
| 188 |
+
["predict", "predict_proba", "decision_function"],
|
| 189 |
+
],
|
| 190 |
+
)
|
| 191 |
+
def test_mock_estimator_on_off_prediction(iris, response_methods):
|
| 192 |
+
X, y = iris
|
| 193 |
+
estimator = _MockEstimatorOnOffPrediction(response_methods=response_methods)
|
| 194 |
+
|
| 195 |
+
estimator.fit(X, y)
|
| 196 |
+
assert hasattr(estimator, "classes_")
|
| 197 |
+
assert_array_equal(estimator.classes_, np.unique(y))
|
| 198 |
+
|
| 199 |
+
possible_responses = ["predict", "predict_proba", "decision_function"]
|
| 200 |
+
for response in possible_responses:
|
| 201 |
+
if response in response_methods:
|
| 202 |
+
assert hasattr(estimator, response)
|
| 203 |
+
assert getattr(estimator, response)(X) == response
|
| 204 |
+
else:
|
| 205 |
+
assert not hasattr(estimator, response)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_multiclass.py
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
import warnings
|
| 2 |
+
from itertools import product
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
from scipy.sparse import issparse
|
| 7 |
+
|
| 8 |
+
from sklearn import config_context, datasets
|
| 9 |
+
from sklearn.model_selection import ShuffleSplit
|
| 10 |
+
from sklearn.svm import SVC
|
| 11 |
+
from sklearn.utils._array_api import (
|
| 12 |
+
_get_namespace_device_dtype_ids,
|
| 13 |
+
yield_namespace_device_dtype_combinations,
|
| 14 |
+
)
|
| 15 |
+
from sklearn.utils._testing import (
|
| 16 |
+
_array_api_for_tests,
|
| 17 |
+
_convert_container,
|
| 18 |
+
assert_allclose,
|
| 19 |
+
assert_array_almost_equal,
|
| 20 |
+
assert_array_equal,
|
| 21 |
+
)
|
| 22 |
+
from sklearn.utils.estimator_checks import _NotAnArray
|
| 23 |
+
from sklearn.utils.fixes import (
|
| 24 |
+
COO_CONTAINERS,
|
| 25 |
+
CSC_CONTAINERS,
|
| 26 |
+
CSR_CONTAINERS,
|
| 27 |
+
DOK_CONTAINERS,
|
| 28 |
+
LIL_CONTAINERS,
|
| 29 |
+
)
|
| 30 |
+
from sklearn.utils.metaestimators import _safe_split
|
| 31 |
+
from sklearn.utils.multiclass import (
|
| 32 |
+
_ovr_decision_function,
|
| 33 |
+
check_classification_targets,
|
| 34 |
+
class_distribution,
|
| 35 |
+
is_multilabel,
|
| 36 |
+
type_of_target,
|
| 37 |
+
unique_labels,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
multilabel_explicit_zero = np.array([[0, 1], [1, 0]])
|
| 41 |
+
multilabel_explicit_zero[:, 0] = 0
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _generate_sparse(
|
| 45 |
+
data,
|
| 46 |
+
sparse_containers=tuple(
|
| 47 |
+
COO_CONTAINERS
|
| 48 |
+
+ CSC_CONTAINERS
|
| 49 |
+
+ CSR_CONTAINERS
|
| 50 |
+
+ DOK_CONTAINERS
|
| 51 |
+
+ LIL_CONTAINERS
|
| 52 |
+
),
|
| 53 |
+
dtypes=(bool, int, np.int8, np.uint8, float, np.float32),
|
| 54 |
+
):
|
| 55 |
+
return [
|
| 56 |
+
sparse_container(data, dtype=dtype)
|
| 57 |
+
for sparse_container in sparse_containers
|
| 58 |
+
for dtype in dtypes
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
EXAMPLES = {
|
| 63 |
+
"multilabel-indicator": [
|
| 64 |
+
# valid when the data is formatted as sparse or dense, identified
|
| 65 |
+
# by CSR format when the testing takes place
|
| 66 |
+
*_generate_sparse(
|
| 67 |
+
np.random.RandomState(42).randint(2, size=(10, 10)),
|
| 68 |
+
sparse_containers=CSR_CONTAINERS,
|
| 69 |
+
dtypes=(int,),
|
| 70 |
+
),
|
| 71 |
+
[[0, 1], [1, 0]],
|
| 72 |
+
[[0, 1]],
|
| 73 |
+
*_generate_sparse(
|
| 74 |
+
multilabel_explicit_zero, sparse_containers=CSC_CONTAINERS, dtypes=(int,)
|
| 75 |
+
),
|
| 76 |
+
*_generate_sparse([[0, 1], [1, 0]]),
|
| 77 |
+
*_generate_sparse([[0, 0], [0, 0]]),
|
| 78 |
+
*_generate_sparse([[0, 1]]),
|
| 79 |
+
# Only valid when data is dense
|
| 80 |
+
[[-1, 1], [1, -1]],
|
| 81 |
+
np.array([[-1, 1], [1, -1]]),
|
| 82 |
+
np.array([[-3, 3], [3, -3]]),
|
| 83 |
+
_NotAnArray(np.array([[-3, 3], [3, -3]])),
|
| 84 |
+
],
|
| 85 |
+
"multiclass": [
|
| 86 |
+
[1, 0, 2, 2, 1, 4, 2, 4, 4, 4],
|
| 87 |
+
np.array([1, 0, 2]),
|
| 88 |
+
np.array([1, 0, 2], dtype=np.int8),
|
| 89 |
+
np.array([1, 0, 2], dtype=np.uint8),
|
| 90 |
+
np.array([1, 0, 2], dtype=float),
|
| 91 |
+
np.array([1, 0, 2], dtype=np.float32),
|
| 92 |
+
np.array([[1], [0], [2]]),
|
| 93 |
+
_NotAnArray(np.array([1, 0, 2])),
|
| 94 |
+
[0, 1, 2],
|
| 95 |
+
["a", "b", "c"],
|
| 96 |
+
np.array(["a", "b", "c"]),
|
| 97 |
+
np.array(["a", "b", "c"], dtype=object),
|
| 98 |
+
np.array(["a", "b", "c"], dtype=object),
|
| 99 |
+
],
|
| 100 |
+
"multiclass-multioutput": [
|
| 101 |
+
[[1, 0, 2, 2], [1, 4, 2, 4]],
|
| 102 |
+
[["a", "b"], ["c", "d"]],
|
| 103 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]]),
|
| 104 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.int8),
|
| 105 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.uint8),
|
| 106 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=float),
|
| 107 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float32),
|
| 108 |
+
*_generate_sparse(
|
| 109 |
+
[[1, 0, 2, 2], [1, 4, 2, 4]],
|
| 110 |
+
sparse_containers=CSC_CONTAINERS + CSR_CONTAINERS,
|
| 111 |
+
dtypes=(int, np.int8, np.uint8, float, np.float32),
|
| 112 |
+
),
|
| 113 |
+
np.array([["a", "b"], ["c", "d"]]),
|
| 114 |
+
np.array([["a", "b"], ["c", "d"]]),
|
| 115 |
+
np.array([["a", "b"], ["c", "d"]], dtype=object),
|
| 116 |
+
np.array([[1, 0, 2]]),
|
| 117 |
+
_NotAnArray(np.array([[1, 0, 2]])),
|
| 118 |
+
],
|
| 119 |
+
"binary": [
|
| 120 |
+
[0, 1],
|
| 121 |
+
[1, 1],
|
| 122 |
+
[],
|
| 123 |
+
[0],
|
| 124 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1]),
|
| 125 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=bool),
|
| 126 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.int8),
|
| 127 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.uint8),
|
| 128 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=float),
|
| 129 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float32),
|
| 130 |
+
np.array([[0], [1]]),
|
| 131 |
+
_NotAnArray(np.array([[0], [1]])),
|
| 132 |
+
[1, -1],
|
| 133 |
+
[3, 5],
|
| 134 |
+
["a"],
|
| 135 |
+
["a", "b"],
|
| 136 |
+
["abc", "def"],
|
| 137 |
+
np.array(["abc", "def"]),
|
| 138 |
+
["a", "b"],
|
| 139 |
+
np.array(["abc", "def"], dtype=object),
|
| 140 |
+
],
|
| 141 |
+
"continuous": [
|
| 142 |
+
[1e-5],
|
| 143 |
+
[0, 0.5],
|
| 144 |
+
np.array([[0], [0.5]]),
|
| 145 |
+
np.array([[0], [0.5]], dtype=np.float32),
|
| 146 |
+
],
|
| 147 |
+
"continuous-multioutput": [
|
| 148 |
+
np.array([[0, 0.5], [0.5, 0]]),
|
| 149 |
+
np.array([[0, 0.5], [0.5, 0]], dtype=np.float32),
|
| 150 |
+
np.array([[0, 0.5]]),
|
| 151 |
+
*_generate_sparse(
|
| 152 |
+
[[0, 0.5], [0.5, 0]],
|
| 153 |
+
sparse_containers=CSC_CONTAINERS + CSR_CONTAINERS,
|
| 154 |
+
dtypes=(float, np.float32),
|
| 155 |
+
),
|
| 156 |
+
*_generate_sparse(
|
| 157 |
+
[[0, 0.5]],
|
| 158 |
+
sparse_containers=CSC_CONTAINERS + CSR_CONTAINERS,
|
| 159 |
+
dtypes=(float, np.float32),
|
| 160 |
+
),
|
| 161 |
+
],
|
| 162 |
+
"unknown": [
|
| 163 |
+
[[]],
|
| 164 |
+
np.array([[]], dtype=object),
|
| 165 |
+
[()],
|
| 166 |
+
# sequence of sequences that weren't supported even before deprecation
|
| 167 |
+
np.array([np.array([]), np.array([1, 2, 3])], dtype=object),
|
| 168 |
+
[np.array([]), np.array([1, 2, 3])],
|
| 169 |
+
[{1, 2, 3}, {1, 2}],
|
| 170 |
+
[frozenset([1, 2, 3]), frozenset([1, 2])],
|
| 171 |
+
# and also confusable as sequences of sequences
|
| 172 |
+
[{0: "a", 1: "b"}, {0: "a"}],
|
| 173 |
+
# ndim 0
|
| 174 |
+
np.array(0),
|
| 175 |
+
# empty second dimension
|
| 176 |
+
np.array([[], []]),
|
| 177 |
+
# 3d
|
| 178 |
+
np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]),
|
| 179 |
+
],
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
ARRAY_API_EXAMPLES = {
|
| 183 |
+
"multilabel-indicator": [
|
| 184 |
+
np.random.RandomState(42).randint(2, size=(10, 10)),
|
| 185 |
+
[[0, 1], [1, 0]],
|
| 186 |
+
[[0, 1]],
|
| 187 |
+
multilabel_explicit_zero,
|
| 188 |
+
[[0, 0], [0, 0]],
|
| 189 |
+
[[-1, 1], [1, -1]],
|
| 190 |
+
np.array([[-1, 1], [1, -1]]),
|
| 191 |
+
np.array([[-3, 3], [3, -3]]),
|
| 192 |
+
_NotAnArray(np.array([[-3, 3], [3, -3]])),
|
| 193 |
+
],
|
| 194 |
+
"multiclass": [
|
| 195 |
+
[1, 0, 2, 2, 1, 4, 2, 4, 4, 4],
|
| 196 |
+
np.array([1, 0, 2]),
|
| 197 |
+
np.array([1, 0, 2], dtype=np.int8),
|
| 198 |
+
np.array([1, 0, 2], dtype=np.uint8),
|
| 199 |
+
np.array([1, 0, 2], dtype=float),
|
| 200 |
+
np.array([1, 0, 2], dtype=np.float32),
|
| 201 |
+
np.array([[1], [0], [2]]),
|
| 202 |
+
_NotAnArray(np.array([1, 0, 2])),
|
| 203 |
+
[0, 1, 2],
|
| 204 |
+
],
|
| 205 |
+
"multiclass-multioutput": [
|
| 206 |
+
[[1, 0, 2, 2], [1, 4, 2, 4]],
|
| 207 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]]),
|
| 208 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.int8),
|
| 209 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.uint8),
|
| 210 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=float),
|
| 211 |
+
np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float32),
|
| 212 |
+
np.array([[1, 0, 2]]),
|
| 213 |
+
_NotAnArray(np.array([[1, 0, 2]])),
|
| 214 |
+
],
|
| 215 |
+
"binary": [
|
| 216 |
+
[0, 1],
|
| 217 |
+
[1, 1],
|
| 218 |
+
[],
|
| 219 |
+
[0],
|
| 220 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1]),
|
| 221 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=bool),
|
| 222 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.int8),
|
| 223 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.uint8),
|
| 224 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=float),
|
| 225 |
+
np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float32),
|
| 226 |
+
np.array([[0], [1]]),
|
| 227 |
+
_NotAnArray(np.array([[0], [1]])),
|
| 228 |
+
[1, -1],
|
| 229 |
+
[3, 5],
|
| 230 |
+
],
|
| 231 |
+
"continuous": [
|
| 232 |
+
[1e-5],
|
| 233 |
+
[0, 0.5],
|
| 234 |
+
np.array([[0], [0.5]]),
|
| 235 |
+
np.array([[0], [0.5]], dtype=np.float32),
|
| 236 |
+
],
|
| 237 |
+
"continuous-multioutput": [
|
| 238 |
+
np.array([[0, 0.5], [0.5, 0]]),
|
| 239 |
+
np.array([[0, 0.5], [0.5, 0]], dtype=np.float32),
|
| 240 |
+
np.array([[0, 0.5]]),
|
| 241 |
+
],
|
| 242 |
+
"unknown": [
|
| 243 |
+
[[]],
|
| 244 |
+
[()],
|
| 245 |
+
np.array(0),
|
| 246 |
+
np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]),
|
| 247 |
+
],
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
NON_ARRAY_LIKE_EXAMPLES = [
|
| 252 |
+
{1, 2, 3},
|
| 253 |
+
{0: "a", 1: "b"},
|
| 254 |
+
{0: [5], 1: [5]},
|
| 255 |
+
"abc",
|
| 256 |
+
frozenset([1, 2, 3]),
|
| 257 |
+
None,
|
| 258 |
+
]
|
| 259 |
+
|
| 260 |
+
MULTILABEL_SEQUENCES = [
|
| 261 |
+
[[1], [2], [0, 1]],
|
| 262 |
+
[(), (2), (0, 1)],
|
| 263 |
+
np.array([[], [1, 2]], dtype="object"),
|
| 264 |
+
_NotAnArray(np.array([[], [1, 2]], dtype="object")),
|
| 265 |
+
]
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def test_unique_labels():
|
| 269 |
+
# Empty iterable
|
| 270 |
+
with pytest.raises(ValueError):
|
| 271 |
+
unique_labels()
|
| 272 |
+
|
| 273 |
+
# Multiclass problem
|
| 274 |
+
assert_array_equal(unique_labels(range(10)), np.arange(10))
|
| 275 |
+
assert_array_equal(unique_labels(np.arange(10)), np.arange(10))
|
| 276 |
+
assert_array_equal(unique_labels([4, 0, 2]), np.array([0, 2, 4]))
|
| 277 |
+
|
| 278 |
+
# Multilabel indicator
|
| 279 |
+
assert_array_equal(
|
| 280 |
+
unique_labels(np.array([[0, 0, 1], [1, 0, 1], [0, 0, 0]])), np.arange(3)
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
assert_array_equal(unique_labels(np.array([[0, 0, 1], [0, 0, 0]])), np.arange(3))
|
| 284 |
+
|
| 285 |
+
# Several arrays passed
|
| 286 |
+
assert_array_equal(unique_labels([4, 0, 2], range(5)), np.arange(5))
|
| 287 |
+
assert_array_equal(unique_labels((0, 1, 2), (0,), (2, 1)), np.arange(3))
|
| 288 |
+
|
| 289 |
+
# Border line case with binary indicator matrix
|
| 290 |
+
with pytest.raises(ValueError):
|
| 291 |
+
unique_labels([4, 0, 2], np.ones((5, 5)))
|
| 292 |
+
with pytest.raises(ValueError):
|
| 293 |
+
unique_labels(np.ones((5, 4)), np.ones((5, 5)))
|
| 294 |
+
|
| 295 |
+
assert_array_equal(unique_labels(np.ones((4, 5)), np.ones((5, 5))), np.arange(5))
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def test_check_classification_targets_too_many_unique_classes():
|
| 299 |
+
"""Check that we raise a warning when the number of unique classes is greater than
|
| 300 |
+
50% of the number of samples.
|
| 301 |
+
|
| 302 |
+
We need to check that we don't raise if we have less than 20 samples.
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
# Create array of unique labels. This does raise a warning.
|
| 306 |
+
y = np.arange(25)
|
| 307 |
+
msg = r"The number of unique classes is greater than 50% of the number of samples."
|
| 308 |
+
with pytest.warns(UserWarning, match=msg):
|
| 309 |
+
check_classification_targets(y)
|
| 310 |
+
|
| 311 |
+
# less than 20 samples, no warning should be raised
|
| 312 |
+
y = np.arange(10)
|
| 313 |
+
with warnings.catch_warnings():
|
| 314 |
+
warnings.simplefilter("error")
|
| 315 |
+
check_classification_targets(y)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def test_unique_labels_non_specific():
|
| 319 |
+
# Test unique_labels with a variety of collected examples
|
| 320 |
+
|
| 321 |
+
# Smoke test for all supported format
|
| 322 |
+
for format in ["binary", "multiclass", "multilabel-indicator"]:
|
| 323 |
+
for y in EXAMPLES[format]:
|
| 324 |
+
unique_labels(y)
|
| 325 |
+
|
| 326 |
+
# We don't support those format at the moment
|
| 327 |
+
for example in NON_ARRAY_LIKE_EXAMPLES:
|
| 328 |
+
with pytest.raises(ValueError):
|
| 329 |
+
unique_labels(example)
|
| 330 |
+
|
| 331 |
+
for y_type in [
|
| 332 |
+
"unknown",
|
| 333 |
+
"continuous",
|
| 334 |
+
"continuous-multioutput",
|
| 335 |
+
"multiclass-multioutput",
|
| 336 |
+
]:
|
| 337 |
+
for example in EXAMPLES[y_type]:
|
| 338 |
+
with pytest.raises(ValueError):
|
| 339 |
+
unique_labels(example)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def test_unique_labels_mixed_types():
|
| 343 |
+
# Mix with binary or multiclass and multilabel
|
| 344 |
+
mix_clf_format = product(
|
| 345 |
+
EXAMPLES["multilabel-indicator"], EXAMPLES["multiclass"] + EXAMPLES["binary"]
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
for y_multilabel, y_multiclass in mix_clf_format:
|
| 349 |
+
with pytest.raises(ValueError):
|
| 350 |
+
unique_labels(y_multiclass, y_multilabel)
|
| 351 |
+
with pytest.raises(ValueError):
|
| 352 |
+
unique_labels(y_multilabel, y_multiclass)
|
| 353 |
+
|
| 354 |
+
with pytest.raises(ValueError):
|
| 355 |
+
unique_labels([[1, 2]], [["a", "d"]])
|
| 356 |
+
|
| 357 |
+
with pytest.raises(ValueError):
|
| 358 |
+
unique_labels(["1", 2])
|
| 359 |
+
|
| 360 |
+
with pytest.raises(ValueError):
|
| 361 |
+
unique_labels([["1", 2], [1, 3]])
|
| 362 |
+
|
| 363 |
+
with pytest.raises(ValueError):
|
| 364 |
+
unique_labels([["1", "2"], [2, 3]])
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def test_is_multilabel():
|
| 368 |
+
for group, group_examples in EXAMPLES.items():
|
| 369 |
+
dense_exp = group == "multilabel-indicator"
|
| 370 |
+
|
| 371 |
+
for example in group_examples:
|
| 372 |
+
# Only mark explicitly defined sparse examples as valid sparse
|
| 373 |
+
# multilabel-indicators
|
| 374 |
+
sparse_exp = dense_exp and issparse(example)
|
| 375 |
+
|
| 376 |
+
if issparse(example) or (
|
| 377 |
+
hasattr(example, "__array__")
|
| 378 |
+
and np.asarray(example).ndim == 2
|
| 379 |
+
and np.asarray(example).dtype.kind in "biuf"
|
| 380 |
+
and np.asarray(example).shape[1] > 0
|
| 381 |
+
):
|
| 382 |
+
examples_sparse = [
|
| 383 |
+
sparse_container(example)
|
| 384 |
+
for sparse_container in (
|
| 385 |
+
COO_CONTAINERS
|
| 386 |
+
+ CSC_CONTAINERS
|
| 387 |
+
+ CSR_CONTAINERS
|
| 388 |
+
+ DOK_CONTAINERS
|
| 389 |
+
+ LIL_CONTAINERS
|
| 390 |
+
)
|
| 391 |
+
]
|
| 392 |
+
for exmpl_sparse in examples_sparse:
|
| 393 |
+
assert sparse_exp == is_multilabel(exmpl_sparse), (
|
| 394 |
+
f"is_multilabel({exmpl_sparse!r}) should be {sparse_exp}"
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
# Densify sparse examples before testing
|
| 398 |
+
if issparse(example):
|
| 399 |
+
example = example.toarray()
|
| 400 |
+
|
| 401 |
+
assert dense_exp == is_multilabel(example), (
|
| 402 |
+
f"is_multilabel({example!r}) should be {dense_exp}"
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
@pytest.mark.parametrize(
|
| 407 |
+
"array_namespace, device, dtype_name",
|
| 408 |
+
yield_namespace_device_dtype_combinations(),
|
| 409 |
+
ids=_get_namespace_device_dtype_ids,
|
| 410 |
+
)
|
| 411 |
+
def test_is_multilabel_array_api_compliance(array_namespace, device, dtype_name):
|
| 412 |
+
xp = _array_api_for_tests(array_namespace, device)
|
| 413 |
+
|
| 414 |
+
for group, group_examples in ARRAY_API_EXAMPLES.items():
|
| 415 |
+
dense_exp = group == "multilabel-indicator"
|
| 416 |
+
for example in group_examples:
|
| 417 |
+
if np.asarray(example).dtype.kind == "f":
|
| 418 |
+
example = np.asarray(example, dtype=dtype_name)
|
| 419 |
+
else:
|
| 420 |
+
example = np.asarray(example)
|
| 421 |
+
example = xp.asarray(example, device=device)
|
| 422 |
+
|
| 423 |
+
with config_context(array_api_dispatch=True):
|
| 424 |
+
assert dense_exp == is_multilabel(example), (
|
| 425 |
+
f"is_multilabel({example!r}) should be {dense_exp}"
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def test_check_classification_targets():
|
| 430 |
+
for y_type in EXAMPLES.keys():
|
| 431 |
+
if y_type in ["unknown", "continuous", "continuous-multioutput"]:
|
| 432 |
+
for example in EXAMPLES[y_type]:
|
| 433 |
+
msg = "Unknown label type: "
|
| 434 |
+
with pytest.raises(ValueError, match=msg):
|
| 435 |
+
check_classification_targets(example)
|
| 436 |
+
else:
|
| 437 |
+
for example in EXAMPLES[y_type]:
|
| 438 |
+
check_classification_targets(example)
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def test_type_of_target():
|
| 442 |
+
for group, group_examples in EXAMPLES.items():
|
| 443 |
+
for example in group_examples:
|
| 444 |
+
assert type_of_target(example) == group, (
|
| 445 |
+
"type_of_target(%r) should be %r, got %r"
|
| 446 |
+
% (
|
| 447 |
+
example,
|
| 448 |
+
group,
|
| 449 |
+
type_of_target(example),
|
| 450 |
+
)
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
for example in NON_ARRAY_LIKE_EXAMPLES:
|
| 454 |
+
msg_regex = r"Expected array-like \(array or non-string sequence\).*"
|
| 455 |
+
with pytest.raises(ValueError, match=msg_regex):
|
| 456 |
+
type_of_target(example)
|
| 457 |
+
|
| 458 |
+
for example in MULTILABEL_SEQUENCES:
|
| 459 |
+
msg = (
|
| 460 |
+
"You appear to be using a legacy multi-label data "
|
| 461 |
+
"representation. Sequence of sequences are no longer supported;"
|
| 462 |
+
" use a binary array or sparse matrix instead."
|
| 463 |
+
)
|
| 464 |
+
with pytest.raises(ValueError, match=msg):
|
| 465 |
+
type_of_target(example)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def test_type_of_target_pandas_sparse():
|
| 469 |
+
pd = pytest.importorskip("pandas")
|
| 470 |
+
|
| 471 |
+
y = pd.arrays.SparseArray([1, np.nan, np.nan, 1, np.nan])
|
| 472 |
+
msg = "y cannot be class 'SparseSeries' or 'SparseArray'"
|
| 473 |
+
with pytest.raises(ValueError, match=msg):
|
| 474 |
+
type_of_target(y)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def test_type_of_target_pandas_nullable():
|
| 478 |
+
"""Check that type_of_target works with pandas nullable dtypes."""
|
| 479 |
+
pd = pytest.importorskip("pandas")
|
| 480 |
+
|
| 481 |
+
for dtype in ["Int32", "Float32"]:
|
| 482 |
+
y_true = pd.Series([1, 0, 2, 3, 4], dtype=dtype)
|
| 483 |
+
assert type_of_target(y_true) == "multiclass"
|
| 484 |
+
|
| 485 |
+
y_true = pd.Series([1, 0, 1, 0], dtype=dtype)
|
| 486 |
+
assert type_of_target(y_true) == "binary"
|
| 487 |
+
|
| 488 |
+
y_true = pd.DataFrame([[1.4, 3.1], [3.1, 1.4]], dtype="Float32")
|
| 489 |
+
assert type_of_target(y_true) == "continuous-multioutput"
|
| 490 |
+
|
| 491 |
+
y_true = pd.DataFrame([[0, 1], [1, 1]], dtype="Int32")
|
| 492 |
+
assert type_of_target(y_true) == "multilabel-indicator"
|
| 493 |
+
|
| 494 |
+
y_true = pd.DataFrame([[1, 2], [3, 1]], dtype="Int32")
|
| 495 |
+
assert type_of_target(y_true) == "multiclass-multioutput"
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"])
|
| 499 |
+
def test_unique_labels_pandas_nullable(dtype):
|
| 500 |
+
"""Checks that unique_labels work with pandas nullable dtypes.
|
| 501 |
+
|
| 502 |
+
Non-regression test for gh-25634.
|
| 503 |
+
"""
|
| 504 |
+
pd = pytest.importorskip("pandas")
|
| 505 |
+
|
| 506 |
+
y_true = pd.Series([1, 0, 0, 1, 0, 1, 1, 0, 1], dtype=dtype)
|
| 507 |
+
y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1], dtype="int64")
|
| 508 |
+
|
| 509 |
+
labels = unique_labels(y_true, y_predicted)
|
| 510 |
+
assert_array_equal(labels, [0, 1])
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 514 |
+
def test_class_distribution(csc_container):
|
| 515 |
+
y = np.array(
|
| 516 |
+
[
|
| 517 |
+
[1, 0, 0, 1],
|
| 518 |
+
[2, 2, 0, 1],
|
| 519 |
+
[1, 3, 0, 1],
|
| 520 |
+
[4, 2, 0, 1],
|
| 521 |
+
[2, 0, 0, 1],
|
| 522 |
+
[1, 3, 0, 1],
|
| 523 |
+
]
|
| 524 |
+
)
|
| 525 |
+
# Define the sparse matrix with a mix of implicit and explicit zeros
|
| 526 |
+
data = np.array([1, 2, 1, 4, 2, 1, 0, 2, 3, 2, 3, 1, 1, 1, 1, 1, 1])
|
| 527 |
+
indices = np.array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 5, 0, 1, 2, 3, 4, 5])
|
| 528 |
+
indptr = np.array([0, 6, 11, 11, 17])
|
| 529 |
+
y_sp = csc_container((data, indices, indptr), shape=(6, 4))
|
| 530 |
+
|
| 531 |
+
classes, n_classes, class_prior = class_distribution(y)
|
| 532 |
+
classes_sp, n_classes_sp, class_prior_sp = class_distribution(y_sp)
|
| 533 |
+
classes_expected = [[1, 2, 4], [0, 2, 3], [0], [1]]
|
| 534 |
+
n_classes_expected = [3, 3, 1, 1]
|
| 535 |
+
class_prior_expected = [[3 / 6, 2 / 6, 1 / 6], [1 / 3, 1 / 3, 1 / 3], [1.0], [1.0]]
|
| 536 |
+
|
| 537 |
+
for k in range(y.shape[1]):
|
| 538 |
+
assert_array_almost_equal(classes[k], classes_expected[k])
|
| 539 |
+
assert_array_almost_equal(n_classes[k], n_classes_expected[k])
|
| 540 |
+
assert_array_almost_equal(class_prior[k], class_prior_expected[k])
|
| 541 |
+
|
| 542 |
+
assert_array_almost_equal(classes_sp[k], classes_expected[k])
|
| 543 |
+
assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k])
|
| 544 |
+
assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k])
|
| 545 |
+
|
| 546 |
+
# Test again with explicit sample weights
|
| 547 |
+
(classes, n_classes, class_prior) = class_distribution(
|
| 548 |
+
y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0]
|
| 549 |
+
)
|
| 550 |
+
(classes_sp, n_classes_sp, class_prior_sp) = class_distribution(
|
| 551 |
+
y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0]
|
| 552 |
+
)
|
| 553 |
+
class_prior_expected = [[4 / 9, 3 / 9, 2 / 9], [2 / 9, 4 / 9, 3 / 9], [1.0], [1.0]]
|
| 554 |
+
|
| 555 |
+
for k in range(y.shape[1]):
|
| 556 |
+
assert_array_almost_equal(classes[k], classes_expected[k])
|
| 557 |
+
assert_array_almost_equal(n_classes[k], n_classes_expected[k])
|
| 558 |
+
assert_array_almost_equal(class_prior[k], class_prior_expected[k])
|
| 559 |
+
|
| 560 |
+
assert_array_almost_equal(classes_sp[k], classes_expected[k])
|
| 561 |
+
assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k])
|
| 562 |
+
assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k])
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def test_safe_split_with_precomputed_kernel():
|
| 566 |
+
clf = SVC()
|
| 567 |
+
clfp = SVC(kernel="precomputed")
|
| 568 |
+
|
| 569 |
+
iris = datasets.load_iris()
|
| 570 |
+
X, y = iris.data, iris.target
|
| 571 |
+
K = np.dot(X, X.T)
|
| 572 |
+
|
| 573 |
+
cv = ShuffleSplit(test_size=0.25, random_state=0)
|
| 574 |
+
train, test = next(iter(cv.split(X)))
|
| 575 |
+
|
| 576 |
+
X_train, y_train = _safe_split(clf, X, y, train)
|
| 577 |
+
K_train, y_train2 = _safe_split(clfp, K, y, train)
|
| 578 |
+
assert_array_almost_equal(K_train, np.dot(X_train, X_train.T))
|
| 579 |
+
assert_array_almost_equal(y_train, y_train2)
|
| 580 |
+
|
| 581 |
+
X_test, y_test = _safe_split(clf, X, y, test, train)
|
| 582 |
+
K_test, y_test2 = _safe_split(clfp, K, y, test, train)
|
| 583 |
+
assert_array_almost_equal(K_test, np.dot(X_test, X_train.T))
|
| 584 |
+
assert_array_almost_equal(y_test, y_test2)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def test_ovr_decision_function():
|
| 588 |
+
# test properties for ovr decision function
|
| 589 |
+
|
| 590 |
+
predictions = np.array([[0, 1, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]])
|
| 591 |
+
|
| 592 |
+
confidences = np.array(
|
| 593 |
+
[[-1e16, 0, -1e16], [1.0, 2.0, -3.0], [-5.0, 2.0, 5.0], [-0.5, 0.2, 0.5]]
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
n_classes = 3
|
| 597 |
+
|
| 598 |
+
dec_values = _ovr_decision_function(predictions, confidences, n_classes)
|
| 599 |
+
|
| 600 |
+
# check that the decision values are within 0.5 range of the votes
|
| 601 |
+
votes = np.array([[1, 0, 2], [1, 1, 1], [1, 0, 2], [1, 0, 2]])
|
| 602 |
+
|
| 603 |
+
assert_allclose(votes, dec_values, atol=0.5)
|
| 604 |
+
|
| 605 |
+
# check that the prediction are what we expect
|
| 606 |
+
# highest vote or highest confidence if there is a tie.
|
| 607 |
+
# for the second sample we have a tie (should be won by 1)
|
| 608 |
+
expected_prediction = np.array([2, 1, 2, 2])
|
| 609 |
+
assert_array_equal(np.argmax(dec_values, axis=1), expected_prediction)
|
| 610 |
+
|
| 611 |
+
# third and fourth sample have the same vote but third sample
|
| 612 |
+
# has higher confidence, this should reflect on the decision values
|
| 613 |
+
assert dec_values[2, 2] > dec_values[3, 2]
|
| 614 |
+
|
| 615 |
+
# assert subset invariance.
|
| 616 |
+
dec_values_one = [
|
| 617 |
+
_ovr_decision_function(
|
| 618 |
+
np.array([predictions[i]]), np.array([confidences[i]]), n_classes
|
| 619 |
+
)[0]
|
| 620 |
+
for i in range(4)
|
| 621 |
+
]
|
| 622 |
+
|
| 623 |
+
assert_allclose(dec_values, dec_values_one, atol=1e-6)
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
@pytest.mark.parametrize("input_type", ["list", "array"])
|
| 627 |
+
def test_labels_in_bytes_format_error(input_type):
|
| 628 |
+
# check that we raise an error with bytes encoded labels
|
| 629 |
+
# non-regression test for:
|
| 630 |
+
# https://github.com/scikit-learn/scikit-learn/issues/16980
|
| 631 |
+
target = _convert_container([b"a", b"b"], input_type)
|
| 632 |
+
err_msg = "Support for labels represented as bytes is not supported"
|
| 633 |
+
with pytest.raises(TypeError, match=err_msg):
|
| 634 |
+
type_of_target(target)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_murmurhash.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: The scikit-learn developers
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy.testing import assert_array_almost_equal, assert_array_equal
|
| 6 |
+
|
| 7 |
+
from sklearn.utils.murmurhash import murmurhash3_32
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_mmhash3_int():
|
| 11 |
+
assert murmurhash3_32(3) == 847579505
|
| 12 |
+
assert murmurhash3_32(3, seed=0) == 847579505
|
| 13 |
+
assert murmurhash3_32(3, seed=42) == -1823081949
|
| 14 |
+
|
| 15 |
+
assert murmurhash3_32(3, positive=False) == 847579505
|
| 16 |
+
assert murmurhash3_32(3, seed=0, positive=False) == 847579505
|
| 17 |
+
assert murmurhash3_32(3, seed=42, positive=False) == -1823081949
|
| 18 |
+
|
| 19 |
+
assert murmurhash3_32(3, positive=True) == 847579505
|
| 20 |
+
assert murmurhash3_32(3, seed=0, positive=True) == 847579505
|
| 21 |
+
assert murmurhash3_32(3, seed=42, positive=True) == 2471885347
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_mmhash3_int_array():
|
| 25 |
+
rng = np.random.RandomState(42)
|
| 26 |
+
keys = rng.randint(-5342534, 345345, size=3 * 2 * 1).astype(np.int32)
|
| 27 |
+
keys = keys.reshape((3, 2, 1))
|
| 28 |
+
|
| 29 |
+
for seed in [0, 42]:
|
| 30 |
+
expected = np.array([murmurhash3_32(int(k), seed) for k in keys.flat])
|
| 31 |
+
expected = expected.reshape(keys.shape)
|
| 32 |
+
assert_array_equal(murmurhash3_32(keys, seed), expected)
|
| 33 |
+
|
| 34 |
+
for seed in [0, 42]:
|
| 35 |
+
expected = np.array([murmurhash3_32(k, seed, positive=True) for k in keys.flat])
|
| 36 |
+
expected = expected.reshape(keys.shape)
|
| 37 |
+
assert_array_equal(murmurhash3_32(keys, seed, positive=True), expected)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_mmhash3_bytes():
|
| 41 |
+
assert murmurhash3_32(b"foo", 0) == -156908512
|
| 42 |
+
assert murmurhash3_32(b"foo", 42) == -1322301282
|
| 43 |
+
|
| 44 |
+
assert murmurhash3_32(b"foo", 0, positive=True) == 4138058784
|
| 45 |
+
assert murmurhash3_32(b"foo", 42, positive=True) == 2972666014
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_mmhash3_unicode():
|
| 49 |
+
assert murmurhash3_32("foo", 0) == -156908512
|
| 50 |
+
assert murmurhash3_32("foo", 42) == -1322301282
|
| 51 |
+
|
| 52 |
+
assert murmurhash3_32("foo", 0, positive=True) == 4138058784
|
| 53 |
+
assert murmurhash3_32("foo", 42, positive=True) == 2972666014
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_no_collision_on_byte_range():
|
| 57 |
+
previous_hashes = set()
|
| 58 |
+
for i in range(100):
|
| 59 |
+
h = murmurhash3_32(" " * i, 0)
|
| 60 |
+
assert h not in previous_hashes, "Found collision on growing empty string"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_uniform_distribution():
|
| 64 |
+
n_bins, n_samples = 10, 100000
|
| 65 |
+
bins = np.zeros(n_bins, dtype=np.float64)
|
| 66 |
+
|
| 67 |
+
for i in range(n_samples):
|
| 68 |
+
bins[murmurhash3_32(i, positive=True) % n_bins] += 1
|
| 69 |
+
|
| 70 |
+
means = bins / n_samples
|
| 71 |
+
expected = np.full(n_bins, 1.0 / n_bins)
|
| 72 |
+
|
| 73 |
+
assert_array_almost_equal(means / expected, np.ones(n_bins), 2)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_optimize.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
from scipy.optimize import fmin_ncg
|
| 6 |
+
|
| 7 |
+
from sklearn.exceptions import ConvergenceWarning
|
| 8 |
+
from sklearn.utils._bunch import Bunch
|
| 9 |
+
from sklearn.utils._testing import assert_allclose
|
| 10 |
+
from sklearn.utils.optimize import _check_optimize_result, _newton_cg
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_newton_cg(global_random_seed):
|
| 14 |
+
# Test that newton_cg gives same result as scipy's fmin_ncg
|
| 15 |
+
|
| 16 |
+
rng = np.random.RandomState(global_random_seed)
|
| 17 |
+
A = rng.normal(size=(10, 10))
|
| 18 |
+
x0 = np.ones(10)
|
| 19 |
+
|
| 20 |
+
def func(x):
|
| 21 |
+
Ax = A.dot(x)
|
| 22 |
+
return 0.5 * (Ax).dot(Ax)
|
| 23 |
+
|
| 24 |
+
def grad(x):
|
| 25 |
+
return A.T.dot(A.dot(x))
|
| 26 |
+
|
| 27 |
+
def hess(x, p):
|
| 28 |
+
return p.dot(A.T.dot(A.dot(x.all())))
|
| 29 |
+
|
| 30 |
+
def grad_hess(x):
|
| 31 |
+
return grad(x), lambda x: A.T.dot(A.dot(x))
|
| 32 |
+
|
| 33 |
+
# func is a definite positive quadratic form, so the minimum is at x = 0
|
| 34 |
+
# hence the use of absolute tolerance.
|
| 35 |
+
assert np.all(np.abs(_newton_cg(grad_hess, func, grad, x0, tol=1e-10)[0]) <= 1e-7)
|
| 36 |
+
assert_allclose(
|
| 37 |
+
_newton_cg(grad_hess, func, grad, x0, tol=1e-7)[0],
|
| 38 |
+
fmin_ncg(f=func, x0=x0, fprime=grad, fhess_p=hess),
|
| 39 |
+
atol=1e-5,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@pytest.mark.parametrize("verbose", [0, 1, 2])
|
| 44 |
+
def test_newton_cg_verbosity(capsys, verbose):
|
| 45 |
+
"""Test the std output of verbose newton_cg solver."""
|
| 46 |
+
A = np.eye(2)
|
| 47 |
+
b = np.array([1, 2], dtype=float)
|
| 48 |
+
|
| 49 |
+
_newton_cg(
|
| 50 |
+
grad_hess=lambda x: (A @ x - b, lambda z: A @ z),
|
| 51 |
+
func=lambda x: 0.5 * x @ A @ x - b @ x,
|
| 52 |
+
grad=lambda x: A @ x - b,
|
| 53 |
+
x0=np.zeros(A.shape[0]),
|
| 54 |
+
verbose=verbose,
|
| 55 |
+
) # returns array([1., 2])
|
| 56 |
+
captured = capsys.readouterr()
|
| 57 |
+
|
| 58 |
+
if verbose == 0:
|
| 59 |
+
assert captured.out == ""
|
| 60 |
+
else:
|
| 61 |
+
msg = [
|
| 62 |
+
"Newton-CG iter = 1",
|
| 63 |
+
"Check Convergence",
|
| 64 |
+
"max |gradient|",
|
| 65 |
+
"Solver did converge at loss = ",
|
| 66 |
+
]
|
| 67 |
+
for m in msg:
|
| 68 |
+
assert m in captured.out
|
| 69 |
+
|
| 70 |
+
if verbose >= 2:
|
| 71 |
+
msg = [
|
| 72 |
+
"Inner CG solver iteration 1 stopped with",
|
| 73 |
+
"sum(|residuals|) <= tol",
|
| 74 |
+
"Line Search",
|
| 75 |
+
"try line search wolfe1",
|
| 76 |
+
"wolfe1 line search was successful",
|
| 77 |
+
]
|
| 78 |
+
for m in msg:
|
| 79 |
+
assert m in captured.out
|
| 80 |
+
|
| 81 |
+
if verbose >= 2:
|
| 82 |
+
# Set up a badly scaled singular Hessian with a completely wrong starting
|
| 83 |
+
# position. This should trigger 2nd line search check
|
| 84 |
+
A = np.array([[1.0, 2], [2, 4]]) * 1e30 # collinear columns
|
| 85 |
+
b = np.array([1.0, 2.0])
|
| 86 |
+
# Note that scipy.optimize._linesearch LineSearchWarning inherits from
|
| 87 |
+
# RuntimeWarning, but we do not want to import from non public APIs.
|
| 88 |
+
with pytest.warns(RuntimeWarning):
|
| 89 |
+
_newton_cg(
|
| 90 |
+
grad_hess=lambda x: (A @ x - b, lambda z: A @ z),
|
| 91 |
+
func=lambda x: 0.5 * x @ A @ x - b @ x,
|
| 92 |
+
grad=lambda x: A @ x - b,
|
| 93 |
+
x0=np.array([-2.0, 1]), # null space of hessian
|
| 94 |
+
verbose=verbose,
|
| 95 |
+
)
|
| 96 |
+
captured = capsys.readouterr()
|
| 97 |
+
msg = [
|
| 98 |
+
"wolfe1 line search was not successful",
|
| 99 |
+
"check loss |improvement| <= eps * |loss_old|:",
|
| 100 |
+
"check sum(|gradient|) < sum(|gradient_old|):",
|
| 101 |
+
"last resort: try line search wolfe2",
|
| 102 |
+
]
|
| 103 |
+
for m in msg:
|
| 104 |
+
assert m in captured.out
|
| 105 |
+
|
| 106 |
+
# Set up a badly conditioned Hessian that leads to tiny curvature.
|
| 107 |
+
# X.T @ X have singular values array([1.00000400e+01, 1.00008192e-11])
|
| 108 |
+
A = np.array([[1.0, 2], [1, 2 + 1e-15]])
|
| 109 |
+
b = np.array([-2.0, 1])
|
| 110 |
+
with pytest.warns(ConvergenceWarning):
|
| 111 |
+
_newton_cg(
|
| 112 |
+
grad_hess=lambda x: (A @ x - b, lambda z: A @ z),
|
| 113 |
+
func=lambda x: 0.5 * x @ A @ x - b @ x,
|
| 114 |
+
grad=lambda x: A @ x - b,
|
| 115 |
+
x0=b,
|
| 116 |
+
verbose=verbose,
|
| 117 |
+
maxiter=2,
|
| 118 |
+
)
|
| 119 |
+
captured = capsys.readouterr()
|
| 120 |
+
msg = [
|
| 121 |
+
"tiny_|p| = eps * ||p||^2",
|
| 122 |
+
]
|
| 123 |
+
for m in msg:
|
| 124 |
+
assert m in captured.out
|
| 125 |
+
|
| 126 |
+
# Test for a case with negative Hessian.
|
| 127 |
+
# We do not trigger "Inner CG solver iteration {i} stopped with negative
|
| 128 |
+
# curvature", but that is very hard to trigger.
|
| 129 |
+
A = np.eye(2)
|
| 130 |
+
b = np.array([-2.0, 1])
|
| 131 |
+
with pytest.warns(RuntimeWarning):
|
| 132 |
+
_newton_cg(
|
| 133 |
+
# Note the wrong sign in the hessian product.
|
| 134 |
+
grad_hess=lambda x: (A @ x - b, lambda z: -A @ z),
|
| 135 |
+
func=lambda x: 0.5 * x @ A @ x - b @ x,
|
| 136 |
+
grad=lambda x: A @ x - b,
|
| 137 |
+
x0=np.array([1.0, 1.0]),
|
| 138 |
+
verbose=verbose,
|
| 139 |
+
maxiter=3,
|
| 140 |
+
)
|
| 141 |
+
captured = capsys.readouterr()
|
| 142 |
+
msg = [
|
| 143 |
+
"Inner CG solver iteration 0 fell back to steepest descent",
|
| 144 |
+
]
|
| 145 |
+
for m in msg:
|
| 146 |
+
assert m in captured.out
|
| 147 |
+
|
| 148 |
+
A = np.diag([1e-3, 1, 1e3])
|
| 149 |
+
b = np.array([-2.0, 1, 2.0])
|
| 150 |
+
with pytest.warns(ConvergenceWarning):
|
| 151 |
+
_newton_cg(
|
| 152 |
+
grad_hess=lambda x: (A @ x - b, lambda z: A @ z),
|
| 153 |
+
func=lambda x: 0.5 * x @ A @ x - b @ x,
|
| 154 |
+
grad=lambda x: A @ x - b,
|
| 155 |
+
x0=np.ones_like(b),
|
| 156 |
+
verbose=verbose,
|
| 157 |
+
maxiter=2,
|
| 158 |
+
maxinner=1,
|
| 159 |
+
)
|
| 160 |
+
captured = capsys.readouterr()
|
| 161 |
+
msg = [
|
| 162 |
+
"Inner CG solver stopped reaching maxiter=1",
|
| 163 |
+
]
|
| 164 |
+
for m in msg:
|
| 165 |
+
assert m in captured.out
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_check_optimize():
|
| 169 |
+
# Mock some lbfgs output using a Bunch instance:
|
| 170 |
+
result = Bunch()
|
| 171 |
+
|
| 172 |
+
# First case: no warnings
|
| 173 |
+
result.nit = 1
|
| 174 |
+
result.status = 0
|
| 175 |
+
result.message = "OK"
|
| 176 |
+
|
| 177 |
+
with warnings.catch_warnings():
|
| 178 |
+
warnings.simplefilter("error")
|
| 179 |
+
_check_optimize_result("lbfgs", result)
|
| 180 |
+
|
| 181 |
+
# Second case: warning about implicit `max_iter`: do not recommend the user
|
| 182 |
+
# to increase `max_iter` this is not a user settable parameter.
|
| 183 |
+
result.status = 1
|
| 184 |
+
result.message = "STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT"
|
| 185 |
+
with pytest.warns(ConvergenceWarning) as record:
|
| 186 |
+
_check_optimize_result("lbfgs", result)
|
| 187 |
+
|
| 188 |
+
assert len(record) == 1
|
| 189 |
+
warn_msg = record[0].message.args[0]
|
| 190 |
+
assert "lbfgs failed to converge after 1 iteration(s)" in warn_msg
|
| 191 |
+
assert result.message in warn_msg
|
| 192 |
+
assert "Increase the number of iterations" not in warn_msg
|
| 193 |
+
assert "scale the data" in warn_msg
|
| 194 |
+
|
| 195 |
+
# Third case: warning about explicit `max_iter`: recommend user to increase
|
| 196 |
+
# `max_iter`.
|
| 197 |
+
with pytest.warns(ConvergenceWarning) as record:
|
| 198 |
+
_check_optimize_result("lbfgs", result, max_iter=1)
|
| 199 |
+
|
| 200 |
+
assert len(record) == 1
|
| 201 |
+
warn_msg = record[0].message.args[0]
|
| 202 |
+
assert "lbfgs failed to converge after 1 iteration(s)" in warn_msg
|
| 203 |
+
assert result.message in warn_msg
|
| 204 |
+
assert "Increase the number of iterations" in warn_msg
|
| 205 |
+
assert "scale the data" in warn_msg
|
| 206 |
+
|
| 207 |
+
# Fourth case: other convergence problem before reaching `max_iter`: do not
|
| 208 |
+
# recommend increasing `max_iter`.
|
| 209 |
+
result.nit = 2
|
| 210 |
+
result.status = 2
|
| 211 |
+
result.message = "ABNORMAL"
|
| 212 |
+
with pytest.warns(ConvergenceWarning) as record:
|
| 213 |
+
_check_optimize_result("lbfgs", result, max_iter=10)
|
| 214 |
+
|
| 215 |
+
assert len(record) == 1
|
| 216 |
+
warn_msg = record[0].message.args[0]
|
| 217 |
+
assert "lbfgs failed to converge after 2 iteration(s)" in warn_msg
|
| 218 |
+
assert result.message in warn_msg
|
| 219 |
+
assert "Increase the number of iterations" not in warn_msg
|
| 220 |
+
assert "scale the data" in warn_msg
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import re
|
| 3 |
+
import time
|
| 4 |
+
import warnings
|
| 5 |
+
|
| 6 |
+
import joblib
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pytest
|
| 9 |
+
from numpy.testing import assert_array_equal
|
| 10 |
+
|
| 11 |
+
from sklearn import config_context, get_config
|
| 12 |
+
from sklearn.compose import make_column_transformer
|
| 13 |
+
from sklearn.datasets import load_iris
|
| 14 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 15 |
+
from sklearn.exceptions import ConvergenceWarning
|
| 16 |
+
from sklearn.model_selection import GridSearchCV
|
| 17 |
+
from sklearn.pipeline import make_pipeline
|
| 18 |
+
from sklearn.preprocessing import StandardScaler
|
| 19 |
+
from sklearn.utils.fixes import _IS_WASM
|
| 20 |
+
from sklearn.utils.parallel import Parallel, delayed
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_working_memory():
|
| 24 |
+
return get_config()["working_memory"]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.mark.parametrize("n_jobs", [1, 2])
|
| 28 |
+
@pytest.mark.parametrize("backend", ["loky", "threading", "multiprocessing"])
|
| 29 |
+
def test_configuration_passes_through_to_joblib(n_jobs, backend):
|
| 30 |
+
# Tests that the global global configuration is passed to joblib jobs
|
| 31 |
+
|
| 32 |
+
with config_context(working_memory=123):
|
| 33 |
+
results = Parallel(n_jobs=n_jobs, backend=backend)(
|
| 34 |
+
delayed(get_working_memory)() for _ in range(2)
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
assert_array_equal(results, [123] * 2)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_parallel_delayed_warnings():
|
| 41 |
+
"""Informative warnings should be raised when mixing sklearn and joblib API"""
|
| 42 |
+
# We should issue a warning when one wants to use sklearn.utils.fixes.Parallel
|
| 43 |
+
# with joblib.delayed. The config will not be propagated to the workers.
|
| 44 |
+
warn_msg = "`sklearn.utils.parallel.Parallel` needs to be used in conjunction"
|
| 45 |
+
with pytest.warns(UserWarning, match=warn_msg) as records:
|
| 46 |
+
Parallel()(joblib.delayed(time.sleep)(0) for _ in range(10))
|
| 47 |
+
assert len(records) == 10
|
| 48 |
+
|
| 49 |
+
# We should issue a warning if one wants to use sklearn.utils.fixes.delayed with
|
| 50 |
+
# joblib.Parallel
|
| 51 |
+
warn_msg = (
|
| 52 |
+
"`sklearn.utils.parallel.delayed` should be used with "
|
| 53 |
+
"`sklearn.utils.parallel.Parallel` to make it possible to propagate"
|
| 54 |
+
)
|
| 55 |
+
with pytest.warns(UserWarning, match=warn_msg) as records:
|
| 56 |
+
joblib.Parallel()(delayed(time.sleep)(0) for _ in range(10))
|
| 57 |
+
assert len(records) == 10
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@pytest.mark.parametrize("n_jobs", [1, 2])
|
| 61 |
+
def test_dispatch_config_parallel(n_jobs):
|
| 62 |
+
"""Check that we properly dispatch the configuration in parallel processing.
|
| 63 |
+
|
| 64 |
+
Non-regression test for:
|
| 65 |
+
https://github.com/scikit-learn/scikit-learn/issues/25239
|
| 66 |
+
"""
|
| 67 |
+
pd = pytest.importorskip("pandas")
|
| 68 |
+
iris = load_iris(as_frame=True)
|
| 69 |
+
|
| 70 |
+
class TransformerRequiredDataFrame(StandardScaler):
|
| 71 |
+
def fit(self, X, y=None):
|
| 72 |
+
assert isinstance(X, pd.DataFrame), "X should be a DataFrame"
|
| 73 |
+
return super().fit(X, y)
|
| 74 |
+
|
| 75 |
+
def transform(self, X, y=None):
|
| 76 |
+
assert isinstance(X, pd.DataFrame), "X should be a DataFrame"
|
| 77 |
+
return super().transform(X, y)
|
| 78 |
+
|
| 79 |
+
dropper = make_column_transformer(
|
| 80 |
+
("drop", [0]),
|
| 81 |
+
remainder="passthrough",
|
| 82 |
+
n_jobs=n_jobs,
|
| 83 |
+
)
|
| 84 |
+
param_grid = {"randomforestclassifier__max_depth": [1, 2, 3]}
|
| 85 |
+
search_cv = GridSearchCV(
|
| 86 |
+
make_pipeline(
|
| 87 |
+
dropper,
|
| 88 |
+
TransformerRequiredDataFrame(),
|
| 89 |
+
RandomForestClassifier(n_estimators=5, n_jobs=n_jobs),
|
| 90 |
+
),
|
| 91 |
+
param_grid,
|
| 92 |
+
cv=5,
|
| 93 |
+
n_jobs=n_jobs,
|
| 94 |
+
error_score="raise", # this search should not fail
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# make sure that `fit` would fail in case we don't request dataframe
|
| 98 |
+
with pytest.raises(AssertionError, match="X should be a DataFrame"):
|
| 99 |
+
search_cv.fit(iris.data, iris.target)
|
| 100 |
+
|
| 101 |
+
with config_context(transform_output="pandas"):
|
| 102 |
+
# we expect each intermediate steps to output a DataFrame
|
| 103 |
+
search_cv.fit(iris.data, iris.target)
|
| 104 |
+
|
| 105 |
+
assert not np.isnan(search_cv.cv_results_["mean_test_score"]).any()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def raise_warning():
|
| 109 |
+
warnings.warn("Convergence warning", ConvergenceWarning)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _yield_n_jobs_backend_combinations():
|
| 113 |
+
n_jobs_values = [1, 2]
|
| 114 |
+
backend_values = ["loky", "threading", "multiprocessing"]
|
| 115 |
+
for n_jobs, backend in itertools.product(n_jobs_values, backend_values):
|
| 116 |
+
if n_jobs == 2 and backend == "loky":
|
| 117 |
+
# XXX Mark thread-unsafe to avoid:
|
| 118 |
+
# RuntimeError: The executor underlying Parallel has been shutdown.
|
| 119 |
+
# See https://github.com/joblib/joblib/issues/1743 for more details.
|
| 120 |
+
yield pytest.param(n_jobs, backend, marks=pytest.mark.thread_unsafe)
|
| 121 |
+
else:
|
| 122 |
+
yield n_jobs, backend
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@pytest.mark.parametrize("n_jobs, backend", _yield_n_jobs_backend_combinations())
|
| 126 |
+
def test_filter_warning_propagates(n_jobs, backend):
|
| 127 |
+
"""Check warning propagates to the job."""
|
| 128 |
+
with warnings.catch_warnings():
|
| 129 |
+
warnings.simplefilter("error", category=ConvergenceWarning)
|
| 130 |
+
|
| 131 |
+
with pytest.raises(ConvergenceWarning):
|
| 132 |
+
Parallel(n_jobs=n_jobs, backend=backend)(
|
| 133 |
+
delayed(raise_warning)() for _ in range(2)
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def get_warning_filters():
|
| 138 |
+
# In free-threading Python >= 3.14, warnings filters are managed through a
|
| 139 |
+
# ContextVar and warnings.filters is not modified inside a
|
| 140 |
+
# warnings.catch_warnings context. You need to use warnings._get_filters().
|
| 141 |
+
# For more details, see
|
| 142 |
+
# https://docs.python.org/3.14/whatsnew/3.14.html#concurrent-safe-warnings-control
|
| 143 |
+
filters_func = getattr(warnings, "_get_filters", None)
|
| 144 |
+
return filters_func() if filters_func is not None else warnings.filters
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_check_warnings_threading():
|
| 148 |
+
"""Check that warnings filters are set correctly in the threading backend."""
|
| 149 |
+
with warnings.catch_warnings():
|
| 150 |
+
warnings.simplefilter("error", category=ConvergenceWarning)
|
| 151 |
+
|
| 152 |
+
main_warning_filters = get_warning_filters()
|
| 153 |
+
|
| 154 |
+
assert ("error", None, ConvergenceWarning, None, 0) in main_warning_filters
|
| 155 |
+
|
| 156 |
+
all_worker_warning_filters = Parallel(n_jobs=2, backend="threading")(
|
| 157 |
+
delayed(get_warning_filters)() for _ in range(2)
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
def normalize_main_module(filters):
|
| 161 |
+
# In Python 3.14 free-threaded, there is a small discrepancy main
|
| 162 |
+
# warning filters have an entry with module = "__main__" whereas it
|
| 163 |
+
# is a regex in the workers
|
| 164 |
+
return [
|
| 165 |
+
(
|
| 166 |
+
action,
|
| 167 |
+
message,
|
| 168 |
+
type_,
|
| 169 |
+
module
|
| 170 |
+
if "__main__" not in str(module)
|
| 171 |
+
or not isinstance(module, re.Pattern)
|
| 172 |
+
else module.pattern,
|
| 173 |
+
lineno,
|
| 174 |
+
)
|
| 175 |
+
for action, message, type_, module, lineno in main_warning_filters
|
| 176 |
+
]
|
| 177 |
+
|
| 178 |
+
for worker_warning_filter in all_worker_warning_filters:
|
| 179 |
+
assert normalize_main_module(
|
| 180 |
+
worker_warning_filter
|
| 181 |
+
) == normalize_main_module(main_warning_filters)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@pytest.mark.xfail(_IS_WASM, reason="Pyodide always use the sequential backend")
|
| 185 |
+
def test_filter_warning_propagates_no_side_effect_with_loky_backend():
|
| 186 |
+
with warnings.catch_warnings():
|
| 187 |
+
warnings.simplefilter("error", category=ConvergenceWarning)
|
| 188 |
+
|
| 189 |
+
Parallel(n_jobs=2, backend="loky")(delayed(time.sleep)(0) for _ in range(10))
|
| 190 |
+
|
| 191 |
+
# Since loky workers are reused, make sure that inside the loky workers,
|
| 192 |
+
# warnings filters have been reset to their original value. Using joblib
|
| 193 |
+
# directly should not turn ConvergenceWarning into an error.
|
| 194 |
+
joblib.Parallel(n_jobs=2, backend="loky")(
|
| 195 |
+
joblib.delayed(warnings.warn)("Convergence warning", ConvergenceWarning)
|
| 196 |
+
for _ in range(10)
|
| 197 |
+
)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_param_validation.py
ADDED
|
@@ -0,0 +1,786 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numbers import Integral, Real
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
from scipy.sparse import csr_matrix
|
| 6 |
+
|
| 7 |
+
from sklearn._config import config_context, get_config
|
| 8 |
+
from sklearn.base import BaseEstimator, _fit_context
|
| 9 |
+
from sklearn.model_selection import LeaveOneOut
|
| 10 |
+
from sklearn.utils import deprecated
|
| 11 |
+
from sklearn.utils._param_validation import (
|
| 12 |
+
HasMethods,
|
| 13 |
+
Hidden,
|
| 14 |
+
Interval,
|
| 15 |
+
InvalidParameterError,
|
| 16 |
+
MissingValues,
|
| 17 |
+
Options,
|
| 18 |
+
RealNotInt,
|
| 19 |
+
StrOptions,
|
| 20 |
+
_ArrayLikes,
|
| 21 |
+
_Booleans,
|
| 22 |
+
_Callables,
|
| 23 |
+
_CVObjects,
|
| 24 |
+
_InstancesOf,
|
| 25 |
+
_IterablesNotString,
|
| 26 |
+
_NanConstraint,
|
| 27 |
+
_NoneConstraint,
|
| 28 |
+
_PandasNAConstraint,
|
| 29 |
+
_RandomStates,
|
| 30 |
+
_SparseMatrices,
|
| 31 |
+
_VerboseHelper,
|
| 32 |
+
generate_invalid_param_val,
|
| 33 |
+
generate_valid_param,
|
| 34 |
+
make_constraint,
|
| 35 |
+
validate_params,
|
| 36 |
+
)
|
| 37 |
+
from sklearn.utils.fixes import CSR_CONTAINERS
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# Some helpers for the tests
|
| 41 |
+
@validate_params(
|
| 42 |
+
{"a": [Real], "b": [Real], "c": [Real], "d": [Real]},
|
| 43 |
+
prefer_skip_nested_validation=True,
|
| 44 |
+
)
|
| 45 |
+
def _func(a, b=0, *args, c, d=0, **kwargs):
|
| 46 |
+
"""A function to test the validation of functions."""
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class _Class:
|
| 50 |
+
"""A class to test the _InstancesOf constraint and the validation of methods."""
|
| 51 |
+
|
| 52 |
+
@validate_params({"a": [Real]}, prefer_skip_nested_validation=True)
|
| 53 |
+
def _method(self, a):
|
| 54 |
+
"""A validated method"""
|
| 55 |
+
|
| 56 |
+
@deprecated()
|
| 57 |
+
@validate_params({"a": [Real]}, prefer_skip_nested_validation=True)
|
| 58 |
+
def _deprecated_method(self, a):
|
| 59 |
+
"""A deprecated validated method"""
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class _Estimator(BaseEstimator):
|
| 63 |
+
"""An estimator to test the validation of estimator parameters."""
|
| 64 |
+
|
| 65 |
+
_parameter_constraints: dict = {"a": [Real]}
|
| 66 |
+
|
| 67 |
+
def __init__(self, a):
|
| 68 |
+
self.a = a
|
| 69 |
+
|
| 70 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
| 71 |
+
def fit(self, X=None, y=None):
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@pytest.mark.parametrize("interval_type", [Integral, Real])
|
| 76 |
+
def test_interval_range(interval_type):
|
| 77 |
+
"""Check the range of values depending on closed."""
|
| 78 |
+
interval = Interval(interval_type, -2, 2, closed="left")
|
| 79 |
+
assert -2 in interval
|
| 80 |
+
assert 2 not in interval
|
| 81 |
+
|
| 82 |
+
interval = Interval(interval_type, -2, 2, closed="right")
|
| 83 |
+
assert -2 not in interval
|
| 84 |
+
assert 2 in interval
|
| 85 |
+
|
| 86 |
+
interval = Interval(interval_type, -2, 2, closed="both")
|
| 87 |
+
assert -2 in interval
|
| 88 |
+
assert 2 in interval
|
| 89 |
+
|
| 90 |
+
interval = Interval(interval_type, -2, 2, closed="neither")
|
| 91 |
+
assert -2 not in interval
|
| 92 |
+
assert 2 not in interval
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@pytest.mark.parametrize("interval_type", [Integral, Real])
|
| 96 |
+
def test_interval_large_integers(interval_type):
|
| 97 |
+
"""Check that Interval constraint work with large integers.
|
| 98 |
+
|
| 99 |
+
non-regression test for #26648.
|
| 100 |
+
"""
|
| 101 |
+
interval = Interval(interval_type, 0, 2, closed="neither")
|
| 102 |
+
assert 2**65 not in interval
|
| 103 |
+
assert 2**128 not in interval
|
| 104 |
+
assert float(2**65) not in interval
|
| 105 |
+
assert float(2**128) not in interval
|
| 106 |
+
|
| 107 |
+
interval = Interval(interval_type, 0, 2**128, closed="neither")
|
| 108 |
+
assert 2**65 in interval
|
| 109 |
+
assert 2**128 not in interval
|
| 110 |
+
assert float(2**65) in interval
|
| 111 |
+
assert float(2**128) not in interval
|
| 112 |
+
|
| 113 |
+
assert 2**1024 not in interval
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def test_interval_inf_in_bounds():
|
| 117 |
+
"""Check that inf is included iff a bound is closed and set to None.
|
| 118 |
+
|
| 119 |
+
Only valid for real intervals.
|
| 120 |
+
"""
|
| 121 |
+
interval = Interval(Real, 0, None, closed="right")
|
| 122 |
+
assert np.inf in interval
|
| 123 |
+
|
| 124 |
+
interval = Interval(Real, None, 0, closed="left")
|
| 125 |
+
assert -np.inf in interval
|
| 126 |
+
|
| 127 |
+
interval = Interval(Real, None, None, closed="neither")
|
| 128 |
+
assert np.inf not in interval
|
| 129 |
+
assert -np.inf not in interval
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@pytest.mark.parametrize(
|
| 133 |
+
"interval",
|
| 134 |
+
[Interval(Real, 0, 1, closed="left"), Interval(Real, None, None, closed="both")],
|
| 135 |
+
)
|
| 136 |
+
def test_nan_not_in_interval(interval):
|
| 137 |
+
"""Check that np.nan is not in any interval."""
|
| 138 |
+
assert np.nan not in interval
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@pytest.mark.parametrize(
|
| 142 |
+
"params, error, match",
|
| 143 |
+
[
|
| 144 |
+
(
|
| 145 |
+
{"type": Integral, "left": 1.0, "right": 2, "closed": "both"},
|
| 146 |
+
TypeError,
|
| 147 |
+
r"Expecting left to be an int for an interval over the integers",
|
| 148 |
+
),
|
| 149 |
+
(
|
| 150 |
+
{"type": Integral, "left": 1, "right": 2.0, "closed": "neither"},
|
| 151 |
+
TypeError,
|
| 152 |
+
"Expecting right to be an int for an interval over the integers",
|
| 153 |
+
),
|
| 154 |
+
(
|
| 155 |
+
{"type": Integral, "left": None, "right": 0, "closed": "left"},
|
| 156 |
+
ValueError,
|
| 157 |
+
r"left can't be None when closed == left",
|
| 158 |
+
),
|
| 159 |
+
(
|
| 160 |
+
{"type": Integral, "left": 0, "right": None, "closed": "right"},
|
| 161 |
+
ValueError,
|
| 162 |
+
r"right can't be None when closed == right",
|
| 163 |
+
),
|
| 164 |
+
(
|
| 165 |
+
{"type": Integral, "left": 1, "right": -1, "closed": "both"},
|
| 166 |
+
ValueError,
|
| 167 |
+
r"right can't be less than left",
|
| 168 |
+
),
|
| 169 |
+
],
|
| 170 |
+
)
|
| 171 |
+
def test_interval_errors(params, error, match):
|
| 172 |
+
"""Check that informative errors are raised for invalid combination of parameters"""
|
| 173 |
+
with pytest.raises(error, match=match):
|
| 174 |
+
Interval(**params)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_stroptions():
|
| 178 |
+
"""Sanity check for the StrOptions constraint"""
|
| 179 |
+
options = StrOptions({"a", "b", "c"}, deprecated={"c"})
|
| 180 |
+
assert options.is_satisfied_by("a")
|
| 181 |
+
assert options.is_satisfied_by("c")
|
| 182 |
+
assert not options.is_satisfied_by("d")
|
| 183 |
+
|
| 184 |
+
assert "'c' (deprecated)" in str(options)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def test_options():
|
| 188 |
+
"""Sanity check for the Options constraint"""
|
| 189 |
+
options = Options(Real, {-0.5, 0.5, np.inf}, deprecated={-0.5})
|
| 190 |
+
assert options.is_satisfied_by(-0.5)
|
| 191 |
+
assert options.is_satisfied_by(np.inf)
|
| 192 |
+
assert not options.is_satisfied_by(1.23)
|
| 193 |
+
|
| 194 |
+
assert "-0.5 (deprecated)" in str(options)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@pytest.mark.parametrize(
|
| 198 |
+
"type, expected_type_name",
|
| 199 |
+
[
|
| 200 |
+
(int, "int"),
|
| 201 |
+
(Integral, "int"),
|
| 202 |
+
(Real, "float"),
|
| 203 |
+
(np.ndarray, "numpy.ndarray"),
|
| 204 |
+
],
|
| 205 |
+
)
|
| 206 |
+
def test_instances_of_type_human_readable(type, expected_type_name):
|
| 207 |
+
"""Check the string representation of the _InstancesOf constraint."""
|
| 208 |
+
constraint = _InstancesOf(type)
|
| 209 |
+
assert str(constraint) == f"an instance of '{expected_type_name}'"
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def test_hasmethods():
|
| 213 |
+
"""Check the HasMethods constraint."""
|
| 214 |
+
constraint = HasMethods(["a", "b"])
|
| 215 |
+
|
| 216 |
+
class _Good:
|
| 217 |
+
def a(self):
|
| 218 |
+
pass # pragma: no cover
|
| 219 |
+
|
| 220 |
+
def b(self):
|
| 221 |
+
pass # pragma: no cover
|
| 222 |
+
|
| 223 |
+
class _Bad:
|
| 224 |
+
def a(self):
|
| 225 |
+
pass # pragma: no cover
|
| 226 |
+
|
| 227 |
+
assert constraint.is_satisfied_by(_Good())
|
| 228 |
+
assert not constraint.is_satisfied_by(_Bad())
|
| 229 |
+
assert str(constraint) == "an object implementing 'a' and 'b'"
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@pytest.mark.parametrize(
|
| 233 |
+
"constraint",
|
| 234 |
+
[
|
| 235 |
+
Interval(Real, None, 0, closed="left"),
|
| 236 |
+
Interval(Real, 0, None, closed="left"),
|
| 237 |
+
Interval(Real, None, None, closed="neither"),
|
| 238 |
+
StrOptions({"a", "b", "c"}),
|
| 239 |
+
MissingValues(),
|
| 240 |
+
MissingValues(numeric_only=True),
|
| 241 |
+
_VerboseHelper(),
|
| 242 |
+
HasMethods("fit"),
|
| 243 |
+
_IterablesNotString(),
|
| 244 |
+
_CVObjects(),
|
| 245 |
+
],
|
| 246 |
+
)
|
| 247 |
+
def test_generate_invalid_param_val(constraint):
|
| 248 |
+
"""Check that the value generated does not satisfy the constraint"""
|
| 249 |
+
bad_value = generate_invalid_param_val(constraint)
|
| 250 |
+
assert not constraint.is_satisfied_by(bad_value)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@pytest.mark.parametrize(
|
| 254 |
+
"integer_interval, real_interval",
|
| 255 |
+
[
|
| 256 |
+
(
|
| 257 |
+
Interval(Integral, None, 3, closed="right"),
|
| 258 |
+
Interval(RealNotInt, -5, 5, closed="both"),
|
| 259 |
+
),
|
| 260 |
+
(
|
| 261 |
+
Interval(Integral, None, 3, closed="right"),
|
| 262 |
+
Interval(RealNotInt, -5, 5, closed="neither"),
|
| 263 |
+
),
|
| 264 |
+
(
|
| 265 |
+
Interval(Integral, None, 3, closed="right"),
|
| 266 |
+
Interval(RealNotInt, 4, 5, closed="both"),
|
| 267 |
+
),
|
| 268 |
+
(
|
| 269 |
+
Interval(Integral, None, 3, closed="right"),
|
| 270 |
+
Interval(RealNotInt, 5, None, closed="left"),
|
| 271 |
+
),
|
| 272 |
+
(
|
| 273 |
+
Interval(Integral, None, 3, closed="right"),
|
| 274 |
+
Interval(RealNotInt, 4, None, closed="neither"),
|
| 275 |
+
),
|
| 276 |
+
(
|
| 277 |
+
Interval(Integral, 3, None, closed="left"),
|
| 278 |
+
Interval(RealNotInt, -5, 5, closed="both"),
|
| 279 |
+
),
|
| 280 |
+
(
|
| 281 |
+
Interval(Integral, 3, None, closed="left"),
|
| 282 |
+
Interval(RealNotInt, -5, 5, closed="neither"),
|
| 283 |
+
),
|
| 284 |
+
(
|
| 285 |
+
Interval(Integral, 3, None, closed="left"),
|
| 286 |
+
Interval(RealNotInt, 1, 2, closed="both"),
|
| 287 |
+
),
|
| 288 |
+
(
|
| 289 |
+
Interval(Integral, 3, None, closed="left"),
|
| 290 |
+
Interval(RealNotInt, None, -5, closed="left"),
|
| 291 |
+
),
|
| 292 |
+
(
|
| 293 |
+
Interval(Integral, 3, None, closed="left"),
|
| 294 |
+
Interval(RealNotInt, None, -4, closed="neither"),
|
| 295 |
+
),
|
| 296 |
+
(
|
| 297 |
+
Interval(Integral, -5, 5, closed="both"),
|
| 298 |
+
Interval(RealNotInt, None, 1, closed="right"),
|
| 299 |
+
),
|
| 300 |
+
(
|
| 301 |
+
Interval(Integral, -5, 5, closed="both"),
|
| 302 |
+
Interval(RealNotInt, 1, None, closed="left"),
|
| 303 |
+
),
|
| 304 |
+
(
|
| 305 |
+
Interval(Integral, -5, 5, closed="both"),
|
| 306 |
+
Interval(RealNotInt, -10, -4, closed="neither"),
|
| 307 |
+
),
|
| 308 |
+
(
|
| 309 |
+
Interval(Integral, -5, 5, closed="both"),
|
| 310 |
+
Interval(RealNotInt, -10, -4, closed="right"),
|
| 311 |
+
),
|
| 312 |
+
(
|
| 313 |
+
Interval(Integral, -5, 5, closed="neither"),
|
| 314 |
+
Interval(RealNotInt, 6, 10, closed="neither"),
|
| 315 |
+
),
|
| 316 |
+
(
|
| 317 |
+
Interval(Integral, -5, 5, closed="neither"),
|
| 318 |
+
Interval(RealNotInt, 6, 10, closed="left"),
|
| 319 |
+
),
|
| 320 |
+
(
|
| 321 |
+
Interval(Integral, 2, None, closed="left"),
|
| 322 |
+
Interval(RealNotInt, 0, 1, closed="both"),
|
| 323 |
+
),
|
| 324 |
+
(
|
| 325 |
+
Interval(Integral, 1, None, closed="left"),
|
| 326 |
+
Interval(RealNotInt, 0, 1, closed="both"),
|
| 327 |
+
),
|
| 328 |
+
],
|
| 329 |
+
)
|
| 330 |
+
def test_generate_invalid_param_val_2_intervals(integer_interval, real_interval):
|
| 331 |
+
"""Check that the value generated for an interval constraint does not satisfy any of
|
| 332 |
+
the interval constraints.
|
| 333 |
+
"""
|
| 334 |
+
bad_value = generate_invalid_param_val(constraint=real_interval)
|
| 335 |
+
assert not real_interval.is_satisfied_by(bad_value)
|
| 336 |
+
assert not integer_interval.is_satisfied_by(bad_value)
|
| 337 |
+
|
| 338 |
+
bad_value = generate_invalid_param_val(constraint=integer_interval)
|
| 339 |
+
assert not real_interval.is_satisfied_by(bad_value)
|
| 340 |
+
assert not integer_interval.is_satisfied_by(bad_value)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
@pytest.mark.parametrize(
|
| 344 |
+
"constraint",
|
| 345 |
+
[
|
| 346 |
+
_ArrayLikes(),
|
| 347 |
+
_InstancesOf(list),
|
| 348 |
+
_Callables(),
|
| 349 |
+
_NoneConstraint(),
|
| 350 |
+
_RandomStates(),
|
| 351 |
+
_SparseMatrices(),
|
| 352 |
+
_Booleans(),
|
| 353 |
+
Interval(Integral, None, None, closed="neither"),
|
| 354 |
+
],
|
| 355 |
+
)
|
| 356 |
+
def test_generate_invalid_param_val_all_valid(constraint):
|
| 357 |
+
"""Check that the function raises NotImplementedError when there's no invalid value
|
| 358 |
+
for the constraint.
|
| 359 |
+
"""
|
| 360 |
+
with pytest.raises(NotImplementedError):
|
| 361 |
+
generate_invalid_param_val(constraint)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
@pytest.mark.parametrize(
|
| 365 |
+
"constraint",
|
| 366 |
+
[
|
| 367 |
+
_ArrayLikes(),
|
| 368 |
+
_Callables(),
|
| 369 |
+
_InstancesOf(list),
|
| 370 |
+
_NoneConstraint(),
|
| 371 |
+
_RandomStates(),
|
| 372 |
+
_SparseMatrices(),
|
| 373 |
+
_Booleans(),
|
| 374 |
+
_VerboseHelper(),
|
| 375 |
+
MissingValues(),
|
| 376 |
+
MissingValues(numeric_only=True),
|
| 377 |
+
StrOptions({"a", "b", "c"}),
|
| 378 |
+
Options(Integral, {1, 2, 3}),
|
| 379 |
+
Interval(Integral, None, None, closed="neither"),
|
| 380 |
+
Interval(Integral, 0, 10, closed="neither"),
|
| 381 |
+
Interval(Integral, 0, None, closed="neither"),
|
| 382 |
+
Interval(Integral, None, 0, closed="neither"),
|
| 383 |
+
Interval(Real, 0, 1, closed="neither"),
|
| 384 |
+
Interval(Real, 0, None, closed="both"),
|
| 385 |
+
Interval(Real, None, 0, closed="right"),
|
| 386 |
+
HasMethods("fit"),
|
| 387 |
+
_IterablesNotString(),
|
| 388 |
+
_CVObjects(),
|
| 389 |
+
],
|
| 390 |
+
)
|
| 391 |
+
def test_generate_valid_param(constraint):
|
| 392 |
+
"""Check that the value generated does satisfy the constraint."""
|
| 393 |
+
value = generate_valid_param(constraint)
|
| 394 |
+
assert constraint.is_satisfied_by(value)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
@pytest.mark.parametrize(
|
| 398 |
+
"constraint_declaration, value",
|
| 399 |
+
[
|
| 400 |
+
(Interval(Real, 0, 1, closed="both"), 0.42),
|
| 401 |
+
(Interval(Integral, 0, None, closed="neither"), 42),
|
| 402 |
+
(StrOptions({"a", "b", "c"}), "b"),
|
| 403 |
+
(Options(type, {np.float32, np.float64}), np.float64),
|
| 404 |
+
(callable, lambda x: x + 1),
|
| 405 |
+
(None, None),
|
| 406 |
+
("array-like", [[1, 2], [3, 4]]),
|
| 407 |
+
("array-like", np.array([[1, 2], [3, 4]])),
|
| 408 |
+
("sparse matrix", csr_matrix([[1, 2], [3, 4]])),
|
| 409 |
+
*[
|
| 410 |
+
("sparse matrix", container([[1, 2], [3, 4]]))
|
| 411 |
+
for container in CSR_CONTAINERS
|
| 412 |
+
],
|
| 413 |
+
("random_state", 0),
|
| 414 |
+
("random_state", np.random.RandomState(0)),
|
| 415 |
+
("random_state", None),
|
| 416 |
+
(_Class, _Class()),
|
| 417 |
+
(int, 1),
|
| 418 |
+
(Real, 0.5),
|
| 419 |
+
("boolean", False),
|
| 420 |
+
("verbose", 1),
|
| 421 |
+
("nan", np.nan),
|
| 422 |
+
(MissingValues(), -1),
|
| 423 |
+
(MissingValues(), -1.0),
|
| 424 |
+
(MissingValues(), 2**1028),
|
| 425 |
+
(MissingValues(), None),
|
| 426 |
+
(MissingValues(), float("nan")),
|
| 427 |
+
(MissingValues(), np.nan),
|
| 428 |
+
(MissingValues(), "missing"),
|
| 429 |
+
(HasMethods("fit"), _Estimator(a=0)),
|
| 430 |
+
("cv_object", 5),
|
| 431 |
+
],
|
| 432 |
+
)
|
| 433 |
+
def test_is_satisfied_by(constraint_declaration, value):
|
| 434 |
+
"""Sanity check for the is_satisfied_by method"""
|
| 435 |
+
constraint = make_constraint(constraint_declaration)
|
| 436 |
+
assert constraint.is_satisfied_by(value)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
@pytest.mark.parametrize(
|
| 440 |
+
"constraint_declaration, expected_constraint_class",
|
| 441 |
+
[
|
| 442 |
+
(Interval(Real, 0, 1, closed="both"), Interval),
|
| 443 |
+
(StrOptions({"option1", "option2"}), StrOptions),
|
| 444 |
+
(Options(Real, {0.42, 1.23}), Options),
|
| 445 |
+
("array-like", _ArrayLikes),
|
| 446 |
+
("sparse matrix", _SparseMatrices),
|
| 447 |
+
("random_state", _RandomStates),
|
| 448 |
+
(None, _NoneConstraint),
|
| 449 |
+
(callable, _Callables),
|
| 450 |
+
(int, _InstancesOf),
|
| 451 |
+
("boolean", _Booleans),
|
| 452 |
+
("verbose", _VerboseHelper),
|
| 453 |
+
(MissingValues(numeric_only=True), MissingValues),
|
| 454 |
+
(HasMethods("fit"), HasMethods),
|
| 455 |
+
("cv_object", _CVObjects),
|
| 456 |
+
("nan", _NanConstraint),
|
| 457 |
+
(np.nan, _NanConstraint),
|
| 458 |
+
],
|
| 459 |
+
)
|
| 460 |
+
def test_make_constraint(constraint_declaration, expected_constraint_class):
|
| 461 |
+
"""Check that make_constraint dispatches to the appropriate constraint class"""
|
| 462 |
+
constraint = make_constraint(constraint_declaration)
|
| 463 |
+
assert constraint.__class__ is expected_constraint_class
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def test_make_constraint_unknown():
|
| 467 |
+
"""Check that an informative error is raised when an unknown constraint is passed"""
|
| 468 |
+
with pytest.raises(ValueError, match="Unknown constraint"):
|
| 469 |
+
make_constraint("not a valid constraint")
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def test_validate_params():
|
| 473 |
+
"""Check that validate_params works no matter how the arguments are passed"""
|
| 474 |
+
with pytest.raises(
|
| 475 |
+
InvalidParameterError, match="The 'a' parameter of _func must be"
|
| 476 |
+
):
|
| 477 |
+
_func("wrong", c=1)
|
| 478 |
+
|
| 479 |
+
with pytest.raises(
|
| 480 |
+
InvalidParameterError, match="The 'b' parameter of _func must be"
|
| 481 |
+
):
|
| 482 |
+
_func(*[1, "wrong"], c=1)
|
| 483 |
+
|
| 484 |
+
with pytest.raises(
|
| 485 |
+
InvalidParameterError, match="The 'c' parameter of _func must be"
|
| 486 |
+
):
|
| 487 |
+
_func(1, **{"c": "wrong"})
|
| 488 |
+
|
| 489 |
+
with pytest.raises(
|
| 490 |
+
InvalidParameterError, match="The 'd' parameter of _func must be"
|
| 491 |
+
):
|
| 492 |
+
_func(1, c=1, d="wrong")
|
| 493 |
+
|
| 494 |
+
# check in the presence of extra positional and keyword args
|
| 495 |
+
with pytest.raises(
|
| 496 |
+
InvalidParameterError, match="The 'b' parameter of _func must be"
|
| 497 |
+
):
|
| 498 |
+
_func(0, *["wrong", 2, 3], c=4, **{"e": 5})
|
| 499 |
+
|
| 500 |
+
with pytest.raises(
|
| 501 |
+
InvalidParameterError, match="The 'c' parameter of _func must be"
|
| 502 |
+
):
|
| 503 |
+
_func(0, *[1, 2, 3], c="four", **{"e": 5})
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def test_validate_params_missing_params():
|
| 507 |
+
"""Check that no error is raised when there are parameters without
|
| 508 |
+
constraints
|
| 509 |
+
"""
|
| 510 |
+
|
| 511 |
+
@validate_params({"a": [int]}, prefer_skip_nested_validation=True)
|
| 512 |
+
def func(a, b):
|
| 513 |
+
pass
|
| 514 |
+
|
| 515 |
+
func(1, 2)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def test_decorate_validated_function():
|
| 519 |
+
"""Check that validate_params functions can be decorated"""
|
| 520 |
+
decorated_function = deprecated()(_func)
|
| 521 |
+
|
| 522 |
+
with pytest.warns(FutureWarning, match="Function _func is deprecated"):
|
| 523 |
+
decorated_function(1, 2, c=3)
|
| 524 |
+
|
| 525 |
+
# outer decorator does not interfere with validation
|
| 526 |
+
with pytest.warns(FutureWarning, match="Function _func is deprecated"):
|
| 527 |
+
with pytest.raises(
|
| 528 |
+
InvalidParameterError, match=r"The 'c' parameter of _func must be"
|
| 529 |
+
):
|
| 530 |
+
decorated_function(1, 2, c="wrong")
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def test_validate_params_method():
|
| 534 |
+
"""Check that validate_params works with methods"""
|
| 535 |
+
with pytest.raises(
|
| 536 |
+
InvalidParameterError, match="The 'a' parameter of _Class._method must be"
|
| 537 |
+
):
|
| 538 |
+
_Class()._method("wrong")
|
| 539 |
+
|
| 540 |
+
# validated method can be decorated
|
| 541 |
+
with pytest.warns(FutureWarning, match="Function _deprecated_method is deprecated"):
|
| 542 |
+
with pytest.raises(
|
| 543 |
+
InvalidParameterError,
|
| 544 |
+
match="The 'a' parameter of _Class._deprecated_method must be",
|
| 545 |
+
):
|
| 546 |
+
_Class()._deprecated_method("wrong")
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def test_validate_params_estimator():
|
| 550 |
+
"""Check that validate_params works with Estimator instances"""
|
| 551 |
+
# no validation in init
|
| 552 |
+
est = _Estimator("wrong")
|
| 553 |
+
|
| 554 |
+
with pytest.raises(
|
| 555 |
+
InvalidParameterError, match="The 'a' parameter of _Estimator must be"
|
| 556 |
+
):
|
| 557 |
+
est.fit()
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def test_stroptions_deprecated_subset():
|
| 561 |
+
"""Check that the deprecated parameter must be a subset of options."""
|
| 562 |
+
with pytest.raises(ValueError, match="deprecated options must be a subset"):
|
| 563 |
+
StrOptions({"a", "b", "c"}, deprecated={"a", "d"})
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def test_hidden_constraint():
|
| 567 |
+
"""Check that internal constraints are not exposed in the error message."""
|
| 568 |
+
|
| 569 |
+
@validate_params(
|
| 570 |
+
{"param": [Hidden(list), dict]}, prefer_skip_nested_validation=True
|
| 571 |
+
)
|
| 572 |
+
def f(param):
|
| 573 |
+
pass
|
| 574 |
+
|
| 575 |
+
# list and dict are valid params
|
| 576 |
+
f({"a": 1, "b": 2, "c": 3})
|
| 577 |
+
f([1, 2, 3])
|
| 578 |
+
|
| 579 |
+
with pytest.raises(
|
| 580 |
+
InvalidParameterError, match="The 'param' parameter"
|
| 581 |
+
) as exc_info:
|
| 582 |
+
f(param="bad")
|
| 583 |
+
|
| 584 |
+
# the list option is not exposed in the error message
|
| 585 |
+
err_msg = str(exc_info.value)
|
| 586 |
+
assert "an instance of 'dict'" in err_msg
|
| 587 |
+
assert "an instance of 'list'" not in err_msg
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def test_hidden_stroptions():
|
| 591 |
+
"""Check that we can have 2 StrOptions constraints, one being hidden."""
|
| 592 |
+
|
| 593 |
+
@validate_params(
|
| 594 |
+
{"param": [StrOptions({"auto"}), Hidden(StrOptions({"warn"}))]},
|
| 595 |
+
prefer_skip_nested_validation=True,
|
| 596 |
+
)
|
| 597 |
+
def f(param):
|
| 598 |
+
pass
|
| 599 |
+
|
| 600 |
+
# "auto" and "warn" are valid params
|
| 601 |
+
f("auto")
|
| 602 |
+
f("warn")
|
| 603 |
+
|
| 604 |
+
with pytest.raises(
|
| 605 |
+
InvalidParameterError, match="The 'param' parameter"
|
| 606 |
+
) as exc_info:
|
| 607 |
+
f(param="bad")
|
| 608 |
+
|
| 609 |
+
# the "warn" option is not exposed in the error message
|
| 610 |
+
err_msg = str(exc_info.value)
|
| 611 |
+
assert "auto" in err_msg
|
| 612 |
+
assert "warn" not in err_msg
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def test_validate_params_set_param_constraints_attribute():
|
| 616 |
+
"""Check that the validate_params decorator properly sets the parameter constraints
|
| 617 |
+
as attribute of the decorated function/method.
|
| 618 |
+
"""
|
| 619 |
+
assert hasattr(_func, "_skl_parameter_constraints")
|
| 620 |
+
assert hasattr(_Class()._method, "_skl_parameter_constraints")
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def test_boolean_constraint_deprecated_int():
|
| 624 |
+
"""Check that validate_params raise a deprecation message but still passes
|
| 625 |
+
validation when using an int for a parameter accepting a boolean.
|
| 626 |
+
"""
|
| 627 |
+
|
| 628 |
+
@validate_params({"param": ["boolean"]}, prefer_skip_nested_validation=True)
|
| 629 |
+
def f(param):
|
| 630 |
+
pass
|
| 631 |
+
|
| 632 |
+
# True/False and np.bool_(True/False) are valid params
|
| 633 |
+
f(True)
|
| 634 |
+
f(np.bool_(False))
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def test_no_validation():
|
| 638 |
+
"""Check that validation can be skipped for a parameter."""
|
| 639 |
+
|
| 640 |
+
@validate_params(
|
| 641 |
+
{"param1": [int, None], "param2": "no_validation"},
|
| 642 |
+
prefer_skip_nested_validation=True,
|
| 643 |
+
)
|
| 644 |
+
def f(param1=None, param2=None):
|
| 645 |
+
pass
|
| 646 |
+
|
| 647 |
+
# param1 is validated
|
| 648 |
+
with pytest.raises(InvalidParameterError, match="The 'param1' parameter"):
|
| 649 |
+
f(param1="wrong")
|
| 650 |
+
|
| 651 |
+
# param2 is not validated: any type is valid.
|
| 652 |
+
class SomeType:
|
| 653 |
+
pass
|
| 654 |
+
|
| 655 |
+
f(param2=SomeType)
|
| 656 |
+
f(param2=SomeType())
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def test_pandas_na_constraint_with_pd_na():
|
| 660 |
+
"""Add a specific test for checking support for `pandas.NA`."""
|
| 661 |
+
pd = pytest.importorskip("pandas")
|
| 662 |
+
|
| 663 |
+
na_constraint = _PandasNAConstraint()
|
| 664 |
+
assert na_constraint.is_satisfied_by(pd.NA)
|
| 665 |
+
assert not na_constraint.is_satisfied_by(np.array([1, 2, 3]))
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def test_iterable_not_string():
|
| 669 |
+
"""Check that a string does not satisfy the _IterableNotString constraint."""
|
| 670 |
+
constraint = _IterablesNotString()
|
| 671 |
+
assert constraint.is_satisfied_by([1, 2, 3])
|
| 672 |
+
assert constraint.is_satisfied_by(range(10))
|
| 673 |
+
assert not constraint.is_satisfied_by("some string")
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def test_cv_objects():
|
| 677 |
+
"""Check that the _CVObjects constraint accepts all current ways
|
| 678 |
+
to pass cv objects."""
|
| 679 |
+
constraint = _CVObjects()
|
| 680 |
+
assert constraint.is_satisfied_by(5)
|
| 681 |
+
assert constraint.is_satisfied_by(LeaveOneOut())
|
| 682 |
+
assert constraint.is_satisfied_by([([1, 2], [3, 4]), ([3, 4], [1, 2])])
|
| 683 |
+
assert constraint.is_satisfied_by(None)
|
| 684 |
+
assert not constraint.is_satisfied_by("not a CV object")
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def test_third_party_estimator():
|
| 688 |
+
"""Check that the validation from a scikit-learn estimator inherited by a third
|
| 689 |
+
party estimator does not impose a match between the dict of constraints and the
|
| 690 |
+
parameters of the estimator.
|
| 691 |
+
"""
|
| 692 |
+
|
| 693 |
+
class ThirdPartyEstimator(_Estimator):
|
| 694 |
+
def __init__(self, b):
|
| 695 |
+
self.b = b
|
| 696 |
+
super().__init__(a=0)
|
| 697 |
+
|
| 698 |
+
def fit(self, X=None, y=None):
|
| 699 |
+
super().fit(X, y)
|
| 700 |
+
|
| 701 |
+
# does not raise, even though "b" is not in the constraints dict and "a" is not
|
| 702 |
+
# a parameter of the estimator.
|
| 703 |
+
ThirdPartyEstimator(b=0).fit()
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def test_interval_real_not_int():
|
| 707 |
+
"""Check for the type RealNotInt in the Interval constraint."""
|
| 708 |
+
constraint = Interval(RealNotInt, 0, 1, closed="both")
|
| 709 |
+
assert constraint.is_satisfied_by(1.0)
|
| 710 |
+
assert not constraint.is_satisfied_by(1)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def test_real_not_int():
|
| 714 |
+
"""Check for the RealNotInt type."""
|
| 715 |
+
assert isinstance(1.0, RealNotInt)
|
| 716 |
+
assert not isinstance(1, RealNotInt)
|
| 717 |
+
assert isinstance(np.float64(1), RealNotInt)
|
| 718 |
+
assert not isinstance(np.int64(1), RealNotInt)
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def test_skip_param_validation():
|
| 722 |
+
"""Check that param validation can be skipped using config_context."""
|
| 723 |
+
|
| 724 |
+
@validate_params({"a": [int]}, prefer_skip_nested_validation=True)
|
| 725 |
+
def f(a):
|
| 726 |
+
pass
|
| 727 |
+
|
| 728 |
+
with pytest.raises(InvalidParameterError, match="The 'a' parameter"):
|
| 729 |
+
f(a="1")
|
| 730 |
+
|
| 731 |
+
# does not raise
|
| 732 |
+
with config_context(skip_parameter_validation=True):
|
| 733 |
+
f(a="1")
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
@pytest.mark.parametrize("prefer_skip_nested_validation", [True, False])
|
| 737 |
+
def test_skip_nested_validation(prefer_skip_nested_validation):
|
| 738 |
+
"""Check that nested validation can be skipped."""
|
| 739 |
+
|
| 740 |
+
@validate_params({"a": [int]}, prefer_skip_nested_validation=True)
|
| 741 |
+
def f(a):
|
| 742 |
+
pass
|
| 743 |
+
|
| 744 |
+
@validate_params(
|
| 745 |
+
{"b": [int]},
|
| 746 |
+
prefer_skip_nested_validation=prefer_skip_nested_validation,
|
| 747 |
+
)
|
| 748 |
+
def g(b):
|
| 749 |
+
# calls f with a bad parameter type
|
| 750 |
+
return f(a="invalid_param_value")
|
| 751 |
+
|
| 752 |
+
# Validation for g is never skipped.
|
| 753 |
+
with pytest.raises(InvalidParameterError, match="The 'b' parameter"):
|
| 754 |
+
g(b="invalid_param_value")
|
| 755 |
+
|
| 756 |
+
if prefer_skip_nested_validation:
|
| 757 |
+
g(b=1) # does not raise because inner f is not validated
|
| 758 |
+
else:
|
| 759 |
+
with pytest.raises(InvalidParameterError, match="The 'a' parameter"):
|
| 760 |
+
g(b=1)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
@pytest.mark.parametrize(
|
| 764 |
+
"skip_parameter_validation, prefer_skip_nested_validation, expected_skipped",
|
| 765 |
+
[
|
| 766 |
+
(True, True, True),
|
| 767 |
+
(True, False, True),
|
| 768 |
+
(False, True, True),
|
| 769 |
+
(False, False, False),
|
| 770 |
+
],
|
| 771 |
+
)
|
| 772 |
+
def test_skip_nested_validation_and_config_context(
|
| 773 |
+
skip_parameter_validation, prefer_skip_nested_validation, expected_skipped
|
| 774 |
+
):
|
| 775 |
+
"""Check interaction between global skip and local skip."""
|
| 776 |
+
|
| 777 |
+
@validate_params(
|
| 778 |
+
{"a": [int]}, prefer_skip_nested_validation=prefer_skip_nested_validation
|
| 779 |
+
)
|
| 780 |
+
def g(a):
|
| 781 |
+
return get_config()["skip_parameter_validation"]
|
| 782 |
+
|
| 783 |
+
with config_context(skip_parameter_validation=skip_parameter_validation):
|
| 784 |
+
actual_skipped = g(1)
|
| 785 |
+
|
| 786 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from sklearn.linear_model import LogisticRegression
|
| 5 |
+
from sklearn.utils._plotting import (
|
| 6 |
+
_BinaryClassifierCurveDisplayMixin,
|
| 7 |
+
_deprecate_estimator_name,
|
| 8 |
+
_despine,
|
| 9 |
+
_interval_max_min_ratio,
|
| 10 |
+
_validate_score_name,
|
| 11 |
+
_validate_style_kwargs,
|
| 12 |
+
)
|
| 13 |
+
from sklearn.utils._response import _get_response_values_binary
|
| 14 |
+
from sklearn.utils._testing import assert_allclose
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.mark.parametrize("ax", [None, "Ax"])
|
| 18 |
+
@pytest.mark.parametrize(
|
| 19 |
+
"name, expected_name_out", [(None, "TestEstimator"), ("CustomName", "CustomName")]
|
| 20 |
+
)
|
| 21 |
+
def test_validate_plot_params(pyplot, ax, name, expected_name_out):
|
| 22 |
+
"""Check `_validate_plot_params` returns the correct values."""
|
| 23 |
+
display = _BinaryClassifierCurveDisplayMixin()
|
| 24 |
+
display.estimator_name = "TestEstimator"
|
| 25 |
+
if ax:
|
| 26 |
+
_, ax = pyplot.subplots()
|
| 27 |
+
ax_out, _, name_out = display._validate_plot_params(ax=ax, name=name)
|
| 28 |
+
|
| 29 |
+
assert name_out == expected_name_out
|
| 30 |
+
|
| 31 |
+
if ax:
|
| 32 |
+
assert ax == ax_out
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.mark.parametrize("pos_label", [None, 0])
|
| 36 |
+
@pytest.mark.parametrize("name", [None, "CustomName"])
|
| 37 |
+
@pytest.mark.parametrize(
|
| 38 |
+
"response_method", ["auto", "predict_proba", "decision_function"]
|
| 39 |
+
)
|
| 40 |
+
def test_validate_and_get_response_values(pyplot, pos_label, name, response_method):
|
| 41 |
+
"""Check `_validate_and_get_response_values` returns the correct values."""
|
| 42 |
+
X = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
|
| 43 |
+
y = np.array([0, 0, 2, 2])
|
| 44 |
+
estimator = LogisticRegression().fit(X, y)
|
| 45 |
+
|
| 46 |
+
y_pred, pos_label, name_out = (
|
| 47 |
+
_BinaryClassifierCurveDisplayMixin._validate_and_get_response_values(
|
| 48 |
+
estimator,
|
| 49 |
+
X,
|
| 50 |
+
y,
|
| 51 |
+
response_method=response_method,
|
| 52 |
+
pos_label=pos_label,
|
| 53 |
+
name=name,
|
| 54 |
+
)
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
expected_y_pred, expected_pos_label = _get_response_values_binary(
|
| 58 |
+
estimator, X, response_method=response_method, pos_label=pos_label
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
assert_allclose(y_pred, expected_y_pred)
|
| 62 |
+
assert pos_label == expected_pos_label
|
| 63 |
+
|
| 64 |
+
# Check name is handled correctly
|
| 65 |
+
expected_name = name if name is not None else "LogisticRegression"
|
| 66 |
+
assert name_out == expected_name
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@pytest.mark.parametrize(
|
| 70 |
+
"y_true, error_message",
|
| 71 |
+
[
|
| 72 |
+
(np.array([0, 1, 2]), "The target y is not binary."),
|
| 73 |
+
(np.array([0, 1]), "Found input variables with inconsistent"),
|
| 74 |
+
(np.array([0, 2, 0, 2]), r"y_true takes value in \{0, 2\} and pos_label"),
|
| 75 |
+
],
|
| 76 |
+
)
|
| 77 |
+
def test_validate_from_predictions_params_errors(pyplot, y_true, error_message):
|
| 78 |
+
"""Check `_validate_from_predictions_params` raises the correct errors."""
|
| 79 |
+
y_pred = np.array([0.1, 0.2, 0.3, 0.4])
|
| 80 |
+
sample_weight = np.ones(4)
|
| 81 |
+
|
| 82 |
+
with pytest.raises(ValueError, match=error_message):
|
| 83 |
+
_BinaryClassifierCurveDisplayMixin._validate_from_predictions_params(
|
| 84 |
+
y_true=y_true,
|
| 85 |
+
y_pred=y_pred,
|
| 86 |
+
sample_weight=sample_weight,
|
| 87 |
+
pos_label=None,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@pytest.mark.parametrize("name", [None, "CustomName"])
|
| 92 |
+
@pytest.mark.parametrize(
|
| 93 |
+
"pos_label, y_true",
|
| 94 |
+
[
|
| 95 |
+
(None, np.array([0, 1, 0, 1])),
|
| 96 |
+
(2, np.array([0, 2, 0, 2])),
|
| 97 |
+
],
|
| 98 |
+
)
|
| 99 |
+
def test_validate_from_predictions_params_returns(pyplot, name, pos_label, y_true):
|
| 100 |
+
"""Check `_validate_from_predictions_params` returns the correct values."""
|
| 101 |
+
y_pred = np.array([0.1, 0.2, 0.3, 0.4])
|
| 102 |
+
pos_label_out, name_out = (
|
| 103 |
+
_BinaryClassifierCurveDisplayMixin._validate_from_predictions_params(
|
| 104 |
+
y_true=y_true,
|
| 105 |
+
y_pred=y_pred,
|
| 106 |
+
sample_weight=None,
|
| 107 |
+
pos_label=pos_label,
|
| 108 |
+
name=name,
|
| 109 |
+
)
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Check name is handled correctly
|
| 113 |
+
expected_name = name if name is not None else "Classifier"
|
| 114 |
+
assert name_out == expected_name
|
| 115 |
+
|
| 116 |
+
# Check pos_label is handled correctly
|
| 117 |
+
expected_pos_label = pos_label if pos_label is not None else 1
|
| 118 |
+
assert pos_label_out == expected_pos_label
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@pytest.mark.parametrize(
|
| 122 |
+
"params, err_msg",
|
| 123 |
+
[
|
| 124 |
+
(
|
| 125 |
+
{
|
| 126 |
+
# Missing "indices" key
|
| 127 |
+
"cv_results": {"estimator": "dummy"},
|
| 128 |
+
"X": np.array([[1, 2], [3, 4]]),
|
| 129 |
+
"y": np.array([0, 1]),
|
| 130 |
+
"sample_weight": None,
|
| 131 |
+
},
|
| 132 |
+
"`cv_results` does not contain one of the following",
|
| 133 |
+
),
|
| 134 |
+
(
|
| 135 |
+
{
|
| 136 |
+
"cv_results": {
|
| 137 |
+
"estimator": "dummy",
|
| 138 |
+
"indices": {"test": [[1, 2], [1, 2]], "train": [[3, 4], [3, 4]]},
|
| 139 |
+
},
|
| 140 |
+
# `X` wrong length
|
| 141 |
+
"X": np.array([[1, 2]]),
|
| 142 |
+
"y": np.array([0, 1]),
|
| 143 |
+
"sample_weight": None,
|
| 144 |
+
},
|
| 145 |
+
"`X` does not contain the correct number of",
|
| 146 |
+
),
|
| 147 |
+
(
|
| 148 |
+
{
|
| 149 |
+
"cv_results": {
|
| 150 |
+
"estimator": "dummy",
|
| 151 |
+
"indices": {"test": [[1, 2], [1, 2]], "train": [[3, 4], [3, 4]]},
|
| 152 |
+
},
|
| 153 |
+
"X": np.array([1, 2, 3, 4]),
|
| 154 |
+
# `y` not binary
|
| 155 |
+
"y": np.array([0, 2, 1, 3]),
|
| 156 |
+
"sample_weight": None,
|
| 157 |
+
},
|
| 158 |
+
"The target `y` is not binary",
|
| 159 |
+
),
|
| 160 |
+
(
|
| 161 |
+
{
|
| 162 |
+
"cv_results": {
|
| 163 |
+
"estimator": "dummy",
|
| 164 |
+
"indices": {"test": [[1, 2], [1, 2]], "train": [[3, 4], [3, 4]]},
|
| 165 |
+
},
|
| 166 |
+
"X": np.array([1, 2, 3, 4]),
|
| 167 |
+
"y": np.array([0, 1, 0, 1]),
|
| 168 |
+
# `sample_weight` wrong length
|
| 169 |
+
"sample_weight": np.array([0.5]),
|
| 170 |
+
},
|
| 171 |
+
"Found input variables with inconsistent",
|
| 172 |
+
),
|
| 173 |
+
],
|
| 174 |
+
)
|
| 175 |
+
def test_validate_from_cv_results_params(pyplot, params, err_msg):
|
| 176 |
+
"""Check parameter validation is performed correctly."""
|
| 177 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 178 |
+
_BinaryClassifierCurveDisplayMixin()._validate_from_cv_results_params(**params)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@pytest.mark.parametrize(
|
| 182 |
+
"curve_legend_metric, curve_name, expected_label",
|
| 183 |
+
[
|
| 184 |
+
(0.85, None, "AUC = 0.85"),
|
| 185 |
+
(None, "Model A", "Model A"),
|
| 186 |
+
(0.95, "Random Forest", "Random Forest (AUC = 0.95)"),
|
| 187 |
+
(None, None, None),
|
| 188 |
+
],
|
| 189 |
+
)
|
| 190 |
+
def test_get_legend_label(curve_legend_metric, curve_name, expected_label):
|
| 191 |
+
"""Check `_get_legend_label` returns the correct label."""
|
| 192 |
+
legend_metric_name = "AUC"
|
| 193 |
+
label = _BinaryClassifierCurveDisplayMixin._get_legend_label(
|
| 194 |
+
curve_legend_metric, curve_name, legend_metric_name
|
| 195 |
+
)
|
| 196 |
+
assert label == expected_label
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# TODO(1.9) : Remove
|
| 200 |
+
@pytest.mark.parametrize("curve_kwargs", [{"alpha": 1.0}, None])
|
| 201 |
+
@pytest.mark.parametrize("kwargs", [{}, {"alpha": 1.0}])
|
| 202 |
+
def test_validate_curve_kwargs_deprecate_kwargs(curve_kwargs, kwargs):
|
| 203 |
+
"""Check `_validate_curve_kwargs` deprecates kwargs correctly."""
|
| 204 |
+
n_curves = 1
|
| 205 |
+
name = None
|
| 206 |
+
legend_metric = {"mean": 0.8, "std": 0.1}
|
| 207 |
+
legend_metric_name = "AUC"
|
| 208 |
+
|
| 209 |
+
if curve_kwargs and kwargs:
|
| 210 |
+
with pytest.raises(ValueError, match="Cannot provide both `curve_kwargs`"):
|
| 211 |
+
_BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 212 |
+
n_curves,
|
| 213 |
+
name,
|
| 214 |
+
legend_metric,
|
| 215 |
+
legend_metric_name,
|
| 216 |
+
curve_kwargs,
|
| 217 |
+
**kwargs,
|
| 218 |
+
)
|
| 219 |
+
elif kwargs:
|
| 220 |
+
with pytest.warns(FutureWarning, match=r"`\*\*kwargs` is deprecated and"):
|
| 221 |
+
_BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 222 |
+
n_curves,
|
| 223 |
+
name,
|
| 224 |
+
legend_metric,
|
| 225 |
+
legend_metric_name,
|
| 226 |
+
curve_kwargs,
|
| 227 |
+
**kwargs,
|
| 228 |
+
)
|
| 229 |
+
else:
|
| 230 |
+
# No warning or error should be raised
|
| 231 |
+
_BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 232 |
+
n_curves, name, legend_metric, legend_metric_name, curve_kwargs, **kwargs
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def test_validate_curve_kwargs_error():
|
| 237 |
+
"""Check `_validate_curve_kwargs` performs parameter validation correctly."""
|
| 238 |
+
n_curves = 3
|
| 239 |
+
legend_metric = {"mean": 0.8, "std": 0.1}
|
| 240 |
+
legend_metric_name = "AUC"
|
| 241 |
+
with pytest.raises(ValueError, match="`curve_kwargs` must be None"):
|
| 242 |
+
_BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 243 |
+
n_curves=n_curves,
|
| 244 |
+
name=None,
|
| 245 |
+
legend_metric=legend_metric,
|
| 246 |
+
legend_metric_name=legend_metric_name,
|
| 247 |
+
curve_kwargs=[{"alpha": 1.0}],
|
| 248 |
+
)
|
| 249 |
+
with pytest.raises(ValueError, match="To avoid labeling individual curves"):
|
| 250 |
+
name = ["one", "two", "three"]
|
| 251 |
+
_BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 252 |
+
n_curves=n_curves,
|
| 253 |
+
name=name,
|
| 254 |
+
legend_metric=legend_metric,
|
| 255 |
+
legend_metric_name=legend_metric_name,
|
| 256 |
+
curve_kwargs=None,
|
| 257 |
+
)
|
| 258 |
+
_BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 259 |
+
n_curves=n_curves,
|
| 260 |
+
name=name,
|
| 261 |
+
legend_metric=legend_metric,
|
| 262 |
+
legend_metric_name=legend_metric_name,
|
| 263 |
+
curve_kwargs={"alpha": 1.0},
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
@pytest.mark.parametrize("name", [None, "curve_name", ["curve_name"]])
|
| 268 |
+
@pytest.mark.parametrize(
|
| 269 |
+
"legend_metric",
|
| 270 |
+
[{"mean": 0.8, "std": 0.2}, {"mean": None, "std": None}],
|
| 271 |
+
)
|
| 272 |
+
@pytest.mark.parametrize("legend_metric_name", ["AUC", "AP"])
|
| 273 |
+
@pytest.mark.parametrize("curve_kwargs", [None, {"color": "red"}])
|
| 274 |
+
def test_validate_curve_kwargs_single_legend(
|
| 275 |
+
name, legend_metric, legend_metric_name, curve_kwargs
|
| 276 |
+
):
|
| 277 |
+
"""Check `_validate_curve_kwargs` returns correct kwargs for single legend entry."""
|
| 278 |
+
n_curves = 3
|
| 279 |
+
curve_kwargs_out = _BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 280 |
+
n_curves=n_curves,
|
| 281 |
+
name=name,
|
| 282 |
+
legend_metric=legend_metric,
|
| 283 |
+
legend_metric_name=legend_metric_name,
|
| 284 |
+
curve_kwargs=curve_kwargs,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
assert isinstance(curve_kwargs_out, list)
|
| 288 |
+
assert len(curve_kwargs_out) == n_curves
|
| 289 |
+
|
| 290 |
+
expected_label = None
|
| 291 |
+
if isinstance(name, list):
|
| 292 |
+
name = name[0]
|
| 293 |
+
if name is not None:
|
| 294 |
+
expected_label = name
|
| 295 |
+
if legend_metric["mean"] is not None:
|
| 296 |
+
expected_label = expected_label + f" ({legend_metric_name} = 0.80 +/- 0.20)"
|
| 297 |
+
# `name` is None
|
| 298 |
+
elif legend_metric["mean"] is not None:
|
| 299 |
+
expected_label = f"{legend_metric_name} = 0.80 +/- 0.20"
|
| 300 |
+
|
| 301 |
+
assert curve_kwargs_out[0]["label"] == expected_label
|
| 302 |
+
# All remaining curves should have None as "label"
|
| 303 |
+
assert curve_kwargs_out[1]["label"] is None
|
| 304 |
+
assert curve_kwargs_out[2]["label"] is None
|
| 305 |
+
|
| 306 |
+
if curve_kwargs is None:
|
| 307 |
+
assert all("color" not in kwargs for kwargs in curve_kwargs_out)
|
| 308 |
+
else:
|
| 309 |
+
assert all(kwargs["color"] == "red" for kwargs in curve_kwargs_out)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@pytest.mark.parametrize("name", [None, "curve_name", ["one", "two", "three"]])
|
| 313 |
+
@pytest.mark.parametrize(
|
| 314 |
+
"legend_metric", [{"metric": [1.0, 1.0, 1.0]}, {"metric": [None, None, None]}]
|
| 315 |
+
)
|
| 316 |
+
@pytest.mark.parametrize("legend_metric_name", ["AUC", "AP"])
|
| 317 |
+
def test_validate_curve_kwargs_multi_legend(name, legend_metric, legend_metric_name):
|
| 318 |
+
"""Check `_validate_curve_kwargs` returns correct kwargs for multi legend entry."""
|
| 319 |
+
n_curves = 3
|
| 320 |
+
curve_kwargs = [{"color": "red"}, {"color": "yellow"}, {"color": "blue"}]
|
| 321 |
+
curve_kwargs_out = _BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 322 |
+
n_curves=n_curves,
|
| 323 |
+
name=name,
|
| 324 |
+
legend_metric=legend_metric,
|
| 325 |
+
legend_metric_name=legend_metric_name,
|
| 326 |
+
curve_kwargs=curve_kwargs,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
assert isinstance(curve_kwargs_out, list)
|
| 330 |
+
assert len(curve_kwargs_out) == n_curves
|
| 331 |
+
|
| 332 |
+
expected_labels = [None, None, None]
|
| 333 |
+
if isinstance(name, str):
|
| 334 |
+
expected_labels = "curve_name"
|
| 335 |
+
if legend_metric["metric"][0] is not None:
|
| 336 |
+
expected_labels = expected_labels + f" ({legend_metric_name} = 1.00)"
|
| 337 |
+
expected_labels = [expected_labels] * n_curves
|
| 338 |
+
elif isinstance(name, list) and legend_metric["metric"][0] is None:
|
| 339 |
+
expected_labels = name
|
| 340 |
+
elif isinstance(name, list) and legend_metric["metric"][0] is not None:
|
| 341 |
+
expected_labels = [
|
| 342 |
+
f"{name_single} ({legend_metric_name} = 1.00)" for name_single in name
|
| 343 |
+
]
|
| 344 |
+
# `name` is None
|
| 345 |
+
elif legend_metric["metric"][0] is not None:
|
| 346 |
+
expected_labels = [f"{legend_metric_name} = 1.00"] * n_curves
|
| 347 |
+
|
| 348 |
+
for idx, expected_label in enumerate(expected_labels):
|
| 349 |
+
assert curve_kwargs_out[idx]["label"] == expected_label
|
| 350 |
+
|
| 351 |
+
for curve_kwarg, curve_kwarg_out in zip(curve_kwargs, curve_kwargs_out):
|
| 352 |
+
assert curve_kwarg_out["color"] == curve_kwarg["color"]
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
@pytest.mark.parametrize("curve_kwargs", [None, {"color": "red"}])
|
| 356 |
+
@pytest.mark.parametrize("n_curves", [1, 3])
|
| 357 |
+
def test_validate_curve_kwargs_default_kwargs(n_curves, curve_kwargs):
|
| 358 |
+
"""Check default kwargs are incorporated correctly."""
|
| 359 |
+
curve_kwargs_out = _BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
|
| 360 |
+
n_curves=n_curves,
|
| 361 |
+
name="test",
|
| 362 |
+
legend_metric={"mean": 0.8, "std": 0.2},
|
| 363 |
+
legend_metric_name="metric",
|
| 364 |
+
curve_kwargs=curve_kwargs,
|
| 365 |
+
default_curve_kwargs={"color": "blue"},
|
| 366 |
+
default_multi_curve_kwargs={"alpha": 0.7, "linestyle": "--", "color": "green"},
|
| 367 |
+
)
|
| 368 |
+
if n_curves > 1:
|
| 369 |
+
# `default_multi_curve_kwargs` are incorporated
|
| 370 |
+
assert all(kwarg["alpha"] == 0.7 for kwarg in curve_kwargs_out)
|
| 371 |
+
assert all(kwarg["linestyle"] == "--" for kwarg in curve_kwargs_out)
|
| 372 |
+
if curve_kwargs is None:
|
| 373 |
+
# `default_multi_curve_kwargs` over-rides `default_curve_kwargs`
|
| 374 |
+
assert all(kwarg["color"] == "green" for kwarg in curve_kwargs_out)
|
| 375 |
+
else:
|
| 376 |
+
# `curve_kwargs` over-rides any defaults
|
| 377 |
+
assert all(kwarg["color"] == "red" for kwarg in curve_kwargs_out)
|
| 378 |
+
# Single curve
|
| 379 |
+
elif curve_kwargs is None:
|
| 380 |
+
# Use `default_curve_kwargs`
|
| 381 |
+
assert all(kwarg["color"] == "blue" for kwarg in curve_kwargs_out)
|
| 382 |
+
else:
|
| 383 |
+
# Use `curve_kwargs`
|
| 384 |
+
assert all(kwarg["color"] == "red" for kwarg in curve_kwargs_out)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def metric():
|
| 388 |
+
pass # pragma: no cover
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def neg_metric():
|
| 392 |
+
pass # pragma: no cover
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@pytest.mark.parametrize(
|
| 396 |
+
"score_name, scoring, negate_score, expected_score_name",
|
| 397 |
+
[
|
| 398 |
+
("accuracy", None, False, "accuracy"), # do not transform the name
|
| 399 |
+
(None, "accuracy", False, "Accuracy"), # capitalize the name
|
| 400 |
+
(None, "accuracy", True, "Negative accuracy"), # add "Negative"
|
| 401 |
+
(None, "neg_mean_absolute_error", False, "Negative mean absolute error"),
|
| 402 |
+
(None, "neg_mean_absolute_error", True, "Mean absolute error"), # remove "neg_"
|
| 403 |
+
("MAE", "neg_mean_absolute_error", True, "MAE"), # keep score_name
|
| 404 |
+
(None, None, False, "Score"), # default name
|
| 405 |
+
(None, None, True, "Negative score"), # default name but negated
|
| 406 |
+
("Some metric", metric, False, "Some metric"), # do not transform the name
|
| 407 |
+
("Some metric", metric, True, "Some metric"), # do not transform the name
|
| 408 |
+
(None, metric, False, "Metric"), # default name
|
| 409 |
+
(None, metric, True, "Negative metric"), # default name but negated
|
| 410 |
+
("Some metric", neg_metric, False, "Some metric"), # do not transform the name
|
| 411 |
+
("Some metric", neg_metric, True, "Some metric"), # do not transform the name
|
| 412 |
+
(None, neg_metric, False, "Negative metric"), # default name
|
| 413 |
+
(None, neg_metric, True, "Metric"), # default name but negated
|
| 414 |
+
],
|
| 415 |
+
)
|
| 416 |
+
def test_validate_score_name(score_name, scoring, negate_score, expected_score_name):
|
| 417 |
+
"""Check that we return the right score name."""
|
| 418 |
+
assert (
|
| 419 |
+
_validate_score_name(score_name, scoring, negate_score) == expected_score_name
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
# In the following test, we check the value of the max to min ratio
|
| 424 |
+
# for parameter value intervals to check that using a decision threshold
|
| 425 |
+
# of 5. is a good heuristic to decide between linear and log scales on
|
| 426 |
+
# common ranges of parameter values.
|
| 427 |
+
@pytest.mark.parametrize(
|
| 428 |
+
"data, lower_bound, upper_bound",
|
| 429 |
+
[
|
| 430 |
+
# Such a range could be clearly displayed with either log scale or linear
|
| 431 |
+
# scale.
|
| 432 |
+
(np.geomspace(0.1, 1, 5), 5, 6),
|
| 433 |
+
# Checking that the ratio is still positive on a negative log scale.
|
| 434 |
+
(-np.geomspace(0.1, 1, 10), 7, 8),
|
| 435 |
+
# Evenly spaced parameter values lead to a ratio of 1.
|
| 436 |
+
(np.linspace(0, 1, 5), 0.9, 1.1),
|
| 437 |
+
# This is not exactly spaced on a log scale but we will benefit from treating
|
| 438 |
+
# it as such for visualization.
|
| 439 |
+
([1, 2, 5, 10, 20, 50], 20, 40),
|
| 440 |
+
],
|
| 441 |
+
)
|
| 442 |
+
def test_inverval_max_min_ratio(data, lower_bound, upper_bound):
|
| 443 |
+
assert lower_bound < _interval_max_min_ratio(data) < upper_bound
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
@pytest.mark.parametrize(
|
| 447 |
+
"default_kwargs, user_kwargs, expected",
|
| 448 |
+
[
|
| 449 |
+
(
|
| 450 |
+
{"color": "blue", "linewidth": 2},
|
| 451 |
+
{"linestyle": "dashed"},
|
| 452 |
+
{"color": "blue", "linewidth": 2, "linestyle": "dashed"},
|
| 453 |
+
),
|
| 454 |
+
(
|
| 455 |
+
{"color": "blue", "linestyle": "solid"},
|
| 456 |
+
{"c": "red", "ls": "dashed"},
|
| 457 |
+
{"color": "red", "linestyle": "dashed"},
|
| 458 |
+
),
|
| 459 |
+
(
|
| 460 |
+
{"label": "xxx", "color": "k", "linestyle": "--"},
|
| 461 |
+
{"ls": "-."},
|
| 462 |
+
{"label": "xxx", "color": "k", "linestyle": "-."},
|
| 463 |
+
),
|
| 464 |
+
({}, {}, {}),
|
| 465 |
+
(
|
| 466 |
+
{},
|
| 467 |
+
{
|
| 468 |
+
"ls": "dashed",
|
| 469 |
+
"c": "red",
|
| 470 |
+
"ec": "black",
|
| 471 |
+
"fc": "yellow",
|
| 472 |
+
"lw": 2,
|
| 473 |
+
"mec": "green",
|
| 474 |
+
"mfcalt": "blue",
|
| 475 |
+
"ms": 5,
|
| 476 |
+
},
|
| 477 |
+
{
|
| 478 |
+
"linestyle": "dashed",
|
| 479 |
+
"color": "red",
|
| 480 |
+
"edgecolor": "black",
|
| 481 |
+
"facecolor": "yellow",
|
| 482 |
+
"linewidth": 2,
|
| 483 |
+
"markeredgecolor": "green",
|
| 484 |
+
"markerfacecoloralt": "blue",
|
| 485 |
+
"markersize": 5,
|
| 486 |
+
},
|
| 487 |
+
),
|
| 488 |
+
],
|
| 489 |
+
)
|
| 490 |
+
def test_validate_style_kwargs(default_kwargs, user_kwargs, expected):
|
| 491 |
+
"""Check the behaviour of `validate_style_kwargs` with various type of entries."""
|
| 492 |
+
result = _validate_style_kwargs(default_kwargs, user_kwargs)
|
| 493 |
+
assert result == expected, (
|
| 494 |
+
"The validation of style keywords does not provide the expected results: "
|
| 495 |
+
f"Got {result} instead of {expected}."
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
@pytest.mark.parametrize(
|
| 500 |
+
"default_kwargs, user_kwargs",
|
| 501 |
+
[({}, {"ls": 2, "linestyle": 3}), ({}, {"c": "r", "color": "blue"})],
|
| 502 |
+
)
|
| 503 |
+
def test_validate_style_kwargs_error(default_kwargs, user_kwargs):
|
| 504 |
+
"""Check that `validate_style_kwargs` raises TypeError"""
|
| 505 |
+
with pytest.raises(TypeError):
|
| 506 |
+
_validate_style_kwargs(default_kwargs, user_kwargs)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def test_despine(pyplot):
|
| 510 |
+
ax = pyplot.gca()
|
| 511 |
+
_despine(ax)
|
| 512 |
+
assert ax.spines["top"].get_visible() is False
|
| 513 |
+
assert ax.spines["right"].get_visible() is False
|
| 514 |
+
assert ax.spines["bottom"].get_bounds() == (0, 1)
|
| 515 |
+
assert ax.spines["left"].get_bounds() == (0, 1)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
@pytest.mark.parametrize("estimator_name", ["my_est_name", "deprecated"])
|
| 519 |
+
@pytest.mark.parametrize("name", [None, "my_name"])
|
| 520 |
+
def test_deprecate_estimator_name(estimator_name, name):
|
| 521 |
+
"""Check `_deprecate_estimator_name` behaves correctly"""
|
| 522 |
+
version = "1.7"
|
| 523 |
+
version_remove = "1.9"
|
| 524 |
+
|
| 525 |
+
if estimator_name == "deprecated":
|
| 526 |
+
name_out = _deprecate_estimator_name(estimator_name, name, version)
|
| 527 |
+
assert name_out == name
|
| 528 |
+
# `estimator_name` is provided and `name` is:
|
| 529 |
+
elif name is None:
|
| 530 |
+
warning_message = (
|
| 531 |
+
f"`estimator_name` is deprecated in {version} and will be removed in "
|
| 532 |
+
f"{version_remove}. Use `name` instead."
|
| 533 |
+
)
|
| 534 |
+
with pytest.warns(FutureWarning, match=warning_message):
|
| 535 |
+
result = _deprecate_estimator_name(estimator_name, name, version)
|
| 536 |
+
assert result == estimator_name
|
| 537 |
+
elif name is not None:
|
| 538 |
+
error_message = (
|
| 539 |
+
f"Cannot provide both `estimator_name` and `name`. `estimator_name` "
|
| 540 |
+
f"is deprecated in {version} and will be removed in {version_remove}. "
|
| 541 |
+
)
|
| 542 |
+
with pytest.raises(ValueError, match=error_message):
|
| 543 |
+
_deprecate_estimator_name(estimator_name, name, version)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_pprint.py
ADDED
|
@@ -0,0 +1,693 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from pprint import PrettyPrinter
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from sklearn import config_context
|
| 8 |
+
from sklearn.base import BaseEstimator, TransformerMixin
|
| 9 |
+
from sklearn.feature_selection import SelectKBest, chi2
|
| 10 |
+
from sklearn.linear_model import LogisticRegressionCV
|
| 11 |
+
from sklearn.pipeline import make_pipeline
|
| 12 |
+
from sklearn.utils._pprint import _EstimatorPrettyPrinter
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# Constructors excerpted to test pprinting
|
| 16 |
+
class LogisticRegression(BaseEstimator):
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
C=1.0,
|
| 20 |
+
l1_ratio=0,
|
| 21 |
+
dual=False,
|
| 22 |
+
tol=1e-4,
|
| 23 |
+
fit_intercept=True,
|
| 24 |
+
intercept_scaling=1,
|
| 25 |
+
class_weight=None,
|
| 26 |
+
random_state=None,
|
| 27 |
+
solver="warn",
|
| 28 |
+
max_iter=100,
|
| 29 |
+
multi_class="warn",
|
| 30 |
+
verbose=0,
|
| 31 |
+
warm_start=False,
|
| 32 |
+
n_jobs=None,
|
| 33 |
+
):
|
| 34 |
+
self.C = C
|
| 35 |
+
self.l1_ratio = l1_ratio
|
| 36 |
+
self.dual = dual
|
| 37 |
+
self.tol = tol
|
| 38 |
+
self.fit_intercept = fit_intercept
|
| 39 |
+
self.intercept_scaling = intercept_scaling
|
| 40 |
+
self.class_weight = class_weight
|
| 41 |
+
self.random_state = random_state
|
| 42 |
+
self.solver = solver
|
| 43 |
+
self.max_iter = max_iter
|
| 44 |
+
self.multi_class = multi_class
|
| 45 |
+
self.verbose = verbose
|
| 46 |
+
self.warm_start = warm_start
|
| 47 |
+
self.n_jobs = n_jobs
|
| 48 |
+
|
| 49 |
+
def fit(self, X, y):
|
| 50 |
+
return self
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class StandardScaler(TransformerMixin, BaseEstimator):
|
| 54 |
+
def __init__(self, copy=True, with_mean=True, with_std=True):
|
| 55 |
+
self.with_mean = with_mean
|
| 56 |
+
self.with_std = with_std
|
| 57 |
+
self.copy = copy
|
| 58 |
+
|
| 59 |
+
def transform(self, X, copy=None):
|
| 60 |
+
return self
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class RFE(BaseEstimator):
|
| 64 |
+
def __init__(self, estimator, n_features_to_select=None, step=1, verbose=0):
|
| 65 |
+
self.estimator = estimator
|
| 66 |
+
self.n_features_to_select = n_features_to_select
|
| 67 |
+
self.step = step
|
| 68 |
+
self.verbose = verbose
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class GridSearchCV(BaseEstimator):
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
estimator,
|
| 75 |
+
param_grid,
|
| 76 |
+
scoring=None,
|
| 77 |
+
n_jobs=None,
|
| 78 |
+
iid="warn",
|
| 79 |
+
refit=True,
|
| 80 |
+
cv="warn",
|
| 81 |
+
verbose=0,
|
| 82 |
+
pre_dispatch="2*n_jobs",
|
| 83 |
+
error_score="raise-deprecating",
|
| 84 |
+
return_train_score=False,
|
| 85 |
+
):
|
| 86 |
+
self.estimator = estimator
|
| 87 |
+
self.param_grid = param_grid
|
| 88 |
+
self.scoring = scoring
|
| 89 |
+
self.n_jobs = n_jobs
|
| 90 |
+
self.iid = iid
|
| 91 |
+
self.refit = refit
|
| 92 |
+
self.cv = cv
|
| 93 |
+
self.verbose = verbose
|
| 94 |
+
self.pre_dispatch = pre_dispatch
|
| 95 |
+
self.error_score = error_score
|
| 96 |
+
self.return_train_score = return_train_score
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class CountVectorizer(BaseEstimator):
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
input="content",
|
| 103 |
+
encoding="utf-8",
|
| 104 |
+
decode_error="strict",
|
| 105 |
+
strip_accents=None,
|
| 106 |
+
lowercase=True,
|
| 107 |
+
preprocessor=None,
|
| 108 |
+
tokenizer=None,
|
| 109 |
+
stop_words=None,
|
| 110 |
+
token_pattern=r"(?u)\b\w\w+\b",
|
| 111 |
+
ngram_range=(1, 1),
|
| 112 |
+
analyzer="word",
|
| 113 |
+
max_df=1.0,
|
| 114 |
+
min_df=1,
|
| 115 |
+
max_features=None,
|
| 116 |
+
vocabulary=None,
|
| 117 |
+
binary=False,
|
| 118 |
+
dtype=np.int64,
|
| 119 |
+
):
|
| 120 |
+
self.input = input
|
| 121 |
+
self.encoding = encoding
|
| 122 |
+
self.decode_error = decode_error
|
| 123 |
+
self.strip_accents = strip_accents
|
| 124 |
+
self.preprocessor = preprocessor
|
| 125 |
+
self.tokenizer = tokenizer
|
| 126 |
+
self.analyzer = analyzer
|
| 127 |
+
self.lowercase = lowercase
|
| 128 |
+
self.token_pattern = token_pattern
|
| 129 |
+
self.stop_words = stop_words
|
| 130 |
+
self.max_df = max_df
|
| 131 |
+
self.min_df = min_df
|
| 132 |
+
self.max_features = max_features
|
| 133 |
+
self.ngram_range = ngram_range
|
| 134 |
+
self.vocabulary = vocabulary
|
| 135 |
+
self.binary = binary
|
| 136 |
+
self.dtype = dtype
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class Pipeline(BaseEstimator):
|
| 140 |
+
def __init__(self, steps, memory=None):
|
| 141 |
+
self.steps = steps
|
| 142 |
+
self.memory = memory
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class SVC(BaseEstimator):
|
| 146 |
+
def __init__(
|
| 147 |
+
self,
|
| 148 |
+
C=1.0,
|
| 149 |
+
kernel="rbf",
|
| 150 |
+
degree=3,
|
| 151 |
+
gamma="auto_deprecated",
|
| 152 |
+
coef0=0.0,
|
| 153 |
+
shrinking=True,
|
| 154 |
+
probability=False,
|
| 155 |
+
tol=1e-3,
|
| 156 |
+
cache_size=200,
|
| 157 |
+
class_weight=None,
|
| 158 |
+
verbose=False,
|
| 159 |
+
max_iter=-1,
|
| 160 |
+
decision_function_shape="ovr",
|
| 161 |
+
random_state=None,
|
| 162 |
+
):
|
| 163 |
+
self.kernel = kernel
|
| 164 |
+
self.degree = degree
|
| 165 |
+
self.gamma = gamma
|
| 166 |
+
self.coef0 = coef0
|
| 167 |
+
self.tol = tol
|
| 168 |
+
self.C = C
|
| 169 |
+
self.shrinking = shrinking
|
| 170 |
+
self.probability = probability
|
| 171 |
+
self.cache_size = cache_size
|
| 172 |
+
self.class_weight = class_weight
|
| 173 |
+
self.verbose = verbose
|
| 174 |
+
self.max_iter = max_iter
|
| 175 |
+
self.decision_function_shape = decision_function_shape
|
| 176 |
+
self.random_state = random_state
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class PCA(BaseEstimator):
|
| 180 |
+
def __init__(
|
| 181 |
+
self,
|
| 182 |
+
n_components=None,
|
| 183 |
+
copy=True,
|
| 184 |
+
whiten=False,
|
| 185 |
+
svd_solver="auto",
|
| 186 |
+
tol=0.0,
|
| 187 |
+
iterated_power="auto",
|
| 188 |
+
random_state=None,
|
| 189 |
+
):
|
| 190 |
+
self.n_components = n_components
|
| 191 |
+
self.copy = copy
|
| 192 |
+
self.whiten = whiten
|
| 193 |
+
self.svd_solver = svd_solver
|
| 194 |
+
self.tol = tol
|
| 195 |
+
self.iterated_power = iterated_power
|
| 196 |
+
self.random_state = random_state
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class NMF(BaseEstimator):
|
| 200 |
+
def __init__(
|
| 201 |
+
self,
|
| 202 |
+
n_components=None,
|
| 203 |
+
init=None,
|
| 204 |
+
solver="cd",
|
| 205 |
+
beta_loss="frobenius",
|
| 206 |
+
tol=1e-4,
|
| 207 |
+
max_iter=200,
|
| 208 |
+
random_state=None,
|
| 209 |
+
alpha=0.0,
|
| 210 |
+
l1_ratio=0.0,
|
| 211 |
+
verbose=0,
|
| 212 |
+
shuffle=False,
|
| 213 |
+
):
|
| 214 |
+
self.n_components = n_components
|
| 215 |
+
self.init = init
|
| 216 |
+
self.solver = solver
|
| 217 |
+
self.beta_loss = beta_loss
|
| 218 |
+
self.tol = tol
|
| 219 |
+
self.max_iter = max_iter
|
| 220 |
+
self.random_state = random_state
|
| 221 |
+
self.alpha = alpha
|
| 222 |
+
self.l1_ratio = l1_ratio
|
| 223 |
+
self.verbose = verbose
|
| 224 |
+
self.shuffle = shuffle
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class SimpleImputer(BaseEstimator):
|
| 228 |
+
def __init__(
|
| 229 |
+
self,
|
| 230 |
+
missing_values=np.nan,
|
| 231 |
+
strategy="mean",
|
| 232 |
+
fill_value=None,
|
| 233 |
+
verbose=0,
|
| 234 |
+
copy=True,
|
| 235 |
+
):
|
| 236 |
+
self.missing_values = missing_values
|
| 237 |
+
self.strategy = strategy
|
| 238 |
+
self.fill_value = fill_value
|
| 239 |
+
self.verbose = verbose
|
| 240 |
+
self.copy = copy
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@config_context(print_changed_only=False)
|
| 244 |
+
def test_basic():
|
| 245 |
+
# Basic pprint test
|
| 246 |
+
lr = LogisticRegression()
|
| 247 |
+
expected = """
|
| 248 |
+
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
|
| 249 |
+
intercept_scaling=1, l1_ratio=0, max_iter=100,
|
| 250 |
+
multi_class='warn', n_jobs=None, random_state=None,
|
| 251 |
+
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
|
| 252 |
+
|
| 253 |
+
expected = expected[1:] # remove first \n
|
| 254 |
+
assert lr.__repr__() == expected
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def test_changed_only():
|
| 258 |
+
# Make sure the changed_only param is correctly used when True (default)
|
| 259 |
+
lr = LogisticRegression(C=99)
|
| 260 |
+
expected = """LogisticRegression(C=99)"""
|
| 261 |
+
assert lr.__repr__() == expected
|
| 262 |
+
|
| 263 |
+
# Check with a repr that doesn't fit on a single line
|
| 264 |
+
lr = LogisticRegression(
|
| 265 |
+
C=99, class_weight=0.4, fit_intercept=False, tol=1234, verbose=True
|
| 266 |
+
)
|
| 267 |
+
expected = """
|
| 268 |
+
LogisticRegression(C=99, class_weight=0.4, fit_intercept=False, tol=1234,
|
| 269 |
+
verbose=True)"""
|
| 270 |
+
expected = expected[1:] # remove first \n
|
| 271 |
+
assert lr.__repr__() == expected
|
| 272 |
+
|
| 273 |
+
imputer = SimpleImputer(missing_values=0)
|
| 274 |
+
expected = """SimpleImputer(missing_values=0)"""
|
| 275 |
+
assert imputer.__repr__() == expected
|
| 276 |
+
|
| 277 |
+
# Defaults to np.nan, trying with float('NaN')
|
| 278 |
+
imputer = SimpleImputer(missing_values=float("NaN"))
|
| 279 |
+
expected = """SimpleImputer()"""
|
| 280 |
+
assert imputer.__repr__() == expected
|
| 281 |
+
|
| 282 |
+
# make sure array parameters don't throw error (see #13583)
|
| 283 |
+
repr(LogisticRegressionCV(Cs=np.array([0.1, 1]), use_legacy_attributes=False))
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
@config_context(print_changed_only=False)
|
| 287 |
+
def test_pipeline():
|
| 288 |
+
# Render a pipeline object
|
| 289 |
+
pipeline = make_pipeline(StandardScaler(), LogisticRegression(C=999))
|
| 290 |
+
expected = """
|
| 291 |
+
Pipeline(memory=None,
|
| 292 |
+
steps=[('standardscaler',
|
| 293 |
+
StandardScaler(copy=True, with_mean=True, with_std=True)),
|
| 294 |
+
('logisticregression',
|
| 295 |
+
LogisticRegression(C=999, class_weight=None, dual=False,
|
| 296 |
+
fit_intercept=True, intercept_scaling=1,
|
| 297 |
+
l1_ratio=0, max_iter=100,
|
| 298 |
+
multi_class='warn', n_jobs=None,
|
| 299 |
+
random_state=None, solver='warn',
|
| 300 |
+
tol=0.0001, verbose=0, warm_start=False))],
|
| 301 |
+
transform_input=None, verbose=False)"""
|
| 302 |
+
|
| 303 |
+
expected = expected[1:] # remove first \n
|
| 304 |
+
assert pipeline.__repr__() == expected
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
@config_context(print_changed_only=False)
|
| 308 |
+
def test_deeply_nested():
|
| 309 |
+
# Render a deeply nested estimator
|
| 310 |
+
rfe = RFE(RFE(RFE(RFE(RFE(RFE(RFE(LogisticRegression())))))))
|
| 311 |
+
expected = """
|
| 312 |
+
RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=LogisticRegression(C=1.0,
|
| 313 |
+
class_weight=None,
|
| 314 |
+
dual=False,
|
| 315 |
+
fit_intercept=True,
|
| 316 |
+
intercept_scaling=1,
|
| 317 |
+
l1_ratio=0,
|
| 318 |
+
max_iter=100,
|
| 319 |
+
multi_class='warn',
|
| 320 |
+
n_jobs=None,
|
| 321 |
+
random_state=None,
|
| 322 |
+
solver='warn',
|
| 323 |
+
tol=0.0001,
|
| 324 |
+
verbose=0,
|
| 325 |
+
warm_start=False),
|
| 326 |
+
n_features_to_select=None,
|
| 327 |
+
step=1,
|
| 328 |
+
verbose=0),
|
| 329 |
+
n_features_to_select=None,
|
| 330 |
+
step=1,
|
| 331 |
+
verbose=0),
|
| 332 |
+
n_features_to_select=None,
|
| 333 |
+
step=1, verbose=0),
|
| 334 |
+
n_features_to_select=None, step=1,
|
| 335 |
+
verbose=0),
|
| 336 |
+
n_features_to_select=None, step=1, verbose=0),
|
| 337 |
+
n_features_to_select=None, step=1, verbose=0),
|
| 338 |
+
n_features_to_select=None, step=1, verbose=0)"""
|
| 339 |
+
|
| 340 |
+
expected = expected[1:] # remove first \n
|
| 341 |
+
assert rfe.__repr__() == expected
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
@pytest.mark.parametrize(
|
| 345 |
+
("print_changed_only", "expected"),
|
| 346 |
+
[
|
| 347 |
+
(True, "RFE(estimator=RFE(...))"),
|
| 348 |
+
(
|
| 349 |
+
False,
|
| 350 |
+
"RFE(estimator=RFE(...), n_features_to_select=None, step=1, verbose=0)",
|
| 351 |
+
),
|
| 352 |
+
],
|
| 353 |
+
)
|
| 354 |
+
def test_print_estimator_max_depth(print_changed_only, expected):
|
| 355 |
+
with config_context(print_changed_only=print_changed_only):
|
| 356 |
+
pp = _EstimatorPrettyPrinter(depth=1)
|
| 357 |
+
|
| 358 |
+
rfe = RFE(RFE(RFE(RFE(RFE(LogisticRegression())))))
|
| 359 |
+
assert pp.pformat(rfe) == expected
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@config_context(print_changed_only=False)
|
| 363 |
+
def test_gridsearch():
|
| 364 |
+
# render a gridsearch
|
| 365 |
+
param_grid = [
|
| 366 |
+
{"kernel": ["rbf"], "gamma": [1e-3, 1e-4], "C": [1, 10, 100, 1000]},
|
| 367 |
+
{"kernel": ["linear"], "C": [1, 10, 100, 1000]},
|
| 368 |
+
]
|
| 369 |
+
gs = GridSearchCV(SVC(), param_grid, cv=5)
|
| 370 |
+
|
| 371 |
+
expected = """
|
| 372 |
+
GridSearchCV(cv=5, error_score='raise-deprecating',
|
| 373 |
+
estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
|
| 374 |
+
decision_function_shape='ovr', degree=3,
|
| 375 |
+
gamma='auto_deprecated', kernel='rbf', max_iter=-1,
|
| 376 |
+
probability=False, random_state=None, shrinking=True,
|
| 377 |
+
tol=0.001, verbose=False),
|
| 378 |
+
iid='warn', n_jobs=None,
|
| 379 |
+
param_grid=[{'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001],
|
| 380 |
+
'kernel': ['rbf']},
|
| 381 |
+
{'C': [1, 10, 100, 1000], 'kernel': ['linear']}],
|
| 382 |
+
pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
|
| 383 |
+
scoring=None, verbose=0)"""
|
| 384 |
+
|
| 385 |
+
expected = expected[1:] # remove first \n
|
| 386 |
+
assert gs.__repr__() == expected
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@config_context(print_changed_only=False)
|
| 390 |
+
def test_gridsearch_pipeline():
|
| 391 |
+
# render a pipeline inside a gridsearch
|
| 392 |
+
pp = _EstimatorPrettyPrinter(compact=True, indent=1, indent_at_name=True)
|
| 393 |
+
|
| 394 |
+
pipeline = Pipeline([("reduce_dim", PCA()), ("classify", SVC())])
|
| 395 |
+
N_FEATURES_OPTIONS = [2, 4, 8]
|
| 396 |
+
C_OPTIONS = [1, 10, 100, 1000]
|
| 397 |
+
param_grid = [
|
| 398 |
+
{
|
| 399 |
+
"reduce_dim": [PCA(iterated_power=7), NMF()],
|
| 400 |
+
"reduce_dim__n_components": N_FEATURES_OPTIONS,
|
| 401 |
+
"classify__C": C_OPTIONS,
|
| 402 |
+
},
|
| 403 |
+
{
|
| 404 |
+
"reduce_dim": [SelectKBest(chi2)],
|
| 405 |
+
"reduce_dim__k": N_FEATURES_OPTIONS,
|
| 406 |
+
"classify__C": C_OPTIONS,
|
| 407 |
+
},
|
| 408 |
+
]
|
| 409 |
+
gspipeline = GridSearchCV(pipeline, cv=3, n_jobs=1, param_grid=param_grid)
|
| 410 |
+
expected = """
|
| 411 |
+
GridSearchCV(cv=3, error_score='raise-deprecating',
|
| 412 |
+
estimator=Pipeline(memory=None,
|
| 413 |
+
steps=[('reduce_dim',
|
| 414 |
+
PCA(copy=True, iterated_power='auto',
|
| 415 |
+
n_components=None,
|
| 416 |
+
random_state=None,
|
| 417 |
+
svd_solver='auto', tol=0.0,
|
| 418 |
+
whiten=False)),
|
| 419 |
+
('classify',
|
| 420 |
+
SVC(C=1.0, cache_size=200,
|
| 421 |
+
class_weight=None, coef0=0.0,
|
| 422 |
+
decision_function_shape='ovr',
|
| 423 |
+
degree=3, gamma='auto_deprecated',
|
| 424 |
+
kernel='rbf', max_iter=-1,
|
| 425 |
+
probability=False,
|
| 426 |
+
random_state=None, shrinking=True,
|
| 427 |
+
tol=0.001, verbose=False))]),
|
| 428 |
+
iid='warn', n_jobs=1,
|
| 429 |
+
param_grid=[{'classify__C': [1, 10, 100, 1000],
|
| 430 |
+
'reduce_dim': [PCA(copy=True, iterated_power=7,
|
| 431 |
+
n_components=None,
|
| 432 |
+
random_state=None,
|
| 433 |
+
svd_solver='auto', tol=0.0,
|
| 434 |
+
whiten=False),
|
| 435 |
+
NMF(alpha=0.0, beta_loss='frobenius',
|
| 436 |
+
init=None, l1_ratio=0.0,
|
| 437 |
+
max_iter=200, n_components=None,
|
| 438 |
+
random_state=None, shuffle=False,
|
| 439 |
+
solver='cd', tol=0.0001,
|
| 440 |
+
verbose=0)],
|
| 441 |
+
'reduce_dim__n_components': [2, 4, 8]},
|
| 442 |
+
{'classify__C': [1, 10, 100, 1000],
|
| 443 |
+
'reduce_dim': [SelectKBest(k=10,
|
| 444 |
+
score_func=<function chi2 at some_address>)],
|
| 445 |
+
'reduce_dim__k': [2, 4, 8]}],
|
| 446 |
+
pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
|
| 447 |
+
scoring=None, verbose=0)""" # noqa: E501
|
| 448 |
+
|
| 449 |
+
expected = expected[1:] # remove first \n
|
| 450 |
+
repr_ = pp.pformat(gspipeline)
|
| 451 |
+
# Remove address of '<function chi2 at 0x.....>' for reproducibility
|
| 452 |
+
repr_ = re.sub("function chi2 at 0x.*>", "function chi2 at some_address>", repr_)
|
| 453 |
+
assert repr_ == expected
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
@config_context(print_changed_only=False)
|
| 457 |
+
def test_n_max_elements_to_show():
|
| 458 |
+
n_max_elements_to_show = 30
|
| 459 |
+
pp = _EstimatorPrettyPrinter(
|
| 460 |
+
compact=True,
|
| 461 |
+
indent=1,
|
| 462 |
+
indent_at_name=True,
|
| 463 |
+
n_max_elements_to_show=n_max_elements_to_show,
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
# No ellipsis
|
| 467 |
+
vocabulary = {i: i for i in range(n_max_elements_to_show)}
|
| 468 |
+
vectorizer = CountVectorizer(vocabulary=vocabulary)
|
| 469 |
+
|
| 470 |
+
expected = r"""
|
| 471 |
+
CountVectorizer(analyzer='word', binary=False, decode_error='strict',
|
| 472 |
+
dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
|
| 473 |
+
lowercase=True, max_df=1.0, max_features=None, min_df=1,
|
| 474 |
+
ngram_range=(1, 1), preprocessor=None, stop_words=None,
|
| 475 |
+
strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',
|
| 476 |
+
tokenizer=None,
|
| 477 |
+
vocabulary={0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7,
|
| 478 |
+
8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14,
|
| 479 |
+
15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20,
|
| 480 |
+
21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26,
|
| 481 |
+
27: 27, 28: 28, 29: 29})"""
|
| 482 |
+
|
| 483 |
+
expected = expected[1:] # remove first \n
|
| 484 |
+
assert pp.pformat(vectorizer) == expected
|
| 485 |
+
|
| 486 |
+
# Now with ellipsis
|
| 487 |
+
vocabulary = {i: i for i in range(n_max_elements_to_show + 1)}
|
| 488 |
+
vectorizer = CountVectorizer(vocabulary=vocabulary)
|
| 489 |
+
|
| 490 |
+
expected = r"""
|
| 491 |
+
CountVectorizer(analyzer='word', binary=False, decode_error='strict',
|
| 492 |
+
dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
|
| 493 |
+
lowercase=True, max_df=1.0, max_features=None, min_df=1,
|
| 494 |
+
ngram_range=(1, 1), preprocessor=None, stop_words=None,
|
| 495 |
+
strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',
|
| 496 |
+
tokenizer=None,
|
| 497 |
+
vocabulary={0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7,
|
| 498 |
+
8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14,
|
| 499 |
+
15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20,
|
| 500 |
+
21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26,
|
| 501 |
+
27: 27, 28: 28, 29: 29, ...})"""
|
| 502 |
+
|
| 503 |
+
expected = expected[1:] # remove first \n
|
| 504 |
+
assert pp.pformat(vectorizer) == expected
|
| 505 |
+
|
| 506 |
+
# Also test with lists
|
| 507 |
+
param_grid = {"C": list(range(n_max_elements_to_show))}
|
| 508 |
+
gs = GridSearchCV(SVC(), param_grid)
|
| 509 |
+
expected = """
|
| 510 |
+
GridSearchCV(cv='warn', error_score='raise-deprecating',
|
| 511 |
+
estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
|
| 512 |
+
decision_function_shape='ovr', degree=3,
|
| 513 |
+
gamma='auto_deprecated', kernel='rbf', max_iter=-1,
|
| 514 |
+
probability=False, random_state=None, shrinking=True,
|
| 515 |
+
tol=0.001, verbose=False),
|
| 516 |
+
iid='warn', n_jobs=None,
|
| 517 |
+
param_grid={'C': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
|
| 518 |
+
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
|
| 519 |
+
27, 28, 29]},
|
| 520 |
+
pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
|
| 521 |
+
scoring=None, verbose=0)"""
|
| 522 |
+
|
| 523 |
+
expected = expected[1:] # remove first \n
|
| 524 |
+
assert pp.pformat(gs) == expected
|
| 525 |
+
|
| 526 |
+
# Now with ellipsis
|
| 527 |
+
param_grid = {"C": list(range(n_max_elements_to_show + 1))}
|
| 528 |
+
gs = GridSearchCV(SVC(), param_grid)
|
| 529 |
+
expected = """
|
| 530 |
+
GridSearchCV(cv='warn', error_score='raise-deprecating',
|
| 531 |
+
estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
|
| 532 |
+
decision_function_shape='ovr', degree=3,
|
| 533 |
+
gamma='auto_deprecated', kernel='rbf', max_iter=-1,
|
| 534 |
+
probability=False, random_state=None, shrinking=True,
|
| 535 |
+
tol=0.001, verbose=False),
|
| 536 |
+
iid='warn', n_jobs=None,
|
| 537 |
+
param_grid={'C': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
|
| 538 |
+
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
|
| 539 |
+
27, 28, 29, ...]},
|
| 540 |
+
pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
|
| 541 |
+
scoring=None, verbose=0)"""
|
| 542 |
+
|
| 543 |
+
expected = expected[1:] # remove first \n
|
| 544 |
+
assert pp.pformat(gs) == expected
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
@config_context(print_changed_only=False)
|
| 548 |
+
def test_bruteforce_ellipsis():
|
| 549 |
+
# Check that the bruteforce ellipsis (used when the number of non-blank
|
| 550 |
+
# characters exceeds N_CHAR_MAX) renders correctly.
|
| 551 |
+
|
| 552 |
+
lr = LogisticRegression()
|
| 553 |
+
|
| 554 |
+
# test when the left and right side of the ellipsis aren't on the same
|
| 555 |
+
# line.
|
| 556 |
+
expected = """
|
| 557 |
+
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
|
| 558 |
+
in...
|
| 559 |
+
multi_class='warn', n_jobs=None, random_state=None,
|
| 560 |
+
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
|
| 561 |
+
|
| 562 |
+
expected = expected[1:] # remove first \n
|
| 563 |
+
assert lr.__repr__(N_CHAR_MAX=150) == expected
|
| 564 |
+
|
| 565 |
+
# test with very small N_CHAR_MAX
|
| 566 |
+
# Note that N_CHAR_MAX is not strictly enforced, but it's normal: to avoid
|
| 567 |
+
# weird reprs we still keep the whole line of the right part (after the
|
| 568 |
+
# ellipsis).
|
| 569 |
+
expected = """
|
| 570 |
+
Lo...
|
| 571 |
+
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
|
| 572 |
+
|
| 573 |
+
expected = expected[1:] # remove first \n
|
| 574 |
+
assert lr.__repr__(N_CHAR_MAX=4) == expected
|
| 575 |
+
|
| 576 |
+
# test with N_CHAR_MAX == number of non-blank characters: In this case we
|
| 577 |
+
# don't want ellipsis
|
| 578 |
+
full_repr = lr.__repr__(N_CHAR_MAX=float("inf"))
|
| 579 |
+
n_nonblank = len("".join(full_repr.split()))
|
| 580 |
+
assert lr.__repr__(N_CHAR_MAX=n_nonblank) == full_repr
|
| 581 |
+
assert "..." not in full_repr
|
| 582 |
+
|
| 583 |
+
# test with N_CHAR_MAX == number of non-blank characters - 10: the left and
|
| 584 |
+
# right side of the ellispsis are on different lines. In this case we
|
| 585 |
+
# want to expend the whole line of the right side
|
| 586 |
+
expected = """
|
| 587 |
+
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
|
| 588 |
+
intercept_scaling=1, l1_ratio=0,...00,
|
| 589 |
+
multi_class='warn', n_jobs=None, random_state=None,
|
| 590 |
+
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
|
| 591 |
+
expected = expected[1:] # remove first \n
|
| 592 |
+
assert lr.__repr__(N_CHAR_MAX=n_nonblank - 10) == expected
|
| 593 |
+
|
| 594 |
+
# test with N_CHAR_MAX == number of non-blank characters - 10: the left and
|
| 595 |
+
# right side of the ellispsis are on the same line. In this case we don't
|
| 596 |
+
# want to expend the whole line of the right side, just add the ellispsis
|
| 597 |
+
# between the 2 sides.
|
| 598 |
+
expected = """
|
| 599 |
+
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
|
| 600 |
+
intercept_scaling=1, l1_ratio=0, max...r=100,
|
| 601 |
+
multi_class='warn', n_jobs=None, random_state=None,
|
| 602 |
+
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
|
| 603 |
+
expected = expected[1:] # remove first \n
|
| 604 |
+
assert lr.__repr__(N_CHAR_MAX=n_nonblank - 4) == expected
|
| 605 |
+
|
| 606 |
+
# test with N_CHAR_MAX == number of non-blank characters - 2: the left and
|
| 607 |
+
# right side of the ellispsis are on the same line, but adding the ellipsis
|
| 608 |
+
# would actually make the repr longer. So we don't add the ellipsis.
|
| 609 |
+
expected = """
|
| 610 |
+
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
|
| 611 |
+
intercept_scaling=1, l1_ratio=0, max_iter=100,
|
| 612 |
+
multi_class='warn', n_jobs=None, random_state=None,
|
| 613 |
+
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
|
| 614 |
+
expected = expected[1:] # remove first \n
|
| 615 |
+
assert lr.__repr__(N_CHAR_MAX=n_nonblank - 2) == expected
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def test_builtin_prettyprinter():
|
| 619 |
+
# non regression test than ensures we can still use the builtin
|
| 620 |
+
# PrettyPrinter class for estimators (as done e.g. by joblib).
|
| 621 |
+
# Used to be a bug
|
| 622 |
+
|
| 623 |
+
PrettyPrinter().pprint(LogisticRegression())
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def test_kwargs_in_init():
|
| 627 |
+
# Make sure the changed_only=True mode is OK when an argument is passed as
|
| 628 |
+
# kwargs.
|
| 629 |
+
# Non-regression test for
|
| 630 |
+
# https://github.com/scikit-learn/scikit-learn/issues/17206
|
| 631 |
+
|
| 632 |
+
class WithKWargs(BaseEstimator):
|
| 633 |
+
# Estimator with a kwargs argument. These need to hack around
|
| 634 |
+
# set_params and get_params. Here we mimic what LightGBM does.
|
| 635 |
+
def __init__(self, a="willchange", b="unchanged", **kwargs):
|
| 636 |
+
self.a = a
|
| 637 |
+
self.b = b
|
| 638 |
+
self._other_params = {}
|
| 639 |
+
self.set_params(**kwargs)
|
| 640 |
+
|
| 641 |
+
def get_params(self, deep=True):
|
| 642 |
+
params = super().get_params(deep=deep)
|
| 643 |
+
params.update(self._other_params)
|
| 644 |
+
return params
|
| 645 |
+
|
| 646 |
+
def set_params(self, **params):
|
| 647 |
+
for key, value in params.items():
|
| 648 |
+
setattr(self, key, value)
|
| 649 |
+
self._other_params[key] = value
|
| 650 |
+
return self
|
| 651 |
+
|
| 652 |
+
est = WithKWargs(a="something", c="abcd", d=None)
|
| 653 |
+
|
| 654 |
+
expected = "WithKWargs(a='something', c='abcd', d=None)"
|
| 655 |
+
assert est.__repr__() == expected
|
| 656 |
+
|
| 657 |
+
with config_context(print_changed_only=False):
|
| 658 |
+
expected = "WithKWargs(a='something', b='unchanged', c='abcd', d=None)"
|
| 659 |
+
assert est.__repr__() == expected
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def test_complexity_print_changed_only():
|
| 663 |
+
# Make sure `__repr__` is called the same amount of times
|
| 664 |
+
# whether `print_changed_only` is True or False
|
| 665 |
+
# Non-regression test for
|
| 666 |
+
# https://github.com/scikit-learn/scikit-learn/issues/18490
|
| 667 |
+
|
| 668 |
+
class DummyEstimator(TransformerMixin, BaseEstimator):
|
| 669 |
+
nb_times_repr_called = 0
|
| 670 |
+
|
| 671 |
+
def __init__(self, estimator=None):
|
| 672 |
+
self.estimator = estimator
|
| 673 |
+
|
| 674 |
+
def __repr__(self):
|
| 675 |
+
DummyEstimator.nb_times_repr_called += 1
|
| 676 |
+
return super().__repr__()
|
| 677 |
+
|
| 678 |
+
def transform(self, X, copy=None): # pragma: no cover
|
| 679 |
+
return X
|
| 680 |
+
|
| 681 |
+
estimator = DummyEstimator(
|
| 682 |
+
make_pipeline(DummyEstimator(DummyEstimator()), DummyEstimator(), "passthrough")
|
| 683 |
+
)
|
| 684 |
+
with config_context(print_changed_only=False):
|
| 685 |
+
repr(estimator)
|
| 686 |
+
nb_repr_print_changed_only_false = DummyEstimator.nb_times_repr_called
|
| 687 |
+
|
| 688 |
+
DummyEstimator.nb_times_repr_called = 0
|
| 689 |
+
with config_context(print_changed_only=True):
|
| 690 |
+
repr(estimator)
|
| 691 |
+
nb_repr_print_changed_only_true = DummyEstimator.nb_times_repr_called
|
| 692 |
+
|
| 693 |
+
assert nb_repr_print_changed_only_false == nb_repr_print_changed_only_true
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_random.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
import scipy.sparse as sp
|
| 4 |
+
from numpy.testing import assert_array_almost_equal
|
| 5 |
+
from scipy.special import comb
|
| 6 |
+
|
| 7 |
+
from sklearn.utils._random import _our_rand_r_py
|
| 8 |
+
from sklearn.utils.random import _random_choice_csc, sample_without_replacement
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
###############################################################################
|
| 12 |
+
# test custom sampling without replacement algorithm
|
| 13 |
+
###############################################################################
|
| 14 |
+
def test_invalid_sample_without_replacement_algorithm():
|
| 15 |
+
with pytest.raises(ValueError):
|
| 16 |
+
sample_without_replacement(5, 4, "unknown")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_sample_without_replacement_algorithms():
|
| 20 |
+
methods = ("auto", "tracking_selection", "reservoir_sampling", "pool")
|
| 21 |
+
|
| 22 |
+
for m in methods:
|
| 23 |
+
|
| 24 |
+
def sample_without_replacement_method(
|
| 25 |
+
n_population, n_samples, random_state=None
|
| 26 |
+
):
|
| 27 |
+
return sample_without_replacement(
|
| 28 |
+
n_population, n_samples, method=m, random_state=random_state
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
check_edge_case_of_sample_int(sample_without_replacement_method)
|
| 32 |
+
check_sample_int(sample_without_replacement_method)
|
| 33 |
+
check_sample_int_distribution(sample_without_replacement_method)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def check_edge_case_of_sample_int(sample_without_replacement):
|
| 37 |
+
# n_population < n_sample
|
| 38 |
+
with pytest.raises(ValueError):
|
| 39 |
+
sample_without_replacement(0, 1)
|
| 40 |
+
with pytest.raises(ValueError):
|
| 41 |
+
sample_without_replacement(1, 2)
|
| 42 |
+
|
| 43 |
+
# n_population == n_samples
|
| 44 |
+
assert sample_without_replacement(0, 0).shape == (0,)
|
| 45 |
+
|
| 46 |
+
assert sample_without_replacement(1, 1).shape == (1,)
|
| 47 |
+
|
| 48 |
+
# n_population >= n_samples
|
| 49 |
+
assert sample_without_replacement(5, 0).shape == (0,)
|
| 50 |
+
assert sample_without_replacement(5, 1).shape == (1,)
|
| 51 |
+
|
| 52 |
+
# n_population < 0 or n_samples < 0
|
| 53 |
+
with pytest.raises(ValueError):
|
| 54 |
+
sample_without_replacement(-1, 5)
|
| 55 |
+
with pytest.raises(ValueError):
|
| 56 |
+
sample_without_replacement(5, -1)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def check_sample_int(sample_without_replacement):
|
| 60 |
+
# This test is heavily inspired from test_random.py of python-core.
|
| 61 |
+
#
|
| 62 |
+
# For the entire allowable range of 0 <= k <= N, validate that
|
| 63 |
+
# the sample is of the correct length and contains only unique items
|
| 64 |
+
n_population = 100
|
| 65 |
+
|
| 66 |
+
for n_samples in range(n_population + 1):
|
| 67 |
+
s = sample_without_replacement(n_population, n_samples)
|
| 68 |
+
assert len(s) == n_samples
|
| 69 |
+
unique = np.unique(s)
|
| 70 |
+
assert np.size(unique) == n_samples
|
| 71 |
+
assert np.all(unique < n_population)
|
| 72 |
+
|
| 73 |
+
# test edge case n_population == n_samples == 0
|
| 74 |
+
assert np.size(sample_without_replacement(0, 0)) == 0
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_sample_int_distribution(sample_without_replacement):
|
| 78 |
+
# This test is heavily inspired from test_random.py of python-core.
|
| 79 |
+
#
|
| 80 |
+
# For the entire allowable range of 0 <= k <= N, validate that
|
| 81 |
+
# sample generates all possible permutations
|
| 82 |
+
n_population = 10
|
| 83 |
+
|
| 84 |
+
# a large number of trials prevents false negatives without slowing normal
|
| 85 |
+
# case
|
| 86 |
+
n_trials = 10000
|
| 87 |
+
|
| 88 |
+
for n_samples in range(n_population):
|
| 89 |
+
# Counting the number of combinations is not as good as counting the
|
| 90 |
+
# the number of permutations. However, it works with sampling algorithm
|
| 91 |
+
# that does not provide a random permutation of the subset of integer.
|
| 92 |
+
n_expected = comb(n_population, n_samples, exact=True)
|
| 93 |
+
|
| 94 |
+
output = {}
|
| 95 |
+
for i in range(n_trials):
|
| 96 |
+
output[frozenset(sample_without_replacement(n_population, n_samples))] = (
|
| 97 |
+
None
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if len(output) == n_expected:
|
| 101 |
+
break
|
| 102 |
+
else:
|
| 103 |
+
raise AssertionError(
|
| 104 |
+
"number of combinations != number of expected (%s != %s)"
|
| 105 |
+
% (len(output), n_expected)
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_random_choice_csc(n_samples=10000, random_state=24):
|
| 110 |
+
# Explicit class probabilities
|
| 111 |
+
classes = [np.array([0, 1]), np.array([0, 1, 2])]
|
| 112 |
+
class_probabilities = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])]
|
| 113 |
+
|
| 114 |
+
got = _random_choice_csc(n_samples, classes, class_probabilities, random_state)
|
| 115 |
+
assert sp.issparse(got)
|
| 116 |
+
|
| 117 |
+
for k in range(len(classes)):
|
| 118 |
+
p = np.bincount(got[:, [k]].toarray().ravel()) / float(n_samples)
|
| 119 |
+
assert_array_almost_equal(class_probabilities[k], p, decimal=1)
|
| 120 |
+
|
| 121 |
+
# Implicit class probabilities
|
| 122 |
+
classes = [[0, 1], [1, 2]] # test for array-like support
|
| 123 |
+
class_probabilities = [np.array([0.5, 0.5]), np.array([0, 1 / 2, 1 / 2])]
|
| 124 |
+
|
| 125 |
+
got = _random_choice_csc(
|
| 126 |
+
n_samples=n_samples, classes=classes, random_state=random_state
|
| 127 |
+
)
|
| 128 |
+
assert sp.issparse(got)
|
| 129 |
+
|
| 130 |
+
for k in range(len(classes)):
|
| 131 |
+
p = np.bincount(got[:, [k]].toarray().ravel()) / float(n_samples)
|
| 132 |
+
assert_array_almost_equal(class_probabilities[k], p, decimal=1)
|
| 133 |
+
|
| 134 |
+
# Edge case probabilities 1.0 and 0.0
|
| 135 |
+
classes = [np.array([0, 1]), np.array([0, 1, 2])]
|
| 136 |
+
class_probabilities = [np.array([0.0, 1.0]), np.array([0.0, 1.0, 0.0])]
|
| 137 |
+
|
| 138 |
+
got = _random_choice_csc(n_samples, classes, class_probabilities, random_state)
|
| 139 |
+
assert sp.issparse(got)
|
| 140 |
+
|
| 141 |
+
for k in range(len(classes)):
|
| 142 |
+
p = (
|
| 143 |
+
np.bincount(
|
| 144 |
+
got[:, [k]].toarray().ravel(), minlength=len(class_probabilities[k])
|
| 145 |
+
)
|
| 146 |
+
/ n_samples
|
| 147 |
+
)
|
| 148 |
+
assert_array_almost_equal(class_probabilities[k], p, decimal=1)
|
| 149 |
+
|
| 150 |
+
# One class target data
|
| 151 |
+
classes = [[1], [0]] # test for array-like support
|
| 152 |
+
class_probabilities = [np.array([0.0, 1.0]), np.array([1.0])]
|
| 153 |
+
|
| 154 |
+
got = _random_choice_csc(
|
| 155 |
+
n_samples=n_samples, classes=classes, random_state=random_state
|
| 156 |
+
)
|
| 157 |
+
assert sp.issparse(got)
|
| 158 |
+
|
| 159 |
+
for k in range(len(classes)):
|
| 160 |
+
p = np.bincount(got[:, [k]].toarray().ravel()) / n_samples
|
| 161 |
+
assert_array_almost_equal(class_probabilities[k], p, decimal=1)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def test_random_choice_csc_errors():
|
| 165 |
+
# the length of an array in classes and class_probabilities is mismatched
|
| 166 |
+
classes = [np.array([0, 1]), np.array([0, 1, 2, 3])]
|
| 167 |
+
class_probabilities = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])]
|
| 168 |
+
with pytest.raises(ValueError):
|
| 169 |
+
_random_choice_csc(4, classes, class_probabilities, 1)
|
| 170 |
+
|
| 171 |
+
# the class dtype is not supported
|
| 172 |
+
classes = [np.array(["a", "1"]), np.array(["z", "1", "2"])]
|
| 173 |
+
class_probabilities = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])]
|
| 174 |
+
with pytest.raises(ValueError):
|
| 175 |
+
_random_choice_csc(4, classes, class_probabilities, 1)
|
| 176 |
+
|
| 177 |
+
# the class dtype is not supported
|
| 178 |
+
classes = [np.array([4.2, 0.1]), np.array([0.1, 0.2, 9.4])]
|
| 179 |
+
class_probabilities = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])]
|
| 180 |
+
with pytest.raises(ValueError):
|
| 181 |
+
_random_choice_csc(4, classes, class_probabilities, 1)
|
| 182 |
+
|
| 183 |
+
# Given probabilities don't sum to 1
|
| 184 |
+
classes = [np.array([0, 1]), np.array([0, 1, 2])]
|
| 185 |
+
class_probabilities = [np.array([0.5, 0.6]), np.array([0.6, 0.1, 0.3])]
|
| 186 |
+
with pytest.raises(ValueError):
|
| 187 |
+
_random_choice_csc(4, classes, class_probabilities, 1)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_our_rand_r():
|
| 191 |
+
assert 131541053 == _our_rand_r_py(1273642419)
|
| 192 |
+
assert 270369 == _our_rand_r_py(0)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_response.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from sklearn.base import clone
|
| 7 |
+
from sklearn.datasets import (
|
| 8 |
+
load_iris,
|
| 9 |
+
make_classification,
|
| 10 |
+
make_multilabel_classification,
|
| 11 |
+
make_regression,
|
| 12 |
+
)
|
| 13 |
+
from sklearn.ensemble import IsolationForest
|
| 14 |
+
from sklearn.linear_model import (
|
| 15 |
+
LinearRegression,
|
| 16 |
+
LogisticRegression,
|
| 17 |
+
)
|
| 18 |
+
from sklearn.multioutput import ClassifierChain
|
| 19 |
+
from sklearn.preprocessing import scale
|
| 20 |
+
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
|
| 21 |
+
from sklearn.utils._mocking import _MockEstimatorOnOffPrediction
|
| 22 |
+
from sklearn.utils._response import _get_response_values, _get_response_values_binary
|
| 23 |
+
from sklearn.utils._testing import assert_allclose, assert_array_equal
|
| 24 |
+
|
| 25 |
+
X, y = load_iris(return_X_y=True)
|
| 26 |
+
# scale the data to avoid ConvergenceWarning with LogisticRegression
|
| 27 |
+
X = scale(X, copy=False)
|
| 28 |
+
X_binary, y_binary = X[:100], y[:100]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@pytest.mark.parametrize(
|
| 32 |
+
"response_method", ["decision_function", "predict_proba", "predict_log_proba"]
|
| 33 |
+
)
|
| 34 |
+
def test_get_response_values_regressor_error(response_method):
|
| 35 |
+
"""Check the error message with regressor an not supported response
|
| 36 |
+
method."""
|
| 37 |
+
my_estimator = _MockEstimatorOnOffPrediction(response_methods=[response_method])
|
| 38 |
+
X = "mocking_data", "mocking_target"
|
| 39 |
+
err_msg = f"{my_estimator.__class__.__name__} should either be a classifier"
|
| 40 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 41 |
+
_get_response_values(my_estimator, X, response_method=response_method)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@pytest.mark.parametrize("return_response_method_used", [True, False])
|
| 45 |
+
def test_get_response_values_regressor(return_response_method_used):
|
| 46 |
+
"""Check the behaviour of `_get_response_values` with regressor."""
|
| 47 |
+
X, y = make_regression(n_samples=10, random_state=0)
|
| 48 |
+
regressor = LinearRegression().fit(X, y)
|
| 49 |
+
results = _get_response_values(
|
| 50 |
+
regressor,
|
| 51 |
+
X,
|
| 52 |
+
response_method="predict",
|
| 53 |
+
return_response_method_used=return_response_method_used,
|
| 54 |
+
)
|
| 55 |
+
assert_array_equal(results[0], regressor.predict(X))
|
| 56 |
+
assert results[1] is None
|
| 57 |
+
if return_response_method_used:
|
| 58 |
+
assert results[2] == "predict"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@pytest.mark.parametrize(
|
| 62 |
+
"response_method",
|
| 63 |
+
["predict", "decision_function", ["decision_function", "predict"]],
|
| 64 |
+
)
|
| 65 |
+
@pytest.mark.parametrize("return_response_method_used", [True, False])
|
| 66 |
+
def test_get_response_values_outlier_detection(
|
| 67 |
+
response_method, return_response_method_used
|
| 68 |
+
):
|
| 69 |
+
"""Check the behaviour of `_get_response_values` with outlier detector."""
|
| 70 |
+
X, y = make_classification(n_samples=50, random_state=0)
|
| 71 |
+
outlier_detector = IsolationForest(random_state=0).fit(X, y)
|
| 72 |
+
results = _get_response_values(
|
| 73 |
+
outlier_detector,
|
| 74 |
+
X,
|
| 75 |
+
response_method=response_method,
|
| 76 |
+
return_response_method_used=return_response_method_used,
|
| 77 |
+
)
|
| 78 |
+
chosen_response_method = (
|
| 79 |
+
response_method[0] if isinstance(response_method, list) else response_method
|
| 80 |
+
)
|
| 81 |
+
prediction_method = getattr(outlier_detector, chosen_response_method)
|
| 82 |
+
assert_array_equal(results[0], prediction_method(X))
|
| 83 |
+
assert results[1] is None
|
| 84 |
+
if return_response_method_used:
|
| 85 |
+
assert results[2] == chosen_response_method
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@pytest.mark.parametrize(
|
| 89 |
+
"response_method",
|
| 90 |
+
["predict_proba", "decision_function", "predict", "predict_log_proba"],
|
| 91 |
+
)
|
| 92 |
+
def test_get_response_values_classifier_unknown_pos_label(response_method):
|
| 93 |
+
"""Check that `_get_response_values` raises the proper error message with
|
| 94 |
+
classifier."""
|
| 95 |
+
X, y = make_classification(n_samples=10, n_classes=2, random_state=0)
|
| 96 |
+
classifier = LogisticRegression().fit(X, y)
|
| 97 |
+
|
| 98 |
+
# provide a `pos_label` which is not in `y`
|
| 99 |
+
err_msg = r"pos_label=whatever is not a valid label: It should be one of \[0 1\]"
|
| 100 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 101 |
+
_get_response_values(
|
| 102 |
+
classifier,
|
| 103 |
+
X,
|
| 104 |
+
response_method=response_method,
|
| 105 |
+
pos_label="whatever",
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@pytest.mark.parametrize("response_method", ["predict_proba", "predict_log_proba"])
|
| 110 |
+
def test_get_response_values_classifier_inconsistent_y_pred_for_binary_proba(
|
| 111 |
+
response_method,
|
| 112 |
+
):
|
| 113 |
+
"""Check that `_get_response_values` will raise an error when `y_pred` has a
|
| 114 |
+
single class with `predict_proba`."""
|
| 115 |
+
X, y_two_class = make_classification(n_samples=10, n_classes=2, random_state=0)
|
| 116 |
+
y_single_class = np.zeros_like(y_two_class)
|
| 117 |
+
classifier = DecisionTreeClassifier().fit(X, y_single_class)
|
| 118 |
+
|
| 119 |
+
err_msg = (
|
| 120 |
+
r"Got predict_proba of shape \(10, 1\), but need classifier with "
|
| 121 |
+
r"two classes"
|
| 122 |
+
)
|
| 123 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 124 |
+
_get_response_values(classifier, X, response_method=response_method)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@pytest.mark.parametrize("return_response_method_used", [True, False])
|
| 128 |
+
def test_get_response_values_binary_classifier_decision_function(
|
| 129 |
+
return_response_method_used,
|
| 130 |
+
):
|
| 131 |
+
"""Check the behaviour of `_get_response_values` with `decision_function`
|
| 132 |
+
and binary classifier."""
|
| 133 |
+
X, y = make_classification(
|
| 134 |
+
n_samples=10,
|
| 135 |
+
n_classes=2,
|
| 136 |
+
weights=[0.3, 0.7],
|
| 137 |
+
random_state=0,
|
| 138 |
+
)
|
| 139 |
+
classifier = LogisticRegression().fit(X, y)
|
| 140 |
+
response_method = "decision_function"
|
| 141 |
+
|
| 142 |
+
# default `pos_label`
|
| 143 |
+
results = _get_response_values(
|
| 144 |
+
classifier,
|
| 145 |
+
X,
|
| 146 |
+
response_method=response_method,
|
| 147 |
+
pos_label=None,
|
| 148 |
+
return_response_method_used=return_response_method_used,
|
| 149 |
+
)
|
| 150 |
+
assert_allclose(results[0], classifier.decision_function(X))
|
| 151 |
+
assert results[1] == 1
|
| 152 |
+
if return_response_method_used:
|
| 153 |
+
assert results[2] == "decision_function"
|
| 154 |
+
|
| 155 |
+
# when forcing `pos_label=classifier.classes_[0]`
|
| 156 |
+
results = _get_response_values(
|
| 157 |
+
classifier,
|
| 158 |
+
X,
|
| 159 |
+
response_method=response_method,
|
| 160 |
+
pos_label=classifier.classes_[0],
|
| 161 |
+
return_response_method_used=return_response_method_used,
|
| 162 |
+
)
|
| 163 |
+
assert_allclose(results[0], classifier.decision_function(X) * -1)
|
| 164 |
+
assert results[1] == 0
|
| 165 |
+
if return_response_method_used:
|
| 166 |
+
assert results[2] == "decision_function"
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@pytest.mark.parametrize("return_response_method_used", [True, False])
|
| 170 |
+
@pytest.mark.parametrize("response_method", ["predict_proba", "predict_log_proba"])
|
| 171 |
+
def test_get_response_values_binary_classifier_predict_proba(
|
| 172 |
+
return_response_method_used, response_method
|
| 173 |
+
):
|
| 174 |
+
"""Check that `_get_response_values` with `predict_proba` and binary
|
| 175 |
+
classifier."""
|
| 176 |
+
X, y = make_classification(
|
| 177 |
+
n_samples=10,
|
| 178 |
+
n_classes=2,
|
| 179 |
+
weights=[0.3, 0.7],
|
| 180 |
+
random_state=0,
|
| 181 |
+
)
|
| 182 |
+
classifier = LogisticRegression().fit(X, y)
|
| 183 |
+
|
| 184 |
+
# default `pos_label`
|
| 185 |
+
results = _get_response_values(
|
| 186 |
+
classifier,
|
| 187 |
+
X,
|
| 188 |
+
response_method=response_method,
|
| 189 |
+
pos_label=None,
|
| 190 |
+
return_response_method_used=return_response_method_used,
|
| 191 |
+
)
|
| 192 |
+
assert_allclose(results[0], getattr(classifier, response_method)(X)[:, 1])
|
| 193 |
+
assert results[1] == 1
|
| 194 |
+
if return_response_method_used:
|
| 195 |
+
assert len(results) == 3
|
| 196 |
+
assert results[2] == response_method
|
| 197 |
+
else:
|
| 198 |
+
assert len(results) == 2
|
| 199 |
+
|
| 200 |
+
# when forcing `pos_label=classifier.classes_[0]`
|
| 201 |
+
y_pred, pos_label, *_ = _get_response_values(
|
| 202 |
+
classifier,
|
| 203 |
+
X,
|
| 204 |
+
response_method=response_method,
|
| 205 |
+
pos_label=classifier.classes_[0],
|
| 206 |
+
return_response_method_used=return_response_method_used,
|
| 207 |
+
)
|
| 208 |
+
assert_allclose(y_pred, getattr(classifier, response_method)(X)[:, 0])
|
| 209 |
+
assert pos_label == 0
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@pytest.mark.parametrize(
|
| 213 |
+
"estimator, X, y, err_msg, params",
|
| 214 |
+
[
|
| 215 |
+
(
|
| 216 |
+
DecisionTreeRegressor(),
|
| 217 |
+
X_binary,
|
| 218 |
+
y_binary,
|
| 219 |
+
"Expected 'estimator' to be a binary classifier",
|
| 220 |
+
{"response_method": "auto"},
|
| 221 |
+
),
|
| 222 |
+
(
|
| 223 |
+
DecisionTreeClassifier(),
|
| 224 |
+
X_binary,
|
| 225 |
+
y_binary,
|
| 226 |
+
r"pos_label=unknown is not a valid label: It should be one of \[0 1\]",
|
| 227 |
+
{"response_method": "auto", "pos_label": "unknown"},
|
| 228 |
+
),
|
| 229 |
+
(
|
| 230 |
+
DecisionTreeClassifier(),
|
| 231 |
+
X,
|
| 232 |
+
y,
|
| 233 |
+
"be a binary classifier. Got 3 classes instead.",
|
| 234 |
+
{"response_method": "predict_proba"},
|
| 235 |
+
),
|
| 236 |
+
],
|
| 237 |
+
)
|
| 238 |
+
def test_get_response_error(estimator, X, y, err_msg, params):
|
| 239 |
+
"""Check that we raise the proper error messages in _get_response_values_binary."""
|
| 240 |
+
|
| 241 |
+
estimator = clone(estimator).fit(X, y) # clone to make test execution thread-safe
|
| 242 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 243 |
+
_get_response_values_binary(estimator, X, **params)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@pytest.mark.parametrize("return_response_method_used", [True, False])
|
| 247 |
+
def test_get_response_predict_proba(return_response_method_used):
|
| 248 |
+
"""Check the behaviour of `_get_response_values_binary` using `predict_proba`."""
|
| 249 |
+
classifier = DecisionTreeClassifier().fit(X_binary, y_binary)
|
| 250 |
+
results = _get_response_values_binary(
|
| 251 |
+
classifier,
|
| 252 |
+
X_binary,
|
| 253 |
+
response_method="predict_proba",
|
| 254 |
+
return_response_method_used=return_response_method_used,
|
| 255 |
+
)
|
| 256 |
+
assert_allclose(results[0], classifier.predict_proba(X_binary)[:, 1])
|
| 257 |
+
assert results[1] == 1
|
| 258 |
+
if return_response_method_used:
|
| 259 |
+
assert results[2] == "predict_proba"
|
| 260 |
+
|
| 261 |
+
results = _get_response_values_binary(
|
| 262 |
+
classifier,
|
| 263 |
+
X_binary,
|
| 264 |
+
response_method="predict_proba",
|
| 265 |
+
pos_label=0,
|
| 266 |
+
return_response_method_used=return_response_method_used,
|
| 267 |
+
)
|
| 268 |
+
assert_allclose(results[0], classifier.predict_proba(X_binary)[:, 0])
|
| 269 |
+
assert results[1] == 0
|
| 270 |
+
if return_response_method_used:
|
| 271 |
+
assert results[2] == "predict_proba"
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@pytest.mark.parametrize("return_response_method_used", [True, False])
|
| 275 |
+
def test_get_response_decision_function(return_response_method_used):
|
| 276 |
+
"""Check the behaviour of `_get_response_values_binary` using decision_function."""
|
| 277 |
+
classifier = LogisticRegression().fit(X_binary, y_binary)
|
| 278 |
+
results = _get_response_values_binary(
|
| 279 |
+
classifier,
|
| 280 |
+
X_binary,
|
| 281 |
+
response_method="decision_function",
|
| 282 |
+
return_response_method_used=return_response_method_used,
|
| 283 |
+
)
|
| 284 |
+
assert_allclose(results[0], classifier.decision_function(X_binary))
|
| 285 |
+
assert results[1] == 1
|
| 286 |
+
if return_response_method_used:
|
| 287 |
+
assert results[2] == "decision_function"
|
| 288 |
+
|
| 289 |
+
results = _get_response_values_binary(
|
| 290 |
+
classifier,
|
| 291 |
+
X_binary,
|
| 292 |
+
response_method="decision_function",
|
| 293 |
+
pos_label=0,
|
| 294 |
+
return_response_method_used=return_response_method_used,
|
| 295 |
+
)
|
| 296 |
+
assert_allclose(results[0], classifier.decision_function(X_binary) * -1)
|
| 297 |
+
assert results[1] == 0
|
| 298 |
+
if return_response_method_used:
|
| 299 |
+
assert results[2] == "decision_function"
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@pytest.mark.parametrize(
|
| 303 |
+
"estimator, response_method",
|
| 304 |
+
[
|
| 305 |
+
(DecisionTreeClassifier(max_depth=2, random_state=0), "predict_proba"),
|
| 306 |
+
(DecisionTreeClassifier(max_depth=2, random_state=0), "predict_log_proba"),
|
| 307 |
+
(LogisticRegression(), "decision_function"),
|
| 308 |
+
],
|
| 309 |
+
)
|
| 310 |
+
def test_get_response_values_multiclass(estimator, response_method):
|
| 311 |
+
"""Check that we can call `_get_response_values` with a multiclass estimator.
|
| 312 |
+
It should return the predictions untouched.
|
| 313 |
+
"""
|
| 314 |
+
estimator = clone(estimator)
|
| 315 |
+
estimator.fit(X, y)
|
| 316 |
+
predictions, pos_label = _get_response_values(
|
| 317 |
+
estimator, X, response_method=response_method
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
assert pos_label is None
|
| 321 |
+
assert predictions.shape == (X.shape[0], len(estimator.classes_))
|
| 322 |
+
if response_method == "predict_proba":
|
| 323 |
+
assert np.logical_and(predictions >= 0, predictions <= 1).all()
|
| 324 |
+
elif response_method == "predict_log_proba":
|
| 325 |
+
assert (predictions <= 0.0).all()
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def test_get_response_values_with_response_list():
|
| 329 |
+
"""Check the behaviour of passing a list of responses to `_get_response_values`."""
|
| 330 |
+
classifier = LogisticRegression().fit(X_binary, y_binary)
|
| 331 |
+
|
| 332 |
+
# it should use `predict_proba`
|
| 333 |
+
y_pred, pos_label, response_method = _get_response_values(
|
| 334 |
+
classifier,
|
| 335 |
+
X_binary,
|
| 336 |
+
response_method=["predict_proba", "decision_function"],
|
| 337 |
+
return_response_method_used=True,
|
| 338 |
+
)
|
| 339 |
+
assert_allclose(y_pred, classifier.predict_proba(X_binary)[:, 1])
|
| 340 |
+
assert pos_label == 1
|
| 341 |
+
assert response_method == "predict_proba"
|
| 342 |
+
|
| 343 |
+
# it should use `decision_function`
|
| 344 |
+
y_pred, pos_label, response_method = _get_response_values(
|
| 345 |
+
classifier,
|
| 346 |
+
X_binary,
|
| 347 |
+
response_method=["decision_function", "predict_proba"],
|
| 348 |
+
return_response_method_used=True,
|
| 349 |
+
)
|
| 350 |
+
assert_allclose(y_pred, classifier.decision_function(X_binary))
|
| 351 |
+
assert pos_label == 1
|
| 352 |
+
assert response_method == "decision_function"
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
@pytest.mark.parametrize(
|
| 356 |
+
"response_method", ["predict_proba", "decision_function", "predict"]
|
| 357 |
+
)
|
| 358 |
+
def test_get_response_values_multilabel_indicator(response_method):
|
| 359 |
+
X, Y = make_multilabel_classification(random_state=0)
|
| 360 |
+
estimator = ClassifierChain(LogisticRegression()).fit(X, Y)
|
| 361 |
+
|
| 362 |
+
y_pred, pos_label = _get_response_values(
|
| 363 |
+
estimator, X, response_method=response_method
|
| 364 |
+
)
|
| 365 |
+
assert pos_label is None
|
| 366 |
+
assert y_pred.shape == Y.shape
|
| 367 |
+
|
| 368 |
+
if response_method == "predict_proba":
|
| 369 |
+
assert np.logical_and(y_pred >= 0, y_pred <= 1).all()
|
| 370 |
+
elif response_method == "decision_function":
|
| 371 |
+
# values returned by `decision_function` are not bounded in [0, 1]
|
| 372 |
+
assert (y_pred < 0).sum() > 0
|
| 373 |
+
assert (y_pred > 1).sum() > 0
|
| 374 |
+
else: # response_method == "predict"
|
| 375 |
+
assert np.logical_or(y_pred == 0, y_pred == 1).all()
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def test_response_values_type_of_target_on_classes_no_warning():
|
| 379 |
+
"""
|
| 380 |
+
Ensure `_get_response_values` doesn't raise spurious warning.
|
| 381 |
+
|
| 382 |
+
"The number of unique classes is greater than > 50% of samples"
|
| 383 |
+
warning should not be raised when calling `type_of_target(classes_)`.
|
| 384 |
+
|
| 385 |
+
Non-regression test for issue #31583.
|
| 386 |
+
"""
|
| 387 |
+
X = np.random.RandomState(0).randn(120, 3)
|
| 388 |
+
# 30 classes, less than 50% of number of samples
|
| 389 |
+
y = np.repeat(np.arange(30), 4)
|
| 390 |
+
|
| 391 |
+
clf = LogisticRegression().fit(X, y)
|
| 392 |
+
|
| 393 |
+
with warnings.catch_warnings():
|
| 394 |
+
warnings.simplefilter("error", UserWarning)
|
| 395 |
+
|
| 396 |
+
_get_response_values(clf, X, response_method="predict_proba")
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_seq_dataset.py
ADDED
|
@@ -0,0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: The scikit-learn developers
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 3 |
+
|
| 4 |
+
from functools import partial
|
| 5 |
+
from itertools import product
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pytest
|
| 9 |
+
from numpy.testing import assert_array_equal
|
| 10 |
+
|
| 11 |
+
from sklearn.datasets import load_iris
|
| 12 |
+
from sklearn.utils._seq_dataset import (
|
| 13 |
+
ArrayDataset32,
|
| 14 |
+
ArrayDataset64,
|
| 15 |
+
CSRDataset32,
|
| 16 |
+
CSRDataset64,
|
| 17 |
+
)
|
| 18 |
+
from sklearn.utils._testing import assert_allclose
|
| 19 |
+
from sklearn.utils.fixes import CSR_CONTAINERS
|
| 20 |
+
|
| 21 |
+
iris = load_iris()
|
| 22 |
+
X64 = iris.data.astype(np.float64)
|
| 23 |
+
y64 = iris.target.astype(np.float64)
|
| 24 |
+
sample_weight64 = np.arange(y64.size, dtype=np.float64)
|
| 25 |
+
|
| 26 |
+
X32 = iris.data.astype(np.float32)
|
| 27 |
+
y32 = iris.target.astype(np.float32)
|
| 28 |
+
sample_weight32 = np.arange(y32.size, dtype=np.float32)
|
| 29 |
+
|
| 30 |
+
floating = [np.float32, np.float64]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def assert_csr_equal_values(current, expected):
|
| 34 |
+
current.eliminate_zeros()
|
| 35 |
+
expected.eliminate_zeros()
|
| 36 |
+
expected = expected.astype(current.dtype)
|
| 37 |
+
assert current.shape[0] == expected.shape[0]
|
| 38 |
+
assert current.shape[1] == expected.shape[1]
|
| 39 |
+
assert_array_equal(current.data, expected.data)
|
| 40 |
+
assert_array_equal(current.indices, expected.indices)
|
| 41 |
+
assert_array_equal(current.indptr, expected.indptr)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _make_dense_dataset(float_dtype):
|
| 45 |
+
if float_dtype == np.float32:
|
| 46 |
+
return ArrayDataset32(X32, y32, sample_weight32, seed=42)
|
| 47 |
+
return ArrayDataset64(X64, y64, sample_weight64, seed=42)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _make_sparse_dataset(csr_container, float_dtype):
|
| 51 |
+
if float_dtype == np.float32:
|
| 52 |
+
X, y, sample_weight, csr_dataset = X32, y32, sample_weight32, CSRDataset32
|
| 53 |
+
else:
|
| 54 |
+
X, y, sample_weight, csr_dataset = X64, y64, sample_weight64, CSRDataset64
|
| 55 |
+
X = csr_container(X)
|
| 56 |
+
return csr_dataset(X.data, X.indptr, X.indices, y, sample_weight, seed=42)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _dense_dataset_factories():
|
| 60 |
+
return [partial(_make_dense_dataset, float_dtype) for float_dtype in floating]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _sparse_dataset_factories():
|
| 64 |
+
return [
|
| 65 |
+
partial(_make_sparse_dataset, csr_container, float_dtype)
|
| 66 |
+
for csr_container, float_dtype in product(CSR_CONTAINERS, floating)
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _fused_types_dataset_factories():
|
| 71 |
+
all_factories = _dense_dataset_factories() + _sparse_dataset_factories()
|
| 72 |
+
# group dataset by array types to get a tuple (float32, float64)
|
| 73 |
+
return [all_factories[idx : idx + 2] for idx in range(0, len(all_factories), 2)]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 77 |
+
@pytest.mark.parametrize(
|
| 78 |
+
"dataset_factory", _dense_dataset_factories() + _sparse_dataset_factories()
|
| 79 |
+
)
|
| 80 |
+
def test_seq_dataset_basic_iteration(dataset_factory, csr_container):
|
| 81 |
+
NUMBER_OF_RUNS = 5
|
| 82 |
+
X_csr64 = csr_container(X64)
|
| 83 |
+
dataset = dataset_factory()
|
| 84 |
+
for _ in range(NUMBER_OF_RUNS):
|
| 85 |
+
# next sample
|
| 86 |
+
xi_, yi, swi, idx = dataset._next_py()
|
| 87 |
+
xi = csr_container(xi_, shape=(1, X64.shape[1]))
|
| 88 |
+
|
| 89 |
+
assert_csr_equal_values(xi, X_csr64[[idx]])
|
| 90 |
+
assert yi == y64[idx]
|
| 91 |
+
assert swi == sample_weight64[idx]
|
| 92 |
+
|
| 93 |
+
# random sample
|
| 94 |
+
xi_, yi, swi, idx = dataset._random_py()
|
| 95 |
+
xi = csr_container(xi_, shape=(1, X64.shape[1]))
|
| 96 |
+
|
| 97 |
+
assert_csr_equal_values(xi, X_csr64[[idx]])
|
| 98 |
+
assert yi == y64[idx]
|
| 99 |
+
assert swi == sample_weight64[idx]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@pytest.mark.parametrize(
|
| 103 |
+
"float_dtype, csr_container", product(floating, CSR_CONTAINERS)
|
| 104 |
+
)
|
| 105 |
+
def test_seq_dataset_shuffle(float_dtype, csr_container):
|
| 106 |
+
dense_dataset = _make_dense_dataset(float_dtype)
|
| 107 |
+
sparse_dataset = _make_sparse_dataset(csr_container, float_dtype)
|
| 108 |
+
# not shuffled
|
| 109 |
+
for i in range(5):
|
| 110 |
+
_, _, _, idx1 = dense_dataset._next_py()
|
| 111 |
+
_, _, _, idx2 = sparse_dataset._next_py()
|
| 112 |
+
assert idx1 == i
|
| 113 |
+
assert idx2 == i
|
| 114 |
+
|
| 115 |
+
for i in [132, 50, 9, 18, 58]:
|
| 116 |
+
_, _, _, idx1 = dense_dataset._random_py()
|
| 117 |
+
_, _, _, idx2 = sparse_dataset._random_py()
|
| 118 |
+
assert idx1 == i
|
| 119 |
+
assert idx2 == i
|
| 120 |
+
|
| 121 |
+
seed = 77
|
| 122 |
+
dense_dataset._shuffle_py(seed)
|
| 123 |
+
sparse_dataset._shuffle_py(seed)
|
| 124 |
+
|
| 125 |
+
idx_next = [63, 91, 148, 87, 29]
|
| 126 |
+
idx_shuffle = [137, 125, 56, 121, 127]
|
| 127 |
+
for i, j in zip(idx_next, idx_shuffle):
|
| 128 |
+
_, _, _, idx1 = dense_dataset._next_py()
|
| 129 |
+
_, _, _, idx2 = sparse_dataset._next_py()
|
| 130 |
+
assert idx1 == i
|
| 131 |
+
assert idx2 == i
|
| 132 |
+
|
| 133 |
+
_, _, _, idx1 = dense_dataset._random_py()
|
| 134 |
+
_, _, _, idx2 = sparse_dataset._random_py()
|
| 135 |
+
assert idx1 == j
|
| 136 |
+
assert idx2 == j
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@pytest.mark.parametrize(
|
| 140 |
+
"dataset_32_factory, dataset_64_factory", _fused_types_dataset_factories()
|
| 141 |
+
)
|
| 142 |
+
def test_fused_types_consistency(dataset_32_factory, dataset_64_factory):
|
| 143 |
+
dataset_32, dataset_64 = dataset_32_factory(), dataset_64_factory()
|
| 144 |
+
NUMBER_OF_RUNS = 5
|
| 145 |
+
for _ in range(NUMBER_OF_RUNS):
|
| 146 |
+
# next sample
|
| 147 |
+
(xi_data32, _, _), yi32, _, _ = dataset_32._next_py()
|
| 148 |
+
(xi_data64, _, _), yi64, _, _ = dataset_64._next_py()
|
| 149 |
+
|
| 150 |
+
assert xi_data32.dtype == np.float32
|
| 151 |
+
assert xi_data64.dtype == np.float64
|
| 152 |
+
|
| 153 |
+
assert_allclose(xi_data64, xi_data32, rtol=1e-5)
|
| 154 |
+
assert_allclose(yi64, yi32, rtol=1e-5)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_buffer_dtype_mismatch_error():
|
| 158 |
+
with pytest.raises(ValueError, match="Buffer dtype mismatch"):
|
| 159 |
+
ArrayDataset64(X32, y32, sample_weight32, seed=42)
|
| 160 |
+
|
| 161 |
+
with pytest.raises(ValueError, match="Buffer dtype mismatch"):
|
| 162 |
+
ArrayDataset32(X64, y64, sample_weight64, seed=42)
|
| 163 |
+
|
| 164 |
+
for csr_container in CSR_CONTAINERS:
|
| 165 |
+
X_csr32 = csr_container(X32)
|
| 166 |
+
X_csr64 = csr_container(X64)
|
| 167 |
+
with pytest.raises(ValueError, match="Buffer dtype mismatch"):
|
| 168 |
+
CSRDataset64(
|
| 169 |
+
X_csr32.data,
|
| 170 |
+
X_csr32.indptr,
|
| 171 |
+
X_csr32.indices,
|
| 172 |
+
y32,
|
| 173 |
+
sample_weight32,
|
| 174 |
+
seed=42,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
with pytest.raises(ValueError, match="Buffer dtype mismatch"):
|
| 178 |
+
CSRDataset32(
|
| 179 |
+
X_csr64.data,
|
| 180 |
+
X_csr64.indptr,
|
| 181 |
+
X_csr64.indices,
|
| 182 |
+
y64,
|
| 183 |
+
sample_weight64,
|
| 184 |
+
seed=42,
|
| 185 |
+
)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_set_output.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
from collections import namedtuple
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
from numpy.testing import assert_array_equal
|
| 7 |
+
|
| 8 |
+
from sklearn._config import config_context, get_config
|
| 9 |
+
from sklearn.preprocessing import StandardScaler
|
| 10 |
+
from sklearn.utils._set_output import (
|
| 11 |
+
ADAPTERS_MANAGER,
|
| 12 |
+
ContainerAdapterProtocol,
|
| 13 |
+
_get_adapter_from_container,
|
| 14 |
+
_get_output_config,
|
| 15 |
+
_safe_set_output,
|
| 16 |
+
_SetOutputMixin,
|
| 17 |
+
_wrap_data_with_container,
|
| 18 |
+
check_library_installed,
|
| 19 |
+
)
|
| 20 |
+
from sklearn.utils.fixes import CSR_CONTAINERS
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_pandas_adapter():
|
| 24 |
+
"""Check pandas adapter has expected behavior."""
|
| 25 |
+
pd = pytest.importorskip("pandas")
|
| 26 |
+
X_np = np.asarray([[1, 0, 3], [0, 0, 1]])
|
| 27 |
+
columns = np.asarray(["f0", "f1", "f2"], dtype=object)
|
| 28 |
+
index = np.asarray([1, 2])
|
| 29 |
+
X_df_orig = pd.DataFrame([[1, 2], [1, 3]], index=index)
|
| 30 |
+
X_ser_orig = pd.Series([2, 3], index=index)
|
| 31 |
+
|
| 32 |
+
adapter = ADAPTERS_MANAGER.adapters["pandas"]
|
| 33 |
+
X_container = adapter.create_container(X_np, X_df_orig, columns=lambda: columns)
|
| 34 |
+
assert isinstance(X_container, pd.DataFrame)
|
| 35 |
+
assert_array_equal(X_container.columns, columns)
|
| 36 |
+
assert_array_equal(X_container.index, index)
|
| 37 |
+
|
| 38 |
+
# use original index when the original is a series
|
| 39 |
+
X_container = adapter.create_container(X_np, X_ser_orig, columns=lambda: columns)
|
| 40 |
+
assert isinstance(X_container, pd.DataFrame)
|
| 41 |
+
assert_array_equal(X_container.columns, columns)
|
| 42 |
+
assert_array_equal(X_container.index, index)
|
| 43 |
+
|
| 44 |
+
# Input dataframe's index does not change
|
| 45 |
+
new_columns = np.asarray(["f0", "f1"], dtype=object)
|
| 46 |
+
X_df = pd.DataFrame([[1, 2], [1, 3]], index=[10, 12])
|
| 47 |
+
new_df = adapter.create_container(X_df, X_df_orig, columns=new_columns)
|
| 48 |
+
assert_array_equal(new_df.columns, new_columns)
|
| 49 |
+
assert_array_equal(new_df.index, X_df.index)
|
| 50 |
+
|
| 51 |
+
assert adapter.is_supported_container(X_df)
|
| 52 |
+
assert not adapter.is_supported_container(X_np)
|
| 53 |
+
|
| 54 |
+
# adapter.update_columns updates the columns
|
| 55 |
+
new_columns = np.array(["a", "c"], dtype=object)
|
| 56 |
+
new_df = adapter.rename_columns(X_df, new_columns)
|
| 57 |
+
assert_array_equal(new_df.columns, new_columns)
|
| 58 |
+
|
| 59 |
+
# adapter.hstack stacks the dataframes horizontally.
|
| 60 |
+
X_df_1 = pd.DataFrame([[1, 2, 5], [3, 4, 6]], columns=["a", "b", "e"])
|
| 61 |
+
X_df_2 = pd.DataFrame([[4], [5]], columns=["c"])
|
| 62 |
+
X_stacked = adapter.hstack([X_df_1, X_df_2])
|
| 63 |
+
|
| 64 |
+
expected_df = pd.DataFrame(
|
| 65 |
+
[[1, 2, 5, 4], [3, 4, 6, 5]], columns=["a", "b", "e", "c"]
|
| 66 |
+
)
|
| 67 |
+
pd.testing.assert_frame_equal(X_stacked, expected_df)
|
| 68 |
+
|
| 69 |
+
# check that we update properly the columns even with duplicate column names
|
| 70 |
+
# this use-case potentially happen when using ColumnTransformer
|
| 71 |
+
# non-regression test for gh-28260
|
| 72 |
+
X_df = pd.DataFrame([[1, 2], [1, 3]], columns=["a", "a"])
|
| 73 |
+
new_columns = np.array(["x__a", "y__a"], dtype=object)
|
| 74 |
+
new_df = adapter.rename_columns(X_df, new_columns)
|
| 75 |
+
assert_array_equal(new_df.columns, new_columns)
|
| 76 |
+
|
| 77 |
+
# check the behavior of the inplace parameter in `create_container`
|
| 78 |
+
# we should trigger a copy
|
| 79 |
+
X_df = pd.DataFrame([[1, 2], [1, 3]], index=index)
|
| 80 |
+
X_output = adapter.create_container(X_df, X_df, columns=["a", "b"], inplace=False)
|
| 81 |
+
assert X_output is not X_df
|
| 82 |
+
assert list(X_df.columns) == [0, 1]
|
| 83 |
+
assert list(X_output.columns) == ["a", "b"]
|
| 84 |
+
|
| 85 |
+
# the operation is inplace
|
| 86 |
+
X_df = pd.DataFrame([[1, 2], [1, 3]], index=index)
|
| 87 |
+
X_output = adapter.create_container(X_df, X_df, columns=["a", "b"], inplace=True)
|
| 88 |
+
assert X_output is X_df
|
| 89 |
+
assert list(X_df.columns) == ["a", "b"]
|
| 90 |
+
assert list(X_output.columns) == ["a", "b"]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_polars_adapter():
|
| 94 |
+
"""Check Polars adapter has expected behavior."""
|
| 95 |
+
pl = pytest.importorskip("polars")
|
| 96 |
+
X_np = np.array([[1, 0, 3], [0, 0, 1]])
|
| 97 |
+
columns = ["f1", "f2", "f3"]
|
| 98 |
+
X_df_orig = pl.DataFrame(X_np, schema=columns, orient="row")
|
| 99 |
+
|
| 100 |
+
adapter = ADAPTERS_MANAGER.adapters["polars"]
|
| 101 |
+
X_container = adapter.create_container(X_np, X_df_orig, columns=lambda: columns)
|
| 102 |
+
|
| 103 |
+
assert isinstance(X_container, pl.DataFrame)
|
| 104 |
+
assert_array_equal(X_container.columns, columns)
|
| 105 |
+
|
| 106 |
+
# Update columns with create_container
|
| 107 |
+
new_columns = np.asarray(["a", "b", "c"], dtype=object)
|
| 108 |
+
new_df = adapter.create_container(X_df_orig, X_df_orig, columns=new_columns)
|
| 109 |
+
assert_array_equal(new_df.columns, new_columns)
|
| 110 |
+
|
| 111 |
+
assert adapter.is_supported_container(X_df_orig)
|
| 112 |
+
assert not adapter.is_supported_container(X_np)
|
| 113 |
+
|
| 114 |
+
# adapter.update_columns updates the columns
|
| 115 |
+
new_columns = np.array(["a", "c", "g"], dtype=object)
|
| 116 |
+
new_df = adapter.rename_columns(X_df_orig, new_columns)
|
| 117 |
+
assert_array_equal(new_df.columns, new_columns)
|
| 118 |
+
|
| 119 |
+
# adapter.hstack stacks the dataframes horizontally.
|
| 120 |
+
X_df_1 = pl.DataFrame([[1, 2, 5], [3, 4, 6]], schema=["a", "b", "e"], orient="row")
|
| 121 |
+
X_df_2 = pl.DataFrame([[4], [5]], schema=["c"], orient="row")
|
| 122 |
+
X_stacked = adapter.hstack([X_df_1, X_df_2])
|
| 123 |
+
|
| 124 |
+
expected_df = pl.DataFrame(
|
| 125 |
+
[[1, 2, 5, 4], [3, 4, 6, 5]], schema=["a", "b", "e", "c"], orient="row"
|
| 126 |
+
)
|
| 127 |
+
from polars.testing import assert_frame_equal
|
| 128 |
+
|
| 129 |
+
assert_frame_equal(X_stacked, expected_df)
|
| 130 |
+
|
| 131 |
+
# check the behavior of the inplace parameter in `create_container`
|
| 132 |
+
# we should trigger a copy
|
| 133 |
+
X_df = pl.DataFrame([[1, 2], [1, 3]], schema=["a", "b"], orient="row")
|
| 134 |
+
X_output = adapter.create_container(X_df, X_df, columns=["c", "d"], inplace=False)
|
| 135 |
+
assert X_output is not X_df
|
| 136 |
+
assert list(X_df.columns) == ["a", "b"]
|
| 137 |
+
assert list(X_output.columns) == ["c", "d"]
|
| 138 |
+
|
| 139 |
+
# the operation is inplace
|
| 140 |
+
X_df = pl.DataFrame([[1, 2], [1, 3]], schema=["a", "b"], orient="row")
|
| 141 |
+
X_output = adapter.create_container(X_df, X_df, columns=["c", "d"], inplace=True)
|
| 142 |
+
assert X_output is X_df
|
| 143 |
+
assert list(X_df.columns) == ["c", "d"]
|
| 144 |
+
assert list(X_output.columns) == ["c", "d"]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 148 |
+
def test__container_error_validation(csr_container):
|
| 149 |
+
"""Check errors in _wrap_data_with_container."""
|
| 150 |
+
X = np.asarray([[1, 0, 3], [0, 0, 1]])
|
| 151 |
+
X_csr = csr_container(X)
|
| 152 |
+
match = "The transformer outputs a scipy sparse matrix."
|
| 153 |
+
with config_context(transform_output="pandas"):
|
| 154 |
+
with pytest.raises(ValueError, match=match):
|
| 155 |
+
_wrap_data_with_container("transform", X_csr, X, StandardScaler())
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class EstimatorWithoutSetOutputAndWithoutTransform:
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class EstimatorNoSetOutputWithTransform:
|
| 163 |
+
def transform(self, X, y=None):
|
| 164 |
+
return X # pragma: no cover
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class EstimatorWithSetOutput(_SetOutputMixin):
|
| 168 |
+
def fit(self, X, y=None):
|
| 169 |
+
self.n_features_in_ = X.shape[1]
|
| 170 |
+
return self
|
| 171 |
+
|
| 172 |
+
def transform(self, X, y=None):
|
| 173 |
+
return X
|
| 174 |
+
|
| 175 |
+
def get_feature_names_out(self, input_features=None):
|
| 176 |
+
return np.asarray([f"X{i}" for i in range(self.n_features_in_)], dtype=object)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test__safe_set_output():
|
| 180 |
+
"""Check _safe_set_output works as expected."""
|
| 181 |
+
|
| 182 |
+
# Estimator without transform will not raise when setting set_output for transform.
|
| 183 |
+
est = EstimatorWithoutSetOutputAndWithoutTransform()
|
| 184 |
+
_safe_set_output(est, transform="pandas")
|
| 185 |
+
|
| 186 |
+
# Estimator with transform but without set_output will raise
|
| 187 |
+
est = EstimatorNoSetOutputWithTransform()
|
| 188 |
+
with pytest.raises(ValueError, match="Unable to configure output"):
|
| 189 |
+
_safe_set_output(est, transform="pandas")
|
| 190 |
+
|
| 191 |
+
est = EstimatorWithSetOutput().fit(np.asarray([[1, 2, 3]]))
|
| 192 |
+
_safe_set_output(est, transform="pandas")
|
| 193 |
+
config = _get_output_config("transform", est)
|
| 194 |
+
assert config["dense"] == "pandas"
|
| 195 |
+
|
| 196 |
+
_safe_set_output(est, transform="default")
|
| 197 |
+
config = _get_output_config("transform", est)
|
| 198 |
+
assert config["dense"] == "default"
|
| 199 |
+
|
| 200 |
+
# transform is None is a no-op, so the config remains "default"
|
| 201 |
+
_safe_set_output(est, transform=None)
|
| 202 |
+
config = _get_output_config("transform", est)
|
| 203 |
+
assert config["dense"] == "default"
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class EstimatorNoSetOutputWithTransformNoFeatureNamesOut(_SetOutputMixin):
|
| 207 |
+
def transform(self, X, y=None):
|
| 208 |
+
return X # pragma: no cover
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def test_set_output_mixin():
|
| 212 |
+
"""Estimator without get_feature_names_out does not define `set_output`."""
|
| 213 |
+
est = EstimatorNoSetOutputWithTransformNoFeatureNamesOut()
|
| 214 |
+
assert not hasattr(est, "set_output")
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def test__safe_set_output_error():
|
| 218 |
+
"""Check transform with invalid config."""
|
| 219 |
+
X = np.asarray([[1, 0, 3], [0, 0, 1]])
|
| 220 |
+
|
| 221 |
+
est = EstimatorWithSetOutput()
|
| 222 |
+
_safe_set_output(est, transform="bad")
|
| 223 |
+
|
| 224 |
+
msg = "output config must be in"
|
| 225 |
+
with pytest.raises(ValueError, match=msg):
|
| 226 |
+
est.transform(X)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@pytest.mark.parametrize("dataframe_lib", ["pandas", "polars"])
|
| 230 |
+
def test_set_output_method(dataframe_lib):
|
| 231 |
+
"""Check that the output is a dataframe."""
|
| 232 |
+
lib = pytest.importorskip(dataframe_lib)
|
| 233 |
+
|
| 234 |
+
X = np.asarray([[1, 0, 3], [0, 0, 1]])
|
| 235 |
+
est = EstimatorWithSetOutput().fit(X)
|
| 236 |
+
|
| 237 |
+
# transform=None is a no-op
|
| 238 |
+
est2 = est.set_output(transform=None)
|
| 239 |
+
assert est2 is est
|
| 240 |
+
X_trans_np = est2.transform(X)
|
| 241 |
+
assert isinstance(X_trans_np, np.ndarray)
|
| 242 |
+
|
| 243 |
+
est.set_output(transform=dataframe_lib)
|
| 244 |
+
|
| 245 |
+
X_trans_pd = est.transform(X)
|
| 246 |
+
|
| 247 |
+
assert isinstance(X_trans_pd, lib.DataFrame)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def test_set_output_method_error():
|
| 251 |
+
"""Check transform fails with invalid transform."""
|
| 252 |
+
|
| 253 |
+
X = np.asarray([[1, 0, 3], [0, 0, 1]])
|
| 254 |
+
est = EstimatorWithSetOutput().fit(X)
|
| 255 |
+
est.set_output(transform="bad")
|
| 256 |
+
|
| 257 |
+
msg = "output config must be in"
|
| 258 |
+
with pytest.raises(ValueError, match=msg):
|
| 259 |
+
est.transform(X)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@pytest.mark.parametrize("transform_output", ["pandas", "polars"])
|
| 263 |
+
def test__get_output_config(transform_output):
|
| 264 |
+
"""Check _get_output_config works as expected."""
|
| 265 |
+
|
| 266 |
+
# Without a configuration set, the global config is used
|
| 267 |
+
global_config = get_config()["transform_output"]
|
| 268 |
+
config = _get_output_config("transform")
|
| 269 |
+
assert config["dense"] == global_config
|
| 270 |
+
|
| 271 |
+
with config_context(transform_output=transform_output):
|
| 272 |
+
# with estimator=None, the global config is used
|
| 273 |
+
config = _get_output_config("transform")
|
| 274 |
+
assert config["dense"] == transform_output
|
| 275 |
+
|
| 276 |
+
est = EstimatorNoSetOutputWithTransform()
|
| 277 |
+
config = _get_output_config("transform", est)
|
| 278 |
+
assert config["dense"] == transform_output
|
| 279 |
+
|
| 280 |
+
est = EstimatorWithSetOutput()
|
| 281 |
+
# If estimator has not config, use global config
|
| 282 |
+
config = _get_output_config("transform", est)
|
| 283 |
+
assert config["dense"] == transform_output
|
| 284 |
+
|
| 285 |
+
# If estimator has a config, use local config
|
| 286 |
+
est.set_output(transform="default")
|
| 287 |
+
config = _get_output_config("transform", est)
|
| 288 |
+
assert config["dense"] == "default"
|
| 289 |
+
|
| 290 |
+
est.set_output(transform=transform_output)
|
| 291 |
+
config = _get_output_config("transform", est)
|
| 292 |
+
assert config["dense"] == transform_output
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class EstimatorWithSetOutputNoAutoWrap(_SetOutputMixin, auto_wrap_output_keys=None):
|
| 296 |
+
def transform(self, X, y=None):
|
| 297 |
+
return X
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def test_get_output_auto_wrap_false():
|
| 301 |
+
"""Check that auto_wrap_output_keys=None does not wrap."""
|
| 302 |
+
est = EstimatorWithSetOutputNoAutoWrap()
|
| 303 |
+
assert not hasattr(est, "set_output")
|
| 304 |
+
|
| 305 |
+
X = np.asarray([[1, 0, 3], [0, 0, 1]])
|
| 306 |
+
assert X is est.transform(X)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def test_auto_wrap_output_keys_errors_with_incorrect_input():
|
| 310 |
+
msg = "auto_wrap_output_keys must be None or a tuple of keys."
|
| 311 |
+
with pytest.raises(ValueError, match=msg):
|
| 312 |
+
|
| 313 |
+
class BadEstimator(_SetOutputMixin, auto_wrap_output_keys="bad_parameter"):
|
| 314 |
+
pass
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class AnotherMixin:
|
| 318 |
+
def __init_subclass__(cls, custom_parameter, **kwargs):
|
| 319 |
+
super().__init_subclass__(**kwargs)
|
| 320 |
+
cls.custom_parameter = custom_parameter
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def test_set_output_mixin_custom_mixin():
|
| 324 |
+
"""Check that multiple init_subclasses passes parameters up."""
|
| 325 |
+
|
| 326 |
+
class BothMixinEstimator(_SetOutputMixin, AnotherMixin, custom_parameter=123):
|
| 327 |
+
def transform(self, X, y=None):
|
| 328 |
+
return X
|
| 329 |
+
|
| 330 |
+
def get_feature_names_out(self, input_features=None):
|
| 331 |
+
return input_features
|
| 332 |
+
|
| 333 |
+
est = BothMixinEstimator()
|
| 334 |
+
assert est.custom_parameter == 123
|
| 335 |
+
assert hasattr(est, "set_output")
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def test_set_output_mro():
|
| 339 |
+
"""Check that multi-inheritance resolves to the correct class method.
|
| 340 |
+
|
| 341 |
+
Non-regression test gh-25293.
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
class Base(_SetOutputMixin):
|
| 345 |
+
def transform(self, X):
|
| 346 |
+
return "Base"
|
| 347 |
+
|
| 348 |
+
class A(Base):
|
| 349 |
+
pass
|
| 350 |
+
|
| 351 |
+
class B(Base):
|
| 352 |
+
def transform(self, X):
|
| 353 |
+
return "B"
|
| 354 |
+
|
| 355 |
+
class C(A, B):
|
| 356 |
+
pass
|
| 357 |
+
|
| 358 |
+
assert C().transform(None) == "B"
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class EstimatorWithSetOutputIndex(_SetOutputMixin):
|
| 362 |
+
def fit(self, X, y=None):
|
| 363 |
+
self.n_features_in_ = X.shape[1]
|
| 364 |
+
return self
|
| 365 |
+
|
| 366 |
+
def transform(self, X, y=None):
|
| 367 |
+
import pandas as pd
|
| 368 |
+
|
| 369 |
+
# transform by giving output a new index.
|
| 370 |
+
return pd.DataFrame(X.to_numpy(), index=[f"s{i}" for i in range(X.shape[0])])
|
| 371 |
+
|
| 372 |
+
def get_feature_names_out(self, input_features=None):
|
| 373 |
+
return np.asarray([f"X{i}" for i in range(self.n_features_in_)], dtype=object)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def test_set_output_pandas_keep_index():
|
| 377 |
+
"""Check that set_output does not override index.
|
| 378 |
+
|
| 379 |
+
Non-regression test for gh-25730.
|
| 380 |
+
"""
|
| 381 |
+
pd = pytest.importorskip("pandas")
|
| 382 |
+
|
| 383 |
+
X = pd.DataFrame([[1, 2, 3], [4, 5, 6]], index=[0, 1])
|
| 384 |
+
est = EstimatorWithSetOutputIndex().set_output(transform="pandas")
|
| 385 |
+
est.fit(X)
|
| 386 |
+
|
| 387 |
+
X_trans = est.transform(X)
|
| 388 |
+
assert_array_equal(X_trans.index, ["s0", "s1"])
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class EstimatorReturnTuple(_SetOutputMixin):
|
| 392 |
+
def __init__(self, OutputTuple):
|
| 393 |
+
self.OutputTuple = OutputTuple
|
| 394 |
+
|
| 395 |
+
def transform(self, X, y=None):
|
| 396 |
+
return self.OutputTuple(X, 2 * X)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def test_set_output_named_tuple_out():
|
| 400 |
+
"""Check that namedtuples are kept by default."""
|
| 401 |
+
Output = namedtuple("Output", "X, Y")
|
| 402 |
+
X = np.asarray([[1, 2, 3]])
|
| 403 |
+
est = EstimatorReturnTuple(OutputTuple=Output)
|
| 404 |
+
X_trans = est.transform(X)
|
| 405 |
+
|
| 406 |
+
assert isinstance(X_trans, Output)
|
| 407 |
+
assert_array_equal(X_trans.X, X)
|
| 408 |
+
assert_array_equal(X_trans.Y, 2 * X)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
class EstimatorWithListInput(_SetOutputMixin):
|
| 412 |
+
def fit(self, X, y=None):
|
| 413 |
+
assert isinstance(X, list)
|
| 414 |
+
self.n_features_in_ = len(X[0])
|
| 415 |
+
return self
|
| 416 |
+
|
| 417 |
+
def transform(self, X, y=None):
|
| 418 |
+
return X
|
| 419 |
+
|
| 420 |
+
def get_feature_names_out(self, input_features=None):
|
| 421 |
+
return np.asarray([f"X{i}" for i in range(self.n_features_in_)], dtype=object)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
@pytest.mark.parametrize("dataframe_lib", ["pandas", "polars"])
|
| 425 |
+
def test_set_output_list_input(dataframe_lib):
|
| 426 |
+
"""Check set_output for list input.
|
| 427 |
+
|
| 428 |
+
Non-regression test for #27037.
|
| 429 |
+
"""
|
| 430 |
+
lib = pytest.importorskip(dataframe_lib)
|
| 431 |
+
|
| 432 |
+
X = [[0, 1, 2, 3], [4, 5, 6, 7]]
|
| 433 |
+
est = EstimatorWithListInput()
|
| 434 |
+
est.set_output(transform=dataframe_lib)
|
| 435 |
+
|
| 436 |
+
X_out = est.fit(X).transform(X)
|
| 437 |
+
assert isinstance(X_out, lib.DataFrame)
|
| 438 |
+
assert_array_equal(X_out.columns, ["X0", "X1", "X2", "X3"])
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
@pytest.mark.parametrize("name", sorted(ADAPTERS_MANAGER.adapters))
|
| 442 |
+
def test_adapter_class_has_interface(name):
|
| 443 |
+
"""Check adapters have the correct interface."""
|
| 444 |
+
assert isinstance(ADAPTERS_MANAGER.adapters[name], ContainerAdapterProtocol)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def test_check_library_installed(monkeypatch):
|
| 448 |
+
"""Check import error changed."""
|
| 449 |
+
orig_import_module = importlib.import_module
|
| 450 |
+
|
| 451 |
+
def patched_import_module(name):
|
| 452 |
+
if name == "pandas":
|
| 453 |
+
raise ImportError()
|
| 454 |
+
orig_import_module(name, package=None)
|
| 455 |
+
|
| 456 |
+
monkeypatch.setattr(importlib, "import_module", patched_import_module)
|
| 457 |
+
|
| 458 |
+
msg = "Setting output container to 'pandas' requires"
|
| 459 |
+
with pytest.raises(ImportError, match=msg):
|
| 460 |
+
check_library_installed("pandas")
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def test_get_adapter_from_container():
|
| 464 |
+
"""Check the behavior fo `_get_adapter_from_container`."""
|
| 465 |
+
pd = pytest.importorskip("pandas")
|
| 466 |
+
X = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 100]})
|
| 467 |
+
adapter = _get_adapter_from_container(X)
|
| 468 |
+
assert adapter.container_lib == "pandas"
|
| 469 |
+
err_msg = "The container does not have a registered adapter in scikit-learn."
|
| 470 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 471 |
+
_get_adapter_from_container(X.to_numpy())
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_shortest_path.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from numpy.testing import assert_array_almost_equal
|
| 5 |
+
|
| 6 |
+
from sklearn.utils.graph import single_source_shortest_path_length
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def floyd_warshall_slow(graph, directed=False):
|
| 10 |
+
N = graph.shape[0]
|
| 11 |
+
|
| 12 |
+
# set nonzero entries to infinity
|
| 13 |
+
graph[np.where(graph == 0)] = np.inf
|
| 14 |
+
|
| 15 |
+
# set diagonal to zero
|
| 16 |
+
graph.flat[:: N + 1] = 0
|
| 17 |
+
|
| 18 |
+
if not directed:
|
| 19 |
+
graph = np.minimum(graph, graph.T)
|
| 20 |
+
|
| 21 |
+
for k in range(N):
|
| 22 |
+
for i in range(N):
|
| 23 |
+
for j in range(N):
|
| 24 |
+
graph[i, j] = min(graph[i, j], graph[i, k] + graph[k, j])
|
| 25 |
+
|
| 26 |
+
graph[np.where(np.isinf(graph))] = 0
|
| 27 |
+
|
| 28 |
+
return graph
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def generate_graph(N=20):
|
| 32 |
+
# sparse grid of distances
|
| 33 |
+
rng = np.random.RandomState(0)
|
| 34 |
+
dist_matrix = rng.random_sample((N, N))
|
| 35 |
+
|
| 36 |
+
# make symmetric: distances are not direction-dependent
|
| 37 |
+
dist_matrix = dist_matrix + dist_matrix.T
|
| 38 |
+
|
| 39 |
+
# make graph sparse
|
| 40 |
+
i = (rng.randint(N, size=N * N // 2), rng.randint(N, size=N * N // 2))
|
| 41 |
+
dist_matrix[i] = 0
|
| 42 |
+
|
| 43 |
+
# set diagonal to zero
|
| 44 |
+
dist_matrix.flat[:: N + 1] = 0
|
| 45 |
+
|
| 46 |
+
return dist_matrix
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_shortest_path():
|
| 50 |
+
dist_matrix = generate_graph(20)
|
| 51 |
+
# We compare path length and not costs (-> set distances to 0 or 1)
|
| 52 |
+
dist_matrix[dist_matrix != 0] = 1
|
| 53 |
+
|
| 54 |
+
for directed in (True, False):
|
| 55 |
+
if not directed:
|
| 56 |
+
dist_matrix = np.minimum(dist_matrix, dist_matrix.T)
|
| 57 |
+
|
| 58 |
+
graph_py = floyd_warshall_slow(dist_matrix.copy(), directed)
|
| 59 |
+
for i in range(dist_matrix.shape[0]):
|
| 60 |
+
# Non-reachable nodes have distance 0 in graph_py
|
| 61 |
+
dist_dict = defaultdict(int)
|
| 62 |
+
dist_dict.update(single_source_shortest_path_length(dist_matrix, i))
|
| 63 |
+
|
| 64 |
+
for j in range(graph_py[i].shape[0]):
|
| 65 |
+
assert_array_almost_equal(dist_dict[j], graph_py[i, j])
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_show_versions.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from threadpoolctl import threadpool_info
|
| 2 |
+
|
| 3 |
+
from sklearn.utils._show_versions import _get_deps_info, _get_sys_info, show_versions
|
| 4 |
+
from sklearn.utils._testing import ignore_warnings
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_get_sys_info():
|
| 8 |
+
sys_info = _get_sys_info()
|
| 9 |
+
|
| 10 |
+
assert "python" in sys_info
|
| 11 |
+
assert "executable" in sys_info
|
| 12 |
+
assert "machine" in sys_info
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_get_deps_info():
|
| 16 |
+
with ignore_warnings():
|
| 17 |
+
deps_info = _get_deps_info()
|
| 18 |
+
|
| 19 |
+
assert "pip" in deps_info
|
| 20 |
+
assert "setuptools" in deps_info
|
| 21 |
+
assert "sklearn" in deps_info
|
| 22 |
+
assert "numpy" in deps_info
|
| 23 |
+
assert "scipy" in deps_info
|
| 24 |
+
assert "Cython" in deps_info
|
| 25 |
+
assert "pandas" in deps_info
|
| 26 |
+
assert "matplotlib" in deps_info
|
| 27 |
+
assert "joblib" in deps_info
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_show_versions(capsys):
|
| 31 |
+
with ignore_warnings():
|
| 32 |
+
show_versions()
|
| 33 |
+
out, err = capsys.readouterr()
|
| 34 |
+
|
| 35 |
+
assert "python" in out
|
| 36 |
+
assert "numpy" in out
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
import scipy.sparse as sp
|
| 4 |
+
from numpy.random import RandomState
|
| 5 |
+
from numpy.testing import assert_array_almost_equal, assert_array_equal
|
| 6 |
+
from scipy import linalg
|
| 7 |
+
|
| 8 |
+
from sklearn.datasets import make_classification
|
| 9 |
+
from sklearn.utils._testing import assert_allclose
|
| 10 |
+
from sklearn.utils.fixes import CSC_CONTAINERS, CSR_CONTAINERS, LIL_CONTAINERS
|
| 11 |
+
from sklearn.utils.sparsefuncs import (
|
| 12 |
+
_implicit_column_offset,
|
| 13 |
+
count_nonzero,
|
| 14 |
+
csc_median_axis_0,
|
| 15 |
+
incr_mean_variance_axis,
|
| 16 |
+
inplace_column_scale,
|
| 17 |
+
inplace_row_scale,
|
| 18 |
+
inplace_swap_column,
|
| 19 |
+
inplace_swap_row,
|
| 20 |
+
mean_variance_axis,
|
| 21 |
+
min_max_axis,
|
| 22 |
+
sparse_matmul_to_dense,
|
| 23 |
+
)
|
| 24 |
+
from sklearn.utils.sparsefuncs_fast import (
|
| 25 |
+
assign_rows_csr,
|
| 26 |
+
csr_row_norms,
|
| 27 |
+
inplace_csr_row_normalize_l1,
|
| 28 |
+
inplace_csr_row_normalize_l2,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 33 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 34 |
+
@pytest.mark.parametrize("lil_container", LIL_CONTAINERS)
|
| 35 |
+
def test_mean_variance_axis0(csc_container, csr_container, lil_container):
|
| 36 |
+
X, _ = make_classification(5, 4, random_state=0)
|
| 37 |
+
# Sparsify the array a little bit
|
| 38 |
+
X[0, 0] = 0
|
| 39 |
+
X[2, 1] = 0
|
| 40 |
+
X[4, 3] = 0
|
| 41 |
+
X_lil = lil_container(X)
|
| 42 |
+
X_lil[1, 0] = 0
|
| 43 |
+
X[1, 0] = 0
|
| 44 |
+
|
| 45 |
+
with pytest.raises(TypeError):
|
| 46 |
+
mean_variance_axis(X_lil, axis=0)
|
| 47 |
+
|
| 48 |
+
X_csr = csr_container(X_lil)
|
| 49 |
+
X_csc = csc_container(X_lil)
|
| 50 |
+
|
| 51 |
+
expected_dtypes = [
|
| 52 |
+
(np.float32, np.float32),
|
| 53 |
+
(np.float64, np.float64),
|
| 54 |
+
(np.int32, np.float64),
|
| 55 |
+
(np.int64, np.float64),
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
for input_dtype, output_dtype in expected_dtypes:
|
| 59 |
+
X_test = X.astype(input_dtype)
|
| 60 |
+
for X_sparse in (X_csr, X_csc):
|
| 61 |
+
X_sparse = X_sparse.astype(input_dtype)
|
| 62 |
+
X_means, X_vars = mean_variance_axis(X_sparse, axis=0)
|
| 63 |
+
assert X_means.dtype == output_dtype
|
| 64 |
+
assert X_vars.dtype == output_dtype
|
| 65 |
+
assert_array_almost_equal(X_means, np.mean(X_test, axis=0))
|
| 66 |
+
assert_array_almost_equal(X_vars, np.var(X_test, axis=0))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
|
| 70 |
+
@pytest.mark.parametrize("sparse_constructor", CSC_CONTAINERS + CSR_CONTAINERS)
|
| 71 |
+
def test_mean_variance_axis0_precision(dtype, sparse_constructor):
|
| 72 |
+
# Check that there's no big loss of precision when the real variance is
|
| 73 |
+
# exactly 0. (#19766)
|
| 74 |
+
rng = np.random.RandomState(0)
|
| 75 |
+
X = np.full(fill_value=100.0, shape=(1000, 1), dtype=dtype)
|
| 76 |
+
# Add some missing records which should be ignored:
|
| 77 |
+
missing_indices = rng.choice(np.arange(X.shape[0]), 10, replace=False)
|
| 78 |
+
X[missing_indices, 0] = np.nan
|
| 79 |
+
X = sparse_constructor(X)
|
| 80 |
+
|
| 81 |
+
# Random positive weights:
|
| 82 |
+
sample_weight = rng.rand(X.shape[0]).astype(dtype)
|
| 83 |
+
|
| 84 |
+
_, var = mean_variance_axis(X, weights=sample_weight, axis=0)
|
| 85 |
+
|
| 86 |
+
assert var < np.finfo(dtype).eps
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 90 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 91 |
+
@pytest.mark.parametrize("lil_container", LIL_CONTAINERS)
|
| 92 |
+
def test_mean_variance_axis1(csc_container, csr_container, lil_container):
|
| 93 |
+
X, _ = make_classification(5, 4, random_state=0)
|
| 94 |
+
# Sparsify the array a little bit
|
| 95 |
+
X[0, 0] = 0
|
| 96 |
+
X[2, 1] = 0
|
| 97 |
+
X[4, 3] = 0
|
| 98 |
+
X_lil = lil_container(X)
|
| 99 |
+
X_lil[1, 0] = 0
|
| 100 |
+
X[1, 0] = 0
|
| 101 |
+
|
| 102 |
+
with pytest.raises(TypeError):
|
| 103 |
+
mean_variance_axis(X_lil, axis=1)
|
| 104 |
+
|
| 105 |
+
X_csr = csr_container(X_lil)
|
| 106 |
+
X_csc = csc_container(X_lil)
|
| 107 |
+
|
| 108 |
+
expected_dtypes = [
|
| 109 |
+
(np.float32, np.float32),
|
| 110 |
+
(np.float64, np.float64),
|
| 111 |
+
(np.int32, np.float64),
|
| 112 |
+
(np.int64, np.float64),
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
for input_dtype, output_dtype in expected_dtypes:
|
| 116 |
+
X_test = X.astype(input_dtype)
|
| 117 |
+
for X_sparse in (X_csr, X_csc):
|
| 118 |
+
X_sparse = X_sparse.astype(input_dtype)
|
| 119 |
+
X_means, X_vars = mean_variance_axis(X_sparse, axis=0)
|
| 120 |
+
assert X_means.dtype == output_dtype
|
| 121 |
+
assert X_vars.dtype == output_dtype
|
| 122 |
+
assert_array_almost_equal(X_means, np.mean(X_test, axis=0))
|
| 123 |
+
assert_array_almost_equal(X_vars, np.var(X_test, axis=0))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@pytest.mark.parametrize(
|
| 127 |
+
["Xw", "X", "weights"],
|
| 128 |
+
[
|
| 129 |
+
([[0, 0, 1], [0, 2, 3]], [[0, 0, 1], [0, 2, 3]], [1, 1, 1]),
|
| 130 |
+
([[0, 0, 1], [0, 1, 1]], [[0, 0, 0, 1], [0, 1, 1, 1]], [1, 2, 1]),
|
| 131 |
+
([[0, 0, 1], [0, 1, 1]], [[0, 0, 1], [0, 1, 1]], None),
|
| 132 |
+
(
|
| 133 |
+
[[0, np.nan, 2], [0, np.nan, np.nan]],
|
| 134 |
+
[[0, np.nan, 2], [0, np.nan, np.nan]],
|
| 135 |
+
[1.0, 1.0, 1.0],
|
| 136 |
+
),
|
| 137 |
+
(
|
| 138 |
+
[[0, 0], [1, np.nan], [2, 0], [0, 3], [np.nan, np.nan], [np.nan, 2]],
|
| 139 |
+
[
|
| 140 |
+
[0, 0, 0],
|
| 141 |
+
[1, 1, np.nan],
|
| 142 |
+
[2, 2, 0],
|
| 143 |
+
[0, 0, 3],
|
| 144 |
+
[np.nan, np.nan, np.nan],
|
| 145 |
+
[np.nan, np.nan, 2],
|
| 146 |
+
],
|
| 147 |
+
[2.0, 1.0],
|
| 148 |
+
),
|
| 149 |
+
(
|
| 150 |
+
[[1, 0, 1], [0, 3, 1]],
|
| 151 |
+
[[1, 0, 0, 0, 1], [0, 3, 3, 3, 1]],
|
| 152 |
+
np.array([1, 3, 1]),
|
| 153 |
+
),
|
| 154 |
+
],
|
| 155 |
+
)
|
| 156 |
+
@pytest.mark.parametrize("sparse_constructor", CSC_CONTAINERS + CSR_CONTAINERS)
|
| 157 |
+
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
|
| 158 |
+
def test_incr_mean_variance_axis_weighted_axis1(
|
| 159 |
+
Xw, X, weights, sparse_constructor, dtype
|
| 160 |
+
):
|
| 161 |
+
axis = 1
|
| 162 |
+
Xw_sparse = sparse_constructor(Xw).astype(dtype)
|
| 163 |
+
X_sparse = sparse_constructor(X).astype(dtype)
|
| 164 |
+
|
| 165 |
+
last_mean = np.zeros(np.shape(Xw)[0], dtype=dtype)
|
| 166 |
+
last_var = np.zeros_like(last_mean, dtype=dtype)
|
| 167 |
+
last_n = np.zeros_like(last_mean, dtype=np.int64)
|
| 168 |
+
means0, vars0, n_incr0 = incr_mean_variance_axis(
|
| 169 |
+
X=X_sparse,
|
| 170 |
+
axis=axis,
|
| 171 |
+
last_mean=last_mean,
|
| 172 |
+
last_var=last_var,
|
| 173 |
+
last_n=last_n,
|
| 174 |
+
weights=None,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
means_w0, vars_w0, n_incr_w0 = incr_mean_variance_axis(
|
| 178 |
+
X=Xw_sparse,
|
| 179 |
+
axis=axis,
|
| 180 |
+
last_mean=last_mean,
|
| 181 |
+
last_var=last_var,
|
| 182 |
+
last_n=last_n,
|
| 183 |
+
weights=weights,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
assert means_w0.dtype == dtype
|
| 187 |
+
assert vars_w0.dtype == dtype
|
| 188 |
+
assert n_incr_w0.dtype == dtype
|
| 189 |
+
|
| 190 |
+
means_simple, vars_simple = mean_variance_axis(X=X_sparse, axis=axis)
|
| 191 |
+
|
| 192 |
+
assert_array_almost_equal(means0, means_w0)
|
| 193 |
+
assert_array_almost_equal(means0, means_simple)
|
| 194 |
+
assert_array_almost_equal(vars0, vars_w0)
|
| 195 |
+
assert_array_almost_equal(vars0, vars_simple)
|
| 196 |
+
assert_array_almost_equal(n_incr0, n_incr_w0)
|
| 197 |
+
|
| 198 |
+
# check second round for incremental
|
| 199 |
+
means1, vars1, n_incr1 = incr_mean_variance_axis(
|
| 200 |
+
X=X_sparse,
|
| 201 |
+
axis=axis,
|
| 202 |
+
last_mean=means0,
|
| 203 |
+
last_var=vars0,
|
| 204 |
+
last_n=n_incr0,
|
| 205 |
+
weights=None,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
means_w1, vars_w1, n_incr_w1 = incr_mean_variance_axis(
|
| 209 |
+
X=Xw_sparse,
|
| 210 |
+
axis=axis,
|
| 211 |
+
last_mean=means_w0,
|
| 212 |
+
last_var=vars_w0,
|
| 213 |
+
last_n=n_incr_w0,
|
| 214 |
+
weights=weights,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
assert_array_almost_equal(means1, means_w1)
|
| 218 |
+
assert_array_almost_equal(vars1, vars_w1)
|
| 219 |
+
assert_array_almost_equal(n_incr1, n_incr_w1)
|
| 220 |
+
|
| 221 |
+
assert means_w1.dtype == dtype
|
| 222 |
+
assert vars_w1.dtype == dtype
|
| 223 |
+
assert n_incr_w1.dtype == dtype
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@pytest.mark.parametrize(
|
| 227 |
+
["Xw", "X", "weights"],
|
| 228 |
+
[
|
| 229 |
+
([[0, 0, 1], [0, 2, 3]], [[0, 0, 1], [0, 2, 3]], [1, 1]),
|
| 230 |
+
([[0, 0, 1], [0, 1, 1]], [[0, 0, 1], [0, 1, 1], [0, 1, 1]], [1, 2]),
|
| 231 |
+
([[0, 0, 1], [0, 1, 1]], [[0, 0, 1], [0, 1, 1]], None),
|
| 232 |
+
(
|
| 233 |
+
[[0, np.nan, 2], [0, np.nan, np.nan]],
|
| 234 |
+
[[0, np.nan, 2], [0, np.nan, np.nan]],
|
| 235 |
+
[1.0, 1.0],
|
| 236 |
+
),
|
| 237 |
+
(
|
| 238 |
+
[[0, 0, 1, np.nan, 2, 0], [0, 3, np.nan, np.nan, np.nan, 2]],
|
| 239 |
+
[
|
| 240 |
+
[0, 0, 1, np.nan, 2, 0],
|
| 241 |
+
[0, 0, 1, np.nan, 2, 0],
|
| 242 |
+
[0, 3, np.nan, np.nan, np.nan, 2],
|
| 243 |
+
],
|
| 244 |
+
[2.0, 1.0],
|
| 245 |
+
),
|
| 246 |
+
(
|
| 247 |
+
[[1, 0, 1], [0, 0, 1]],
|
| 248 |
+
[[1, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]],
|
| 249 |
+
np.array([1, 3]),
|
| 250 |
+
),
|
| 251 |
+
],
|
| 252 |
+
)
|
| 253 |
+
@pytest.mark.parametrize("sparse_constructor", CSC_CONTAINERS + CSR_CONTAINERS)
|
| 254 |
+
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
|
| 255 |
+
def test_incr_mean_variance_axis_weighted_axis0(
|
| 256 |
+
Xw, X, weights, sparse_constructor, dtype
|
| 257 |
+
):
|
| 258 |
+
axis = 0
|
| 259 |
+
Xw_sparse = sparse_constructor(Xw).astype(dtype)
|
| 260 |
+
X_sparse = sparse_constructor(X).astype(dtype)
|
| 261 |
+
|
| 262 |
+
last_mean = np.zeros(np.size(Xw, 1), dtype=dtype)
|
| 263 |
+
last_var = np.zeros_like(last_mean)
|
| 264 |
+
last_n = np.zeros_like(last_mean, dtype=np.int64)
|
| 265 |
+
means0, vars0, n_incr0 = incr_mean_variance_axis(
|
| 266 |
+
X=X_sparse,
|
| 267 |
+
axis=axis,
|
| 268 |
+
last_mean=last_mean,
|
| 269 |
+
last_var=last_var,
|
| 270 |
+
last_n=last_n,
|
| 271 |
+
weights=None,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
means_w0, vars_w0, n_incr_w0 = incr_mean_variance_axis(
|
| 275 |
+
X=Xw_sparse,
|
| 276 |
+
axis=axis,
|
| 277 |
+
last_mean=last_mean,
|
| 278 |
+
last_var=last_var,
|
| 279 |
+
last_n=last_n,
|
| 280 |
+
weights=weights,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
assert means_w0.dtype == dtype
|
| 284 |
+
assert vars_w0.dtype == dtype
|
| 285 |
+
assert n_incr_w0.dtype == dtype
|
| 286 |
+
|
| 287 |
+
means_simple, vars_simple = mean_variance_axis(X=X_sparse, axis=axis)
|
| 288 |
+
|
| 289 |
+
assert_array_almost_equal(means0, means_w0)
|
| 290 |
+
assert_array_almost_equal(means0, means_simple)
|
| 291 |
+
assert_array_almost_equal(vars0, vars_w0)
|
| 292 |
+
assert_array_almost_equal(vars0, vars_simple)
|
| 293 |
+
assert_array_almost_equal(n_incr0, n_incr_w0)
|
| 294 |
+
|
| 295 |
+
# check second round for incremental
|
| 296 |
+
means1, vars1, n_incr1 = incr_mean_variance_axis(
|
| 297 |
+
X=X_sparse,
|
| 298 |
+
axis=axis,
|
| 299 |
+
last_mean=means0,
|
| 300 |
+
last_var=vars0,
|
| 301 |
+
last_n=n_incr0,
|
| 302 |
+
weights=None,
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
means_w1, vars_w1, n_incr_w1 = incr_mean_variance_axis(
|
| 306 |
+
X=Xw_sparse,
|
| 307 |
+
axis=axis,
|
| 308 |
+
last_mean=means_w0,
|
| 309 |
+
last_var=vars_w0,
|
| 310 |
+
last_n=n_incr_w0,
|
| 311 |
+
weights=weights,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
assert_array_almost_equal(means1, means_w1)
|
| 315 |
+
assert_array_almost_equal(vars1, vars_w1)
|
| 316 |
+
assert_array_almost_equal(n_incr1, n_incr_w1)
|
| 317 |
+
|
| 318 |
+
assert means_w1.dtype == dtype
|
| 319 |
+
assert vars_w1.dtype == dtype
|
| 320 |
+
assert n_incr_w1.dtype == dtype
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 324 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 325 |
+
@pytest.mark.parametrize("lil_container", LIL_CONTAINERS)
|
| 326 |
+
def test_incr_mean_variance_axis(csc_container, csr_container, lil_container):
|
| 327 |
+
for axis in [0, 1]:
|
| 328 |
+
rng = np.random.RandomState(0)
|
| 329 |
+
n_features = 50
|
| 330 |
+
n_samples = 10
|
| 331 |
+
if axis == 0:
|
| 332 |
+
data_chunks = [rng.randint(0, 2, size=n_features) for i in range(n_samples)]
|
| 333 |
+
else:
|
| 334 |
+
data_chunks = [rng.randint(0, 2, size=n_samples) for i in range(n_features)]
|
| 335 |
+
|
| 336 |
+
# default params for incr_mean_variance
|
| 337 |
+
last_mean = np.zeros(n_features) if axis == 0 else np.zeros(n_samples)
|
| 338 |
+
last_var = np.zeros_like(last_mean)
|
| 339 |
+
last_n = np.zeros_like(last_mean, dtype=np.int64)
|
| 340 |
+
|
| 341 |
+
# Test errors
|
| 342 |
+
X = np.array(data_chunks[0])
|
| 343 |
+
X = np.atleast_2d(X)
|
| 344 |
+
X = X.T if axis == 1 else X
|
| 345 |
+
X_lil = lil_container(X)
|
| 346 |
+
X_csr = csr_container(X_lil)
|
| 347 |
+
|
| 348 |
+
with pytest.raises(TypeError):
|
| 349 |
+
incr_mean_variance_axis(
|
| 350 |
+
X=axis, axis=last_mean, last_mean=last_var, last_var=last_n
|
| 351 |
+
)
|
| 352 |
+
with pytest.raises(TypeError):
|
| 353 |
+
incr_mean_variance_axis(
|
| 354 |
+
X_lil, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
# Test _incr_mean_and_var with a 1 row input
|
| 358 |
+
X_means, X_vars = mean_variance_axis(X_csr, axis)
|
| 359 |
+
X_means_incr, X_vars_incr, n_incr = incr_mean_variance_axis(
|
| 360 |
+
X_csr, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n
|
| 361 |
+
)
|
| 362 |
+
assert_array_almost_equal(X_means, X_means_incr)
|
| 363 |
+
assert_array_almost_equal(X_vars, X_vars_incr)
|
| 364 |
+
# X.shape[axis] picks # samples
|
| 365 |
+
assert_array_equal(X.shape[axis], n_incr)
|
| 366 |
+
|
| 367 |
+
X_csc = csc_container(X_lil)
|
| 368 |
+
X_means, X_vars = mean_variance_axis(X_csc, axis)
|
| 369 |
+
assert_array_almost_equal(X_means, X_means_incr)
|
| 370 |
+
assert_array_almost_equal(X_vars, X_vars_incr)
|
| 371 |
+
assert_array_equal(X.shape[axis], n_incr)
|
| 372 |
+
|
| 373 |
+
# Test _incremental_mean_and_var with whole data
|
| 374 |
+
X = np.vstack(data_chunks)
|
| 375 |
+
X = X.T if axis == 1 else X
|
| 376 |
+
X_lil = lil_container(X)
|
| 377 |
+
X_csr = csr_container(X_lil)
|
| 378 |
+
X_csc = csc_container(X_lil)
|
| 379 |
+
|
| 380 |
+
expected_dtypes = [
|
| 381 |
+
(np.float32, np.float32),
|
| 382 |
+
(np.float64, np.float64),
|
| 383 |
+
(np.int32, np.float64),
|
| 384 |
+
(np.int64, np.float64),
|
| 385 |
+
]
|
| 386 |
+
|
| 387 |
+
for input_dtype, output_dtype in expected_dtypes:
|
| 388 |
+
for X_sparse in (X_csr, X_csc):
|
| 389 |
+
X_sparse = X_sparse.astype(input_dtype)
|
| 390 |
+
last_mean = last_mean.astype(output_dtype)
|
| 391 |
+
last_var = last_var.astype(output_dtype)
|
| 392 |
+
X_means, X_vars = mean_variance_axis(X_sparse, axis)
|
| 393 |
+
X_means_incr, X_vars_incr, n_incr = incr_mean_variance_axis(
|
| 394 |
+
X_sparse,
|
| 395 |
+
axis=axis,
|
| 396 |
+
last_mean=last_mean,
|
| 397 |
+
last_var=last_var,
|
| 398 |
+
last_n=last_n,
|
| 399 |
+
)
|
| 400 |
+
assert X_means_incr.dtype == output_dtype
|
| 401 |
+
assert X_vars_incr.dtype == output_dtype
|
| 402 |
+
assert_array_almost_equal(X_means, X_means_incr)
|
| 403 |
+
assert_array_almost_equal(X_vars, X_vars_incr)
|
| 404 |
+
assert_array_equal(X.shape[axis], n_incr)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
@pytest.mark.parametrize("sparse_constructor", CSC_CONTAINERS + CSR_CONTAINERS)
|
| 408 |
+
def test_incr_mean_variance_axis_dim_mismatch(sparse_constructor):
|
| 409 |
+
"""Check that we raise proper error when axis=1 and the dimension mismatch.
|
| 410 |
+
Non-regression test for:
|
| 411 |
+
https://github.com/scikit-learn/scikit-learn/pull/18655
|
| 412 |
+
"""
|
| 413 |
+
n_samples, n_features = 60, 4
|
| 414 |
+
rng = np.random.RandomState(42)
|
| 415 |
+
X = sparse_constructor(rng.rand(n_samples, n_features))
|
| 416 |
+
|
| 417 |
+
last_mean = np.zeros(n_features)
|
| 418 |
+
last_var = np.zeros_like(last_mean)
|
| 419 |
+
last_n = np.zeros(last_mean.shape, dtype=np.int64)
|
| 420 |
+
|
| 421 |
+
kwargs = dict(last_mean=last_mean, last_var=last_var, last_n=last_n)
|
| 422 |
+
mean0, var0, _ = incr_mean_variance_axis(X, axis=0, **kwargs)
|
| 423 |
+
assert_allclose(np.mean(X.toarray(), axis=0), mean0)
|
| 424 |
+
assert_allclose(np.var(X.toarray(), axis=0), var0)
|
| 425 |
+
|
| 426 |
+
# test ValueError if axis=1 and last_mean.size == n_features
|
| 427 |
+
with pytest.raises(ValueError):
|
| 428 |
+
incr_mean_variance_axis(X, axis=1, **kwargs)
|
| 429 |
+
|
| 430 |
+
# test inconsistent shapes of last_mean, last_var, last_n
|
| 431 |
+
kwargs = dict(last_mean=last_mean[:-1], last_var=last_var, last_n=last_n)
|
| 432 |
+
with pytest.raises(ValueError):
|
| 433 |
+
incr_mean_variance_axis(X, axis=0, **kwargs)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
@pytest.mark.parametrize(
|
| 437 |
+
"X1, X2",
|
| 438 |
+
[
|
| 439 |
+
(
|
| 440 |
+
sp.random(5, 2, density=0.8, format="csr", random_state=0),
|
| 441 |
+
sp.random(13, 2, density=0.8, format="csr", random_state=0),
|
| 442 |
+
),
|
| 443 |
+
(
|
| 444 |
+
sp.random(5, 2, density=0.8, format="csr", random_state=0),
|
| 445 |
+
sp.hstack(
|
| 446 |
+
[
|
| 447 |
+
np.full((13, 1), fill_value=np.nan),
|
| 448 |
+
sp.random(13, 1, density=0.8, random_state=42),
|
| 449 |
+
],
|
| 450 |
+
format="csr",
|
| 451 |
+
),
|
| 452 |
+
),
|
| 453 |
+
],
|
| 454 |
+
)
|
| 455 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 456 |
+
def test_incr_mean_variance_axis_equivalence_mean_variance(X1, X2, csr_container):
|
| 457 |
+
# non-regression test for:
|
| 458 |
+
# https://github.com/scikit-learn/scikit-learn/issues/16448
|
| 459 |
+
# check that computing the incremental mean and variance is equivalent to
|
| 460 |
+
# computing the mean and variance on the stacked dataset.
|
| 461 |
+
X1 = csr_container(X1)
|
| 462 |
+
X2 = csr_container(X2)
|
| 463 |
+
axis = 0
|
| 464 |
+
last_mean, last_var = np.zeros(X1.shape[1]), np.zeros(X1.shape[1])
|
| 465 |
+
last_n = np.zeros(X1.shape[1], dtype=np.int64)
|
| 466 |
+
updated_mean, updated_var, updated_n = incr_mean_variance_axis(
|
| 467 |
+
X1, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n
|
| 468 |
+
)
|
| 469 |
+
updated_mean, updated_var, updated_n = incr_mean_variance_axis(
|
| 470 |
+
X2, axis=axis, last_mean=updated_mean, last_var=updated_var, last_n=updated_n
|
| 471 |
+
)
|
| 472 |
+
X = sp.vstack([X1, X2])
|
| 473 |
+
assert_allclose(updated_mean, np.nanmean(X.toarray(), axis=axis))
|
| 474 |
+
assert_allclose(updated_var, np.nanvar(X.toarray(), axis=axis))
|
| 475 |
+
assert_allclose(updated_n, np.count_nonzero(~np.isnan(X.toarray()), axis=0))
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def test_incr_mean_variance_no_new_n():
|
| 479 |
+
# check the behaviour when we update the variance with an empty matrix
|
| 480 |
+
axis = 0
|
| 481 |
+
X1 = sp.random(5, 1, density=0.8, random_state=0).tocsr()
|
| 482 |
+
X2 = sp.random(0, 1, density=0.8, random_state=0).tocsr()
|
| 483 |
+
last_mean, last_var = np.zeros(X1.shape[1]), np.zeros(X1.shape[1])
|
| 484 |
+
last_n = np.zeros(X1.shape[1], dtype=np.int64)
|
| 485 |
+
last_mean, last_var, last_n = incr_mean_variance_axis(
|
| 486 |
+
X1, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n
|
| 487 |
+
)
|
| 488 |
+
# update statistic with a column which should ignored
|
| 489 |
+
updated_mean, updated_var, updated_n = incr_mean_variance_axis(
|
| 490 |
+
X2, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n
|
| 491 |
+
)
|
| 492 |
+
assert_allclose(updated_mean, last_mean)
|
| 493 |
+
assert_allclose(updated_var, last_var)
|
| 494 |
+
assert_allclose(updated_n, last_n)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def test_incr_mean_variance_n_float():
|
| 498 |
+
# check the behaviour when last_n is just a number
|
| 499 |
+
axis = 0
|
| 500 |
+
X = sp.random(5, 2, density=0.8, random_state=0).tocsr()
|
| 501 |
+
last_mean, last_var = np.zeros(X.shape[1]), np.zeros(X.shape[1])
|
| 502 |
+
last_n = 0
|
| 503 |
+
_, _, new_n = incr_mean_variance_axis(
|
| 504 |
+
X, axis=axis, last_mean=last_mean, last_var=last_var, last_n=last_n
|
| 505 |
+
)
|
| 506 |
+
assert_allclose(new_n, np.full(X.shape[1], X.shape[0]))
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
@pytest.mark.parametrize("axis", [0, 1])
|
| 510 |
+
@pytest.mark.parametrize("sparse_constructor", CSC_CONTAINERS + CSR_CONTAINERS)
|
| 511 |
+
def test_incr_mean_variance_axis_ignore_nan(axis, sparse_constructor):
|
| 512 |
+
old_means = np.array([535.0, 535.0, 535.0, 535.0])
|
| 513 |
+
old_variances = np.array([4225.0, 4225.0, 4225.0, 4225.0])
|
| 514 |
+
old_sample_count = np.array([2, 2, 2, 2], dtype=np.int64)
|
| 515 |
+
|
| 516 |
+
X = sparse_constructor(
|
| 517 |
+
np.array([[170, 170, 170, 170], [430, 430, 430, 430], [300, 300, 300, 300]])
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
X_nan = sparse_constructor(
|
| 521 |
+
np.array(
|
| 522 |
+
[
|
| 523 |
+
[170, np.nan, 170, 170],
|
| 524 |
+
[np.nan, 170, 430, 430],
|
| 525 |
+
[430, 430, np.nan, 300],
|
| 526 |
+
[300, 300, 300, np.nan],
|
| 527 |
+
]
|
| 528 |
+
)
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
# we avoid creating specific data for axis 0 and 1: translating the data is
|
| 532 |
+
# enough.
|
| 533 |
+
if axis:
|
| 534 |
+
X = X.T
|
| 535 |
+
X_nan = X_nan.T
|
| 536 |
+
|
| 537 |
+
# take a copy of the old statistics since they are modified in place.
|
| 538 |
+
X_means, X_vars, X_sample_count = incr_mean_variance_axis(
|
| 539 |
+
X,
|
| 540 |
+
axis=axis,
|
| 541 |
+
last_mean=old_means.copy(),
|
| 542 |
+
last_var=old_variances.copy(),
|
| 543 |
+
last_n=old_sample_count.copy(),
|
| 544 |
+
)
|
| 545 |
+
X_nan_means, X_nan_vars, X_nan_sample_count = incr_mean_variance_axis(
|
| 546 |
+
X_nan,
|
| 547 |
+
axis=axis,
|
| 548 |
+
last_mean=old_means.copy(),
|
| 549 |
+
last_var=old_variances.copy(),
|
| 550 |
+
last_n=old_sample_count.copy(),
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
assert_allclose(X_nan_means, X_means)
|
| 554 |
+
assert_allclose(X_nan_vars, X_vars)
|
| 555 |
+
assert_allclose(X_nan_sample_count, X_sample_count)
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 559 |
+
def test_mean_variance_illegal_axis(csr_container):
|
| 560 |
+
X, _ = make_classification(5, 4, random_state=0)
|
| 561 |
+
# Sparsify the array a little bit
|
| 562 |
+
X[0, 0] = 0
|
| 563 |
+
X[2, 1] = 0
|
| 564 |
+
X[4, 3] = 0
|
| 565 |
+
X_csr = csr_container(X)
|
| 566 |
+
with pytest.raises(ValueError):
|
| 567 |
+
mean_variance_axis(X_csr, axis=-3)
|
| 568 |
+
with pytest.raises(ValueError):
|
| 569 |
+
mean_variance_axis(X_csr, axis=2)
|
| 570 |
+
with pytest.raises(ValueError):
|
| 571 |
+
mean_variance_axis(X_csr, axis=-1)
|
| 572 |
+
|
| 573 |
+
with pytest.raises(ValueError):
|
| 574 |
+
incr_mean_variance_axis(
|
| 575 |
+
X_csr, axis=-3, last_mean=None, last_var=None, last_n=None
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
with pytest.raises(ValueError):
|
| 579 |
+
incr_mean_variance_axis(
|
| 580 |
+
X_csr, axis=2, last_mean=None, last_var=None, last_n=None
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
with pytest.raises(ValueError):
|
| 584 |
+
incr_mean_variance_axis(
|
| 585 |
+
X_csr, axis=-1, last_mean=None, last_var=None, last_n=None
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 590 |
+
def test_densify_rows(csr_container):
|
| 591 |
+
for dtype in (np.float32, np.float64):
|
| 592 |
+
X = csr_container(
|
| 593 |
+
[[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=dtype
|
| 594 |
+
)
|
| 595 |
+
X_rows = np.array([0, 2, 3], dtype=np.intp)
|
| 596 |
+
out = np.ones((6, X.shape[1]), dtype=dtype)
|
| 597 |
+
out_rows = np.array([1, 3, 4], dtype=np.intp)
|
| 598 |
+
|
| 599 |
+
expect = np.ones_like(out)
|
| 600 |
+
expect[out_rows] = X[X_rows, :].toarray()
|
| 601 |
+
|
| 602 |
+
assign_rows_csr(X, X_rows, out_rows, out)
|
| 603 |
+
assert_array_equal(out, expect)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def test_inplace_column_scale():
|
| 607 |
+
rng = np.random.RandomState(0)
|
| 608 |
+
X = sp.random(100, 200, density=0.05)
|
| 609 |
+
Xr = X.tocsr()
|
| 610 |
+
Xc = X.tocsc()
|
| 611 |
+
XA = X.toarray()
|
| 612 |
+
scale = rng.rand(200)
|
| 613 |
+
XA *= scale
|
| 614 |
+
|
| 615 |
+
inplace_column_scale(Xc, scale)
|
| 616 |
+
inplace_column_scale(Xr, scale)
|
| 617 |
+
assert_array_almost_equal(Xr.toarray(), Xc.toarray())
|
| 618 |
+
assert_array_almost_equal(XA, Xc.toarray())
|
| 619 |
+
assert_array_almost_equal(XA, Xr.toarray())
|
| 620 |
+
with pytest.raises(TypeError):
|
| 621 |
+
inplace_column_scale(X.tolil(), scale)
|
| 622 |
+
|
| 623 |
+
X = X.astype(np.float32)
|
| 624 |
+
scale = scale.astype(np.float32)
|
| 625 |
+
Xr = X.tocsr()
|
| 626 |
+
Xc = X.tocsc()
|
| 627 |
+
XA = X.toarray()
|
| 628 |
+
XA *= scale
|
| 629 |
+
inplace_column_scale(Xc, scale)
|
| 630 |
+
inplace_column_scale(Xr, scale)
|
| 631 |
+
assert_array_almost_equal(Xr.toarray(), Xc.toarray())
|
| 632 |
+
assert_array_almost_equal(XA, Xc.toarray())
|
| 633 |
+
assert_array_almost_equal(XA, Xr.toarray())
|
| 634 |
+
with pytest.raises(TypeError):
|
| 635 |
+
inplace_column_scale(X.tolil(), scale)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def test_inplace_row_scale():
|
| 639 |
+
rng = np.random.RandomState(0)
|
| 640 |
+
X = sp.random(100, 200, density=0.05)
|
| 641 |
+
Xr = X.tocsr()
|
| 642 |
+
Xc = X.tocsc()
|
| 643 |
+
XA = X.toarray()
|
| 644 |
+
scale = rng.rand(100)
|
| 645 |
+
XA *= scale.reshape(-1, 1)
|
| 646 |
+
|
| 647 |
+
inplace_row_scale(Xc, scale)
|
| 648 |
+
inplace_row_scale(Xr, scale)
|
| 649 |
+
assert_array_almost_equal(Xr.toarray(), Xc.toarray())
|
| 650 |
+
assert_array_almost_equal(XA, Xc.toarray())
|
| 651 |
+
assert_array_almost_equal(XA, Xr.toarray())
|
| 652 |
+
with pytest.raises(TypeError):
|
| 653 |
+
inplace_column_scale(X.tolil(), scale)
|
| 654 |
+
|
| 655 |
+
X = X.astype(np.float32)
|
| 656 |
+
scale = scale.astype(np.float32)
|
| 657 |
+
Xr = X.tocsr()
|
| 658 |
+
Xc = X.tocsc()
|
| 659 |
+
XA = X.toarray()
|
| 660 |
+
XA *= scale.reshape(-1, 1)
|
| 661 |
+
inplace_row_scale(Xc, scale)
|
| 662 |
+
inplace_row_scale(Xr, scale)
|
| 663 |
+
assert_array_almost_equal(Xr.toarray(), Xc.toarray())
|
| 664 |
+
assert_array_almost_equal(XA, Xc.toarray())
|
| 665 |
+
assert_array_almost_equal(XA, Xr.toarray())
|
| 666 |
+
with pytest.raises(TypeError):
|
| 667 |
+
inplace_column_scale(X.tolil(), scale)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 671 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 672 |
+
def test_inplace_swap_row(csc_container, csr_container):
|
| 673 |
+
X = np.array(
|
| 674 |
+
[[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64
|
| 675 |
+
)
|
| 676 |
+
X_csr = csr_container(X)
|
| 677 |
+
X_csc = csc_container(X)
|
| 678 |
+
|
| 679 |
+
swap = linalg.get_blas_funcs(("swap",), (X,))
|
| 680 |
+
swap = swap[0]
|
| 681 |
+
X[0], X[-1] = swap(X[0], X[-1])
|
| 682 |
+
inplace_swap_row(X_csr, 0, -1)
|
| 683 |
+
inplace_swap_row(X_csc, 0, -1)
|
| 684 |
+
assert_array_equal(X_csr.toarray(), X_csc.toarray())
|
| 685 |
+
assert_array_equal(X, X_csc.toarray())
|
| 686 |
+
assert_array_equal(X, X_csr.toarray())
|
| 687 |
+
|
| 688 |
+
X[2], X[3] = swap(X[2], X[3])
|
| 689 |
+
inplace_swap_row(X_csr, 2, 3)
|
| 690 |
+
inplace_swap_row(X_csc, 2, 3)
|
| 691 |
+
assert_array_equal(X_csr.toarray(), X_csc.toarray())
|
| 692 |
+
assert_array_equal(X, X_csc.toarray())
|
| 693 |
+
assert_array_equal(X, X_csr.toarray())
|
| 694 |
+
with pytest.raises(TypeError):
|
| 695 |
+
inplace_swap_row(X_csr.tolil())
|
| 696 |
+
|
| 697 |
+
X = np.array(
|
| 698 |
+
[[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float32
|
| 699 |
+
)
|
| 700 |
+
X_csr = csr_container(X)
|
| 701 |
+
X_csc = csc_container(X)
|
| 702 |
+
swap = linalg.get_blas_funcs(("swap",), (X,))
|
| 703 |
+
swap = swap[0]
|
| 704 |
+
X[0], X[-1] = swap(X[0], X[-1])
|
| 705 |
+
inplace_swap_row(X_csr, 0, -1)
|
| 706 |
+
inplace_swap_row(X_csc, 0, -1)
|
| 707 |
+
assert_array_equal(X_csr.toarray(), X_csc.toarray())
|
| 708 |
+
assert_array_equal(X, X_csc.toarray())
|
| 709 |
+
assert_array_equal(X, X_csr.toarray())
|
| 710 |
+
X[2], X[3] = swap(X[2], X[3])
|
| 711 |
+
inplace_swap_row(X_csr, 2, 3)
|
| 712 |
+
inplace_swap_row(X_csc, 2, 3)
|
| 713 |
+
assert_array_equal(X_csr.toarray(), X_csc.toarray())
|
| 714 |
+
assert_array_equal(X, X_csc.toarray())
|
| 715 |
+
assert_array_equal(X, X_csr.toarray())
|
| 716 |
+
with pytest.raises(TypeError):
|
| 717 |
+
inplace_swap_row(X_csr.tolil())
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 721 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 722 |
+
def test_inplace_swap_column(csc_container, csr_container):
|
| 723 |
+
X = np.array(
|
| 724 |
+
[[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64
|
| 725 |
+
)
|
| 726 |
+
X_csr = csr_container(X)
|
| 727 |
+
X_csc = csc_container(X)
|
| 728 |
+
|
| 729 |
+
swap = linalg.get_blas_funcs(("swap",), (X,))
|
| 730 |
+
swap = swap[0]
|
| 731 |
+
X[:, 0], X[:, -1] = swap(X[:, 0], X[:, -1])
|
| 732 |
+
inplace_swap_column(X_csr, 0, -1)
|
| 733 |
+
inplace_swap_column(X_csc, 0, -1)
|
| 734 |
+
assert_array_equal(X_csr.toarray(), X_csc.toarray())
|
| 735 |
+
assert_array_equal(X, X_csc.toarray())
|
| 736 |
+
assert_array_equal(X, X_csr.toarray())
|
| 737 |
+
|
| 738 |
+
X[:, 0], X[:, 1] = swap(X[:, 0], X[:, 1])
|
| 739 |
+
inplace_swap_column(X_csr, 0, 1)
|
| 740 |
+
inplace_swap_column(X_csc, 0, 1)
|
| 741 |
+
assert_array_equal(X_csr.toarray(), X_csc.toarray())
|
| 742 |
+
assert_array_equal(X, X_csc.toarray())
|
| 743 |
+
assert_array_equal(X, X_csr.toarray())
|
| 744 |
+
with pytest.raises(TypeError):
|
| 745 |
+
inplace_swap_column(X_csr.tolil())
|
| 746 |
+
|
| 747 |
+
X = np.array(
|
| 748 |
+
[[0, 3, 0], [2, 4, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float32
|
| 749 |
+
)
|
| 750 |
+
X_csr = csr_container(X)
|
| 751 |
+
X_csc = csc_container(X)
|
| 752 |
+
swap = linalg.get_blas_funcs(("swap",), (X,))
|
| 753 |
+
swap = swap[0]
|
| 754 |
+
X[:, 0], X[:, -1] = swap(X[:, 0], X[:, -1])
|
| 755 |
+
inplace_swap_column(X_csr, 0, -1)
|
| 756 |
+
inplace_swap_column(X_csc, 0, -1)
|
| 757 |
+
assert_array_equal(X_csr.toarray(), X_csc.toarray())
|
| 758 |
+
assert_array_equal(X, X_csc.toarray())
|
| 759 |
+
assert_array_equal(X, X_csr.toarray())
|
| 760 |
+
X[:, 0], X[:, 1] = swap(X[:, 0], X[:, 1])
|
| 761 |
+
inplace_swap_column(X_csr, 0, 1)
|
| 762 |
+
inplace_swap_column(X_csc, 0, 1)
|
| 763 |
+
assert_array_equal(X_csr.toarray(), X_csc.toarray())
|
| 764 |
+
assert_array_equal(X, X_csc.toarray())
|
| 765 |
+
assert_array_equal(X, X_csr.toarray())
|
| 766 |
+
with pytest.raises(TypeError):
|
| 767 |
+
inplace_swap_column(X_csr.tolil())
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
|
| 771 |
+
@pytest.mark.parametrize("axis", [0, 1, None])
|
| 772 |
+
@pytest.mark.parametrize("sparse_format", CSC_CONTAINERS + CSR_CONTAINERS)
|
| 773 |
+
@pytest.mark.parametrize(
|
| 774 |
+
"missing_values, min_func, max_func, ignore_nan",
|
| 775 |
+
[(0, np.min, np.max, False), (np.nan, np.nanmin, np.nanmax, True)],
|
| 776 |
+
)
|
| 777 |
+
@pytest.mark.parametrize("large_indices", [True, False])
|
| 778 |
+
def test_min_max(
|
| 779 |
+
dtype,
|
| 780 |
+
axis,
|
| 781 |
+
sparse_format,
|
| 782 |
+
missing_values,
|
| 783 |
+
min_func,
|
| 784 |
+
max_func,
|
| 785 |
+
ignore_nan,
|
| 786 |
+
large_indices,
|
| 787 |
+
):
|
| 788 |
+
X = np.array(
|
| 789 |
+
[
|
| 790 |
+
[0, 3, 0],
|
| 791 |
+
[2, -1, missing_values],
|
| 792 |
+
[0, 0, 0],
|
| 793 |
+
[9, missing_values, 7],
|
| 794 |
+
[4, 0, 5],
|
| 795 |
+
],
|
| 796 |
+
dtype=dtype,
|
| 797 |
+
)
|
| 798 |
+
X_sparse = sparse_format(X)
|
| 799 |
+
|
| 800 |
+
if large_indices:
|
| 801 |
+
X_sparse.indices = X_sparse.indices.astype("int64")
|
| 802 |
+
X_sparse.indptr = X_sparse.indptr.astype("int64")
|
| 803 |
+
|
| 804 |
+
mins_sparse, maxs_sparse = min_max_axis(X_sparse, axis=axis, ignore_nan=ignore_nan)
|
| 805 |
+
assert_array_equal(mins_sparse, min_func(X, axis=axis))
|
| 806 |
+
assert_array_equal(maxs_sparse, max_func(X, axis=axis))
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 810 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 811 |
+
def test_min_max_axis_errors(csc_container, csr_container):
|
| 812 |
+
X = np.array(
|
| 813 |
+
[[0, 3, 0], [2, -1, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64
|
| 814 |
+
)
|
| 815 |
+
X_csr = csr_container(X)
|
| 816 |
+
X_csc = csc_container(X)
|
| 817 |
+
with pytest.raises(TypeError):
|
| 818 |
+
min_max_axis(X_csr.tolil(), axis=0)
|
| 819 |
+
with pytest.raises(ValueError):
|
| 820 |
+
min_max_axis(X_csr, axis=2)
|
| 821 |
+
with pytest.raises(ValueError):
|
| 822 |
+
min_max_axis(X_csc, axis=-3)
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 826 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 827 |
+
def test_count_nonzero(csc_container, csr_container):
|
| 828 |
+
X = np.array(
|
| 829 |
+
[[0, 3, 0], [2, -1, 0], [0, 0, 0], [9, 8, 7], [4, 0, 5]], dtype=np.float64
|
| 830 |
+
)
|
| 831 |
+
X_csr = csr_container(X)
|
| 832 |
+
X_csc = csc_container(X)
|
| 833 |
+
X_nonzero = X != 0
|
| 834 |
+
sample_weight = [0.5, 0.2, 0.3, 0.1, 0.1]
|
| 835 |
+
X_nonzero_weighted = X_nonzero * np.array(sample_weight)[:, None]
|
| 836 |
+
|
| 837 |
+
for axis in [0, 1, -1, -2, None]:
|
| 838 |
+
assert_array_almost_equal(
|
| 839 |
+
count_nonzero(X_csr, axis=axis), X_nonzero.sum(axis=axis)
|
| 840 |
+
)
|
| 841 |
+
assert_array_almost_equal(
|
| 842 |
+
count_nonzero(X_csr, axis=axis, sample_weight=sample_weight),
|
| 843 |
+
X_nonzero_weighted.sum(axis=axis),
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
with pytest.raises(TypeError):
|
| 847 |
+
count_nonzero(X_csc)
|
| 848 |
+
with pytest.raises(ValueError):
|
| 849 |
+
count_nonzero(X_csr, axis=2)
|
| 850 |
+
|
| 851 |
+
assert count_nonzero(X_csr, axis=0).dtype == count_nonzero(X_csr, axis=1).dtype
|
| 852 |
+
assert (
|
| 853 |
+
count_nonzero(X_csr, axis=0, sample_weight=sample_weight).dtype
|
| 854 |
+
== count_nonzero(X_csr, axis=1, sample_weight=sample_weight).dtype
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
# Check dtypes with large sparse matrices too
|
| 858 |
+
# XXX: test fails on 32bit (Windows/Linux)
|
| 859 |
+
try:
|
| 860 |
+
X_csr.indices = X_csr.indices.astype(np.int64)
|
| 861 |
+
X_csr.indptr = X_csr.indptr.astype(np.int64)
|
| 862 |
+
assert count_nonzero(X_csr, axis=0).dtype == count_nonzero(X_csr, axis=1).dtype
|
| 863 |
+
assert (
|
| 864 |
+
count_nonzero(X_csr, axis=0, sample_weight=sample_weight).dtype
|
| 865 |
+
== count_nonzero(X_csr, axis=1, sample_weight=sample_weight).dtype
|
| 866 |
+
)
|
| 867 |
+
except TypeError as e:
|
| 868 |
+
assert "according to the rule 'safe'" in e.args[0] and np.intp().nbytes < 8, e
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
|
| 872 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 873 |
+
def test_csc_row_median(csc_container, csr_container):
|
| 874 |
+
# Test csc_row_median actually calculates the median.
|
| 875 |
+
|
| 876 |
+
# Test that it gives the same output when X is dense.
|
| 877 |
+
rng = np.random.RandomState(0)
|
| 878 |
+
X = rng.rand(100, 50)
|
| 879 |
+
dense_median = np.median(X, axis=0)
|
| 880 |
+
csc = csc_container(X)
|
| 881 |
+
sparse_median = csc_median_axis_0(csc)
|
| 882 |
+
assert_array_equal(sparse_median, dense_median)
|
| 883 |
+
|
| 884 |
+
# Test that it gives the same output when X is sparse
|
| 885 |
+
X = rng.rand(51, 100)
|
| 886 |
+
X[X < 0.7] = 0.0
|
| 887 |
+
ind = rng.randint(0, 50, 10)
|
| 888 |
+
X[ind] = -X[ind]
|
| 889 |
+
csc = csc_container(X)
|
| 890 |
+
dense_median = np.median(X, axis=0)
|
| 891 |
+
sparse_median = csc_median_axis_0(csc)
|
| 892 |
+
assert_array_equal(sparse_median, dense_median)
|
| 893 |
+
|
| 894 |
+
# Test for toy data.
|
| 895 |
+
X = [[0, -2], [-1, -1], [1, 0], [2, 1]]
|
| 896 |
+
csc = csc_container(X)
|
| 897 |
+
assert_array_equal(csc_median_axis_0(csc), np.array([0.5, -0.5]))
|
| 898 |
+
X = [[0, -2], [-1, -5], [1, -3]]
|
| 899 |
+
csc = csc_container(X)
|
| 900 |
+
assert_array_equal(csc_median_axis_0(csc), np.array([0.0, -3]))
|
| 901 |
+
|
| 902 |
+
# Test that it raises an Error for non-csc matrices.
|
| 903 |
+
with pytest.raises(TypeError):
|
| 904 |
+
csc_median_axis_0(csr_container(X))
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
@pytest.mark.parametrize(
|
| 908 |
+
"inplace_csr_row_normalize",
|
| 909 |
+
(inplace_csr_row_normalize_l1, inplace_csr_row_normalize_l2),
|
| 910 |
+
)
|
| 911 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 912 |
+
def test_inplace_normalize(csr_container, inplace_csr_row_normalize):
|
| 913 |
+
if csr_container is sp.csr_matrix:
|
| 914 |
+
ones = np.ones((10, 1))
|
| 915 |
+
else:
|
| 916 |
+
ones = np.ones(10)
|
| 917 |
+
rs = RandomState(10)
|
| 918 |
+
|
| 919 |
+
for dtype in (np.float64, np.float32):
|
| 920 |
+
X = rs.randn(10, 5).astype(dtype)
|
| 921 |
+
X_csr = csr_container(X)
|
| 922 |
+
for index_dtype in [np.int32, np.int64]:
|
| 923 |
+
# csr_matrix will use int32 indices by default,
|
| 924 |
+
# up-casting those to int64 when necessary
|
| 925 |
+
if index_dtype is np.int64:
|
| 926 |
+
X_csr.indptr = X_csr.indptr.astype(index_dtype)
|
| 927 |
+
X_csr.indices = X_csr.indices.astype(index_dtype)
|
| 928 |
+
assert X_csr.indices.dtype == index_dtype
|
| 929 |
+
assert X_csr.indptr.dtype == index_dtype
|
| 930 |
+
inplace_csr_row_normalize(X_csr)
|
| 931 |
+
assert X_csr.dtype == dtype
|
| 932 |
+
if inplace_csr_row_normalize is inplace_csr_row_normalize_l2:
|
| 933 |
+
X_csr.data **= 2
|
| 934 |
+
assert_array_almost_equal(np.abs(X_csr).sum(axis=1), ones)
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
|
| 938 |
+
def test_csr_row_norms(dtype):
|
| 939 |
+
# checks that csr_row_norms returns the same output as
|
| 940 |
+
# scipy.sparse.linalg.norm, and that the dype is the same as X.dtype.
|
| 941 |
+
X = sp.random(100, 10, format="csr", dtype=dtype, random_state=42)
|
| 942 |
+
|
| 943 |
+
scipy_norms = sp.linalg.norm(X, axis=1) ** 2
|
| 944 |
+
norms = csr_row_norms(X)
|
| 945 |
+
|
| 946 |
+
assert norms.dtype == dtype
|
| 947 |
+
rtol = 1e-6 if dtype == np.float32 else 1e-7
|
| 948 |
+
assert_allclose(norms, scipy_norms, rtol=rtol)
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
@pytest.fixture(scope="module", params=CSR_CONTAINERS + CSC_CONTAINERS)
|
| 952 |
+
def centered_matrices(request):
|
| 953 |
+
"""Returns equivalent tuple[sp.linalg.LinearOperator, np.ndarray]."""
|
| 954 |
+
sparse_container = request.param
|
| 955 |
+
|
| 956 |
+
random_state = np.random.default_rng(42)
|
| 957 |
+
|
| 958 |
+
X_sparse = sparse_container(
|
| 959 |
+
sp.random(500, 100, density=0.1, format="csr", random_state=random_state)
|
| 960 |
+
)
|
| 961 |
+
X_dense = X_sparse.toarray()
|
| 962 |
+
mu = np.asarray(X_sparse.mean(axis=0)).ravel()
|
| 963 |
+
|
| 964 |
+
X_sparse_centered = _implicit_column_offset(X_sparse, mu)
|
| 965 |
+
X_dense_centered = X_dense - mu
|
| 966 |
+
|
| 967 |
+
return X_sparse_centered, X_dense_centered
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
def test_implicit_center_matmat(global_random_seed, centered_matrices):
|
| 971 |
+
X_sparse_centered, X_dense_centered = centered_matrices
|
| 972 |
+
rng = np.random.default_rng(global_random_seed)
|
| 973 |
+
Y = rng.standard_normal((X_dense_centered.shape[1], 50))
|
| 974 |
+
assert_allclose(X_dense_centered @ Y, X_sparse_centered.matmat(Y))
|
| 975 |
+
assert_allclose(X_dense_centered @ Y, X_sparse_centered @ Y)
|
| 976 |
+
|
| 977 |
+
|
| 978 |
+
def test_implicit_center_matvec(global_random_seed, centered_matrices):
|
| 979 |
+
X_sparse_centered, X_dense_centered = centered_matrices
|
| 980 |
+
rng = np.random.default_rng(global_random_seed)
|
| 981 |
+
y = rng.standard_normal(X_dense_centered.shape[1])
|
| 982 |
+
assert_allclose(X_dense_centered @ y, X_sparse_centered.matvec(y))
|
| 983 |
+
assert_allclose(X_dense_centered @ y, X_sparse_centered @ y)
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def test_implicit_center_rmatmat(global_random_seed, centered_matrices):
|
| 987 |
+
X_sparse_centered, X_dense_centered = centered_matrices
|
| 988 |
+
rng = np.random.default_rng(global_random_seed)
|
| 989 |
+
Y = rng.standard_normal((X_dense_centered.shape[0], 50))
|
| 990 |
+
assert_allclose(X_dense_centered.T @ Y, X_sparse_centered.rmatmat(Y))
|
| 991 |
+
assert_allclose(X_dense_centered.T @ Y, X_sparse_centered.T @ Y)
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
def test_implit_center_rmatvec(global_random_seed, centered_matrices):
|
| 995 |
+
X_sparse_centered, X_dense_centered = centered_matrices
|
| 996 |
+
rng = np.random.default_rng(global_random_seed)
|
| 997 |
+
y = rng.standard_normal(X_dense_centered.shape[0])
|
| 998 |
+
assert_allclose(X_dense_centered.T @ y, X_sparse_centered.rmatvec(y))
|
| 999 |
+
assert_allclose(X_dense_centered.T @ y, X_sparse_centered.T @ y)
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
@pytest.mark.parametrize(
|
| 1003 |
+
["A", "B", "out", "msg"],
|
| 1004 |
+
[
|
| 1005 |
+
(sp.eye(3, format="csr"), sp.eye(2, format="csr"), None, "Shapes must fulfil"),
|
| 1006 |
+
(sp.eye(2, format="csr"), sp.eye(2, format="csr"), np.eye(3), "Shape of out"),
|
| 1007 |
+
(sp.eye(2, format="coo"), sp.eye(2, format="csr"), None, "Input 'A' must"),
|
| 1008 |
+
(sp.eye(2, format="csr"), sp.eye(2, format="coo"), None, "Input 'B' must"),
|
| 1009 |
+
(
|
| 1010 |
+
sp.eye(2, format="csr", dtype=np.int32),
|
| 1011 |
+
sp.eye(2, format="csr"),
|
| 1012 |
+
None,
|
| 1013 |
+
"Dtype of A and B",
|
| 1014 |
+
),
|
| 1015 |
+
(
|
| 1016 |
+
sp.eye(2, format="csr", dtype=np.float32),
|
| 1017 |
+
sp.eye(2, format="csr", dtype=np.float64),
|
| 1018 |
+
None,
|
| 1019 |
+
"Dtype of A and B",
|
| 1020 |
+
),
|
| 1021 |
+
],
|
| 1022 |
+
)
|
| 1023 |
+
def test_sparse_matmul_to_dense_raises(A, B, out, msg):
|
| 1024 |
+
"""Test that sparse_matmul_to_dense raises when it should."""
|
| 1025 |
+
with pytest.raises(ValueError, match=msg):
|
| 1026 |
+
sparse_matmul_to_dense(A, B, out=out)
|
| 1027 |
+
|
| 1028 |
+
|
| 1029 |
+
@pytest.mark.parametrize("out_is_None", [False, True])
|
| 1030 |
+
@pytest.mark.parametrize("a_container", CSC_CONTAINERS + CSR_CONTAINERS)
|
| 1031 |
+
@pytest.mark.parametrize("b_container", CSC_CONTAINERS + CSR_CONTAINERS)
|
| 1032 |
+
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
|
| 1033 |
+
def test_sparse_matmul_to_dense(
|
| 1034 |
+
global_random_seed, out_is_None, a_container, b_container, dtype
|
| 1035 |
+
):
|
| 1036 |
+
"""Test that sparse_matmul_to_dense computes correctly."""
|
| 1037 |
+
rng = np.random.default_rng(global_random_seed)
|
| 1038 |
+
n1, n2, n3 = 10, 19, 13
|
| 1039 |
+
a_dense = rng.standard_normal((n1, n2)).astype(dtype)
|
| 1040 |
+
b_dense = rng.standard_normal((n2, n3)).astype(dtype)
|
| 1041 |
+
a_dense.flat[rng.choice([False, True], size=n1 * n2, p=[0.5, 0.5])] = 0
|
| 1042 |
+
b_dense.flat[rng.choice([False, True], size=n2 * n3, p=[0.5, 0.5])] = 0
|
| 1043 |
+
a = a_container(a_dense)
|
| 1044 |
+
b = b_container(b_dense)
|
| 1045 |
+
if out_is_None:
|
| 1046 |
+
out = None
|
| 1047 |
+
else:
|
| 1048 |
+
out = np.empty((n1, n3), dtype=dtype)
|
| 1049 |
+
|
| 1050 |
+
result = sparse_matmul_to_dense(a, b, out=out)
|
| 1051 |
+
# Use atol to account for the wide range of values in the computed matrix.
|
| 1052 |
+
assert_allcl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 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
from numpy.testing import assert_allclose, assert_array_equal
|
| 4 |
+
from pytest import approx
|
| 5 |
+
|
| 6 |
+
from sklearn._config import config_context
|
| 7 |
+
from sklearn.utils._array_api import (
|
| 8 |
+
_convert_to_numpy,
|
| 9 |
+
get_namespace,
|
| 10 |
+
yield_namespace_device_dtype_combinations,
|
| 11 |
+
)
|
| 12 |
+
from sklearn.utils._array_api import device as array_device
|
| 13 |
+
from sklearn.utils.estimator_checks import _array_api_for_tests
|
| 14 |
+
from sklearn.utils.fixes import np_version, parse_version
|
| 15 |
+
from sklearn.utils.stats import _weighted_percentile
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.parametrize("average", [True, False])
|
| 19 |
+
@pytest.mark.parametrize("size", [10, 15])
|
| 20 |
+
def test_weighted_percentile_matches_median(size, average):
|
| 21 |
+
"""Ensure `_weighted_percentile` matches `median` when expected.
|
| 22 |
+
|
| 23 |
+
With unit `sample_weight`, `_weighted_percentile` should match the median except
|
| 24 |
+
when `average=False` and the number of samples is even.
|
| 25 |
+
For an even array and `average=False`, `percentile_rank=50` gives the lower
|
| 26 |
+
of the two 'middle' values, that are averaged when calculating the `median`.
|
| 27 |
+
"""
|
| 28 |
+
y = np.arange(size)
|
| 29 |
+
sample_weight = np.ones_like(y)
|
| 30 |
+
|
| 31 |
+
score = _weighted_percentile(y, sample_weight, 50, average=average)
|
| 32 |
+
|
| 33 |
+
# `_weighted_percentile(average=False)` does not match `median` when n is even
|
| 34 |
+
if size % 2 == 0 and average is False:
|
| 35 |
+
assert score != np.median(y)
|
| 36 |
+
else:
|
| 37 |
+
assert approx(score) == np.median(y)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.mark.parametrize("average", [True, False])
|
| 41 |
+
@pytest.mark.parametrize("percentile_rank", [20, 35, 61, [5, 47]])
|
| 42 |
+
@pytest.mark.parametrize("size", [10, 15])
|
| 43 |
+
def test_weighted_percentile_matches_numpy(
|
| 44 |
+
global_random_seed, size, percentile_rank, average
|
| 45 |
+
):
|
| 46 |
+
"""Check `_weighted_percentile` with unit weights is correct.
|
| 47 |
+
|
| 48 |
+
`average=True` results should be the same as `np.percentile`'s
|
| 49 |
+
'averaged_inverted_cdf'.
|
| 50 |
+
`average=False` results should be the same as `np.percentile`'s
|
| 51 |
+
'inverted_cdf'.
|
| 52 |
+
Note `np.percentile` is the same as `np.quantile` except `q` is in range [0, 100].
|
| 53 |
+
|
| 54 |
+
We parametrize through different `percentile_rank` and `size` to
|
| 55 |
+
ensure we get cases where `g=0` and `g>0` (see Hyndman and Fan 1996 for details).
|
| 56 |
+
"""
|
| 57 |
+
rng = np.random.RandomState(global_random_seed)
|
| 58 |
+
y = rng.randint(20, size=size)
|
| 59 |
+
sw = np.ones_like(y)
|
| 60 |
+
|
| 61 |
+
score = _weighted_percentile(y, sw, percentile_rank, average=average)
|
| 62 |
+
|
| 63 |
+
if average:
|
| 64 |
+
method = "averaged_inverted_cdf"
|
| 65 |
+
else:
|
| 66 |
+
method = "inverted_cdf"
|
| 67 |
+
|
| 68 |
+
assert approx(score) == np.percentile(y, percentile_rank, method=method)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@pytest.mark.parametrize("percentile_rank", [50, 100])
|
| 72 |
+
def test_weighted_percentile_plus_one_clip_max(percentile_rank):
|
| 73 |
+
"""Check `j+1` index is clipped to max, when `average=True`.
|
| 74 |
+
|
| 75 |
+
`percentile_plus_one_indices` can exceed max index when `percentile_indices`
|
| 76 |
+
is already at max index.
|
| 77 |
+
Note that when `g` (Hyndman and Fan) / `fraction_above` is greater than 0,
|
| 78 |
+
`j+1` (Hyndman and Fan) / `percentile_plus_one_indices` is calculated but
|
| 79 |
+
never used, so it does not matter what this value is.
|
| 80 |
+
When percentile of percentile rank 100 falls exactly on the last value in the
|
| 81 |
+
`weighted_cdf`, `g=0` and `percentile_indices` is at max index. In this case
|
| 82 |
+
we set `percentile_plus_one_indices` to be max index as well, so the result is
|
| 83 |
+
the average of 2x the max index (i.e. last value of `weighted_cdf`).
|
| 84 |
+
"""
|
| 85 |
+
# Note for both `percentile_rank`s 50 and 100,`percentile_indices` is already at
|
| 86 |
+
# max index
|
| 87 |
+
y = np.array([[0, 0], [1, 1]])
|
| 88 |
+
sw = np.array([[0.1, 0.2], [2, 3]])
|
| 89 |
+
score = _weighted_percentile(y, sw, percentile_rank, average=True)
|
| 90 |
+
for idx in range(2):
|
| 91 |
+
assert score[idx] == approx(1.0)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_weighted_percentile_equal():
|
| 95 |
+
"""Check `weighted_percentile` with unit weights and all 0 values in `array`."""
|
| 96 |
+
y = np.zeros(102, dtype=np.float64)
|
| 97 |
+
sw = np.ones(102, dtype=np.float64)
|
| 98 |
+
score = _weighted_percentile(y, sw, 50)
|
| 99 |
+
assert approx(score) == 0
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# XXX: is this really what we want? Shouldn't we raise instead?
|
| 103 |
+
# https://github.com/scikit-learn/scikit-learn/issues/31032
|
| 104 |
+
def test_weighted_percentile_all_zero_weights():
|
| 105 |
+
"""Check `weighted_percentile` with all weights equal to 0 returns last index."""
|
| 106 |
+
y = np.arange(10)
|
| 107 |
+
sw = np.zeros(10)
|
| 108 |
+
value = _weighted_percentile(y, sw, 50)
|
| 109 |
+
assert approx(value) == 9.0
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@pytest.mark.parametrize("average", [True, False])
|
| 113 |
+
@pytest.mark.parametrize("percentile_rank, expected_value", [(0, 2), (50, 3), (100, 5)])
|
| 114 |
+
def test_weighted_percentile_ignores_zero_weight(
|
| 115 |
+
average, percentile_rank, expected_value
|
| 116 |
+
):
|
| 117 |
+
"""Check leading, trailing and middle 0 weights behave correctly.
|
| 118 |
+
|
| 119 |
+
Check that leading zero-weight observations are ignored when `percentile_rank=0`.
|
| 120 |
+
See #20528 for details.
|
| 121 |
+
Check that when `average=True` and the `j+1` ('plus one') index has sample weight
|
| 122 |
+
of 0, it is ignored. Also check that trailing zero weight observations are ignored
|
| 123 |
+
(e.g., when `percentile_rank=100`).
|
| 124 |
+
"""
|
| 125 |
+
y = np.array([0, 1, 2, 3, 4, 5, 6])
|
| 126 |
+
sw = np.array([0, 0, 1, 1, 0, 1, 0])
|
| 127 |
+
|
| 128 |
+
value = _weighted_percentile(
|
| 129 |
+
np.vstack((y, y)).T, np.vstack((sw, sw)).T, percentile_rank, average=average
|
| 130 |
+
)
|
| 131 |
+
for idx in range(2):
|
| 132 |
+
assert approx(value[idx]) == expected_value
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@pytest.mark.parametrize("average", [True, False])
|
| 136 |
+
@pytest.mark.parametrize("percentile_rank", [20, 35, 50, 61])
|
| 137 |
+
def test_weighted_percentile_frequency_weight_semantics(
|
| 138 |
+
global_random_seed, percentile_rank, average
|
| 139 |
+
):
|
| 140 |
+
"""Check integer weights give the same result as repeating values."""
|
| 141 |
+
rng = np.random.RandomState(global_random_seed)
|
| 142 |
+
x = rng.randint(20, size=10)
|
| 143 |
+
weights = rng.choice(5, size=10)
|
| 144 |
+
|
| 145 |
+
x_repeated = np.repeat(x, weights)
|
| 146 |
+
percentile_weights = _weighted_percentile(
|
| 147 |
+
x, weights, percentile_rank, average=average
|
| 148 |
+
)
|
| 149 |
+
percentile_repeated = _weighted_percentile(
|
| 150 |
+
x_repeated, np.ones_like(x_repeated), percentile_rank, average=average
|
| 151 |
+
)
|
| 152 |
+
assert percentile_weights == approx(percentile_repeated)
|
| 153 |
+
# Also check `percentile_rank=50` matches `median`
|
| 154 |
+
if percentile_rank == 50 and average:
|
| 155 |
+
assert percentile_weights == approx(np.median(x_repeated))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@pytest.mark.parametrize("constant", [5, 8])
|
| 159 |
+
@pytest.mark.parametrize("average", [True, False])
|
| 160 |
+
@pytest.mark.parametrize("percentile_rank", [20, 35, 50, 61, [20, 35, 50, 61]])
|
| 161 |
+
def test_weighted_percentile_constant_multiplier(
|
| 162 |
+
global_random_seed, percentile_rank, average, constant
|
| 163 |
+
):
|
| 164 |
+
"""Check multiplying weights by a constant does not change the result.
|
| 165 |
+
|
| 166 |
+
Note scale invariance does not always hold when multiplying by a
|
| 167 |
+
float due to cumulative sum numerical error (which grows proportional to n).
|
| 168 |
+
"""
|
| 169 |
+
rng = np.random.RandomState(global_random_seed)
|
| 170 |
+
x = rng.randint(20, size=20)
|
| 171 |
+
weights = rng.choice(5, size=20)
|
| 172 |
+
weights_multiplied = weights * constant
|
| 173 |
+
|
| 174 |
+
percentile = _weighted_percentile(x, weights, percentile_rank, average=average)
|
| 175 |
+
percentile_multiplier = _weighted_percentile(
|
| 176 |
+
x, weights_multiplied, percentile_rank, average=average
|
| 177 |
+
)
|
| 178 |
+
assert percentile == approx(percentile_multiplier)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@pytest.mark.parametrize("percentile_rank", [50, [20, 35, 50]])
|
| 182 |
+
@pytest.mark.parametrize("average", [True, False])
|
| 183 |
+
def test_weighted_percentile_2d(global_random_seed, percentile_rank, average):
|
| 184 |
+
"""Check `_weighted_percentile` behaviour is correct when `array` is 2D."""
|
| 185 |
+
# Check for when array 2D and sample_weight 1D
|
| 186 |
+
rng = np.random.RandomState(global_random_seed)
|
| 187 |
+
x1 = rng.randint(10, size=10)
|
| 188 |
+
w1 = rng.choice(5, size=10)
|
| 189 |
+
|
| 190 |
+
x2 = rng.randint(20, size=10)
|
| 191 |
+
x_2d = np.vstack((x1, x2)).T
|
| 192 |
+
|
| 193 |
+
wp = _weighted_percentile(
|
| 194 |
+
x_2d, w1, percentile_rank=percentile_rank, average=average
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
if isinstance(percentile_rank, list):
|
| 198 |
+
p_list = []
|
| 199 |
+
for pr in percentile_rank:
|
| 200 |
+
p_list.append(
|
| 201 |
+
[
|
| 202 |
+
_weighted_percentile(
|
| 203 |
+
x_2d[:, i], w1, percentile_rank=pr, average=average
|
| 204 |
+
)
|
| 205 |
+
for i in range(x_2d.shape[1])
|
| 206 |
+
]
|
| 207 |
+
)
|
| 208 |
+
p_axis_0 = np.stack(p_list, axis=-1)
|
| 209 |
+
assert wp.shape == (x_2d.shape[1], len(percentile_rank))
|
| 210 |
+
else:
|
| 211 |
+
# percentile_rank is scalar
|
| 212 |
+
p_axis_0 = [
|
| 213 |
+
_weighted_percentile(
|
| 214 |
+
x_2d[:, i], w1, percentile_rank=percentile_rank, average=average
|
| 215 |
+
)
|
| 216 |
+
for i in range(x_2d.shape[1])
|
| 217 |
+
]
|
| 218 |
+
assert wp.shape == (x_2d.shape[1],)
|
| 219 |
+
|
| 220 |
+
assert_allclose(wp, p_axis_0)
|
| 221 |
+
|
| 222 |
+
# Check when array and sample_weight both 2D
|
| 223 |
+
w2 = rng.choice(5, size=10)
|
| 224 |
+
w_2d = np.vstack((w1, w2)).T
|
| 225 |
+
|
| 226 |
+
wp = _weighted_percentile(
|
| 227 |
+
x_2d, w_2d, percentile_rank=percentile_rank, average=average
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
if isinstance(percentile_rank, list):
|
| 231 |
+
p_list = []
|
| 232 |
+
for pr in percentile_rank:
|
| 233 |
+
p_list.append(
|
| 234 |
+
[
|
| 235 |
+
_weighted_percentile(
|
| 236 |
+
x_2d[:, i], w_2d[:, i], percentile_rank=pr, average=average
|
| 237 |
+
)
|
| 238 |
+
for i in range(x_2d.shape[1])
|
| 239 |
+
]
|
| 240 |
+
)
|
| 241 |
+
p_axis_0 = np.stack(p_list, axis=-1)
|
| 242 |
+
assert wp.shape == (x_2d.shape[1], len(percentile_rank))
|
| 243 |
+
else:
|
| 244 |
+
# percentile_rank is scalar
|
| 245 |
+
p_axis_0 = [
|
| 246 |
+
_weighted_percentile(
|
| 247 |
+
x_2d[:, i], w_2d[:, i], percentile_rank=percentile_rank, average=average
|
| 248 |
+
)
|
| 249 |
+
for i in range(x_2d.shape[1])
|
| 250 |
+
]
|
| 251 |
+
assert wp.shape == (x_2d.shape[1],)
|
| 252 |
+
|
| 253 |
+
assert_allclose(wp, p_axis_0)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
@pytest.mark.parametrize(
|
| 257 |
+
"array_namespace, device, dtype_name", yield_namespace_device_dtype_combinations()
|
| 258 |
+
)
|
| 259 |
+
@pytest.mark.parametrize(
|
| 260 |
+
"data, weights, percentile",
|
| 261 |
+
[
|
| 262 |
+
# NumPy scalars input (handled as 0D arrays on array API)
|
| 263 |
+
(np.float32(42), np.int32(1), 50),
|
| 264 |
+
# Random 1D array, constant weights
|
| 265 |
+
(lambda rng: rng.rand(50), np.ones(50).astype(np.int32), 50),
|
| 266 |
+
# Random 2D array and random 1D weights
|
| 267 |
+
(lambda rng: rng.rand(50, 3), lambda rng: rng.rand(50).astype(np.float32), 75),
|
| 268 |
+
# Random 2D array and random 2D weights
|
| 269 |
+
(
|
| 270 |
+
lambda rng: rng.rand(20, 3),
|
| 271 |
+
lambda rng: rng.rand(20, 3).astype(np.float32),
|
| 272 |
+
[25, 75],
|
| 273 |
+
),
|
| 274 |
+
# zero-weights and `rank_percentile=0` (#20528) (`sample_weight` dtype: int64)
|
| 275 |
+
(np.array([0, 1, 2, 3, 4, 5]), np.array([0, 0, 1, 1, 1, 0]), 0),
|
| 276 |
+
# np.nan's in data and some zero-weights (`sample_weight` dtype: int64)
|
| 277 |
+
(np.array([np.nan, np.nan, 0, 3, 4, 5]), np.array([0, 1, 1, 1, 1, 0]), 0),
|
| 278 |
+
# `sample_weight` dtype: int32
|
| 279 |
+
(
|
| 280 |
+
np.array([0, 1, 2, 3, 4, 5]),
|
| 281 |
+
np.array([0, 1, 1, 1, 1, 0], dtype=np.int32),
|
| 282 |
+
[25, 75],
|
| 283 |
+
),
|
| 284 |
+
],
|
| 285 |
+
)
|
| 286 |
+
def test_weighted_percentile_array_api_consistency(
|
| 287 |
+
global_random_seed, array_namespace, device, dtype_name, data, weights, percentile
|
| 288 |
+
):
|
| 289 |
+
"""Check `_weighted_percentile` gives consistent results with array API."""
|
| 290 |
+
xp = _array_api_for_tests(array_namespace, device)
|
| 291 |
+
|
| 292 |
+
# Skip test for percentile=0 edge case (#20528) on namespace/device where
|
| 293 |
+
# xp.nextafter is broken. This is the case for torch with MPS device:
|
| 294 |
+
# https://github.com/pytorch/pytorch/issues/150027
|
| 295 |
+
zero = xp.zeros(1, device=device)
|
| 296 |
+
one = xp.ones(1, device=device)
|
| 297 |
+
if percentile == 0 and xp.all(xp.nextafter(zero, one) == zero):
|
| 298 |
+
pytest.xfail(f"xp.nextafter is broken on {device}")
|
| 299 |
+
|
| 300 |
+
rng = np.random.RandomState(global_random_seed)
|
| 301 |
+
X_np = data(rng) if callable(data) else data
|
| 302 |
+
weights_np = weights(rng) if callable(weights) else weights
|
| 303 |
+
# Ensure `data` of correct dtype
|
| 304 |
+
X_np = X_np.astype(dtype_name)
|
| 305 |
+
|
| 306 |
+
result_np = _weighted_percentile(X_np, weights_np, percentile)
|
| 307 |
+
# Convert to Array API arrays
|
| 308 |
+
X_xp = xp.asarray(X_np, device=device)
|
| 309 |
+
weights_xp = xp.asarray(weights_np, device=device)
|
| 310 |
+
|
| 311 |
+
with config_context(array_api_dispatch=True):
|
| 312 |
+
result_xp = _weighted_percentile(X_xp, weights_xp, percentile)
|
| 313 |
+
assert array_device(result_xp) == array_device(X_xp)
|
| 314 |
+
assert get_namespace(result_xp)[0] == get_namespace(X_xp)[0]
|
| 315 |
+
result_xp_np = _convert_to_numpy(result_xp, xp=xp)
|
| 316 |
+
|
| 317 |
+
assert result_xp_np.dtype == result_np.dtype
|
| 318 |
+
assert result_xp_np.shape == result_np.shape
|
| 319 |
+
assert_allclose(result_np, result_xp_np)
|
| 320 |
+
|
| 321 |
+
# Check dtype correct (`sample_weight` should follow `array`)
|
| 322 |
+
if dtype_name == "float32":
|
| 323 |
+
assert result_xp_np.dtype == result_np.dtype == np.float32
|
| 324 |
+
else:
|
| 325 |
+
assert result_xp_np.dtype == np.float64
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@pytest.mark.parametrize("average", [True, False])
|
| 329 |
+
@pytest.mark.parametrize("sample_weight_ndim", [1, 2])
|
| 330 |
+
def test_weighted_percentile_nan_filtered(
|
| 331 |
+
global_random_seed, sample_weight_ndim, average
|
| 332 |
+
):
|
| 333 |
+
"""Test `_weighted_percentile` ignores NaNs.
|
| 334 |
+
|
| 335 |
+
Calling `_weighted_percentile` on an array with nan values returns the same
|
| 336 |
+
results as calling `_weighted_percentile` on a filtered version of the data.
|
| 337 |
+
We test both with sample_weight of the same shape as the data and with
|
| 338 |
+
one-dimensional sample_weight.
|
| 339 |
+
"""
|
| 340 |
+
|
| 341 |
+
rng = np.random.RandomState(global_random_seed)
|
| 342 |
+
array_with_nans = rng.rand(100, 10)
|
| 343 |
+
array_with_nans[rng.rand(*array_with_nans.shape) < 0.5] = np.nan
|
| 344 |
+
nan_mask = np.isnan(array_with_nans)
|
| 345 |
+
|
| 346 |
+
if sample_weight_ndim == 2:
|
| 347 |
+
sample_weight = rng.randint(1, 6, size=(100, 10))
|
| 348 |
+
else:
|
| 349 |
+
sample_weight = rng.randint(1, 6, size=(100,))
|
| 350 |
+
|
| 351 |
+
# Find the weighted percentile on the array with nans:
|
| 352 |
+
results = _weighted_percentile(array_with_nans, sample_weight, 30, average=average)
|
| 353 |
+
|
| 354 |
+
# Find the weighted percentile on the filtered array:
|
| 355 |
+
filtered_array = [
|
| 356 |
+
array_with_nans[~nan_mask[:, col], col]
|
| 357 |
+
for col in range(array_with_nans.shape[1])
|
| 358 |
+
]
|
| 359 |
+
if sample_weight.ndim == 1:
|
| 360 |
+
sample_weight = np.repeat(sample_weight, array_with_nans.shape[1]).reshape(
|
| 361 |
+
array_with_nans.shape[0], array_with_nans.shape[1]
|
| 362 |
+
)
|
| 363 |
+
filtered_weights = [
|
| 364 |
+
sample_weight[~nan_mask[:, col], col] for col in range(array_with_nans.shape[1])
|
| 365 |
+
]
|
| 366 |
+
|
| 367 |
+
expected_results = np.array(
|
| 368 |
+
[
|
| 369 |
+
_weighted_percentile(
|
| 370 |
+
filtered_array[col], filtered_weights[col], 30, average=average
|
| 371 |
+
)
|
| 372 |
+
for col in range(array_with_nans.shape[1])
|
| 373 |
+
]
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
assert_array_equal(expected_results, results)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
@pytest.mark.parametrize(
|
| 380 |
+
"percentile_rank, expected",
|
| 381 |
+
[
|
| 382 |
+
(90, [np.nan, 5]),
|
| 383 |
+
([50, 90], [[np.nan, np.nan], [2.0, 5.0]]),
|
| 384 |
+
],
|
| 385 |
+
)
|
| 386 |
+
def test_weighted_percentile_all_nan_column(percentile_rank, expected):
|
| 387 |
+
"""Check that nans are ignored in general, except for all NaN columns."""
|
| 388 |
+
|
| 389 |
+
array = np.array(
|
| 390 |
+
[
|
| 391 |
+
[np.nan, 5],
|
| 392 |
+
[np.nan, 1],
|
| 393 |
+
[np.nan, np.nan],
|
| 394 |
+
[np.nan, np.nan],
|
| 395 |
+
[np.nan, 2],
|
| 396 |
+
[np.nan, np.nan],
|
| 397 |
+
]
|
| 398 |
+
)
|
| 399 |
+
weights = np.ones_like(array)
|
| 400 |
+
values = _weighted_percentile(array, weights, percentile_rank)
|
| 401 |
+
|
| 402 |
+
# The percentile of the second column should be `5` even though there are many nan
|
| 403 |
+
# values present; the percentile of the first column can only be nan, since there
|
| 404 |
+
# are no other possible values:
|
| 405 |
+
assert np.array_equal(values, expected, equal_nan=True)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@pytest.mark.skipif(
|
| 409 |
+
np_version < parse_version("2.0"),
|
| 410 |
+
reason="np.quantile only accepts weights since version 2.0",
|
| 411 |
+
)
|
| 412 |
+
@pytest.mark.parametrize("percentile", [66, 10, 50])
|
| 413 |
+
@pytest.mark.parametrize("average", [False, True])
|
| 414 |
+
@pytest.mark.parametrize("uniform_weight", [False, True])
|
| 415 |
+
def test_weighted_percentile_like_numpy_quantile(
|
| 416 |
+
percentile, average, uniform_weight, global_random_seed
|
| 417 |
+
):
|
| 418 |
+
"""Check `_weighted_percentile` is equivalent to `np.quantile` with weights."""
|
| 419 |
+
# TODO: remove the following skip once no longer applicable.
|
| 420 |
+
if average and not uniform_weight:
|
| 421 |
+
pytest.skip(
|
| 422 |
+
"np.quantile does not support weights with method='averaged_inverted_cdf'"
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
rng = np.random.RandomState(global_random_seed)
|
| 426 |
+
array = rng.rand(10, 100)
|
| 427 |
+
if uniform_weight:
|
| 428 |
+
sample_weight = np.ones_like(array) * rng.randint(1, 6, size=1)
|
| 429 |
+
else:
|
| 430 |
+
sample_weight = rng.randint(1, 6, size=(10, 100))
|
| 431 |
+
|
| 432 |
+
percentile_weighted_percentile = _weighted_percentile(
|
| 433 |
+
array, sample_weight, percentile, average=average
|
| 434 |
+
)
|
| 435 |
+
percentile_numpy_quantile = np.quantile(
|
| 436 |
+
array,
|
| 437 |
+
percentile / 100,
|
| 438 |
+
weights=sample_weight if not uniform_weight else None,
|
| 439 |
+
method="averaged_inverted_cdf" if average else "inverted_cdf",
|
| 440 |
+
axis=0,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
assert_array_equal(percentile_weighted_percentile, percentile_numpy_quantile)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
@pytest.mark.skipif(
|
| 447 |
+
np_version < parse_version("2.0"),
|
| 448 |
+
reason="np.nanquantile only accepts weights since version 2.0",
|
| 449 |
+
)
|
| 450 |
+
@pytest.mark.parametrize("percentile", [66, 10, 50])
|
| 451 |
+
@pytest.mark.parametrize("average", [False, True])
|
| 452 |
+
@pytest.mark.parametrize("uniform_weight", [False, True])
|
| 453 |
+
def test_weighted_percentile_like_numpy_nanquantile(
|
| 454 |
+
percentile, average, uniform_weight, global_random_seed
|
| 455 |
+
):
|
| 456 |
+
"""Check `_weighted_percentile` equivalent to `np.nanquantile` with weights."""
|
| 457 |
+
# TODO: remove the following skip once no longer applicable.
|
| 458 |
+
if average and not uniform_weight:
|
| 459 |
+
pytest.skip(
|
| 460 |
+
"np.nanquantile does not support weights with "
|
| 461 |
+
"method='averaged_inverted_cdf'"
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
rng = np.random.RandomState(global_random_seed)
|
| 465 |
+
array_with_nans = rng.rand(10, 100)
|
| 466 |
+
array_with_nans[rng.rand(*array_with_nans.shape) < 0.5] = np.nan
|
| 467 |
+
if uniform_weight:
|
| 468 |
+
sample_weight = np.ones_like(array_with_nans) * rng.randint(
|
| 469 |
+
1,
|
| 470 |
+
6,
|
| 471 |
+
size=1,
|
| 472 |
+
)
|
| 473 |
+
else:
|
| 474 |
+
sample_weight = rng.randint(1, 6, size=(10, 100))
|
| 475 |
+
|
| 476 |
+
percentile_weighted_percentile = _weighted_percentile(
|
| 477 |
+
array_with_nans, sample_weight, percentile, average=average
|
| 478 |
+
)
|
| 479 |
+
percentile_numpy_nanquantile = np.nanquantile(
|
| 480 |
+
array_with_nans,
|
| 481 |
+
percentile / 100,
|
| 482 |
+
weights=sample_weight if not uniform_weight else None,
|
| 483 |
+
method="averaged_inverted_cdf" if average else "inverted_cdf",
|
| 484 |
+
axis=0,
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
assert_array_equal(percentile_weighted_percentile, percentile_numpy_nanquantile)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_tags.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, fields
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from sklearn.base import (
|
| 7 |
+
BaseEstimator,
|
| 8 |
+
ClassifierMixin,
|
| 9 |
+
RegressorMixin,
|
| 10 |
+
TransformerMixin,
|
| 11 |
+
)
|
| 12 |
+
from sklearn.pipeline import Pipeline
|
| 13 |
+
from sklearn.utils import (
|
| 14 |
+
Tags,
|
| 15 |
+
get_tags,
|
| 16 |
+
)
|
| 17 |
+
from sklearn.utils.estimator_checks import (
|
| 18 |
+
check_estimator_tags_renamed,
|
| 19 |
+
check_valid_tag_types,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class EmptyClassifier(ClassifierMixin, BaseEstimator):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class EmptyTransformer(TransformerMixin, BaseEstimator):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class EmptyRegressor(RegressorMixin, BaseEstimator):
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.mark.parametrize(
|
| 36 |
+
"estimator, value",
|
| 37 |
+
[
|
| 38 |
+
[EmptyClassifier(), True],
|
| 39 |
+
[EmptyTransformer(), False],
|
| 40 |
+
[EmptyRegressor(), True],
|
| 41 |
+
[BaseEstimator(), False],
|
| 42 |
+
],
|
| 43 |
+
)
|
| 44 |
+
def test_requires_y(estimator, value):
|
| 45 |
+
assert get_tags(estimator).target_tags.required == value
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_no___sklearn_tags__with_more_tags():
|
| 49 |
+
"""Test that calling `get_tags` on a class that defines `_more_tags` but not
|
| 50 |
+
`__sklearn_tags__` raises an error.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
class MoreTagsEstimator(BaseEstimator):
|
| 54 |
+
def _more_tags(self):
|
| 55 |
+
return {"requires_y": True} # pragma: no cover
|
| 56 |
+
|
| 57 |
+
with pytest.raises(
|
| 58 |
+
TypeError, match="has defined either `_more_tags` or `_get_tags`"
|
| 59 |
+
):
|
| 60 |
+
check_estimator_tags_renamed("MoreTagsEstimator", MoreTagsEstimator())
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_tag_test_passes_with_inheritance():
|
| 64 |
+
@dataclass
|
| 65 |
+
class MyTags(Tags):
|
| 66 |
+
my_tag: bool = True # type: ignore[annotation-unchecked]
|
| 67 |
+
|
| 68 |
+
class MyEstimator(BaseEstimator):
|
| 69 |
+
def __sklearn_tags__(self):
|
| 70 |
+
tags_orig = super().__sklearn_tags__()
|
| 71 |
+
as_dict = {
|
| 72 |
+
field.name: getattr(tags_orig, field.name)
|
| 73 |
+
for field in fields(tags_orig)
|
| 74 |
+
}
|
| 75 |
+
tags = MyTags(**as_dict)
|
| 76 |
+
tags.my_tag = True
|
| 77 |
+
return tags
|
| 78 |
+
|
| 79 |
+
check_valid_tag_types("MyEstimator", MyEstimator())
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_tags_no_sklearn_tags_concrete_implementation():
|
| 83 |
+
"""Non-regression test for:
|
| 84 |
+
https://github.com/scikit-learn/scikit-learn/issues/30479
|
| 85 |
+
|
| 86 |
+
Either the estimator doesn't implement `__sklearn_tags` or there is no class
|
| 87 |
+
implementing `__sklearn_tags__` without calling `super().__sklearn_tags__()` in
|
| 88 |
+
its mro. Thus, we raise an error and request to inherit from
|
| 89 |
+
`BaseEstimator` that implements `__sklearn_tags__`.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
X = np.array([[1, 2], [2, 3], [3, 4]])
|
| 93 |
+
y = np.array([1, 0, 1])
|
| 94 |
+
|
| 95 |
+
# 1st case, the estimator inherits from a class that only implements
|
| 96 |
+
# `__sklearn_tags__` by calling `super().__sklearn_tags__()`.
|
| 97 |
+
class MyEstimator(ClassifierMixin):
|
| 98 |
+
def __init__(self, *, param=1):
|
| 99 |
+
self.param = param
|
| 100 |
+
|
| 101 |
+
def fit(self, X, y=None):
|
| 102 |
+
self.is_fitted_ = True
|
| 103 |
+
return self
|
| 104 |
+
|
| 105 |
+
def predict(self, X):
|
| 106 |
+
return np.full(shape=X.shape[0], fill_value=self.param)
|
| 107 |
+
|
| 108 |
+
my_pipeline = Pipeline([("estimator", MyEstimator(param=1))])
|
| 109 |
+
with pytest.raises(AttributeError, match="The following error was raised"):
|
| 110 |
+
my_pipeline.fit(X, y).predict(X)
|
| 111 |
+
|
| 112 |
+
# 2nd case, the estimator doesn't implement `__sklearn_tags__` at all.
|
| 113 |
+
class MyEstimator2:
|
| 114 |
+
def __init__(self, *, param=1):
|
| 115 |
+
self.param = param
|
| 116 |
+
|
| 117 |
+
def fit(self, X, y=None):
|
| 118 |
+
self.is_fitted_ = True
|
| 119 |
+
return self
|
| 120 |
+
|
| 121 |
+
def predict(self, X):
|
| 122 |
+
return np.full(shape=X.shape[0], fill_value=self.param)
|
| 123 |
+
|
| 124 |
+
my_pipeline = Pipeline([("estimator", MyEstimator2(param=1))])
|
| 125 |
+
with pytest.raises(AttributeError, match="The following error was raised"):
|
| 126 |
+
my_pipeline.fit(X, y).predict(X)
|
| 127 |
+
|
| 128 |
+
# check that we still raise an error if it is not an AttributeError or related to
|
| 129 |
+
# __sklearn_tags__
|
| 130 |
+
class MyEstimator3(MyEstimator, BaseEstimator):
|
| 131 |
+
def __init__(self, *, param=1, error_type=AttributeError):
|
| 132 |
+
self.param = param
|
| 133 |
+
self.error_type = error_type
|
| 134 |
+
|
| 135 |
+
def __sklearn_tags__(self):
|
| 136 |
+
super().__sklearn_tags__()
|
| 137 |
+
raise self.error_type("test")
|
| 138 |
+
|
| 139 |
+
for error_type in (AttributeError, TypeError, ValueError):
|
| 140 |
+
estimator = MyEstimator3(param=1, error_type=error_type)
|
| 141 |
+
with pytest.raises(error_type):
|
| 142 |
+
get_tags(estimator)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_testing.py
ADDED
|
@@ -0,0 +1,1143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import atexit
|
| 2 |
+
import os
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
from scipy import sparse
|
| 8 |
+
|
| 9 |
+
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
|
| 10 |
+
from sklearn.tree import DecisionTreeClassifier
|
| 11 |
+
from sklearn.utils._testing import (
|
| 12 |
+
TempMemmap,
|
| 13 |
+
_convert_container,
|
| 14 |
+
_delete_folder,
|
| 15 |
+
_get_warnings_filters_info_list,
|
| 16 |
+
assert_allclose,
|
| 17 |
+
assert_allclose_dense_sparse,
|
| 18 |
+
assert_docstring_consistency,
|
| 19 |
+
assert_run_python_script_without_output,
|
| 20 |
+
check_docstring_parameters,
|
| 21 |
+
create_memmap_backed_data,
|
| 22 |
+
ignore_warnings,
|
| 23 |
+
raises,
|
| 24 |
+
set_random_state,
|
| 25 |
+
skip_if_no_numpydoc,
|
| 26 |
+
turn_warnings_into_errors,
|
| 27 |
+
)
|
| 28 |
+
from sklearn.utils.deprecation import deprecated
|
| 29 |
+
from sklearn.utils.fixes import (
|
| 30 |
+
_IS_WASM,
|
| 31 |
+
CSC_CONTAINERS,
|
| 32 |
+
CSR_CONTAINERS,
|
| 33 |
+
)
|
| 34 |
+
from sklearn.utils.metaestimators import available_if
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_set_random_state():
|
| 38 |
+
lda = LinearDiscriminantAnalysis()
|
| 39 |
+
tree = DecisionTreeClassifier()
|
| 40 |
+
# Linear Discriminant Analysis doesn't have random state: smoke test
|
| 41 |
+
set_random_state(lda, 3)
|
| 42 |
+
set_random_state(tree, 3)
|
| 43 |
+
assert tree.random_state == 3
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@pytest.mark.parametrize("csr_container", CSC_CONTAINERS)
|
| 47 |
+
def test_assert_allclose_dense_sparse(csr_container):
|
| 48 |
+
x = np.arange(9).reshape(3, 3)
|
| 49 |
+
msg = "Not equal to tolerance "
|
| 50 |
+
y = csr_container(x)
|
| 51 |
+
for X in [x, y]:
|
| 52 |
+
# basic compare
|
| 53 |
+
with pytest.raises(AssertionError, match=msg):
|
| 54 |
+
assert_allclose_dense_sparse(X, X * 2)
|
| 55 |
+
assert_allclose_dense_sparse(X, X)
|
| 56 |
+
|
| 57 |
+
with pytest.raises(ValueError, match="Can only compare two sparse"):
|
| 58 |
+
assert_allclose_dense_sparse(x, y)
|
| 59 |
+
|
| 60 |
+
A = sparse.diags(np.ones(5), offsets=0).tocsr()
|
| 61 |
+
B = csr_container(np.ones((1, 5)))
|
| 62 |
+
with pytest.raises(AssertionError, match="Arrays are not equal"):
|
| 63 |
+
assert_allclose_dense_sparse(B, A)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_ignore_warning():
|
| 67 |
+
# This check that ignore_warning decorator and context manager are working
|
| 68 |
+
# as expected
|
| 69 |
+
def _warning_function():
|
| 70 |
+
warnings.warn("deprecation warning", DeprecationWarning)
|
| 71 |
+
|
| 72 |
+
def _multiple_warning_function():
|
| 73 |
+
warnings.warn("deprecation warning", DeprecationWarning)
|
| 74 |
+
warnings.warn("deprecation warning")
|
| 75 |
+
|
| 76 |
+
# Check the function directly
|
| 77 |
+
with warnings.catch_warnings():
|
| 78 |
+
warnings.simplefilter("error")
|
| 79 |
+
|
| 80 |
+
ignore_warnings(_warning_function)
|
| 81 |
+
ignore_warnings(_warning_function, category=DeprecationWarning)
|
| 82 |
+
|
| 83 |
+
with pytest.warns(DeprecationWarning):
|
| 84 |
+
ignore_warnings(_warning_function, category=UserWarning)()
|
| 85 |
+
|
| 86 |
+
with pytest.warns() as record:
|
| 87 |
+
ignore_warnings(_multiple_warning_function, category=FutureWarning)()
|
| 88 |
+
assert len(record) == 2
|
| 89 |
+
assert isinstance(record[0].message, DeprecationWarning)
|
| 90 |
+
assert isinstance(record[1].message, UserWarning)
|
| 91 |
+
|
| 92 |
+
with pytest.warns() as record:
|
| 93 |
+
ignore_warnings(_multiple_warning_function, category=UserWarning)()
|
| 94 |
+
assert len(record) == 1
|
| 95 |
+
assert isinstance(record[0].message, DeprecationWarning)
|
| 96 |
+
|
| 97 |
+
with warnings.catch_warnings():
|
| 98 |
+
warnings.simplefilter("error")
|
| 99 |
+
|
| 100 |
+
ignore_warnings(_warning_function, category=(DeprecationWarning, UserWarning))
|
| 101 |
+
|
| 102 |
+
# Check the decorator
|
| 103 |
+
@ignore_warnings
|
| 104 |
+
def decorator_no_warning():
|
| 105 |
+
_warning_function()
|
| 106 |
+
_multiple_warning_function()
|
| 107 |
+
|
| 108 |
+
@ignore_warnings(category=(DeprecationWarning, UserWarning))
|
| 109 |
+
def decorator_no_warning_multiple():
|
| 110 |
+
_multiple_warning_function()
|
| 111 |
+
|
| 112 |
+
@ignore_warnings(category=DeprecationWarning)
|
| 113 |
+
def decorator_no_deprecation_warning():
|
| 114 |
+
_warning_function()
|
| 115 |
+
|
| 116 |
+
@ignore_warnings(category=UserWarning)
|
| 117 |
+
def decorator_no_user_warning():
|
| 118 |
+
_warning_function()
|
| 119 |
+
|
| 120 |
+
@ignore_warnings(category=DeprecationWarning)
|
| 121 |
+
def decorator_no_deprecation_multiple_warning():
|
| 122 |
+
_multiple_warning_function()
|
| 123 |
+
|
| 124 |
+
@ignore_warnings(category=UserWarning)
|
| 125 |
+
def decorator_no_user_multiple_warning():
|
| 126 |
+
_multiple_warning_function()
|
| 127 |
+
|
| 128 |
+
with warnings.catch_warnings():
|
| 129 |
+
warnings.simplefilter("error")
|
| 130 |
+
|
| 131 |
+
decorator_no_warning()
|
| 132 |
+
decorator_no_warning_multiple()
|
| 133 |
+
decorator_no_deprecation_warning()
|
| 134 |
+
|
| 135 |
+
with pytest.warns(DeprecationWarning):
|
| 136 |
+
decorator_no_user_warning()
|
| 137 |
+
with pytest.warns(UserWarning):
|
| 138 |
+
decorator_no_deprecation_multiple_warning()
|
| 139 |
+
with pytest.warns(DeprecationWarning):
|
| 140 |
+
decorator_no_user_multiple_warning()
|
| 141 |
+
|
| 142 |
+
# Check the context manager
|
| 143 |
+
def context_manager_no_warning():
|
| 144 |
+
with ignore_warnings():
|
| 145 |
+
_warning_function()
|
| 146 |
+
|
| 147 |
+
def context_manager_no_warning_multiple():
|
| 148 |
+
with ignore_warnings(category=(DeprecationWarning, UserWarning)):
|
| 149 |
+
_multiple_warning_function()
|
| 150 |
+
|
| 151 |
+
def context_manager_no_deprecation_warning():
|
| 152 |
+
with ignore_warnings(category=DeprecationWarning):
|
| 153 |
+
_warning_function()
|
| 154 |
+
|
| 155 |
+
def context_manager_no_user_warning():
|
| 156 |
+
with ignore_warnings(category=UserWarning):
|
| 157 |
+
_warning_function()
|
| 158 |
+
|
| 159 |
+
def context_manager_no_deprecation_multiple_warning():
|
| 160 |
+
with ignore_warnings(category=DeprecationWarning):
|
| 161 |
+
_multiple_warning_function()
|
| 162 |
+
|
| 163 |
+
def context_manager_no_user_multiple_warning():
|
| 164 |
+
with ignore_warnings(category=UserWarning):
|
| 165 |
+
_multiple_warning_function()
|
| 166 |
+
|
| 167 |
+
with warnings.catch_warnings():
|
| 168 |
+
warnings.simplefilter("error")
|
| 169 |
+
|
| 170 |
+
context_manager_no_warning()
|
| 171 |
+
context_manager_no_warning_multiple()
|
| 172 |
+
context_manager_no_deprecation_warning()
|
| 173 |
+
|
| 174 |
+
with pytest.warns(DeprecationWarning):
|
| 175 |
+
context_manager_no_user_warning()
|
| 176 |
+
with pytest.warns(UserWarning):
|
| 177 |
+
context_manager_no_deprecation_multiple_warning()
|
| 178 |
+
with pytest.warns(DeprecationWarning):
|
| 179 |
+
context_manager_no_user_multiple_warning()
|
| 180 |
+
|
| 181 |
+
# Check that passing warning class as first positional argument
|
| 182 |
+
warning_class = UserWarning
|
| 183 |
+
match = "'obj' should be a callable.+you should use 'category=UserWarning'"
|
| 184 |
+
|
| 185 |
+
with pytest.raises(ValueError, match=match):
|
| 186 |
+
silence_warnings_func = ignore_warnings(warning_class)(_warning_function)
|
| 187 |
+
silence_warnings_func()
|
| 188 |
+
|
| 189 |
+
with pytest.raises(ValueError, match=match):
|
| 190 |
+
|
| 191 |
+
@ignore_warnings(warning_class)
|
| 192 |
+
def test():
|
| 193 |
+
pass
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# Tests for docstrings:
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def f_ok(a, b):
|
| 200 |
+
"""Function f
|
| 201 |
+
|
| 202 |
+
Parameters
|
| 203 |
+
----------
|
| 204 |
+
a : int
|
| 205 |
+
Parameter a
|
| 206 |
+
b : float
|
| 207 |
+
Parameter b
|
| 208 |
+
|
| 209 |
+
Returns
|
| 210 |
+
-------
|
| 211 |
+
c : list
|
| 212 |
+
Parameter c
|
| 213 |
+
"""
|
| 214 |
+
c = a + b
|
| 215 |
+
return c
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def f_bad_sections(a, b):
|
| 219 |
+
"""Function f
|
| 220 |
+
|
| 221 |
+
Parameters
|
| 222 |
+
----------
|
| 223 |
+
a : int
|
| 224 |
+
Parameter a
|
| 225 |
+
b : float
|
| 226 |
+
Parameter b
|
| 227 |
+
|
| 228 |
+
Results
|
| 229 |
+
-------
|
| 230 |
+
c : list
|
| 231 |
+
Parameter c
|
| 232 |
+
"""
|
| 233 |
+
c = a + b
|
| 234 |
+
return c
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def f_bad_order(b, a):
|
| 238 |
+
"""Function f
|
| 239 |
+
|
| 240 |
+
Parameters
|
| 241 |
+
----------
|
| 242 |
+
a : int
|
| 243 |
+
Parameter a
|
| 244 |
+
b : float
|
| 245 |
+
Parameter b
|
| 246 |
+
|
| 247 |
+
Returns
|
| 248 |
+
-------
|
| 249 |
+
c : list
|
| 250 |
+
Parameter c
|
| 251 |
+
"""
|
| 252 |
+
c = a + b
|
| 253 |
+
return c
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def f_too_many_param_docstring(a, b):
|
| 257 |
+
"""Function f
|
| 258 |
+
|
| 259 |
+
Parameters
|
| 260 |
+
----------
|
| 261 |
+
a : int
|
| 262 |
+
Parameter a
|
| 263 |
+
b : int
|
| 264 |
+
Parameter b
|
| 265 |
+
c : int
|
| 266 |
+
Parameter c
|
| 267 |
+
|
| 268 |
+
Returns
|
| 269 |
+
-------
|
| 270 |
+
d : list
|
| 271 |
+
Parameter c
|
| 272 |
+
"""
|
| 273 |
+
d = a + b
|
| 274 |
+
return d
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def f_missing(a, b):
|
| 278 |
+
"""Function f
|
| 279 |
+
|
| 280 |
+
Parameters
|
| 281 |
+
----------
|
| 282 |
+
a : int
|
| 283 |
+
Parameter a
|
| 284 |
+
|
| 285 |
+
Returns
|
| 286 |
+
-------
|
| 287 |
+
c : list
|
| 288 |
+
Parameter c
|
| 289 |
+
"""
|
| 290 |
+
c = a + b
|
| 291 |
+
return c
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def f_check_param_definition(a, b, c, d, e):
|
| 295 |
+
"""Function f
|
| 296 |
+
|
| 297 |
+
Parameters
|
| 298 |
+
----------
|
| 299 |
+
a: int
|
| 300 |
+
Parameter a
|
| 301 |
+
b:
|
| 302 |
+
Parameter b
|
| 303 |
+
c :
|
| 304 |
+
This is parsed correctly in numpydoc 1.2
|
| 305 |
+
d:int
|
| 306 |
+
Parameter d
|
| 307 |
+
e
|
| 308 |
+
No typespec is allowed without colon
|
| 309 |
+
"""
|
| 310 |
+
return a + b + c + d
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class Klass:
|
| 314 |
+
def f_missing(self, X, y):
|
| 315 |
+
pass
|
| 316 |
+
|
| 317 |
+
def f_bad_sections(self, X, y):
|
| 318 |
+
"""Function f
|
| 319 |
+
|
| 320 |
+
Parameter
|
| 321 |
+
---------
|
| 322 |
+
a : int
|
| 323 |
+
Parameter a
|
| 324 |
+
b : float
|
| 325 |
+
Parameter b
|
| 326 |
+
|
| 327 |
+
Results
|
| 328 |
+
-------
|
| 329 |
+
c : list
|
| 330 |
+
Parameter c
|
| 331 |
+
"""
|
| 332 |
+
pass
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class MockEst:
|
| 336 |
+
def __init__(self):
|
| 337 |
+
"""MockEstimator"""
|
| 338 |
+
|
| 339 |
+
def fit(self, X, y):
|
| 340 |
+
return X
|
| 341 |
+
|
| 342 |
+
def predict(self, X):
|
| 343 |
+
return X
|
| 344 |
+
|
| 345 |
+
def predict_proba(self, X):
|
| 346 |
+
return X
|
| 347 |
+
|
| 348 |
+
def score(self, X):
|
| 349 |
+
return 1.0
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class MockMetaEstimator:
|
| 353 |
+
def __init__(self, delegate):
|
| 354 |
+
"""MetaEstimator to check if doctest on delegated methods work.
|
| 355 |
+
|
| 356 |
+
Parameters
|
| 357 |
+
---------
|
| 358 |
+
delegate : estimator
|
| 359 |
+
Delegated estimator.
|
| 360 |
+
"""
|
| 361 |
+
self.delegate = delegate
|
| 362 |
+
|
| 363 |
+
@available_if(lambda self: hasattr(self.delegate, "predict"))
|
| 364 |
+
def predict(self, X):
|
| 365 |
+
"""This is available only if delegate has predict.
|
| 366 |
+
|
| 367 |
+
Parameters
|
| 368 |
+
----------
|
| 369 |
+
y : ndarray
|
| 370 |
+
Parameter y
|
| 371 |
+
"""
|
| 372 |
+
return self.delegate.predict(X)
|
| 373 |
+
|
| 374 |
+
@available_if(lambda self: hasattr(self.delegate, "score"))
|
| 375 |
+
@deprecated("Testing a deprecated delegated method")
|
| 376 |
+
def score(self, X):
|
| 377 |
+
"""This is available only if delegate has score.
|
| 378 |
+
|
| 379 |
+
Parameters
|
| 380 |
+
---------
|
| 381 |
+
y : ndarray
|
| 382 |
+
Parameter y
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
@available_if(lambda self: hasattr(self.delegate, "predict_proba"))
|
| 386 |
+
def predict_proba(self, X):
|
| 387 |
+
"""This is available only if delegate has predict_proba.
|
| 388 |
+
|
| 389 |
+
Parameters
|
| 390 |
+
---------
|
| 391 |
+
X : ndarray
|
| 392 |
+
Parameter X
|
| 393 |
+
"""
|
| 394 |
+
return X
|
| 395 |
+
|
| 396 |
+
@deprecated("Testing deprecated function with wrong params")
|
| 397 |
+
def fit(self, X, y):
|
| 398 |
+
"""Incorrect docstring but should not be tested"""
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
@skip_if_no_numpydoc
|
| 402 |
+
def test_check_docstring_parameters():
|
| 403 |
+
incorrect = check_docstring_parameters(f_ok)
|
| 404 |
+
assert incorrect == []
|
| 405 |
+
incorrect = check_docstring_parameters(f_ok, ignore=["b"])
|
| 406 |
+
assert incorrect == []
|
| 407 |
+
incorrect = check_docstring_parameters(f_missing, ignore=["b"])
|
| 408 |
+
assert incorrect == []
|
| 409 |
+
with pytest.raises(RuntimeError, match="Unknown section Results"):
|
| 410 |
+
check_docstring_parameters(f_bad_sections)
|
| 411 |
+
with pytest.raises(RuntimeError, match="Unknown section Parameter"):
|
| 412 |
+
check_docstring_parameters(Klass.f_bad_sections)
|
| 413 |
+
|
| 414 |
+
incorrect = check_docstring_parameters(f_check_param_definition)
|
| 415 |
+
mock_meta = MockMetaEstimator(delegate=MockEst())
|
| 416 |
+
mock_meta_name = mock_meta.__class__.__name__
|
| 417 |
+
assert incorrect == [
|
| 418 |
+
(
|
| 419 |
+
"sklearn.utils.tests.test_testing.f_check_param_definition There "
|
| 420 |
+
"was no space between the param name and colon ('a: int')"
|
| 421 |
+
),
|
| 422 |
+
(
|
| 423 |
+
"sklearn.utils.tests.test_testing.f_check_param_definition There "
|
| 424 |
+
"was no space between the param name and colon ('b:')"
|
| 425 |
+
),
|
| 426 |
+
(
|
| 427 |
+
"sklearn.utils.tests.test_testing.f_check_param_definition There "
|
| 428 |
+
"was no space between the param name and colon ('d:int')"
|
| 429 |
+
),
|
| 430 |
+
]
|
| 431 |
+
|
| 432 |
+
messages = [
|
| 433 |
+
[
|
| 434 |
+
"In function: sklearn.utils.tests.test_testing.f_bad_order",
|
| 435 |
+
(
|
| 436 |
+
"There's a parameter name mismatch in function docstring w.r.t."
|
| 437 |
+
" function signature, at index 0 diff: 'b' != 'a'"
|
| 438 |
+
),
|
| 439 |
+
"Full diff:",
|
| 440 |
+
"- ['b', 'a']",
|
| 441 |
+
"+ ['a', 'b']",
|
| 442 |
+
],
|
| 443 |
+
[
|
| 444 |
+
"In function: sklearn.utils.tests.test_testing.f_too_many_param_docstring",
|
| 445 |
+
(
|
| 446 |
+
"Parameters in function docstring have more items w.r.t. function"
|
| 447 |
+
" signature, first extra item: c"
|
| 448 |
+
),
|
| 449 |
+
"Full diff:",
|
| 450 |
+
"- ['a', 'b']",
|
| 451 |
+
"+ ['a', 'b', 'c']",
|
| 452 |
+
"? +++++",
|
| 453 |
+
],
|
| 454 |
+
[
|
| 455 |
+
"In function: sklearn.utils.tests.test_testing.f_missing",
|
| 456 |
+
(
|
| 457 |
+
"Parameters in function docstring have less items w.r.t. function"
|
| 458 |
+
" signature, first missing item: b"
|
| 459 |
+
),
|
| 460 |
+
"Full diff:",
|
| 461 |
+
"- ['a', 'b']",
|
| 462 |
+
"+ ['a']",
|
| 463 |
+
],
|
| 464 |
+
[
|
| 465 |
+
"In function: sklearn.utils.tests.test_testing.Klass.f_missing",
|
| 466 |
+
(
|
| 467 |
+
"Parameters in function docstring have less items w.r.t. function"
|
| 468 |
+
" signature, first missing item: X"
|
| 469 |
+
),
|
| 470 |
+
"Full diff:",
|
| 471 |
+
"- ['X', 'y']",
|
| 472 |
+
"+ []",
|
| 473 |
+
],
|
| 474 |
+
[
|
| 475 |
+
f"In function: sklearn.utils.tests.test_testing.{mock_meta_name}.predict",
|
| 476 |
+
(
|
| 477 |
+
"There's a parameter name mismatch in function docstring w.r.t."
|
| 478 |
+
" function signature, at index 0 diff: 'X' != 'y'"
|
| 479 |
+
),
|
| 480 |
+
"Full diff:",
|
| 481 |
+
"- ['X']",
|
| 482 |
+
"? ^",
|
| 483 |
+
"+ ['y']",
|
| 484 |
+
"? ^",
|
| 485 |
+
],
|
| 486 |
+
[
|
| 487 |
+
"In function: "
|
| 488 |
+
f"sklearn.utils.tests.test_testing.{mock_meta_name}."
|
| 489 |
+
"predict_proba",
|
| 490 |
+
"potentially wrong underline length... ",
|
| 491 |
+
"Parameters ",
|
| 492 |
+
"--------- in ",
|
| 493 |
+
],
|
| 494 |
+
[
|
| 495 |
+
f"In function: sklearn.utils.tests.test_testing.{mock_meta_name}.score",
|
| 496 |
+
"potentially wrong underline length... ",
|
| 497 |
+
"Parameters ",
|
| 498 |
+
"--------- in ",
|
| 499 |
+
],
|
| 500 |
+
[
|
| 501 |
+
f"In function: sklearn.utils.tests.test_testing.{mock_meta_name}.fit",
|
| 502 |
+
(
|
| 503 |
+
"Parameters in function docstring have less items w.r.t. function"
|
| 504 |
+
" signature, first missing item: X"
|
| 505 |
+
),
|
| 506 |
+
"Full diff:",
|
| 507 |
+
"- ['X', 'y']",
|
| 508 |
+
"+ []",
|
| 509 |
+
],
|
| 510 |
+
]
|
| 511 |
+
|
| 512 |
+
for msg, f in zip(
|
| 513 |
+
messages,
|
| 514 |
+
[
|
| 515 |
+
f_bad_order,
|
| 516 |
+
f_too_many_param_docstring,
|
| 517 |
+
f_missing,
|
| 518 |
+
Klass.f_missing,
|
| 519 |
+
mock_meta.predict,
|
| 520 |
+
mock_meta.predict_proba,
|
| 521 |
+
mock_meta.score,
|
| 522 |
+
mock_meta.fit,
|
| 523 |
+
],
|
| 524 |
+
):
|
| 525 |
+
incorrect = check_docstring_parameters(f)
|
| 526 |
+
assert msg == incorrect, '\n"%s"\n not in \n"%s"' % (msg, incorrect)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def f_one(a, b): # pragma: no cover
|
| 530 |
+
"""Function one.
|
| 531 |
+
|
| 532 |
+
Parameters
|
| 533 |
+
----------
|
| 534 |
+
a : int, float
|
| 535 |
+
Parameter a.
|
| 536 |
+
Second line.
|
| 537 |
+
|
| 538 |
+
b : str
|
| 539 |
+
Parameter b.
|
| 540 |
+
|
| 541 |
+
Returns
|
| 542 |
+
-------
|
| 543 |
+
c : int
|
| 544 |
+
Returning
|
| 545 |
+
|
| 546 |
+
d : int
|
| 547 |
+
Returning
|
| 548 |
+
"""
|
| 549 |
+
pass
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def f_two(a, b): # pragma: no cover
|
| 553 |
+
"""Function two.
|
| 554 |
+
|
| 555 |
+
Parameters
|
| 556 |
+
----------
|
| 557 |
+
a : int, float
|
| 558 |
+
Parameter a.
|
| 559 |
+
Second line.
|
| 560 |
+
|
| 561 |
+
b : str
|
| 562 |
+
Parameter bb.
|
| 563 |
+
|
| 564 |
+
e : int
|
| 565 |
+
Extra parameter.
|
| 566 |
+
|
| 567 |
+
Returns
|
| 568 |
+
-------
|
| 569 |
+
c : int
|
| 570 |
+
Returning
|
| 571 |
+
|
| 572 |
+
d : int
|
| 573 |
+
Returning
|
| 574 |
+
"""
|
| 575 |
+
pass
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def f_three(a, b): # pragma: no cover
|
| 579 |
+
"""Function two.
|
| 580 |
+
|
| 581 |
+
Parameters
|
| 582 |
+
----------
|
| 583 |
+
a : int, float
|
| 584 |
+
Parameter a.
|
| 585 |
+
|
| 586 |
+
b : str
|
| 587 |
+
Parameter B!
|
| 588 |
+
|
| 589 |
+
e :
|
| 590 |
+
Extra parameter.
|
| 591 |
+
|
| 592 |
+
Returns
|
| 593 |
+
-------
|
| 594 |
+
c : int
|
| 595 |
+
Returning.
|
| 596 |
+
|
| 597 |
+
d : int
|
| 598 |
+
Returning
|
| 599 |
+
"""
|
| 600 |
+
pass
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
@skip_if_no_numpydoc
|
| 604 |
+
def test_assert_docstring_consistency_object_type():
|
| 605 |
+
"""Check error raised when `objects` incorrect type."""
|
| 606 |
+
with pytest.raises(TypeError, match="All 'objects' must be one of"):
|
| 607 |
+
assert_docstring_consistency(["string", f_one])
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
@skip_if_no_numpydoc
|
| 611 |
+
@pytest.mark.parametrize(
|
| 612 |
+
"objects, kwargs, error",
|
| 613 |
+
[
|
| 614 |
+
(
|
| 615 |
+
[f_one, f_two],
|
| 616 |
+
{"include_params": ["a"], "exclude_params": ["b"]},
|
| 617 |
+
"The 'exclude_params' argument",
|
| 618 |
+
),
|
| 619 |
+
(
|
| 620 |
+
[f_one, f_two],
|
| 621 |
+
{"include_returns": False, "exclude_returns": ["c"]},
|
| 622 |
+
"The 'exclude_returns' argument",
|
| 623 |
+
),
|
| 624 |
+
],
|
| 625 |
+
)
|
| 626 |
+
def test_assert_docstring_consistency_arg_checks(objects, kwargs, error):
|
| 627 |
+
"""Check `assert_docstring_consistency` argument checking correct."""
|
| 628 |
+
with pytest.raises(TypeError, match=error):
|
| 629 |
+
assert_docstring_consistency(objects, **kwargs)
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
@skip_if_no_numpydoc
|
| 633 |
+
@pytest.mark.parametrize(
|
| 634 |
+
"objects, kwargs, error, warn",
|
| 635 |
+
[
|
| 636 |
+
pytest.param(
|
| 637 |
+
[f_one, f_two], {"include_params": ["a"]}, "", "", id="whitespace"
|
| 638 |
+
),
|
| 639 |
+
pytest.param([f_one, f_two], {"include_returns": True}, "", "", id="incl_all"),
|
| 640 |
+
pytest.param(
|
| 641 |
+
[f_one, f_two, f_three],
|
| 642 |
+
{"include_params": ["a"]},
|
| 643 |
+
(
|
| 644 |
+
r"The description of Parameter 'a' is inconsistent between "
|
| 645 |
+
r"\['f_one',\n'f_two'\]"
|
| 646 |
+
),
|
| 647 |
+
"",
|
| 648 |
+
id="2-1 group",
|
| 649 |
+
),
|
| 650 |
+
pytest.param(
|
| 651 |
+
[f_one, f_two, f_three],
|
| 652 |
+
{"include_params": ["b"]},
|
| 653 |
+
(
|
| 654 |
+
r"The description of Parameter 'b' is inconsistent between "
|
| 655 |
+
r"\['f_one'\] and\n\['f_two'\] and"
|
| 656 |
+
),
|
| 657 |
+
"",
|
| 658 |
+
id="1-1-1 group",
|
| 659 |
+
),
|
| 660 |
+
pytest.param(
|
| 661 |
+
[f_two, f_three],
|
| 662 |
+
{"include_params": ["e"]},
|
| 663 |
+
(
|
| 664 |
+
r"The type specification of Parameter 'e' is inconsistent between\n"
|
| 665 |
+
r"\['f_two'\] and"
|
| 666 |
+
),
|
| 667 |
+
"",
|
| 668 |
+
id="empty type",
|
| 669 |
+
),
|
| 670 |
+
pytest.param(
|
| 671 |
+
[f_one, f_two],
|
| 672 |
+
{"include_params": True, "exclude_params": ["b"]},
|
| 673 |
+
"",
|
| 674 |
+
r"Checking was skipped for Parameters: \['e'\]",
|
| 675 |
+
id="skip warn",
|
| 676 |
+
),
|
| 677 |
+
],
|
| 678 |
+
)
|
| 679 |
+
def test_assert_docstring_consistency(objects, kwargs, error, warn):
|
| 680 |
+
"""Check `assert_docstring_consistency` gives correct results."""
|
| 681 |
+
if error:
|
| 682 |
+
with pytest.raises(AssertionError, match=error):
|
| 683 |
+
assert_docstring_consistency(objects, **kwargs)
|
| 684 |
+
elif warn:
|
| 685 |
+
with pytest.warns(UserWarning, match=warn):
|
| 686 |
+
assert_docstring_consistency(objects, **kwargs)
|
| 687 |
+
else:
|
| 688 |
+
assert_docstring_consistency(objects, **kwargs)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def f_four(labels): # pragma: no cover
|
| 692 |
+
"""Function four.
|
| 693 |
+
|
| 694 |
+
Parameters
|
| 695 |
+
----------
|
| 696 |
+
|
| 697 |
+
labels : array-like, default=None
|
| 698 |
+
The set of labels to include when `average != 'binary'`, and their
|
| 699 |
+
order if `average is None`. Labels present in the data can be excluded.
|
| 700 |
+
"""
|
| 701 |
+
pass
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
def f_five(labels): # pragma: no cover
|
| 705 |
+
"""Function five.
|
| 706 |
+
|
| 707 |
+
Parameters
|
| 708 |
+
----------
|
| 709 |
+
|
| 710 |
+
labels : array-like, default=None
|
| 711 |
+
The set of labels to include when `average != 'binary'`, and their
|
| 712 |
+
order if `average is None`. This is an extra line. Labels present in the
|
| 713 |
+
data can be excluded.
|
| 714 |
+
"""
|
| 715 |
+
pass
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def f_six(labels): # pragma: no cover
|
| 719 |
+
"""Function six.
|
| 720 |
+
|
| 721 |
+
Parameters
|
| 722 |
+
----------
|
| 723 |
+
|
| 724 |
+
labels : array-like, default=None
|
| 725 |
+
The group of labels to add when `average != 'binary'`, and the
|
| 726 |
+
order if `average is None`. Labels present on them datas can be excluded.
|
| 727 |
+
"""
|
| 728 |
+
pass
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
@skip_if_no_numpydoc
|
| 732 |
+
def test_assert_docstring_consistency_error_msg():
|
| 733 |
+
"""Check `assert_docstring_consistency` difference message."""
|
| 734 |
+
msg = r"""The description of Parameter 'labels' is inconsistent between
|
| 735 |
+
\['f_four'\] and \['f_five'\] and \['f_six'\]:
|
| 736 |
+
|
| 737 |
+
\*\*\* \['f_four'\]
|
| 738 |
+
--- \['f_five'\]
|
| 739 |
+
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
|
| 740 |
+
|
| 741 |
+
\*\*\* 10,25 \*\*\*\*
|
| 742 |
+
|
| 743 |
+
--- 10,30 ----
|
| 744 |
+
|
| 745 |
+
'binary'`, and their order if `average is None`.
|
| 746 |
+
\+ This is an extra line.
|
| 747 |
+
Labels present in the data can be excluded.
|
| 748 |
+
|
| 749 |
+
\*\*\* \['f_four'\]
|
| 750 |
+
--- \['f_six'\]
|
| 751 |
+
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
|
| 752 |
+
|
| 753 |
+
\*\*\* 1,25 \*\*\*\*
|
| 754 |
+
|
| 755 |
+
The
|
| 756 |
+
! set
|
| 757 |
+
of labels to
|
| 758 |
+
! include
|
| 759 |
+
when `average != 'binary'`, and
|
| 760 |
+
! their
|
| 761 |
+
order if `average is None`. Labels present
|
| 762 |
+
! in the data
|
| 763 |
+
can be excluded.
|
| 764 |
+
--- 1,25 ----
|
| 765 |
+
|
| 766 |
+
The
|
| 767 |
+
! group
|
| 768 |
+
of labels to
|
| 769 |
+
! add
|
| 770 |
+
when `average != 'binary'`, and
|
| 771 |
+
! the
|
| 772 |
+
order if `average is None`. Labels present
|
| 773 |
+
! on them datas
|
| 774 |
+
can be excluded."""
|
| 775 |
+
|
| 776 |
+
with pytest.raises(AssertionError, match=msg):
|
| 777 |
+
assert_docstring_consistency([f_four, f_five, f_six], include_params=True)
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
@skip_if_no_numpydoc
|
| 781 |
+
def test_assert_docstring_consistency_descr_regex_pattern():
|
| 782 |
+
"""Check `assert_docstring_consistency` `descr_regex_pattern` works."""
|
| 783 |
+
# Check regex that matches full parameter descriptions
|
| 784 |
+
regex_full = (
|
| 785 |
+
r"The (set|group) " # match 'set' or 'group'
|
| 786 |
+
r"of labels to (include|add) " # match 'include' or 'add'
|
| 787 |
+
r"when `average \!\= 'binary'`, and (their|the) " # match 'their' or 'the'
|
| 788 |
+
r"order if `average is None`\."
|
| 789 |
+
r"[\s\w]*\.* " # optionally match additional sentence
|
| 790 |
+
r"Labels present (on|in) " # match 'on' or 'in'
|
| 791 |
+
r"(them|the) " # match 'them' or 'the'
|
| 792 |
+
r"datas? can be excluded\." # match 'data' or 'datas'
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
assert_docstring_consistency(
|
| 796 |
+
[f_four, f_five, f_six],
|
| 797 |
+
include_params=True,
|
| 798 |
+
descr_regex_pattern=" ".join(regex_full.split()),
|
| 799 |
+
)
|
| 800 |
+
# Check we can just match a few alternate words
|
| 801 |
+
regex_words = r"(labels|average|binary)" # match any of these 3 words
|
| 802 |
+
assert_docstring_consistency(
|
| 803 |
+
[f_four, f_five, f_six],
|
| 804 |
+
include_params=True,
|
| 805 |
+
descr_regex_pattern=" ".join(regex_words.split()),
|
| 806 |
+
)
|
| 807 |
+
# Check error raised when regex doesn't match
|
| 808 |
+
regex_error = r"The set of labels to include when.+"
|
| 809 |
+
msg = r"The description of Parameter 'labels' in \['f_six'\] does not match"
|
| 810 |
+
with pytest.raises(AssertionError, match=msg):
|
| 811 |
+
assert_docstring_consistency(
|
| 812 |
+
[f_four, f_five, f_six],
|
| 813 |
+
include_params=True,
|
| 814 |
+
descr_regex_pattern=" ".join(regex_error.split()),
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
class RegistrationCounter:
|
| 819 |
+
def __init__(self):
|
| 820 |
+
self.nb_calls = 0
|
| 821 |
+
|
| 822 |
+
def __call__(self, to_register_func):
|
| 823 |
+
self.nb_calls += 1
|
| 824 |
+
assert to_register_func.func is _delete_folder
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def check_memmap(input_array, mmap_data, mmap_mode="r"):
|
| 828 |
+
assert isinstance(mmap_data, np.memmap)
|
| 829 |
+
writeable = mmap_mode != "r"
|
| 830 |
+
assert mmap_data.flags.writeable is writeable
|
| 831 |
+
np.testing.assert_array_equal(input_array, mmap_data)
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def test_tempmemmap(monkeypatch):
|
| 835 |
+
registration_counter = RegistrationCounter()
|
| 836 |
+
monkeypatch.setattr(atexit, "register", registration_counter)
|
| 837 |
+
|
| 838 |
+
input_array = np.ones(3)
|
| 839 |
+
with TempMemmap(input_array) as data:
|
| 840 |
+
check_memmap(input_array, data)
|
| 841 |
+
temp_folder = os.path.dirname(data.filename)
|
| 842 |
+
if os.name != "nt":
|
| 843 |
+
assert not os.path.exists(temp_folder)
|
| 844 |
+
assert registration_counter.nb_calls == 1
|
| 845 |
+
|
| 846 |
+
mmap_mode = "r+"
|
| 847 |
+
with TempMemmap(input_array, mmap_mode=mmap_mode) as data:
|
| 848 |
+
check_memmap(input_array, data, mmap_mode=mmap_mode)
|
| 849 |
+
temp_folder = os.path.dirname(data.filename)
|
| 850 |
+
if os.name != "nt":
|
| 851 |
+
assert not os.path.exists(temp_folder)
|
| 852 |
+
assert registration_counter.nb_calls == 2
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def test_create_memmap_backed_data(monkeypatch):
|
| 856 |
+
registration_counter = RegistrationCounter()
|
| 857 |
+
monkeypatch.setattr(atexit, "register", registration_counter)
|
| 858 |
+
|
| 859 |
+
input_array = np.ones(3)
|
| 860 |
+
data = create_memmap_backed_data(input_array)
|
| 861 |
+
check_memmap(input_array, data)
|
| 862 |
+
assert registration_counter.nb_calls == 1
|
| 863 |
+
|
| 864 |
+
data, folder = create_memmap_backed_data(input_array, return_folder=True)
|
| 865 |
+
check_memmap(input_array, data)
|
| 866 |
+
assert folder == os.path.dirname(data.filename)
|
| 867 |
+
assert registration_counter.nb_calls == 2
|
| 868 |
+
|
| 869 |
+
mmap_mode = "r+"
|
| 870 |
+
data = create_memmap_backed_data(input_array, mmap_mode=mmap_mode)
|
| 871 |
+
check_memmap(input_array, data, mmap_mode)
|
| 872 |
+
assert registration_counter.nb_calls == 3
|
| 873 |
+
|
| 874 |
+
input_list = [input_array, input_array + 1, input_array + 2]
|
| 875 |
+
mmap_data_list = create_memmap_backed_data(input_list)
|
| 876 |
+
for input_array, data in zip(input_list, mmap_data_list):
|
| 877 |
+
check_memmap(input_array, data)
|
| 878 |
+
assert registration_counter.nb_calls == 4
|
| 879 |
+
|
| 880 |
+
output_data, other = create_memmap_backed_data([input_array, "not-an-array"])
|
| 881 |
+
check_memmap(input_array, output_data)
|
| 882 |
+
assert other == "not-an-array"
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
@pytest.mark.parametrize(
|
| 886 |
+
"constructor_name, container_type",
|
| 887 |
+
[
|
| 888 |
+
("list", list),
|
| 889 |
+
("tuple", tuple),
|
| 890 |
+
("array", np.ndarray),
|
| 891 |
+
("sparse", sparse.csr_matrix),
|
| 892 |
+
# using `zip` will only keep the available sparse containers
|
| 893 |
+
# depending of the installed SciPy version
|
| 894 |
+
*zip(["sparse_csr", "sparse_csr_array"], CSR_CONTAINERS),
|
| 895 |
+
*zip(["sparse_csc", "sparse_csc_array"], CSC_CONTAINERS),
|
| 896 |
+
("dataframe", lambda: pytest.importorskip("pandas").DataFrame),
|
| 897 |
+
("series", lambda: pytest.importorskip("pandas").Series),
|
| 898 |
+
("index", lambda: pytest.importorskip("pandas").Index),
|
| 899 |
+
("pyarrow", lambda: pytest.importorskip("pyarrow").Table),
|
| 900 |
+
("pyarrow_array", lambda: pytest.importorskip("pyarrow").Array),
|
| 901 |
+
("polars", lambda: pytest.importorskip("polars").DataFrame),
|
| 902 |
+
("polars_series", lambda: pytest.importorskip("polars").Series),
|
| 903 |
+
("slice", slice),
|
| 904 |
+
],
|
| 905 |
+
)
|
| 906 |
+
@pytest.mark.parametrize(
|
| 907 |
+
"dtype, superdtype",
|
| 908 |
+
[
|
| 909 |
+
(np.int32, np.integer),
|
| 910 |
+
(np.int64, np.integer),
|
| 911 |
+
(np.float32, np.floating),
|
| 912 |
+
(np.float64, np.floating),
|
| 913 |
+
],
|
| 914 |
+
)
|
| 915 |
+
def test_convert_container(
|
| 916 |
+
constructor_name,
|
| 917 |
+
container_type,
|
| 918 |
+
dtype,
|
| 919 |
+
superdtype,
|
| 920 |
+
):
|
| 921 |
+
"""Check that we convert the container to the right type of array with the
|
| 922 |
+
right data type."""
|
| 923 |
+
if constructor_name in (
|
| 924 |
+
"dataframe",
|
| 925 |
+
"index",
|
| 926 |
+
"polars",
|
| 927 |
+
"polars_series",
|
| 928 |
+
"pyarrow",
|
| 929 |
+
"pyarrow_array",
|
| 930 |
+
"series",
|
| 931 |
+
):
|
| 932 |
+
# delay the import of pandas/polars within the function to only skip this test
|
| 933 |
+
# instead of the whole file
|
| 934 |
+
container_type = container_type()
|
| 935 |
+
container = [0, 1]
|
| 936 |
+
|
| 937 |
+
container_converted = _convert_container(
|
| 938 |
+
container,
|
| 939 |
+
constructor_name,
|
| 940 |
+
dtype=dtype,
|
| 941 |
+
)
|
| 942 |
+
assert isinstance(container_converted, container_type)
|
| 943 |
+
|
| 944 |
+
if constructor_name in ("list", "tuple", "index"):
|
| 945 |
+
# list and tuple will use Python class dtype: int, float
|
| 946 |
+
# pandas index will always use high precision: np.int64 and np.float64
|
| 947 |
+
assert np.issubdtype(type(container_converted[0]), superdtype)
|
| 948 |
+
elif constructor_name in ("polars", "polars_series", "pyarrow", "pyarrow_array"):
|
| 949 |
+
return
|
| 950 |
+
elif hasattr(container_converted, "dtype"):
|
| 951 |
+
assert container_converted.dtype == dtype
|
| 952 |
+
elif hasattr(container_converted, "dtypes"):
|
| 953 |
+
assert container_converted.dtypes[0] == dtype
|
| 954 |
+
|
| 955 |
+
|
| 956 |
+
def test_convert_container_categories_pandas():
|
| 957 |
+
pytest.importorskip("pandas")
|
| 958 |
+
df = _convert_container(
|
| 959 |
+
[["x"]], "dataframe", ["A"], categorical_feature_names=["A"]
|
| 960 |
+
)
|
| 961 |
+
assert df.dtypes.iloc[0] == "category"
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
def test_convert_container_categories_polars():
|
| 965 |
+
pl = pytest.importorskip("polars")
|
| 966 |
+
df = _convert_container([["x"]], "polars", ["A"], categorical_feature_names=["A"])
|
| 967 |
+
assert df.schema["A"] == pl.Categorical()
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
def test_convert_container_categories_pyarrow():
|
| 971 |
+
pa = pytest.importorskip("pyarrow")
|
| 972 |
+
df = _convert_container([["x"]], "pyarrow", ["A"], categorical_feature_names=["A"])
|
| 973 |
+
assert type(df.schema[0].type) is pa.DictionaryType
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
def test_raises():
|
| 977 |
+
# Tests for the raises context manager
|
| 978 |
+
|
| 979 |
+
# Proper type, no match
|
| 980 |
+
with raises(TypeError):
|
| 981 |
+
raise TypeError()
|
| 982 |
+
|
| 983 |
+
# Proper type, proper match
|
| 984 |
+
with raises(TypeError, match="how are you") as cm:
|
| 985 |
+
raise TypeError("hello how are you")
|
| 986 |
+
assert cm.raised_and_matched
|
| 987 |
+
|
| 988 |
+
# Proper type, proper match with multiple patterns
|
| 989 |
+
with raises(TypeError, match=["not this one", "how are you"]) as cm:
|
| 990 |
+
raise TypeError("hello how are you")
|
| 991 |
+
assert cm.raised_and_matched
|
| 992 |
+
|
| 993 |
+
# bad type, no match
|
| 994 |
+
with pytest.raises(ValueError, match="this will be raised"):
|
| 995 |
+
with raises(TypeError) as cm:
|
| 996 |
+
raise ValueError("this will be raised")
|
| 997 |
+
assert not cm.raised_and_matched
|
| 998 |
+
|
| 999 |
+
# Bad type, no match, with an err_msg
|
| 1000 |
+
with pytest.raises(AssertionError, match="the failure message"):
|
| 1001 |
+
with raises(TypeError, err_msg="the failure message") as cm:
|
| 1002 |
+
raise ValueError()
|
| 1003 |
+
assert not cm.raised_and_matched
|
| 1004 |
+
|
| 1005 |
+
# bad type, with match (is ignored anyway)
|
| 1006 |
+
with pytest.raises(ValueError, match="this will be raised"):
|
| 1007 |
+
with raises(TypeError, match="this is ignored") as cm:
|
| 1008 |
+
raise ValueError("this will be raised")
|
| 1009 |
+
assert not cm.raised_and_matched
|
| 1010 |
+
|
| 1011 |
+
# proper type but bad match
|
| 1012 |
+
with pytest.raises(
|
| 1013 |
+
AssertionError, match="should contain one of the following patterns"
|
| 1014 |
+
):
|
| 1015 |
+
with raises(TypeError, match="hello") as cm:
|
| 1016 |
+
raise TypeError("Bad message")
|
| 1017 |
+
assert not cm.raised_and_matched
|
| 1018 |
+
|
| 1019 |
+
# proper type but bad match, with err_msg
|
| 1020 |
+
with pytest.raises(AssertionError, match="the failure message"):
|
| 1021 |
+
with raises(TypeError, match="hello", err_msg="the failure message") as cm:
|
| 1022 |
+
raise TypeError("Bad message")
|
| 1023 |
+
assert not cm.raised_and_matched
|
| 1024 |
+
|
| 1025 |
+
# no raise with default may_pass=False
|
| 1026 |
+
with pytest.raises(AssertionError, match="Did not raise"):
|
| 1027 |
+
with raises(TypeError) as cm:
|
| 1028 |
+
pass
|
| 1029 |
+
assert not cm.raised_and_matched
|
| 1030 |
+
|
| 1031 |
+
# no raise with may_pass=True
|
| 1032 |
+
with raises(TypeError, match="hello", may_pass=True) as cm:
|
| 1033 |
+
pass # still OK
|
| 1034 |
+
assert not cm.raised_and_matched
|
| 1035 |
+
|
| 1036 |
+
# Multiple exception types:
|
| 1037 |
+
with raises((TypeError, ValueError)):
|
| 1038 |
+
raise TypeError()
|
| 1039 |
+
with raises((TypeError, ValueError)):
|
| 1040 |
+
raise ValueError()
|
| 1041 |
+
with pytest.raises(AssertionError):
|
| 1042 |
+
with raises((TypeError, ValueError)):
|
| 1043 |
+
pass
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
def test_float32_aware_assert_allclose():
|
| 1047 |
+
# The relative tolerance for float32 inputs is 1e-4
|
| 1048 |
+
assert_allclose(np.array([1.0 + 2e-5], dtype=np.float32), 1.0)
|
| 1049 |
+
with pytest.raises(AssertionError):
|
| 1050 |
+
assert_allclose(np.array([1.0 + 2e-4], dtype=np.float32), 1.0)
|
| 1051 |
+
|
| 1052 |
+
# The relative tolerance for other inputs is left to 1e-7 as in
|
| 1053 |
+
# the original numpy version.
|
| 1054 |
+
assert_allclose(np.array([1.0 + 2e-8], dtype=np.float64), 1.0)
|
| 1055 |
+
with pytest.raises(AssertionError):
|
| 1056 |
+
assert_allclose(np.array([1.0 + 2e-7], dtype=np.float64), 1.0)
|
| 1057 |
+
|
| 1058 |
+
# atol is left to 0.0 by default, even for float32
|
| 1059 |
+
with pytest.raises(AssertionError):
|
| 1060 |
+
assert_allclose(np.array([1e-5], dtype=np.float32), 0.0)
|
| 1061 |
+
assert_allclose(np.array([1e-5], dtype=np.float32), 0.0, atol=2e-5)
|
| 1062 |
+
|
| 1063 |
+
|
| 1064 |
+
@pytest.mark.xfail(_IS_WASM, reason="cannot start subprocess")
|
| 1065 |
+
def test_assert_run_python_script_without_output():
|
| 1066 |
+
code = "x = 1"
|
| 1067 |
+
assert_run_python_script_without_output(code)
|
| 1068 |
+
|
| 1069 |
+
code = "print('something to stdout')"
|
| 1070 |
+
with pytest.raises(AssertionError, match="Expected no output"):
|
| 1071 |
+
assert_run_python_script_without_output(code)
|
| 1072 |
+
|
| 1073 |
+
code = "print('something to stdout')"
|
| 1074 |
+
with pytest.raises(
|
| 1075 |
+
AssertionError,
|
| 1076 |
+
match="output was not supposed to match.+got.+something to stdout",
|
| 1077 |
+
):
|
| 1078 |
+
assert_run_python_script_without_output(code, pattern="to.+stdout")
|
| 1079 |
+
|
| 1080 |
+
code = "\n".join(["import sys", "print('something to stderr', file=sys.stderr)"])
|
| 1081 |
+
with pytest.raises(
|
| 1082 |
+
AssertionError,
|
| 1083 |
+
match="output was not supposed to match.+got.+something to stderr",
|
| 1084 |
+
):
|
| 1085 |
+
assert_run_python_script_without_output(code, pattern="to.+stderr")
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
@pytest.mark.parametrize(
|
| 1089 |
+
"constructor_name",
|
| 1090 |
+
[
|
| 1091 |
+
"sparse_csr",
|
| 1092 |
+
"sparse_csc",
|
| 1093 |
+
pytest.param(
|
| 1094 |
+
"sparse_csr_array",
|
| 1095 |
+
),
|
| 1096 |
+
pytest.param(
|
| 1097 |
+
"sparse_csc_array",
|
| 1098 |
+
),
|
| 1099 |
+
],
|
| 1100 |
+
)
|
| 1101 |
+
def test_convert_container_sparse_to_sparse(constructor_name):
|
| 1102 |
+
"""Non-regression test to check that we can still convert a sparse container
|
| 1103 |
+
from a given format to another format.
|
| 1104 |
+
"""
|
| 1105 |
+
X_sparse = sparse.random(10, 10, density=0.1, format="csr")
|
| 1106 |
+
_convert_container(X_sparse, constructor_name)
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
def check_warnings_as_errors(warning_info, warnings_as_errors):
|
| 1110 |
+
if warning_info.action == "error" and warnings_as_errors:
|
| 1111 |
+
with pytest.raises(warning_info.category, match=warning_info.message):
|
| 1112 |
+
warnings.warn(
|
| 1113 |
+
message=warning_info.message,
|
| 1114 |
+
category=warning_info.category,
|
| 1115 |
+
)
|
| 1116 |
+
if warning_info.action == "ignore":
|
| 1117 |
+
with warnings.catch_warnings(record=True) as record:
|
| 1118 |
+
message = warning_info.message
|
| 1119 |
+
# Special treatment when regex is used
|
| 1120 |
+
if "Pyarrow" in message:
|
| 1121 |
+
message = "\nPyarrow will become a required dependency"
|
| 1122 |
+
|
| 1123 |
+
warnings.warn(
|
| 1124 |
+
message=message,
|
| 1125 |
+
category=warning_info.category,
|
| 1126 |
+
)
|
| 1127 |
+
assert len(record) == 0 if warnings_as_errors else 1
|
| 1128 |
+
if record:
|
| 1129 |
+
assert str(record[0].message) == message
|
| 1130 |
+
assert record[0].category == warning_info.category
|
| 1131 |
+
|
| 1132 |
+
|
| 1133 |
+
@pytest.mark.parametrize("warning_info", _get_warnings_filters_info_list())
|
| 1134 |
+
def test_sklearn_warnings_as_errors(warning_info):
|
| 1135 |
+
warnings_as_errors = os.environ.get("SKLEARN_WARNINGS_AS_ERRORS", "0") != "0"
|
| 1136 |
+
check_warnings_as_errors(warning_info, warnings_as_errors=warnings_as_errors)
|
| 1137 |
+
|
| 1138 |
+
|
| 1139 |
+
@pytest.mark.parametrize("warning_info", _get_warnings_filters_info_list())
|
| 1140 |
+
def test_turn_warnings_into_errors(warning_info):
|
| 1141 |
+
with warnings.catch_warnings():
|
| 1142 |
+
turn_warnings_into_errors()
|
| 1143 |
+
check_warnings_as_errors(warning_info, warnings_as_errors=True)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_typedefs.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from sklearn.utils._typedefs import testing_make_array_from_typed_val
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.parametrize(
|
| 8 |
+
"type_t, value, expected_dtype",
|
| 9 |
+
[
|
| 10 |
+
("float64_t", 1.0, np.float64),
|
| 11 |
+
("float32_t", 1.0, np.float32),
|
| 12 |
+
("intp_t", 1, np.intp),
|
| 13 |
+
("int8_t", 1, np.int8),
|
| 14 |
+
("int32_t", 1, np.int32),
|
| 15 |
+
("int64_t", 1, np.int64),
|
| 16 |
+
("uint8_t", 1, np.uint8),
|
| 17 |
+
("uint32_t", 1, np.uint32),
|
| 18 |
+
("uint64_t", 1, np.uint64),
|
| 19 |
+
],
|
| 20 |
+
)
|
| 21 |
+
def test_types(type_t, value, expected_dtype):
|
| 22 |
+
"""Check that the types defined in _typedefs correspond to the expected
|
| 23 |
+
numpy dtypes.
|
| 24 |
+
"""
|
| 25 |
+
assert testing_make_array_from_typed_val[type_t](value).dtype == expected_dtype
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_unique.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numpy.testing import assert_array_equal
|
| 3 |
+
|
| 4 |
+
from sklearn.utils._unique import attach_unique, cached_unique
|
| 5 |
+
from sklearn.utils.validation import check_array
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def 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 |
+
|
| 15 |
+
def 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 |
+
|
| 21 |
+
def 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 |
+
|
| 28 |
+
def 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 |
+
|
| 35 |
+
def 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 |
+
|
| 48 |
+
def 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)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_user_interface.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import string
|
| 2 |
+
import timeit
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from sklearn.utils._user_interface import _message_with_time, _print_elapsed_time
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.mark.parametrize(
|
| 10 |
+
["source", "message", "is_long"],
|
| 11 |
+
[
|
| 12 |
+
("ABC", string.ascii_lowercase, False),
|
| 13 |
+
("ABCDEF", string.ascii_lowercase, False),
|
| 14 |
+
("ABC", string.ascii_lowercase * 3, True),
|
| 15 |
+
("ABC" * 10, string.ascii_lowercase, True),
|
| 16 |
+
("ABC", string.ascii_lowercase + "\u1048", False),
|
| 17 |
+
],
|
| 18 |
+
)
|
| 19 |
+
@pytest.mark.parametrize(
|
| 20 |
+
["time", "time_str"],
|
| 21 |
+
[
|
| 22 |
+
(0.2, " 0.2s"),
|
| 23 |
+
(20, " 20.0s"),
|
| 24 |
+
(2000, "33.3min"),
|
| 25 |
+
(20000, "333.3min"),
|
| 26 |
+
],
|
| 27 |
+
)
|
| 28 |
+
def test_message_with_time(source, message, is_long, time, time_str):
|
| 29 |
+
out = _message_with_time(source, message, time)
|
| 30 |
+
if is_long:
|
| 31 |
+
assert len(out) > 70
|
| 32 |
+
else:
|
| 33 |
+
assert len(out) == 70
|
| 34 |
+
|
| 35 |
+
assert out.startswith("[" + source + "] ")
|
| 36 |
+
out = out[len(source) + 3 :]
|
| 37 |
+
|
| 38 |
+
assert out.endswith(time_str)
|
| 39 |
+
out = out[: -len(time_str)]
|
| 40 |
+
assert out.endswith(", total=")
|
| 41 |
+
out = out[: -len(", total=")]
|
| 42 |
+
assert out.endswith(message)
|
| 43 |
+
out = out[: -len(message)]
|
| 44 |
+
assert out.endswith(" ")
|
| 45 |
+
out = out[:-1]
|
| 46 |
+
|
| 47 |
+
if is_long:
|
| 48 |
+
assert not out
|
| 49 |
+
else:
|
| 50 |
+
assert list(set(out)) == ["."]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@pytest.mark.parametrize(
|
| 54 |
+
["message", "expected"],
|
| 55 |
+
[
|
| 56 |
+
("hello", _message_with_time("ABC", "hello", 0.1) + "\n"),
|
| 57 |
+
("", _message_with_time("ABC", "", 0.1) + "\n"),
|
| 58 |
+
(None, ""),
|
| 59 |
+
],
|
| 60 |
+
)
|
| 61 |
+
def test_print_elapsed_time(message, expected, capsys, monkeypatch):
|
| 62 |
+
monkeypatch.setattr(timeit, "default_timer", lambda: 0)
|
| 63 |
+
with _print_elapsed_time("ABC", message):
|
| 64 |
+
monkeypatch.setattr(timeit, "default_timer", lambda: 0.1)
|
| 65 |
+
assert capsys.readouterr().out == expected
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_validation.py
ADDED
|
@@ -0,0 +1,2357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for input validation functions"""
|
| 2 |
+
|
| 3 |
+
import numbers
|
| 4 |
+
import re
|
| 5 |
+
import warnings
|
| 6 |
+
from itertools import product
|
| 7 |
+
from operator import itemgetter
|
| 8 |
+
from tempfile import NamedTemporaryFile
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pytest
|
| 12 |
+
import scipy.sparse as sp
|
| 13 |
+
from pytest import importorskip
|
| 14 |
+
|
| 15 |
+
import sklearn
|
| 16 |
+
from sklearn._config import config_context
|
| 17 |
+
from sklearn.base import BaseEstimator
|
| 18 |
+
from sklearn.datasets import make_blobs
|
| 19 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 20 |
+
from sklearn.exceptions import NotFittedError, PositiveSpectrumWarning
|
| 21 |
+
from sklearn.linear_model import ARDRegression
|
| 22 |
+
|
| 23 |
+
# TODO: add this estimator into the _mocking module in a further refactoring
|
| 24 |
+
from sklearn.metrics.tests.test_score_objects import EstimatorWithFit
|
| 25 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 26 |
+
from sklearn.random_projection import _sparse_random_matrix
|
| 27 |
+
from sklearn.svm import SVR
|
| 28 |
+
from sklearn.utils import (
|
| 29 |
+
_safe_indexing,
|
| 30 |
+
as_float_array,
|
| 31 |
+
check_array,
|
| 32 |
+
check_symmetric,
|
| 33 |
+
check_X_y,
|
| 34 |
+
deprecated,
|
| 35 |
+
)
|
| 36 |
+
from sklearn.utils._array_api import (
|
| 37 |
+
_convert_to_numpy,
|
| 38 |
+
_get_namespace_device_dtype_ids,
|
| 39 |
+
_is_numpy_namespace,
|
| 40 |
+
yield_namespace_device_dtype_combinations,
|
| 41 |
+
)
|
| 42 |
+
from sklearn.utils._mocking import (
|
| 43 |
+
MockDataFrame,
|
| 44 |
+
_MockEstimatorOnOffPrediction,
|
| 45 |
+
)
|
| 46 |
+
from sklearn.utils._testing import (
|
| 47 |
+
SkipTest,
|
| 48 |
+
TempMemmap,
|
| 49 |
+
_array_api_for_tests,
|
| 50 |
+
_convert_container,
|
| 51 |
+
assert_allclose,
|
| 52 |
+
assert_allclose_dense_sparse,
|
| 53 |
+
assert_array_equal,
|
| 54 |
+
create_memmap_backed_data,
|
| 55 |
+
skip_if_array_api_compat_not_configured,
|
| 56 |
+
)
|
| 57 |
+
from sklearn.utils.estimator_checks import _NotAnArray
|
| 58 |
+
from sklearn.utils.fixes import (
|
| 59 |
+
COO_CONTAINERS,
|
| 60 |
+
CSC_CONTAINERS,
|
| 61 |
+
CSR_CONTAINERS,
|
| 62 |
+
DIA_CONTAINERS,
|
| 63 |
+
DOK_CONTAINERS,
|
| 64 |
+
)
|
| 65 |
+
from sklearn.utils.validation import (
|
| 66 |
+
FLOAT_DTYPES,
|
| 67 |
+
_allclose_dense_sparse,
|
| 68 |
+
_check_feature_names_in,
|
| 69 |
+
_check_method_params,
|
| 70 |
+
_check_pos_label_consistency,
|
| 71 |
+
_check_psd_eigenvalues,
|
| 72 |
+
_check_response_method,
|
| 73 |
+
_check_sample_weight,
|
| 74 |
+
_check_y,
|
| 75 |
+
_deprecate_positional_args,
|
| 76 |
+
_estimator_has,
|
| 77 |
+
_get_feature_names,
|
| 78 |
+
_is_fitted,
|
| 79 |
+
_num_features,
|
| 80 |
+
_num_samples,
|
| 81 |
+
_to_object_array,
|
| 82 |
+
assert_all_finite,
|
| 83 |
+
check_consistent_length,
|
| 84 |
+
check_is_fitted,
|
| 85 |
+
check_memory,
|
| 86 |
+
check_non_negative,
|
| 87 |
+
check_random_state,
|
| 88 |
+
check_scalar,
|
| 89 |
+
column_or_1d,
|
| 90 |
+
has_fit_parameter,
|
| 91 |
+
validate_data,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_make_rng():
|
| 96 |
+
# Check the check_random_state utility function behavior
|
| 97 |
+
assert check_random_state(None) is np.random.mtrand._rand
|
| 98 |
+
assert check_random_state(np.random) is np.random.mtrand._rand
|
| 99 |
+
|
| 100 |
+
rng_42 = np.random.RandomState(42)
|
| 101 |
+
assert check_random_state(42).randint(100) == rng_42.randint(100)
|
| 102 |
+
|
| 103 |
+
rng_42 = np.random.RandomState(42)
|
| 104 |
+
assert check_random_state(rng_42) is rng_42
|
| 105 |
+
|
| 106 |
+
rng_42 = np.random.RandomState(42)
|
| 107 |
+
assert check_random_state(43).randint(100) != rng_42.randint(100)
|
| 108 |
+
|
| 109 |
+
with pytest.raises(ValueError):
|
| 110 |
+
check_random_state("some invalid seed")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_as_float_array():
|
| 114 |
+
# Test function for as_float_array
|
| 115 |
+
X = np.ones((3, 10), dtype=np.int32)
|
| 116 |
+
X = X + np.arange(10, dtype=np.int32)
|
| 117 |
+
X2 = as_float_array(X, copy=False)
|
| 118 |
+
assert X2.dtype == np.float32
|
| 119 |
+
# Another test
|
| 120 |
+
X = X.astype(np.int64)
|
| 121 |
+
X2 = as_float_array(X, copy=True)
|
| 122 |
+
# Checking that the array wasn't overwritten
|
| 123 |
+
assert as_float_array(X, copy=False) is not X
|
| 124 |
+
assert X2.dtype == np.float64
|
| 125 |
+
# Test int dtypes <= 32bit
|
| 126 |
+
tested_dtypes = [bool, np.int8, np.int16, np.int32, np.uint8, np.uint16, np.uint32]
|
| 127 |
+
for dtype in tested_dtypes:
|
| 128 |
+
X = X.astype(dtype)
|
| 129 |
+
X2 = as_float_array(X)
|
| 130 |
+
assert X2.dtype == np.float32
|
| 131 |
+
|
| 132 |
+
# Test object dtype
|
| 133 |
+
X = X.astype(object)
|
| 134 |
+
X2 = as_float_array(X, copy=True)
|
| 135 |
+
assert X2.dtype == np.float64
|
| 136 |
+
|
| 137 |
+
# Here, X is of the right type, it shouldn't be modified
|
| 138 |
+
X = np.ones((3, 2), dtype=np.float32)
|
| 139 |
+
assert as_float_array(X, copy=False) is X
|
| 140 |
+
# Test that if X is fortran ordered it stays
|
| 141 |
+
X = np.asfortranarray(X)
|
| 142 |
+
assert np.isfortran(as_float_array(X, copy=True))
|
| 143 |
+
|
| 144 |
+
# Test the copy parameter with some matrices
|
| 145 |
+
matrices = [
|
| 146 |
+
sp.csc_matrix(np.arange(5)).toarray(),
|
| 147 |
+
_sparse_random_matrix(10, 10, density=0.10).toarray(),
|
| 148 |
+
]
|
| 149 |
+
for M in matrices:
|
| 150 |
+
N = as_float_array(M, copy=True)
|
| 151 |
+
N[0, 0] = np.nan
|
| 152 |
+
assert not np.isnan(M).any()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@pytest.mark.parametrize(
|
| 156 |
+
"X", [np.random.random((10, 2)), sp.random(10, 2, format="csr")]
|
| 157 |
+
)
|
| 158 |
+
def test_as_float_array_nan(X):
|
| 159 |
+
X = X.copy()
|
| 160 |
+
X[5, 0] = np.nan
|
| 161 |
+
X[6, 1] = np.nan
|
| 162 |
+
X_converted = as_float_array(X, ensure_all_finite="allow-nan")
|
| 163 |
+
assert_allclose_dense_sparse(X_converted, X)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_np_matrix():
|
| 167 |
+
# Confirm that input validation code does not return np.matrix
|
| 168 |
+
X = np.arange(12).reshape(3, 4)
|
| 169 |
+
|
| 170 |
+
assert not isinstance(as_float_array(X), np.matrix)
|
| 171 |
+
assert not isinstance(as_float_array(sp.csc_matrix(X)), np.matrix)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def test_memmap():
|
| 175 |
+
# Confirm that input validation code doesn't copy memory mapped arrays
|
| 176 |
+
|
| 177 |
+
asflt = lambda x: as_float_array(x, copy=False)
|
| 178 |
+
|
| 179 |
+
with NamedTemporaryFile(prefix="sklearn-test") as tmp:
|
| 180 |
+
M = np.memmap(tmp, shape=(10, 10), dtype=np.float32)
|
| 181 |
+
M[:] = 0
|
| 182 |
+
|
| 183 |
+
for f in (check_array, np.asarray, asflt):
|
| 184 |
+
X = f(M)
|
| 185 |
+
X[:] = 1
|
| 186 |
+
assert_array_equal(X.ravel(), M.ravel())
|
| 187 |
+
X[:] = 0
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_ordering():
|
| 191 |
+
# Check that ordering is enforced correctly by validation utilities.
|
| 192 |
+
# We need to check each validation utility, because a 'copy' without
|
| 193 |
+
# 'order=K' will kill the ordering.
|
| 194 |
+
X = np.ones((10, 5))
|
| 195 |
+
for A in X, X.T:
|
| 196 |
+
for copy in (True, False):
|
| 197 |
+
B = check_array(A, order="C", copy=copy)
|
| 198 |
+
assert B.flags["C_CONTIGUOUS"]
|
| 199 |
+
B = check_array(A, order="F", copy=copy)
|
| 200 |
+
assert B.flags["F_CONTIGUOUS"]
|
| 201 |
+
if copy:
|
| 202 |
+
assert A is not B
|
| 203 |
+
|
| 204 |
+
X = sp.csr_matrix(X)
|
| 205 |
+
X.data = X.data[::-1]
|
| 206 |
+
assert not X.data.flags["C_CONTIGUOUS"]
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@pytest.mark.parametrize(
|
| 210 |
+
"value, ensure_all_finite",
|
| 211 |
+
[(np.inf, False), (np.nan, "allow-nan"), (np.nan, False)],
|
| 212 |
+
)
|
| 213 |
+
@pytest.mark.parametrize("retype", [np.asarray, sp.csr_matrix])
|
| 214 |
+
def test_check_array_ensure_all_finite_valid(value, ensure_all_finite, retype):
|
| 215 |
+
X = retype(np.arange(4).reshape(2, 2).astype(float))
|
| 216 |
+
X[0, 0] = value
|
| 217 |
+
X_checked = check_array(X, ensure_all_finite=ensure_all_finite, accept_sparse=True)
|
| 218 |
+
assert_allclose_dense_sparse(X, X_checked)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@pytest.mark.parametrize(
|
| 222 |
+
"value, input_name, ensure_all_finite, match_msg",
|
| 223 |
+
[
|
| 224 |
+
(np.inf, "", True, "Input contains infinity"),
|
| 225 |
+
(np.inf, "X", True, "Input X contains infinity"),
|
| 226 |
+
(np.inf, "sample_weight", True, "Input sample_weight contains infinity"),
|
| 227 |
+
(np.inf, "X", "allow-nan", "Input X contains infinity"),
|
| 228 |
+
(np.nan, "", True, "Input contains NaN"),
|
| 229 |
+
(np.nan, "X", True, "Input X contains NaN"),
|
| 230 |
+
(np.nan, "y", True, "Input y contains NaN"),
|
| 231 |
+
(
|
| 232 |
+
np.nan,
|
| 233 |
+
"",
|
| 234 |
+
"allow-inf",
|
| 235 |
+
"ensure_all_finite should be a bool or 'allow-nan'",
|
| 236 |
+
),
|
| 237 |
+
(np.nan, "", 1, "Input contains NaN"),
|
| 238 |
+
],
|
| 239 |
+
)
|
| 240 |
+
@pytest.mark.parametrize("retype", [np.asarray, sp.csr_matrix])
|
| 241 |
+
def test_check_array_ensure_all_finite_invalid(
|
| 242 |
+
value, input_name, ensure_all_finite, match_msg, retype
|
| 243 |
+
):
|
| 244 |
+
X = retype(np.arange(4).reshape(2, 2).astype(np.float64))
|
| 245 |
+
X[0, 0] = value
|
| 246 |
+
with pytest.raises(ValueError, match=match_msg):
|
| 247 |
+
check_array(
|
| 248 |
+
X,
|
| 249 |
+
input_name=input_name,
|
| 250 |
+
ensure_all_finite=ensure_all_finite,
|
| 251 |
+
accept_sparse=True,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@pytest.mark.parametrize("input_name", ["X", "y", "sample_weight"])
|
| 256 |
+
@pytest.mark.parametrize("retype", [np.asarray, sp.csr_matrix])
|
| 257 |
+
def test_check_array_links_to_imputer_doc_only_for_X(input_name, retype):
|
| 258 |
+
data = retype(np.arange(4).reshape(2, 2).astype(np.float64))
|
| 259 |
+
data[0, 0] = np.nan
|
| 260 |
+
estimator = SVR()
|
| 261 |
+
extended_msg = (
|
| 262 |
+
f"\n{estimator.__class__.__name__} does not accept missing values"
|
| 263 |
+
" encoded as NaN natively. For supervised learning, you might want"
|
| 264 |
+
" to consider sklearn.ensemble.HistGradientBoostingClassifier and Regressor"
|
| 265 |
+
" which accept missing values encoded as NaNs natively."
|
| 266 |
+
" Alternatively, it is possible to preprocess the"
|
| 267 |
+
" data, for instance by using an imputer transformer in a pipeline"
|
| 268 |
+
" or drop samples with missing values. See"
|
| 269 |
+
" https://scikit-learn.org/stable/modules/impute.html"
|
| 270 |
+
" You can find a list of all estimators that handle NaN values"
|
| 271 |
+
" at the following page:"
|
| 272 |
+
" https://scikit-learn.org/stable/modules/impute.html"
|
| 273 |
+
"#estimators-that-handle-nan-values"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
with pytest.raises(ValueError, match=f"Input {input_name} contains NaN") as ctx:
|
| 277 |
+
check_array(
|
| 278 |
+
data,
|
| 279 |
+
estimator=estimator,
|
| 280 |
+
input_name=input_name,
|
| 281 |
+
accept_sparse=True,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
if input_name == "X":
|
| 285 |
+
assert extended_msg in ctx.value.args[0]
|
| 286 |
+
else:
|
| 287 |
+
assert extended_msg not in ctx.value.args[0]
|
| 288 |
+
|
| 289 |
+
if input_name == "X":
|
| 290 |
+
# Verify that _validate_data is automatically called with the right argument
|
| 291 |
+
# to generate the same exception:
|
| 292 |
+
with pytest.raises(ValueError, match=f"Input {input_name} contains NaN") as ctx:
|
| 293 |
+
SVR().fit(data, np.ones(data.shape[0]))
|
| 294 |
+
assert extended_msg in ctx.value.args[0]
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def test_check_array_ensure_all_finite_object():
|
| 298 |
+
X = np.array([["a", "b", np.nan]], dtype=object).T
|
| 299 |
+
|
| 300 |
+
X_checked = check_array(X, dtype=None, ensure_all_finite="allow-nan")
|
| 301 |
+
assert X is X_checked
|
| 302 |
+
|
| 303 |
+
X_checked = check_array(X, dtype=None, ensure_all_finite=False)
|
| 304 |
+
assert X is X_checked
|
| 305 |
+
|
| 306 |
+
with pytest.raises(ValueError, match="Input contains NaN"):
|
| 307 |
+
check_array(X, dtype=None, ensure_all_finite=True)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
@pytest.mark.parametrize(
|
| 311 |
+
"X, err_msg",
|
| 312 |
+
[
|
| 313 |
+
(
|
| 314 |
+
np.array([[1, np.nan]]),
|
| 315 |
+
"Input contains NaN.",
|
| 316 |
+
),
|
| 317 |
+
(
|
| 318 |
+
np.array([[1, np.nan]]),
|
| 319 |
+
"Input contains NaN.",
|
| 320 |
+
),
|
| 321 |
+
(
|
| 322 |
+
np.array([[1, np.inf]]),
|
| 323 |
+
"Input contains infinity or a value too large for.*int",
|
| 324 |
+
),
|
| 325 |
+
(np.array([[1, np.nan]], dtype=object), "cannot convert float NaN to integer"),
|
| 326 |
+
],
|
| 327 |
+
)
|
| 328 |
+
@pytest.mark.parametrize("ensure_all_finite", [True, False])
|
| 329 |
+
def test_check_array_ensure_all_finite_object_unsafe_casting(
|
| 330 |
+
X, err_msg, ensure_all_finite
|
| 331 |
+
):
|
| 332 |
+
# casting a float array containing NaN or inf to int dtype should
|
| 333 |
+
# raise an error irrespective of the ensure_all_finite parameter.
|
| 334 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 335 |
+
check_array(X, dtype=int, ensure_all_finite=ensure_all_finite)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def test_check_array_series_err_msg():
|
| 339 |
+
"""
|
| 340 |
+
Check that we raise a proper error message when passing a Series and we expect a
|
| 341 |
+
2-dimensional container.
|
| 342 |
+
|
| 343 |
+
Non-regression test for:
|
| 344 |
+
https://github.com/scikit-learn/scikit-learn/issues/27498
|
| 345 |
+
"""
|
| 346 |
+
pd = pytest.importorskip("pandas")
|
| 347 |
+
ser = pd.Series([1, 2, 3])
|
| 348 |
+
msg = f"Expected a 2-dimensional container but got {type(ser)} instead."
|
| 349 |
+
with pytest.raises(ValueError, match=msg):
|
| 350 |
+
check_array(ser, ensure_2d=True)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
@pytest.mark.filterwarnings("ignore:Can't check dok sparse matrix for nan or inf")
|
| 354 |
+
def test_check_array():
|
| 355 |
+
# accept_sparse == False
|
| 356 |
+
# raise error on sparse inputs
|
| 357 |
+
X = [[1, 2], [3, 4]]
|
| 358 |
+
X_csr = sp.csr_matrix(X)
|
| 359 |
+
with pytest.raises(TypeError):
|
| 360 |
+
check_array(X_csr)
|
| 361 |
+
|
| 362 |
+
# ensure_2d=False
|
| 363 |
+
X_array = check_array([0, 1, 2], ensure_2d=False)
|
| 364 |
+
assert X_array.ndim == 1
|
| 365 |
+
# ensure_2d=True with 1d array
|
| 366 |
+
with pytest.raises(ValueError, match="Expected 2D array, got 1D array instead"):
|
| 367 |
+
check_array([0, 1, 2], ensure_2d=True)
|
| 368 |
+
|
| 369 |
+
# ensure_2d=True with scalar array
|
| 370 |
+
with pytest.raises(ValueError, match="Expected 2D array, got scalar array instead"):
|
| 371 |
+
check_array(10, ensure_2d=True)
|
| 372 |
+
|
| 373 |
+
# ensure_2d=True with 1d sparse array
|
| 374 |
+
if hasattr(sp, "csr_array"):
|
| 375 |
+
sparse_row = next(iter(sp.csr_array(X)))
|
| 376 |
+
if sparse_row.ndim == 1:
|
| 377 |
+
# In scipy 1.14 and later, sparse row is 1D while it was 2D before.
|
| 378 |
+
with pytest.raises(ValueError, match="Expected 2D input, got"):
|
| 379 |
+
check_array(sparse_row, accept_sparse=True, ensure_2d=True)
|
| 380 |
+
|
| 381 |
+
# don't allow ndim > 3
|
| 382 |
+
X_ndim = np.arange(8).reshape(2, 2, 2)
|
| 383 |
+
with pytest.raises(ValueError):
|
| 384 |
+
check_array(X_ndim)
|
| 385 |
+
check_array(X_ndim, allow_nd=True) # doesn't raise
|
| 386 |
+
|
| 387 |
+
# dtype and order enforcement.
|
| 388 |
+
X_C = np.arange(4).reshape(2, 2).copy("C")
|
| 389 |
+
X_F = X_C.copy("F")
|
| 390 |
+
X_int = X_C.astype(int)
|
| 391 |
+
X_float = X_C.astype(float)
|
| 392 |
+
Xs = [X_C, X_F, X_int, X_float]
|
| 393 |
+
dtypes = [np.int32, int, float, np.float32, None, bool, object]
|
| 394 |
+
orders = ["C", "F", None]
|
| 395 |
+
copys = [True, False]
|
| 396 |
+
|
| 397 |
+
for X, dtype, order, copy in product(Xs, dtypes, orders, copys):
|
| 398 |
+
X_checked = check_array(X, dtype=dtype, order=order, copy=copy)
|
| 399 |
+
if dtype is not None:
|
| 400 |
+
assert X_checked.dtype == dtype
|
| 401 |
+
else:
|
| 402 |
+
assert X_checked.dtype == X.dtype
|
| 403 |
+
if order == "C":
|
| 404 |
+
assert X_checked.flags["C_CONTIGUOUS"]
|
| 405 |
+
assert not X_checked.flags["F_CONTIGUOUS"]
|
| 406 |
+
elif order == "F":
|
| 407 |
+
assert X_checked.flags["F_CONTIGUOUS"]
|
| 408 |
+
assert not X_checked.flags["C_CONTIGUOUS"]
|
| 409 |
+
if copy:
|
| 410 |
+
assert X is not X_checked
|
| 411 |
+
else:
|
| 412 |
+
# doesn't copy if it was already good
|
| 413 |
+
if (
|
| 414 |
+
X.dtype == X_checked.dtype
|
| 415 |
+
and X_checked.flags["C_CONTIGUOUS"] == X.flags["C_CONTIGUOUS"]
|
| 416 |
+
and X_checked.flags["F_CONTIGUOUS"] == X.flags["F_CONTIGUOUS"]
|
| 417 |
+
):
|
| 418 |
+
assert X is X_checked
|
| 419 |
+
|
| 420 |
+
# allowed sparse != None
|
| 421 |
+
|
| 422 |
+
# try different type of sparse format
|
| 423 |
+
Xs = []
|
| 424 |
+
Xs.extend(
|
| 425 |
+
[
|
| 426 |
+
sparse_container(X_C)
|
| 427 |
+
for sparse_container in CSR_CONTAINERS
|
| 428 |
+
+ CSC_CONTAINERS
|
| 429 |
+
+ COO_CONTAINERS
|
| 430 |
+
+ DOK_CONTAINERS
|
| 431 |
+
]
|
| 432 |
+
)
|
| 433 |
+
Xs.extend([Xs[0].astype(np.int64), Xs[0].astype(np.float64)])
|
| 434 |
+
|
| 435 |
+
accept_sparses = [["csr", "coo"], ["coo", "dok"]]
|
| 436 |
+
# scipy sparse matrices do not support the object dtype so
|
| 437 |
+
# this dtype is skipped in this loop
|
| 438 |
+
non_object_dtypes = [dt for dt in dtypes if dt is not object]
|
| 439 |
+
for X, dtype, accept_sparse, copy in product(
|
| 440 |
+
Xs, non_object_dtypes, accept_sparses, copys
|
| 441 |
+
):
|
| 442 |
+
X_checked = check_array(X, dtype=dtype, accept_sparse=accept_sparse, copy=copy)
|
| 443 |
+
if dtype is not None:
|
| 444 |
+
assert X_checked.dtype == dtype
|
| 445 |
+
else:
|
| 446 |
+
assert X_checked.dtype == X.dtype
|
| 447 |
+
if X.format in accept_sparse:
|
| 448 |
+
# no change if allowed
|
| 449 |
+
assert X.format == X_checked.format
|
| 450 |
+
else:
|
| 451 |
+
# got converted
|
| 452 |
+
assert X_checked.format == accept_sparse[0]
|
| 453 |
+
if copy:
|
| 454 |
+
assert X is not X_checked
|
| 455 |
+
else:
|
| 456 |
+
# doesn't copy if it was already good
|
| 457 |
+
if X.dtype == X_checked.dtype and X.format == X_checked.format:
|
| 458 |
+
assert X is X_checked
|
| 459 |
+
|
| 460 |
+
# other input formats
|
| 461 |
+
# convert lists to arrays
|
| 462 |
+
X_dense = check_array([[1, 2], [3, 4]])
|
| 463 |
+
assert isinstance(X_dense, np.ndarray)
|
| 464 |
+
# raise on too deep lists
|
| 465 |
+
with pytest.raises(ValueError):
|
| 466 |
+
check_array(X_ndim.tolist())
|
| 467 |
+
check_array(X_ndim.tolist(), allow_nd=True) # doesn't raise
|
| 468 |
+
|
| 469 |
+
# convert weird stuff to arrays
|
| 470 |
+
X_no_array = _NotAnArray(X_dense)
|
| 471 |
+
result = check_array(X_no_array)
|
| 472 |
+
assert isinstance(result, np.ndarray)
|
| 473 |
+
|
| 474 |
+
# check negative values when ensure_non_negative=True
|
| 475 |
+
X_neg = check_array([[1, 2], [-3, 4]])
|
| 476 |
+
err_msg = "Negative values in data passed to X in RandomForestRegressor"
|
| 477 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 478 |
+
check_array(
|
| 479 |
+
X_neg,
|
| 480 |
+
ensure_non_negative=True,
|
| 481 |
+
input_name="X",
|
| 482 |
+
estimator=RandomForestRegressor(),
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
@pytest.mark.parametrize(
|
| 487 |
+
"X",
|
| 488 |
+
[
|
| 489 |
+
[["1", "2"], ["3", "4"]],
|
| 490 |
+
np.array([["1", "2"], ["3", "4"]], dtype="U"),
|
| 491 |
+
np.array([["1", "2"], ["3", "4"]], dtype="S"),
|
| 492 |
+
[[b"1", b"2"], [b"3", b"4"]],
|
| 493 |
+
np.array([[b"1", b"2"], [b"3", b"4"]], dtype="V1"),
|
| 494 |
+
],
|
| 495 |
+
)
|
| 496 |
+
def test_check_array_numeric_error(X):
|
| 497 |
+
"""Test that check_array errors when it receives an array of bytes/string
|
| 498 |
+
while a numeric dtype is required."""
|
| 499 |
+
expected_msg = r"dtype='numeric' is not compatible with arrays of bytes/strings"
|
| 500 |
+
with pytest.raises(ValueError, match=expected_msg):
|
| 501 |
+
check_array(X, dtype="numeric")
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
@pytest.mark.parametrize(
|
| 505 |
+
"pd_dtype", ["Int8", "Int16", "UInt8", "UInt16", "Float32", "Float64"]
|
| 506 |
+
)
|
| 507 |
+
@pytest.mark.parametrize(
|
| 508 |
+
"dtype, expected_dtype",
|
| 509 |
+
[
|
| 510 |
+
([np.float32, np.float64], np.float32),
|
| 511 |
+
(np.float64, np.float64),
|
| 512 |
+
("numeric", np.float64),
|
| 513 |
+
],
|
| 514 |
+
)
|
| 515 |
+
def test_check_array_pandas_na_support(pd_dtype, dtype, expected_dtype):
|
| 516 |
+
# Test pandas numerical extension arrays with pd.NA
|
| 517 |
+
pd = pytest.importorskip("pandas")
|
| 518 |
+
|
| 519 |
+
if pd_dtype in {"Float32", "Float64"}:
|
| 520 |
+
# Extension dtypes with Floats was added in 1.2
|
| 521 |
+
pd = pytest.importorskip("pandas", minversion="1.2")
|
| 522 |
+
|
| 523 |
+
X_np = np.array(
|
| 524 |
+
[[1, 2, 3, np.nan, np.nan], [np.nan, np.nan, 8, 4, 6], [1, 2, 3, 4, 5]]
|
| 525 |
+
).T
|
| 526 |
+
|
| 527 |
+
# Creates dataframe with numerical extension arrays with pd.NA
|
| 528 |
+
X = pd.DataFrame(X_np, dtype=pd_dtype, columns=["a", "b", "c"])
|
| 529 |
+
# column c has no nans
|
| 530 |
+
X["c"] = X["c"].astype("float")
|
| 531 |
+
X_checked = check_array(X, ensure_all_finite="allow-nan", dtype=dtype)
|
| 532 |
+
assert_allclose(X_checked, X_np)
|
| 533 |
+
assert X_checked.dtype == expected_dtype
|
| 534 |
+
|
| 535 |
+
X_checked = check_array(X, ensure_all_finite=False, dtype=dtype)
|
| 536 |
+
assert_allclose(X_checked, X_np)
|
| 537 |
+
assert X_checked.dtype == expected_dtype
|
| 538 |
+
|
| 539 |
+
msg = "Input contains NaN"
|
| 540 |
+
with pytest.raises(ValueError, match=msg):
|
| 541 |
+
check_array(X, ensure_all_finite=True)
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def test_check_array_panadas_na_support_series():
|
| 545 |
+
"""Check check_array is correct with pd.NA in a series."""
|
| 546 |
+
pd = pytest.importorskip("pandas")
|
| 547 |
+
|
| 548 |
+
X_int64 = pd.Series([1, 2, pd.NA], dtype="Int64")
|
| 549 |
+
|
| 550 |
+
msg = "Input contains NaN"
|
| 551 |
+
with pytest.raises(ValueError, match=msg):
|
| 552 |
+
check_array(X_int64, ensure_all_finite=True, ensure_2d=False)
|
| 553 |
+
|
| 554 |
+
X_out = check_array(X_int64, ensure_all_finite=False, ensure_2d=False)
|
| 555 |
+
assert_allclose(X_out, [1, 2, np.nan])
|
| 556 |
+
assert X_out.dtype == np.float64
|
| 557 |
+
|
| 558 |
+
X_out = check_array(
|
| 559 |
+
X_int64, ensure_all_finite=False, ensure_2d=False, dtype=np.float32
|
| 560 |
+
)
|
| 561 |
+
assert_allclose(X_out, [1, 2, np.nan])
|
| 562 |
+
assert X_out.dtype == np.float32
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def test_check_array_pandas_dtype_casting():
|
| 566 |
+
# test that data-frames with homogeneous dtype are not upcast
|
| 567 |
+
pd = pytest.importorskip("pandas")
|
| 568 |
+
X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)
|
| 569 |
+
X_df = pd.DataFrame(X)
|
| 570 |
+
assert check_array(X_df).dtype == np.float32
|
| 571 |
+
assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float32
|
| 572 |
+
|
| 573 |
+
X_df = X_df.astype({0: np.float16})
|
| 574 |
+
assert_array_equal(X_df.dtypes, (np.float16, np.float32, np.float32))
|
| 575 |
+
assert check_array(X_df).dtype == np.float32
|
| 576 |
+
assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float32
|
| 577 |
+
|
| 578 |
+
X_df = X_df.astype({0: np.int16})
|
| 579 |
+
# float16, int16, float32 casts to float32
|
| 580 |
+
assert check_array(X_df).dtype == np.float32
|
| 581 |
+
assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float32
|
| 582 |
+
|
| 583 |
+
X_df = X_df.astype({2: np.float16})
|
| 584 |
+
# float16, int16, float16 casts to float32
|
| 585 |
+
assert check_array(X_df).dtype == np.float32
|
| 586 |
+
assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float32
|
| 587 |
+
|
| 588 |
+
X_df = X_df.astype(np.int16)
|
| 589 |
+
assert check_array(X_df).dtype == np.int16
|
| 590 |
+
# we're not using upcasting rules for determining
|
| 591 |
+
# the target type yet, so we cast to the default of float64
|
| 592 |
+
assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float64
|
| 593 |
+
|
| 594 |
+
# check that we handle pandas dtypes in a semi-reasonable way
|
| 595 |
+
# this is actually tricky because we can't really know that this
|
| 596 |
+
# should be integer ahead of converting it.
|
| 597 |
+
cat_df = pd.DataFrame({"cat_col": pd.Categorical([1, 2, 3])})
|
| 598 |
+
assert check_array(cat_df).dtype == np.int64
|
| 599 |
+
assert check_array(cat_df, dtype=FLOAT_DTYPES).dtype == np.float64
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def test_check_array_on_mock_dataframe():
|
| 603 |
+
arr = np.array([[0.2, 0.7], [0.6, 0.5], [0.4, 0.1], [0.7, 0.2]])
|
| 604 |
+
mock_df = MockDataFrame(arr)
|
| 605 |
+
checked_arr = check_array(mock_df)
|
| 606 |
+
assert checked_arr.dtype == arr.dtype
|
| 607 |
+
checked_arr = check_array(mock_df, dtype=np.float32)
|
| 608 |
+
assert checked_arr.dtype == np.dtype(np.float32)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def test_check_array_dtype_stability():
|
| 612 |
+
# test that lists with ints don't get converted to floats
|
| 613 |
+
X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
|
| 614 |
+
assert check_array(X).dtype.kind == "i"
|
| 615 |
+
assert check_array(X, ensure_2d=False).dtype.kind == "i"
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def test_check_array_dtype_warning():
|
| 619 |
+
X_int_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
|
| 620 |
+
X_float32 = np.asarray(X_int_list, dtype=np.float32)
|
| 621 |
+
X_int64 = np.asarray(X_int_list, dtype=np.int64)
|
| 622 |
+
X_csr_float32 = sp.csr_matrix(X_float32)
|
| 623 |
+
X_csc_float32 = sp.csc_matrix(X_float32)
|
| 624 |
+
X_csc_int32 = sp.csc_matrix(X_int64, dtype=np.int32)
|
| 625 |
+
integer_data = [X_int64, X_csc_int32]
|
| 626 |
+
float32_data = [X_float32, X_csr_float32, X_csc_float32]
|
| 627 |
+
with warnings.catch_warnings():
|
| 628 |
+
warnings.simplefilter("error")
|
| 629 |
+
|
| 630 |
+
for X in integer_data:
|
| 631 |
+
X_checked = check_array(X, dtype=np.float64, accept_sparse=True)
|
| 632 |
+
assert X_checked.dtype == np.float64
|
| 633 |
+
|
| 634 |
+
for X in float32_data:
|
| 635 |
+
X_checked = check_array(
|
| 636 |
+
X, dtype=[np.float64, np.float32], accept_sparse=True
|
| 637 |
+
)
|
| 638 |
+
assert X_checked.dtype == np.float32
|
| 639 |
+
assert X_checked is X
|
| 640 |
+
|
| 641 |
+
X_checked = check_array(
|
| 642 |
+
X,
|
| 643 |
+
dtype=[np.float64, np.float32],
|
| 644 |
+
accept_sparse=["csr", "dok"],
|
| 645 |
+
copy=True,
|
| 646 |
+
)
|
| 647 |
+
assert X_checked.dtype == np.float32
|
| 648 |
+
assert X_checked is not X
|
| 649 |
+
|
| 650 |
+
X_checked = check_array(
|
| 651 |
+
X_csc_float32,
|
| 652 |
+
dtype=[np.float64, np.float32],
|
| 653 |
+
accept_sparse=["csr", "dok"],
|
| 654 |
+
copy=False,
|
| 655 |
+
)
|
| 656 |
+
assert X_checked.dtype == np.float32
|
| 657 |
+
assert X_checked is not X_csc_float32
|
| 658 |
+
assert X_checked.format == "csr"
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def test_check_array_accept_sparse_type_exception():
|
| 662 |
+
X = [[1, 2], [3, 4]]
|
| 663 |
+
X_csr = sp.csr_matrix(X)
|
| 664 |
+
invalid_type = SVR()
|
| 665 |
+
|
| 666 |
+
msg = (
|
| 667 |
+
"Sparse data was passed, but dense data is required. "
|
| 668 |
+
r"Use '.toarray\(\)' to convert to a dense numpy array."
|
| 669 |
+
)
|
| 670 |
+
with pytest.raises(TypeError, match=msg):
|
| 671 |
+
check_array(X_csr, accept_sparse=False)
|
| 672 |
+
|
| 673 |
+
msg = (
|
| 674 |
+
"Parameter 'accept_sparse' should be a string, "
|
| 675 |
+
"boolean or list of strings. You provided 'accept_sparse=.*'."
|
| 676 |
+
)
|
| 677 |
+
with pytest.raises(ValueError, match=msg):
|
| 678 |
+
check_array(X_csr, accept_sparse=invalid_type)
|
| 679 |
+
|
| 680 |
+
msg = (
|
| 681 |
+
"When providing 'accept_sparse' as a tuple or list, "
|
| 682 |
+
"it must contain at least one string value."
|
| 683 |
+
)
|
| 684 |
+
with pytest.raises(ValueError, match=msg):
|
| 685 |
+
check_array(X_csr, accept_sparse=[])
|
| 686 |
+
with pytest.raises(ValueError, match=msg):
|
| 687 |
+
check_array(X_csr, accept_sparse=())
|
| 688 |
+
with pytest.raises(TypeError, match="SVR"):
|
| 689 |
+
check_array(X_csr, accept_sparse=[invalid_type])
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def test_check_array_accept_sparse_no_exception():
|
| 693 |
+
X = [[1, 2], [3, 4]]
|
| 694 |
+
X_csr = sp.csr_matrix(X)
|
| 695 |
+
|
| 696 |
+
check_array(X_csr, accept_sparse=True)
|
| 697 |
+
check_array(X_csr, accept_sparse="csr")
|
| 698 |
+
check_array(X_csr, accept_sparse=["csr"])
|
| 699 |
+
check_array(X_csr, accept_sparse=("csr",))
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
@pytest.fixture(params=["csr", "csc", "coo", "bsr"])
|
| 703 |
+
def X_64bit(request):
|
| 704 |
+
X = sp.random(20, 10, format=request.param)
|
| 705 |
+
|
| 706 |
+
if request.param == "coo":
|
| 707 |
+
if hasattr(X, "coords"):
|
| 708 |
+
# for scipy >= 1.13 .coords is a new attribute and is a tuple. The
|
| 709 |
+
# .col and .row attributes do not seem to be able to change the
|
| 710 |
+
# dtype, for more details see https://github.com/scipy/scipy/pull/18530/
|
| 711 |
+
# and https://github.com/scipy/scipy/pull/20003 where .indices was
|
| 712 |
+
# renamed to .coords
|
| 713 |
+
X.coords = tuple(v.astype("int64") for v in X.coords)
|
| 714 |
+
else:
|
| 715 |
+
# scipy < 1.13
|
| 716 |
+
X.row = X.row.astype("int64")
|
| 717 |
+
X.col = X.col.astype("int64")
|
| 718 |
+
else:
|
| 719 |
+
X.indices = X.indices.astype("int64")
|
| 720 |
+
X.indptr = X.indptr.astype("int64")
|
| 721 |
+
|
| 722 |
+
yield X
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def test_check_array_accept_large_sparse_no_exception(X_64bit):
|
| 726 |
+
# When large sparse are allowed
|
| 727 |
+
check_array(X_64bit, accept_large_sparse=True, accept_sparse=True)
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
def test_check_array_accept_large_sparse_raise_exception(X_64bit):
|
| 731 |
+
# When large sparse are not allowed
|
| 732 |
+
msg = (
|
| 733 |
+
"Only sparse matrices with 32-bit integer indices "
|
| 734 |
+
"are accepted. Got int64 indices. Please do report"
|
| 735 |
+
)
|
| 736 |
+
with pytest.raises(ValueError, match=msg):
|
| 737 |
+
check_array(X_64bit, accept_sparse=True, accept_large_sparse=False)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def test_check_array_min_samples_and_features_messages():
|
| 741 |
+
# empty list is considered 2D by default:
|
| 742 |
+
msg = r"0 feature\(s\) \(shape=\(1, 0\)\) while a minimum of 1 is required."
|
| 743 |
+
with pytest.raises(ValueError, match=msg):
|
| 744 |
+
check_array([[]])
|
| 745 |
+
|
| 746 |
+
# If considered a 1D collection when ensure_2d=False, then the minimum
|
| 747 |
+
# number of samples will break:
|
| 748 |
+
msg = r"0 sample\(s\) \(shape=\(0,\)\) while a minimum of 1 is required."
|
| 749 |
+
with pytest.raises(ValueError, match=msg):
|
| 750 |
+
check_array([], ensure_2d=False)
|
| 751 |
+
|
| 752 |
+
# Invalid edge case when checking the default minimum sample of a scalar
|
| 753 |
+
msg = re.escape(
|
| 754 |
+
(
|
| 755 |
+
"Input should have at least 1 dimension i.e. satisfy "
|
| 756 |
+
"`len(x.shape) > 0`, got scalar `array(42)` instead."
|
| 757 |
+
)
|
| 758 |
+
)
|
| 759 |
+
with pytest.raises(TypeError, match=msg):
|
| 760 |
+
check_array(42, ensure_2d=False)
|
| 761 |
+
|
| 762 |
+
# Simulate a model that would need at least 2 samples to be well defined
|
| 763 |
+
X = np.ones((1, 10))
|
| 764 |
+
y = np.ones(1)
|
| 765 |
+
msg = r"1 sample\(s\) \(shape=\(1, 10\)\) while a minimum of 2 is required."
|
| 766 |
+
with pytest.raises(ValueError, match=msg):
|
| 767 |
+
check_X_y(X, y, ensure_min_samples=2)
|
| 768 |
+
|
| 769 |
+
# The same message is raised if the data has 2 dimensions even if this is
|
| 770 |
+
# not mandatory
|
| 771 |
+
with pytest.raises(ValueError, match=msg):
|
| 772 |
+
check_X_y(X, y, ensure_min_samples=2, ensure_2d=False)
|
| 773 |
+
|
| 774 |
+
# Simulate a model that would require at least 3 features (e.g. SelectKBest
|
| 775 |
+
# with k=3)
|
| 776 |
+
X = np.ones((10, 2))
|
| 777 |
+
y = np.ones(2)
|
| 778 |
+
msg = r"2 feature\(s\) \(shape=\(10, 2\)\) while a minimum of 3 is required."
|
| 779 |
+
with pytest.raises(ValueError, match=msg):
|
| 780 |
+
check_X_y(X, y, ensure_min_features=3)
|
| 781 |
+
|
| 782 |
+
# Only the feature check is enabled whenever the number of dimensions is 2
|
| 783 |
+
# even if allow_nd is enabled:
|
| 784 |
+
with pytest.raises(ValueError, match=msg):
|
| 785 |
+
check_X_y(X, y, ensure_min_features=3, allow_nd=True)
|
| 786 |
+
|
| 787 |
+
# Simulate a case where a pipeline stage as trimmed all the features of a
|
| 788 |
+
# 2D dataset.
|
| 789 |
+
X = np.empty(0).reshape(10, 0)
|
| 790 |
+
y = np.ones(10)
|
| 791 |
+
msg = r"0 feature\(s\) \(shape=\(10, 0\)\) while a minimum of 1 is required."
|
| 792 |
+
with pytest.raises(ValueError, match=msg):
|
| 793 |
+
check_X_y(X, y)
|
| 794 |
+
|
| 795 |
+
# nd-data is not checked for any minimum number of features by default:
|
| 796 |
+
X = np.ones((10, 0, 28, 28))
|
| 797 |
+
y = np.ones(10)
|
| 798 |
+
X_checked, y_checked = check_X_y(X, y, allow_nd=True)
|
| 799 |
+
assert_array_equal(X, X_checked)
|
| 800 |
+
assert_array_equal(y, y_checked)
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def test_check_array_complex_data_error():
|
| 804 |
+
X = np.array([[1 + 2j, 3 + 4j, 5 + 7j], [2 + 3j, 4 + 5j, 6 + 7j]])
|
| 805 |
+
with pytest.raises(ValueError, match="Complex data not supported"):
|
| 806 |
+
check_array(X)
|
| 807 |
+
|
| 808 |
+
# list of lists
|
| 809 |
+
X = [[1 + 2j, 3 + 4j, 5 + 7j], [2 + 3j, 4 + 5j, 6 + 7j]]
|
| 810 |
+
with pytest.raises(ValueError, match="Complex data not supported"):
|
| 811 |
+
check_array(X)
|
| 812 |
+
|
| 813 |
+
# tuple of tuples
|
| 814 |
+
X = ((1 + 2j, 3 + 4j, 5 + 7j), (2 + 3j, 4 + 5j, 6 + 7j))
|
| 815 |
+
with pytest.raises(ValueError, match="Complex data not supported"):
|
| 816 |
+
check_array(X)
|
| 817 |
+
|
| 818 |
+
# list of np arrays
|
| 819 |
+
X = [np.array([1 + 2j, 3 + 4j, 5 + 7j]), np.array([2 + 3j, 4 + 5j, 6 + 7j])]
|
| 820 |
+
with pytest.raises(ValueError, match="Complex data not supported"):
|
| 821 |
+
check_array(X)
|
| 822 |
+
|
| 823 |
+
# tuple of np arrays
|
| 824 |
+
X = (np.array([1 + 2j, 3 + 4j, 5 + 7j]), np.array([2 + 3j, 4 + 5j, 6 + 7j]))
|
| 825 |
+
with pytest.raises(ValueError, match="Complex data not supported"):
|
| 826 |
+
check_array(X)
|
| 827 |
+
|
| 828 |
+
# dataframe
|
| 829 |
+
X = MockDataFrame(np.array([[1 + 2j, 3 + 4j, 5 + 7j], [2 + 3j, 4 + 5j, 6 + 7j]]))
|
| 830 |
+
with pytest.raises(ValueError, match="Complex data not supported"):
|
| 831 |
+
check_array(X)
|
| 832 |
+
|
| 833 |
+
# sparse matrix
|
| 834 |
+
X = sp.coo_matrix([[0, 1 + 2j], [0, 0]])
|
| 835 |
+
with pytest.raises(ValueError, match="Complex data not supported"):
|
| 836 |
+
check_array(X)
|
| 837 |
+
|
| 838 |
+
# target variable does not always go through check_array but should
|
| 839 |
+
# never accept complex data either.
|
| 840 |
+
y = np.array([1 + 2j, 3 + 4j, 5 + 7j, 2 + 3j, 4 + 5j, 6 + 7j])
|
| 841 |
+
with pytest.raises(ValueError, match="Complex data not supported"):
|
| 842 |
+
_check_y(y)
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
def test_has_fit_parameter():
|
| 846 |
+
assert not has_fit_parameter(KNeighborsClassifier, "sample_weight")
|
| 847 |
+
assert has_fit_parameter(RandomForestRegressor, "sample_weight")
|
| 848 |
+
assert has_fit_parameter(SVR, "sample_weight")
|
| 849 |
+
assert has_fit_parameter(SVR(), "sample_weight")
|
| 850 |
+
|
| 851 |
+
class TestClassWithDeprecatedFitMethod:
|
| 852 |
+
@deprecated("Deprecated for the purpose of testing has_fit_parameter")
|
| 853 |
+
def fit(self, X, y, sample_weight=None):
|
| 854 |
+
pass
|
| 855 |
+
|
| 856 |
+
assert has_fit_parameter(TestClassWithDeprecatedFitMethod, "sample_weight"), (
|
| 857 |
+
"has_fit_parameter fails for class with deprecated fit method."
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
def test_check_symmetric():
|
| 862 |
+
arr_sym = np.array([[0, 1], [1, 2]])
|
| 863 |
+
arr_bad = np.ones(2)
|
| 864 |
+
arr_asym = np.array([[0, 2], [0, 2]])
|
| 865 |
+
|
| 866 |
+
test_arrays = {
|
| 867 |
+
"dense": arr_asym,
|
| 868 |
+
"dok": sp.dok_matrix(arr_asym),
|
| 869 |
+
"csr": sp.csr_matrix(arr_asym),
|
| 870 |
+
"csc": sp.csc_matrix(arr_asym),
|
| 871 |
+
"coo": sp.coo_matrix(arr_asym),
|
| 872 |
+
"lil": sp.lil_matrix(arr_asym),
|
| 873 |
+
"bsr": sp.bsr_matrix(arr_asym),
|
| 874 |
+
}
|
| 875 |
+
|
| 876 |
+
# check error for bad inputs
|
| 877 |
+
with pytest.raises(ValueError):
|
| 878 |
+
check_symmetric(arr_bad)
|
| 879 |
+
|
| 880 |
+
# check that asymmetric arrays are properly symmetrized
|
| 881 |
+
for arr_format, arr in test_arrays.items():
|
| 882 |
+
# Check for warnings and errors
|
| 883 |
+
with pytest.warns(UserWarning):
|
| 884 |
+
check_symmetric(arr)
|
| 885 |
+
with pytest.raises(ValueError):
|
| 886 |
+
check_symmetric(arr, raise_exception=True)
|
| 887 |
+
|
| 888 |
+
output = check_symmetric(arr, raise_warning=False)
|
| 889 |
+
if sp.issparse(output):
|
| 890 |
+
assert output.format == arr_format
|
| 891 |
+
assert_array_equal(output.toarray(), arr_sym)
|
| 892 |
+
else:
|
| 893 |
+
assert_array_equal(output, arr_sym)
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
def test_check_is_fitted_with_is_fitted():
|
| 897 |
+
class Estimator(BaseEstimator):
|
| 898 |
+
def fit(self, **kwargs):
|
| 899 |
+
self._is_fitted = True
|
| 900 |
+
return self
|
| 901 |
+
|
| 902 |
+
def __sklearn_is_fitted__(self):
|
| 903 |
+
return hasattr(self, "_is_fitted") and self._is_fitted
|
| 904 |
+
|
| 905 |
+
with pytest.raises(NotFittedError):
|
| 906 |
+
check_is_fitted(Estimator())
|
| 907 |
+
check_is_fitted(Estimator().fit())
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
def test_check_is_fitted_stateless():
|
| 911 |
+
"""Check that check_is_fitted passes for stateless estimators."""
|
| 912 |
+
|
| 913 |
+
class StatelessEstimator(BaseEstimator):
|
| 914 |
+
def fit(self, **kwargs):
|
| 915 |
+
return self # pragma: no cover
|
| 916 |
+
|
| 917 |
+
def __sklearn_tags__(self):
|
| 918 |
+
tags = super().__sklearn_tags__()
|
| 919 |
+
tags.requires_fit = False
|
| 920 |
+
return tags
|
| 921 |
+
|
| 922 |
+
check_is_fitted(StatelessEstimator())
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
def test_check_is_fitted():
|
| 926 |
+
# Check is TypeError raised when non estimator instance passed
|
| 927 |
+
with pytest.raises(TypeError):
|
| 928 |
+
check_is_fitted(ARDRegression)
|
| 929 |
+
with pytest.raises(TypeError):
|
| 930 |
+
check_is_fitted("SVR")
|
| 931 |
+
|
| 932 |
+
ard = ARDRegression()
|
| 933 |
+
svr = SVR()
|
| 934 |
+
|
| 935 |
+
try:
|
| 936 |
+
with pytest.raises(NotFittedError):
|
| 937 |
+
check_is_fitted(ard)
|
| 938 |
+
with pytest.raises(NotFittedError):
|
| 939 |
+
check_is_fitted(svr)
|
| 940 |
+
except ValueError:
|
| 941 |
+
assert False, "check_is_fitted failed with ValueError"
|
| 942 |
+
|
| 943 |
+
# NotFittedError is a subclass of both ValueError and AttributeError
|
| 944 |
+
msg = "Random message %(name)s, %(name)s"
|
| 945 |
+
match = "Random message ARDRegression, ARDRegression"
|
| 946 |
+
with pytest.raises(ValueError, match=match):
|
| 947 |
+
check_is_fitted(ard, msg=msg)
|
| 948 |
+
|
| 949 |
+
msg = "Another message %(name)s, %(name)s"
|
| 950 |
+
match = "Another message SVR, SVR"
|
| 951 |
+
with pytest.raises(AttributeError, match=match):
|
| 952 |
+
check_is_fitted(svr, msg=msg)
|
| 953 |
+
|
| 954 |
+
ard.fit(*make_blobs())
|
| 955 |
+
svr.fit(*make_blobs())
|
| 956 |
+
|
| 957 |
+
assert check_is_fitted(ard) is None
|
| 958 |
+
assert check_is_fitted(svr) is None
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
def test_check_is_fitted_attributes():
|
| 962 |
+
class MyEstimator(BaseEstimator):
|
| 963 |
+
def fit(self, X, y):
|
| 964 |
+
return self
|
| 965 |
+
|
| 966 |
+
msg = "not fitted"
|
| 967 |
+
est = MyEstimator()
|
| 968 |
+
|
| 969 |
+
assert not _is_fitted(est, attributes=["a_", "b_"])
|
| 970 |
+
with pytest.raises(NotFittedError, match=msg):
|
| 971 |
+
check_is_fitted(est, attributes=["a_", "b_"])
|
| 972 |
+
assert not _is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
|
| 973 |
+
with pytest.raises(NotFittedError, match=msg):
|
| 974 |
+
check_is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
|
| 975 |
+
assert not _is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
|
| 976 |
+
with pytest.raises(NotFittedError, match=msg):
|
| 977 |
+
check_is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
|
| 978 |
+
|
| 979 |
+
est.a_ = "a"
|
| 980 |
+
assert not _is_fitted(est, attributes=["a_", "b_"])
|
| 981 |
+
with pytest.raises(NotFittedError, match=msg):
|
| 982 |
+
check_is_fitted(est, attributes=["a_", "b_"])
|
| 983 |
+
assert not _is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
|
| 984 |
+
with pytest.raises(NotFittedError, match=msg):
|
| 985 |
+
check_is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
|
| 986 |
+
assert _is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
|
| 987 |
+
check_is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
|
| 988 |
+
|
| 989 |
+
est.b_ = "b"
|
| 990 |
+
assert _is_fitted(est, attributes=["a_", "b_"])
|
| 991 |
+
check_is_fitted(est, attributes=["a_", "b_"])
|
| 992 |
+
assert _is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
|
| 993 |
+
check_is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
|
| 994 |
+
assert _is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
|
| 995 |
+
check_is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
@pytest.mark.parametrize(
|
| 999 |
+
"wrap", [itemgetter(0), list, tuple], ids=["single", "list", "tuple"]
|
| 1000 |
+
)
|
| 1001 |
+
def test_check_is_fitted_with_attributes(wrap):
|
| 1002 |
+
ard = ARDRegression()
|
| 1003 |
+
with pytest.raises(NotFittedError, match="is not fitted yet"):
|
| 1004 |
+
check_is_fitted(ard, wrap(["coef_"]))
|
| 1005 |
+
|
| 1006 |
+
ard.fit(*make_blobs())
|
| 1007 |
+
|
| 1008 |
+
# Does not raise
|
| 1009 |
+
check_is_fitted(ard, wrap(["coef_"]))
|
| 1010 |
+
|
| 1011 |
+
# Raises when using attribute that is not defined
|
| 1012 |
+
with pytest.raises(NotFittedError, match="is not fitted yet"):
|
| 1013 |
+
check_is_fitted(ard, wrap(["coef_bad_"]))
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
def test_check_consistent_length():
|
| 1017 |
+
"""Test that `check_consistent_length` raises on inconsistent lengths and wrong
|
| 1018 |
+
input types trigger TypeErrors."""
|
| 1019 |
+
check_consistent_length([1], [2], [3], [4], [5])
|
| 1020 |
+
check_consistent_length([[1, 2], [[1, 2]]], [1, 2], ["a", "b"])
|
| 1021 |
+
check_consistent_length([1], (2,), np.array([3]), sp.csr_matrix((1, 2)))
|
| 1022 |
+
with pytest.raises(ValueError, match="inconsistent numbers of samples"):
|
| 1023 |
+
check_consistent_length([1, 2], [1])
|
| 1024 |
+
with pytest.raises(TypeError, match=r"got <\w+ 'int'>"):
|
| 1025 |
+
check_consistent_length([1, 2], 1)
|
| 1026 |
+
with pytest.raises(TypeError, match=r"got <\w+ 'object'>"):
|
| 1027 |
+
check_consistent_length([1, 2], object())
|
| 1028 |
+
with pytest.raises(TypeError):
|
| 1029 |
+
check_consistent_length([1, 2], np.array(1))
|
| 1030 |
+
# Despite ensembles having __len__ they must raise TypeError
|
| 1031 |
+
with pytest.raises(TypeError, match="Expected sequence or array-like"):
|
| 1032 |
+
check_consistent_length([1, 2], RandomForestRegressor())
|
| 1033 |
+
# XXX: We should have a test with a string, but what is correct behaviour?
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
@pytest.mark.parametrize(
|
| 1037 |
+
"array_namespace, device, _",
|
| 1038 |
+
yield_namespace_device_dtype_combinations(),
|
| 1039 |
+
ids=_get_namespace_device_dtype_ids,
|
| 1040 |
+
)
|
| 1041 |
+
def test_check_consistent_length_array_api(array_namespace, device, _):
|
| 1042 |
+
"""Test that check_consistent_length works with different array types."""
|
| 1043 |
+
xp = _array_api_for_tests(array_namespace, device)
|
| 1044 |
+
|
| 1045 |
+
with config_context(array_api_dispatch=True):
|
| 1046 |
+
check_consistent_length(
|
| 1047 |
+
xp.asarray([1, 2, 3], device=device),
|
| 1048 |
+
xp.asarray([[1, 1], [2, 2], [3, 3]], device=device),
|
| 1049 |
+
[1, 2, 3],
|
| 1050 |
+
["a", "b", "c"],
|
| 1051 |
+
np.asarray(("a", "b", "c"), dtype=object),
|
| 1052 |
+
sp.csr_array([[0, 1], [1, 0], [0, 0]]),
|
| 1053 |
+
)
|
| 1054 |
+
|
| 1055 |
+
with pytest.raises(ValueError, match="inconsistent numbers of samples"):
|
| 1056 |
+
check_consistent_length(
|
| 1057 |
+
xp.asarray([1, 2], device=device), xp.asarray([1], device=device)
|
| 1058 |
+
)
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
def test_check_dataframe_fit_attribute():
|
| 1062 |
+
# check pandas dataframe with 'fit' column does not raise error
|
| 1063 |
+
# https://github.com/scikit-learn/scikit-learn/issues/8415
|
| 1064 |
+
try:
|
| 1065 |
+
import pandas as pd
|
| 1066 |
+
|
| 1067 |
+
X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 1068 |
+
X_df = pd.DataFrame(X, columns=["a", "b", "fit"])
|
| 1069 |
+
check_consistent_length(X_df)
|
| 1070 |
+
except ImportError:
|
| 1071 |
+
raise SkipTest("Pandas not found")
|
| 1072 |
+
|
| 1073 |
+
|
| 1074 |
+
def test_suppress_validation():
|
| 1075 |
+
X = np.array([0, np.inf])
|
| 1076 |
+
with pytest.raises(ValueError):
|
| 1077 |
+
assert_all_finite(X)
|
| 1078 |
+
sklearn.set_config(assume_finite=True)
|
| 1079 |
+
assert_all_finite(X)
|
| 1080 |
+
sklearn.set_config(assume_finite=False)
|
| 1081 |
+
with pytest.raises(ValueError):
|
| 1082 |
+
assert_all_finite(X)
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
def test_check_array_series():
|
| 1086 |
+
# regression test that check_array works on pandas Series
|
| 1087 |
+
pd = importorskip("pandas")
|
| 1088 |
+
res = check_array(pd.Series([1, 2, 3]), ensure_2d=False)
|
| 1089 |
+
assert_array_equal(res, np.array([1, 2, 3]))
|
| 1090 |
+
|
| 1091 |
+
# with categorical dtype (not a numpy dtype) (GH12699)
|
| 1092 |
+
s = pd.Series(["a", "b", "c"]).astype("category")
|
| 1093 |
+
res = check_array(s, dtype=None, ensure_2d=False)
|
| 1094 |
+
assert_array_equal(res, np.array(["a", "b", "c"], dtype=object))
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
@pytest.mark.parametrize(
|
| 1098 |
+
"dtype", ((np.float64, np.float32), np.float64, None, "numeric")
|
| 1099 |
+
)
|
| 1100 |
+
@pytest.mark.parametrize("bool_dtype", ("bool", "boolean"))
|
| 1101 |
+
def test_check_dataframe_mixed_float_dtypes(dtype, bool_dtype):
|
| 1102 |
+
# pandas dataframe will coerce a boolean into a object, this is a mismatch
|
| 1103 |
+
# with np.result_type which will return a float
|
| 1104 |
+
# check_array needs to explicitly check for bool dtype in a dataframe for
|
| 1105 |
+
# this situation
|
| 1106 |
+
# https://github.com/scikit-learn/scikit-learn/issues/15787
|
| 1107 |
+
|
| 1108 |
+
pd = importorskip("pandas")
|
| 1109 |
+
|
| 1110 |
+
df = pd.DataFrame(
|
| 1111 |
+
{
|
| 1112 |
+
"int": [1, 2, 3],
|
| 1113 |
+
"float": [0, 0.1, 2.1],
|
| 1114 |
+
"bool": pd.Series([True, False, True], dtype=bool_dtype),
|
| 1115 |
+
},
|
| 1116 |
+
columns=["int", "float", "bool"],
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
array = check_array(df, dtype=dtype)
|
| 1120 |
+
assert array.dtype == np.float64
|
| 1121 |
+
expected_array = np.array(
|
| 1122 |
+
[[1.0, 0.0, 1.0], [2.0, 0.1, 0.0], [3.0, 2.1, 1.0]], dtype=float
|
| 1123 |
+
)
|
| 1124 |
+
assert_allclose_dense_sparse(array, expected_array)
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
def test_check_dataframe_with_only_bool():
|
| 1128 |
+
"""Check that dataframe with bool return a boolean arrays."""
|
| 1129 |
+
pd = importorskip("pandas")
|
| 1130 |
+
df = pd.DataFrame({"bool": [True, False, True]})
|
| 1131 |
+
|
| 1132 |
+
array = check_array(df, dtype=None)
|
| 1133 |
+
assert array.dtype == np.bool_
|
| 1134 |
+
assert_array_equal(array, [[True], [False], [True]])
|
| 1135 |
+
|
| 1136 |
+
# common dtype is int for bool + int
|
| 1137 |
+
df = pd.DataFrame(
|
| 1138 |
+
{"bool": [True, False, True], "int": [1, 2, 3]},
|
| 1139 |
+
columns=["bool", "int"],
|
| 1140 |
+
)
|
| 1141 |
+
array = check_array(df, dtype="numeric")
|
| 1142 |
+
assert array.dtype == np.int64
|
| 1143 |
+
assert_array_equal(array, [[1, 1], [0, 2], [1, 3]])
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
def test_check_dataframe_with_only_boolean():
|
| 1147 |
+
"""Check that dataframe with boolean return a float array with dtype=None"""
|
| 1148 |
+
pd = importorskip("pandas")
|
| 1149 |
+
df = pd.DataFrame({"bool": pd.Series([True, False, True], dtype="boolean")})
|
| 1150 |
+
|
| 1151 |
+
array = check_array(df, dtype=None)
|
| 1152 |
+
assert array.dtype == np.float64
|
| 1153 |
+
assert_array_equal(array, [[True], [False], [True]])
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
class DummyMemory:
|
| 1157 |
+
def cache(self, func):
|
| 1158 |
+
return func
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
class WrongDummyMemory:
|
| 1162 |
+
pass
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
def test_check_memory(tmp_path):
|
| 1166 |
+
cache_directory = str(tmp_path / "cache_directory")
|
| 1167 |
+
memory = check_memory(cache_directory)
|
| 1168 |
+
assert memory.location == cache_directory
|
| 1169 |
+
|
| 1170 |
+
memory = check_memory(None)
|
| 1171 |
+
assert memory.location is None
|
| 1172 |
+
|
| 1173 |
+
dummy = DummyMemory()
|
| 1174 |
+
memory = check_memory(dummy)
|
| 1175 |
+
assert memory is dummy
|
| 1176 |
+
|
| 1177 |
+
msg = (
|
| 1178 |
+
"'memory' should be None, a string or have the same interface as"
|
| 1179 |
+
" joblib.Memory. Got memory='1' instead."
|
| 1180 |
+
)
|
| 1181 |
+
with pytest.raises(ValueError, match=msg):
|
| 1182 |
+
check_memory(1)
|
| 1183 |
+
dummy = WrongDummyMemory()
|
| 1184 |
+
msg = (
|
| 1185 |
+
"'memory' should be None, a string or have the same interface as"
|
| 1186 |
+
" joblib.Memory. Got memory='{}' instead.".format(dummy)
|
| 1187 |
+
)
|
| 1188 |
+
with pytest.raises(ValueError, match=msg):
|
| 1189 |
+
check_memory(dummy)
|
| 1190 |
+
|
| 1191 |
+
|
| 1192 |
+
@pytest.mark.parametrize("copy", [True, False])
|
| 1193 |
+
def test_check_array_memmap(copy):
|
| 1194 |
+
X = np.ones((4, 4))
|
| 1195 |
+
with TempMemmap(X, mmap_mode="r") as X_memmap:
|
| 1196 |
+
X_checked = check_array(X_memmap, copy=copy)
|
| 1197 |
+
assert np.may_share_memory(X_memmap, X_checked) == (not copy)
|
| 1198 |
+
assert X_checked.flags["WRITEABLE"] == copy
|
| 1199 |
+
|
| 1200 |
+
|
| 1201 |
+
@pytest.mark.parametrize(
|
| 1202 |
+
"estimator_name, estimator_value, delegates, expected_result, expected_exception",
|
| 1203 |
+
[
|
| 1204 |
+
(
|
| 1205 |
+
"estimator_",
|
| 1206 |
+
type("SubEstimator", (), {"attribute_present": True}),
|
| 1207 |
+
None, # default delegates - ["estimator_", "estimator"]
|
| 1208 |
+
True, # expected_result is True b/c delegate and attribute are present
|
| 1209 |
+
None, # expected_exception not relevant for this case
|
| 1210 |
+
),
|
| 1211 |
+
(
|
| 1212 |
+
"estimator",
|
| 1213 |
+
type("SubEstimator", (), {"attribute_present": True}),
|
| 1214 |
+
None, # default delegates - ["estimator_", "estimator"]
|
| 1215 |
+
True, # expected_result is True b/c delegate and attribute are present
|
| 1216 |
+
None, # expected_exception not relevant for this case
|
| 1217 |
+
),
|
| 1218 |
+
(
|
| 1219 |
+
"estimators_",
|
| 1220 |
+
[
|
| 1221 |
+
type("SubEstimator", (), {"attribute_present": True})
|
| 1222 |
+
], # list of sub-estimators
|
| 1223 |
+
["estimators_"],
|
| 1224 |
+
True, # expected_result is True b/c delegate and attribute are present
|
| 1225 |
+
None, # expected_exception not relevant for this case
|
| 1226 |
+
),
|
| 1227 |
+
(
|
| 1228 |
+
"custom_estimator", # custom estimator attribute name
|
| 1229 |
+
type("SubEstimator", (), {"attribute_present": True}),
|
| 1230 |
+
["custom_estimator"], # custom delegates
|
| 1231 |
+
True, # expected_result is True b/c delegate and attribute are present
|
| 1232 |
+
None, # expected_exception not relevant for this case
|
| 1233 |
+
),
|
| 1234 |
+
(
|
| 1235 |
+
"no_estimator", # no estimator attribute name
|
| 1236 |
+
type("SubEstimator", (), {"attribute_present": True}),
|
| 1237 |
+
None, # default delegates - ["estimator_", "estimator"]
|
| 1238 |
+
None, # expected_result is not relevant for this case
|
| 1239 |
+
ValueError, # should raise ValueError b/c no estimator found from delegates
|
| 1240 |
+
),
|
| 1241 |
+
(
|
| 1242 |
+
"estimator",
|
| 1243 |
+
type("SubEstimator", (), {"attribute_absent": True}), # attribute_absent
|
| 1244 |
+
None, # default delegates - ["estimator_", "estimator"]
|
| 1245 |
+
None, # expected_result is not relevant for this case
|
| 1246 |
+
AttributeError, # should raise AttributeError b/c attribute is absent
|
| 1247 |
+
),
|
| 1248 |
+
],
|
| 1249 |
+
ids=[
|
| 1250 |
+
"fitted_estimator_with_default_delegates",
|
| 1251 |
+
"estimator_with_default_delegates",
|
| 1252 |
+
"list_of_estimators_with_estimators_",
|
| 1253 |
+
"custom_estimator_with_custom_delegates",
|
| 1254 |
+
"no_estimator_with_default_delegates",
|
| 1255 |
+
"estimator_with_default_delegates_but_absent_attribute",
|
| 1256 |
+
],
|
| 1257 |
+
)
|
| 1258 |
+
def test_estimator_has(
|
| 1259 |
+
estimator_name, estimator_value, delegates, expected_result, expected_exception
|
| 1260 |
+
):
|
| 1261 |
+
"""
|
| 1262 |
+
Tests the _estimator_has function by verifying:
|
| 1263 |
+
- Functionality with default and custom delegates.
|
| 1264 |
+
- Raises ValueError if delegates are missing.
|
| 1265 |
+
- Raises AttributeError if the specified attribute is missing.
|
| 1266 |
+
"""
|
| 1267 |
+
|
| 1268 |
+
# always checks for attribute - "attribute_present"
|
| 1269 |
+
# ["estimator_", "estimator"] is default value for delegates
|
| 1270 |
+
if delegates is None:
|
| 1271 |
+
check = _estimator_has("attribute_present")
|
| 1272 |
+
else:
|
| 1273 |
+
check = _estimator_has("attribute_present", delegates=delegates)
|
| 1274 |
+
|
| 1275 |
+
class MockEstimator:
|
| 1276 |
+
pass
|
| 1277 |
+
|
| 1278 |
+
a = MockEstimator()
|
| 1279 |
+
setattr(a, estimator_name, estimator_value)
|
| 1280 |
+
|
| 1281 |
+
if expected_exception:
|
| 1282 |
+
with pytest.raises(expected_exception):
|
| 1283 |
+
check(a)
|
| 1284 |
+
else:
|
| 1285 |
+
assert check(a) == expected_result
|
| 1286 |
+
|
| 1287 |
+
|
| 1288 |
+
@pytest.mark.parametrize(
|
| 1289 |
+
"retype",
|
| 1290 |
+
[
|
| 1291 |
+
np.asarray,
|
| 1292 |
+
sp.csr_matrix,
|
| 1293 |
+
sp.csc_matrix,
|
| 1294 |
+
sp.coo_matrix,
|
| 1295 |
+
sp.lil_matrix,
|
| 1296 |
+
sp.bsr_matrix,
|
| 1297 |
+
sp.dok_matrix,
|
| 1298 |
+
sp.dia_matrix,
|
| 1299 |
+
],
|
| 1300 |
+
)
|
| 1301 |
+
def test_check_non_negative(retype):
|
| 1302 |
+
A = np.array([[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
|
| 1303 |
+
X = retype(A)
|
| 1304 |
+
check_non_negative(X, "")
|
| 1305 |
+
X = retype([[0, 0], [0, 0]])
|
| 1306 |
+
check_non_negative(X, "")
|
| 1307 |
+
|
| 1308 |
+
A[0, 0] = -1
|
| 1309 |
+
X = retype(A)
|
| 1310 |
+
with pytest.raises(ValueError, match="Negative "):
|
| 1311 |
+
check_non_negative(X, "")
|
| 1312 |
+
|
| 1313 |
+
|
| 1314 |
+
def test_check_X_y_informative_error():
|
| 1315 |
+
X = np.ones((2, 2))
|
| 1316 |
+
y = None
|
| 1317 |
+
msg = "estimator requires y to be passed, but the target y is None"
|
| 1318 |
+
with pytest.raises(ValueError, match=msg):
|
| 1319 |
+
check_X_y(X, y)
|
| 1320 |
+
|
| 1321 |
+
msg = "RandomForestRegressor requires y to be passed, but the target y is None"
|
| 1322 |
+
with pytest.raises(ValueError, match=msg):
|
| 1323 |
+
check_X_y(X, y, estimator=RandomForestRegressor())
|
| 1324 |
+
|
| 1325 |
+
|
| 1326 |
+
def test_retrieve_samples_from_non_standard_shape():
|
| 1327 |
+
class TestNonNumericShape:
|
| 1328 |
+
def __init__(self):
|
| 1329 |
+
self.shape = ("not numeric",)
|
| 1330 |
+
|
| 1331 |
+
def __len__(self):
|
| 1332 |
+
return len([1, 2, 3])
|
| 1333 |
+
|
| 1334 |
+
X = TestNonNumericShape()
|
| 1335 |
+
assert _num_samples(X) == len(X)
|
| 1336 |
+
|
| 1337 |
+
# check that it gives a good error if there's no __len__
|
| 1338 |
+
class TestNoLenWeirdShape:
|
| 1339 |
+
def __init__(self):
|
| 1340 |
+
self.shape = ("not numeric",)
|
| 1341 |
+
|
| 1342 |
+
with pytest.raises(TypeError, match="Expected sequence or array-like"):
|
| 1343 |
+
_num_samples(TestNoLenWeirdShape())
|
| 1344 |
+
|
| 1345 |
+
|
| 1346 |
+
@pytest.mark.parametrize("x", [2, 3, 2.5, 5])
|
| 1347 |
+
def test_check_scalar_valid(x):
|
| 1348 |
+
"""Test that check_scalar returns no error/warning if valid inputs are
|
| 1349 |
+
provided"""
|
| 1350 |
+
with warnings.catch_warnings():
|
| 1351 |
+
warnings.simplefilter("error")
|
| 1352 |
+
scalar = check_scalar(
|
| 1353 |
+
x,
|
| 1354 |
+
"test_name",
|
| 1355 |
+
target_type=numbers.Real,
|
| 1356 |
+
min_val=2,
|
| 1357 |
+
max_val=5,
|
| 1358 |
+
include_boundaries="both",
|
| 1359 |
+
)
|
| 1360 |
+
assert scalar == x
|
| 1361 |
+
|
| 1362 |
+
|
| 1363 |
+
@pytest.mark.parametrize(
|
| 1364 |
+
"x, target_name, target_type, min_val, max_val, include_boundaries, err_msg",
|
| 1365 |
+
[
|
| 1366 |
+
(
|
| 1367 |
+
1,
|
| 1368 |
+
"test_name1",
|
| 1369 |
+
float,
|
| 1370 |
+
2,
|
| 1371 |
+
4,
|
| 1372 |
+
"neither",
|
| 1373 |
+
TypeError("test_name1 must be an instance of float, not int."),
|
| 1374 |
+
),
|
| 1375 |
+
(
|
| 1376 |
+
None,
|
| 1377 |
+
"test_name1",
|
| 1378 |
+
numbers.Real,
|
| 1379 |
+
2,
|
| 1380 |
+
4,
|
| 1381 |
+
"neither",
|
| 1382 |
+
TypeError("test_name1 must be an instance of float, not NoneType."),
|
| 1383 |
+
),
|
| 1384 |
+
(
|
| 1385 |
+
None,
|
| 1386 |
+
"test_name1",
|
| 1387 |
+
numbers.Integral,
|
| 1388 |
+
2,
|
| 1389 |
+
4,
|
| 1390 |
+
"neither",
|
| 1391 |
+
TypeError("test_name1 must be an instance of int, not NoneType."),
|
| 1392 |
+
),
|
| 1393 |
+
(
|
| 1394 |
+
1,
|
| 1395 |
+
"test_name1",
|
| 1396 |
+
(float, bool),
|
| 1397 |
+
2,
|
| 1398 |
+
4,
|
| 1399 |
+
"neither",
|
| 1400 |
+
TypeError("test_name1 must be an instance of {float, bool}, not int."),
|
| 1401 |
+
),
|
| 1402 |
+
(
|
| 1403 |
+
1,
|
| 1404 |
+
"test_name2",
|
| 1405 |
+
int,
|
| 1406 |
+
2,
|
| 1407 |
+
4,
|
| 1408 |
+
"neither",
|
| 1409 |
+
ValueError("test_name2 == 1, must be > 2."),
|
| 1410 |
+
),
|
| 1411 |
+
(
|
| 1412 |
+
5,
|
| 1413 |
+
"test_name3",
|
| 1414 |
+
int,
|
| 1415 |
+
2,
|
| 1416 |
+
4,
|
| 1417 |
+
"neither",
|
| 1418 |
+
ValueError("test_name3 == 5, must be < 4."),
|
| 1419 |
+
),
|
| 1420 |
+
(
|
| 1421 |
+
2,
|
| 1422 |
+
"test_name4",
|
| 1423 |
+
int,
|
| 1424 |
+
2,
|
| 1425 |
+
4,
|
| 1426 |
+
"right",
|
| 1427 |
+
ValueError("test_name4 == 2, must be > 2."),
|
| 1428 |
+
),
|
| 1429 |
+
(
|
| 1430 |
+
4,
|
| 1431 |
+
"test_name5",
|
| 1432 |
+
int,
|
| 1433 |
+
2,
|
| 1434 |
+
4,
|
| 1435 |
+
"left",
|
| 1436 |
+
ValueError("test_name5 == 4, must be < 4."),
|
| 1437 |
+
),
|
| 1438 |
+
(
|
| 1439 |
+
4,
|
| 1440 |
+
"test_name6",
|
| 1441 |
+
int,
|
| 1442 |
+
2,
|
| 1443 |
+
4,
|
| 1444 |
+
"bad parameter value",
|
| 1445 |
+
ValueError(
|
| 1446 |
+
"Unknown value for `include_boundaries`: 'bad parameter value'. "
|
| 1447 |
+
"Possible values are: ('left', 'right', 'both', 'neither')."
|
| 1448 |
+
),
|
| 1449 |
+
),
|
| 1450 |
+
(
|
| 1451 |
+
4,
|
| 1452 |
+
"test_name7",
|
| 1453 |
+
int,
|
| 1454 |
+
None,
|
| 1455 |
+
4,
|
| 1456 |
+
"left",
|
| 1457 |
+
ValueError(
|
| 1458 |
+
"`include_boundaries`='left' without specifying explicitly `min_val` "
|
| 1459 |
+
"is inconsistent."
|
| 1460 |
+
),
|
| 1461 |
+
),
|
| 1462 |
+
(
|
| 1463 |
+
4,
|
| 1464 |
+
"test_name8",
|
| 1465 |
+
int,
|
| 1466 |
+
2,
|
| 1467 |
+
None,
|
| 1468 |
+
"right",
|
| 1469 |
+
ValueError(
|
| 1470 |
+
"`include_boundaries`='right' without specifying explicitly `max_val` "
|
| 1471 |
+
"is inconsistent."
|
| 1472 |
+
),
|
| 1473 |
+
),
|
| 1474 |
+
],
|
| 1475 |
+
)
|
| 1476 |
+
def test_check_scalar_invalid(
|
| 1477 |
+
x, target_name, target_type, min_val, max_val, include_boundaries, err_msg
|
| 1478 |
+
):
|
| 1479 |
+
"""Test that check_scalar returns the right error if a wrong input is
|
| 1480 |
+
given"""
|
| 1481 |
+
with pytest.raises(Exception) as raised_error:
|
| 1482 |
+
check_scalar(
|
| 1483 |
+
x,
|
| 1484 |
+
target_name,
|
| 1485 |
+
target_type=target_type,
|
| 1486 |
+
min_val=min_val,
|
| 1487 |
+
max_val=max_val,
|
| 1488 |
+
include_boundaries=include_boundaries,
|
| 1489 |
+
)
|
| 1490 |
+
assert str(raised_error.value) == str(err_msg)
|
| 1491 |
+
assert isinstance(raised_error.value, type(err_msg))
|
| 1492 |
+
|
| 1493 |
+
|
| 1494 |
+
_psd_cases_valid = {
|
| 1495 |
+
"nominal": ((1, 2), np.array([1, 2]), None, ""),
|
| 1496 |
+
"nominal_np_array": (np.array([1, 2]), np.array([1, 2]), None, ""),
|
| 1497 |
+
"insignificant_imag": (
|
| 1498 |
+
(5, 5e-5j),
|
| 1499 |
+
np.array([5, 0]),
|
| 1500 |
+
PositiveSpectrumWarning,
|
| 1501 |
+
"There are imaginary parts in eigenvalues \\(1e\\-05 of the maximum real part",
|
| 1502 |
+
),
|
| 1503 |
+
"insignificant neg": ((5, -5e-5), np.array([5, 0]), PositiveSpectrumWarning, ""),
|
| 1504 |
+
"insignificant neg float32": (
|
| 1505 |
+
np.array([1, -1e-6], dtype=np.float32),
|
| 1506 |
+
np.array([1, 0], dtype=np.float32),
|
| 1507 |
+
PositiveSpectrumWarning,
|
| 1508 |
+
"There are negative eigenvalues \\(1e\\-06 of the maximum positive",
|
| 1509 |
+
),
|
| 1510 |
+
"insignificant neg float64": (
|
| 1511 |
+
np.array([1, -1e-10], dtype=np.float64),
|
| 1512 |
+
np.array([1, 0], dtype=np.float64),
|
| 1513 |
+
PositiveSpectrumWarning,
|
| 1514 |
+
"There are negative eigenvalues \\(1e\\-10 of the maximum positive",
|
| 1515 |
+
),
|
| 1516 |
+
"insignificant pos": (
|
| 1517 |
+
(5, 4e-12),
|
| 1518 |
+
np.array([5, 0]),
|
| 1519 |
+
PositiveSpectrumWarning,
|
| 1520 |
+
"the largest eigenvalue is more than 1e\\+12 times the smallest",
|
| 1521 |
+
),
|
| 1522 |
+
}
|
| 1523 |
+
|
| 1524 |
+
|
| 1525 |
+
@pytest.mark.parametrize(
|
| 1526 |
+
"lambdas, expected_lambdas, w_type, w_msg",
|
| 1527 |
+
list(_psd_cases_valid.values()),
|
| 1528 |
+
ids=list(_psd_cases_valid.keys()),
|
| 1529 |
+
)
|
| 1530 |
+
@pytest.mark.parametrize("enable_warnings", [True, False])
|
| 1531 |
+
def test_check_psd_eigenvalues_valid(
|
| 1532 |
+
lambdas, expected_lambdas, w_type, w_msg, enable_warnings
|
| 1533 |
+
):
|
| 1534 |
+
# Test that ``_check_psd_eigenvalues`` returns the right output for valid
|
| 1535 |
+
# input, possibly raising the right warning
|
| 1536 |
+
|
| 1537 |
+
if not enable_warnings:
|
| 1538 |
+
w_type = None
|
| 1539 |
+
|
| 1540 |
+
if w_type is None:
|
| 1541 |
+
with warnings.catch_warnings():
|
| 1542 |
+
warnings.simplefilter("error", PositiveSpectrumWarning)
|
| 1543 |
+
lambdas_fixed = _check_psd_eigenvalues(
|
| 1544 |
+
lambdas, enable_warnings=enable_warnings
|
| 1545 |
+
)
|
| 1546 |
+
else:
|
| 1547 |
+
with pytest.warns(w_type, match=w_msg):
|
| 1548 |
+
lambdas_fixed = _check_psd_eigenvalues(
|
| 1549 |
+
lambdas, enable_warnings=enable_warnings
|
| 1550 |
+
)
|
| 1551 |
+
|
| 1552 |
+
assert_allclose(expected_lambdas, lambdas_fixed)
|
| 1553 |
+
|
| 1554 |
+
|
| 1555 |
+
_psd_cases_invalid = {
|
| 1556 |
+
"significant_imag": (
|
| 1557 |
+
(5, 5j),
|
| 1558 |
+
ValueError,
|
| 1559 |
+
"There are significant imaginary parts in eigenv",
|
| 1560 |
+
),
|
| 1561 |
+
"all negative": (
|
| 1562 |
+
(-5, -1),
|
| 1563 |
+
ValueError,
|
| 1564 |
+
"All eigenvalues are negative \\(maximum is -1",
|
| 1565 |
+
),
|
| 1566 |
+
"significant neg": (
|
| 1567 |
+
(5, -1),
|
| 1568 |
+
ValueError,
|
| 1569 |
+
"There are significant negative eigenvalues",
|
| 1570 |
+
),
|
| 1571 |
+
"significant neg float32": (
|
| 1572 |
+
np.array([3e-4, -2e-6], dtype=np.float32),
|
| 1573 |
+
ValueError,
|
| 1574 |
+
"There are significant negative eigenvalues",
|
| 1575 |
+
),
|
| 1576 |
+
"significant neg float64": (
|
| 1577 |
+
np.array([1e-5, -2e-10], dtype=np.float64),
|
| 1578 |
+
ValueError,
|
| 1579 |
+
"There are significant negative eigenvalues",
|
| 1580 |
+
),
|
| 1581 |
+
}
|
| 1582 |
+
|
| 1583 |
+
|
| 1584 |
+
@pytest.mark.parametrize(
|
| 1585 |
+
"lambdas, err_type, err_msg",
|
| 1586 |
+
list(_psd_cases_invalid.values()),
|
| 1587 |
+
ids=list(_psd_cases_invalid.keys()),
|
| 1588 |
+
)
|
| 1589 |
+
def test_check_psd_eigenvalues_invalid(lambdas, err_type, err_msg):
|
| 1590 |
+
# Test that ``_check_psd_eigenvalues`` raises the right error for invalid
|
| 1591 |
+
# input
|
| 1592 |
+
|
| 1593 |
+
with pytest.raises(err_type, match=err_msg):
|
| 1594 |
+
_check_psd_eigenvalues(lambdas)
|
| 1595 |
+
|
| 1596 |
+
|
| 1597 |
+
def _check_sample_weight_common(xp):
|
| 1598 |
+
# Common checks between numpy/array api tests
|
| 1599 |
+
# for check_sample_weight
|
| 1600 |
+
# check None input
|
| 1601 |
+
sample_weight = _check_sample_weight(None, X=xp.ones((5, 2)))
|
| 1602 |
+
assert_allclose(_convert_to_numpy(sample_weight, xp), np.ones(5))
|
| 1603 |
+
|
| 1604 |
+
# check numbers input
|
| 1605 |
+
sample_weight = _check_sample_weight(2.0, X=xp.ones((5, 2)))
|
| 1606 |
+
assert_allclose(_convert_to_numpy(sample_weight, xp), 2 * np.ones(5))
|
| 1607 |
+
|
| 1608 |
+
# check wrong number of dimensions
|
| 1609 |
+
with pytest.raises(ValueError, match=r"Sample weights must be 1D array or scalar"):
|
| 1610 |
+
_check_sample_weight(xp.ones((2, 4)), X=xp.ones((2, 2)))
|
| 1611 |
+
|
| 1612 |
+
# check incorrect n_samples
|
| 1613 |
+
msg = re.escape(f"sample_weight.shape == {xp.ones(4).shape}, expected (2,)!")
|
| 1614 |
+
with pytest.raises(ValueError, match=msg):
|
| 1615 |
+
_check_sample_weight(xp.ones(4), X=xp.ones((2, 2)))
|
| 1616 |
+
|
| 1617 |
+
# float32 dtype is preserved
|
| 1618 |
+
X = xp.ones((5, 2))
|
| 1619 |
+
sample_weight = xp.ones(5, dtype=xp.float32)
|
| 1620 |
+
sample_weight = _check_sample_weight(sample_weight, X)
|
| 1621 |
+
assert sample_weight.dtype == xp.float32
|
| 1622 |
+
|
| 1623 |
+
# check negative weight when ensure_non_negative=True
|
| 1624 |
+
X = xp.ones((5, 2))
|
| 1625 |
+
sample_weight = xp.ones(_num_samples(X))
|
| 1626 |
+
sample_weight[-1] = -10
|
| 1627 |
+
err_msg = "Negative values in data passed to `sample_weight`"
|
| 1628 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 1629 |
+
_check_sample_weight(sample_weight, X, ensure_non_negative=True)
|
| 1630 |
+
|
| 1631 |
+
|
| 1632 |
+
def test_check_sample_weight():
|
| 1633 |
+
# check array order
|
| 1634 |
+
sample_weight = np.ones(10)[::2]
|
| 1635 |
+
assert not sample_weight.flags["C_CONTIGUOUS"]
|
| 1636 |
+
sample_weight = _check_sample_weight(sample_weight, X=np.ones((5, 1)))
|
| 1637 |
+
assert sample_weight.flags["C_CONTIGUOUS"]
|
| 1638 |
+
|
| 1639 |
+
_check_sample_weight_common(np)
|
| 1640 |
+
|
| 1641 |
+
# int dtype will be converted to float64 instead
|
| 1642 |
+
X = np.ones((5, 2), dtype=int)
|
| 1643 |
+
sample_weight = _check_sample_weight(None, X, dtype=X.dtype)
|
| 1644 |
+
assert sample_weight.dtype == np.float64
|
| 1645 |
+
|
| 1646 |
+
|
| 1647 |
+
@pytest.mark.parametrize(
|
| 1648 |
+
"array_namespace,device,dtype", yield_namespace_device_dtype_combinations()
|
| 1649 |
+
)
|
| 1650 |
+
def test_check_sample_weight_array_api(array_namespace, device, dtype):
|
| 1651 |
+
xp = _array_api_for_tests(array_namespace, device)
|
| 1652 |
+
with config_context(array_api_dispatch=True):
|
| 1653 |
+
# check array order
|
| 1654 |
+
sample_weight = xp.ones(10)[::2]
|
| 1655 |
+
if _is_numpy_namespace(xp):
|
| 1656 |
+
assert not sample_weight.flags["C_CONTIGUOUS"]
|
| 1657 |
+
sample_weight = _check_sample_weight(sample_weight, X=xp.ones((5, 1)))
|
| 1658 |
+
if _is_numpy_namespace(xp):
|
| 1659 |
+
assert sample_weight.flags["C_CONTIGUOUS"]
|
| 1660 |
+
|
| 1661 |
+
_check_sample_weight_common(xp)
|
| 1662 |
+
|
| 1663 |
+
|
| 1664 |
+
@pytest.mark.parametrize("y_true", [[0], [0, 1], [-1, 1], [1, 1, 1], [-1, -1, -1]])
|
| 1665 |
+
def test_check_pos_label_consistency(y_true):
|
| 1666 |
+
assert _check_pos_label_consistency(None, y_true) == 1
|
| 1667 |
+
|
| 1668 |
+
|
| 1669 |
+
@pytest.mark.parametrize(
|
| 1670 |
+
"array_namespace,device,dtype",
|
| 1671 |
+
yield_namespace_device_dtype_combinations(),
|
| 1672 |
+
ids=_get_namespace_device_dtype_ids,
|
| 1673 |
+
)
|
| 1674 |
+
@pytest.mark.parametrize("y_true", [[0], [0, 1], [-1, 1], [1, 1, 1], [-1, -1, -1]])
|
| 1675 |
+
def test_check_pos_label_consistency_array_api(array_namespace, device, dtype, y_true):
|
| 1676 |
+
xp = _array_api_for_tests(array_namespace, device)
|
| 1677 |
+
with config_context(array_api_dispatch=True):
|
| 1678 |
+
arr = xp.asarray(y_true, device=device)
|
| 1679 |
+
assert _check_pos_label_consistency(None, arr) == 1
|
| 1680 |
+
|
| 1681 |
+
|
| 1682 |
+
@pytest.mark.parametrize("y_true", [[2, 3, 4], [-10], [0, -1]])
|
| 1683 |
+
def test_check_pos_label_consistency_invalid(y_true):
|
| 1684 |
+
with pytest.raises(ValueError, match="y_true takes value in"):
|
| 1685 |
+
_check_pos_label_consistency(None, y_true)
|
| 1686 |
+
# Make sure we only raise if pos_label is None
|
| 1687 |
+
assert _check_pos_label_consistency("a", y_true) == "a"
|
| 1688 |
+
|
| 1689 |
+
|
| 1690 |
+
@pytest.mark.parametrize(
|
| 1691 |
+
"array_namespace,device,dtype",
|
| 1692 |
+
yield_namespace_device_dtype_combinations(),
|
| 1693 |
+
ids=_get_namespace_device_dtype_ids,
|
| 1694 |
+
)
|
| 1695 |
+
@pytest.mark.parametrize("y_true", [[2, 3, 4], [-10], [0, -1]])
|
| 1696 |
+
def test_check_pos_label_consistency_invalid_array_api(
|
| 1697 |
+
array_namespace, device, dtype, y_true
|
| 1698 |
+
):
|
| 1699 |
+
xp = _array_api_for_tests(array_namespace, device)
|
| 1700 |
+
with config_context(array_api_dispatch=True):
|
| 1701 |
+
arr = xp.asarray(y_true, device=device)
|
| 1702 |
+
with pytest.raises(ValueError, match="y_true takes value in"):
|
| 1703 |
+
_check_pos_label_consistency(None, arr)
|
| 1704 |
+
# Make sure we only raise if pos_label is None
|
| 1705 |
+
assert _check_pos_label_consistency("a", arr) == "a"
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
@pytest.mark.parametrize("toarray", [np.array, sp.csr_matrix, sp.csc_matrix])
|
| 1709 |
+
def test_allclose_dense_sparse_equals(toarray):
|
| 1710 |
+
base = np.arange(9).reshape(3, 3)
|
| 1711 |
+
x, y = toarray(base), toarray(base)
|
| 1712 |
+
assert _allclose_dense_sparse(x, y)
|
| 1713 |
+
|
| 1714 |
+
|
| 1715 |
+
@pytest.mark.parametrize("toarray", [np.array, sp.csr_matrix, sp.csc_matrix])
|
| 1716 |
+
def test_allclose_dense_sparse_not_equals(toarray):
|
| 1717 |
+
base = np.arange(9).reshape(3, 3)
|
| 1718 |
+
x, y = toarray(base), toarray(base + 1)
|
| 1719 |
+
assert not _allclose_dense_sparse(x, y)
|
| 1720 |
+
|
| 1721 |
+
|
| 1722 |
+
@pytest.mark.parametrize("toarray", [sp.csr_matrix, sp.csc_matrix])
|
| 1723 |
+
def test_allclose_dense_sparse_raise(toarray):
|
| 1724 |
+
x = np.arange(9).reshape(3, 3)
|
| 1725 |
+
y = toarray(x + 1)
|
| 1726 |
+
|
| 1727 |
+
msg = "Can only compare two sparse matrices, not a sparse matrix and an array"
|
| 1728 |
+
with pytest.raises(ValueError, match=msg):
|
| 1729 |
+
_allclose_dense_sparse(x, y)
|
| 1730 |
+
|
| 1731 |
+
|
| 1732 |
+
def test_deprecate_positional_args_warns_for_function():
|
| 1733 |
+
@_deprecate_positional_args
|
| 1734 |
+
def f1(a, b, *, c=1, d=1):
|
| 1735 |
+
pass
|
| 1736 |
+
|
| 1737 |
+
with pytest.warns(FutureWarning, match=r"Pass c=3 as keyword args"):
|
| 1738 |
+
f1(1, 2, 3)
|
| 1739 |
+
|
| 1740 |
+
with pytest.warns(FutureWarning, match=r"Pass c=3, d=4 as keyword args"):
|
| 1741 |
+
f1(1, 2, 3, 4)
|
| 1742 |
+
|
| 1743 |
+
@_deprecate_positional_args
|
| 1744 |
+
def f2(a=1, *, b=1, c=1, d=1):
|
| 1745 |
+
pass
|
| 1746 |
+
|
| 1747 |
+
with pytest.warns(FutureWarning, match=r"Pass b=2 as keyword args"):
|
| 1748 |
+
f2(1, 2)
|
| 1749 |
+
|
| 1750 |
+
# The * is place before a keyword only argument without a default value
|
| 1751 |
+
@_deprecate_positional_args
|
| 1752 |
+
def f3(a, *, b, c=1, d=1):
|
| 1753 |
+
pass
|
| 1754 |
+
|
| 1755 |
+
with pytest.warns(FutureWarning, match=r"Pass b=2 as keyword args"):
|
| 1756 |
+
f3(1, 2)
|
| 1757 |
+
|
| 1758 |
+
|
| 1759 |
+
def test_deprecate_positional_args_warns_for_function_version():
|
| 1760 |
+
@_deprecate_positional_args(version="1.1")
|
| 1761 |
+
def f1(a, *, b):
|
| 1762 |
+
pass
|
| 1763 |
+
|
| 1764 |
+
with pytest.warns(
|
| 1765 |
+
FutureWarning, match=r"From version 1.1 passing these as positional"
|
| 1766 |
+
):
|
| 1767 |
+
f1(1, 2)
|
| 1768 |
+
|
| 1769 |
+
|
| 1770 |
+
def test_deprecate_positional_args_warns_for_class():
|
| 1771 |
+
class A1:
|
| 1772 |
+
@_deprecate_positional_args
|
| 1773 |
+
def __init__(self, a, b, *, c=1, d=1):
|
| 1774 |
+
pass
|
| 1775 |
+
|
| 1776 |
+
with pytest.warns(FutureWarning, match=r"Pass c=3 as keyword args"):
|
| 1777 |
+
A1(1, 2, 3)
|
| 1778 |
+
|
| 1779 |
+
with pytest.warns(FutureWarning, match=r"Pass c=3, d=4 as keyword args"):
|
| 1780 |
+
A1(1, 2, 3, 4)
|
| 1781 |
+
|
| 1782 |
+
class A2:
|
| 1783 |
+
@_deprecate_positional_args
|
| 1784 |
+
def __init__(self, a=1, b=1, *, c=1, d=1):
|
| 1785 |
+
pass
|
| 1786 |
+
|
| 1787 |
+
with pytest.warns(FutureWarning, match=r"Pass c=3 as keyword args"):
|
| 1788 |
+
A2(1, 2, 3)
|
| 1789 |
+
|
| 1790 |
+
with pytest.warns(FutureWarning, match=r"Pass c=3, d=4 as keyword args"):
|
| 1791 |
+
A2(1, 2, 3, 4)
|
| 1792 |
+
|
| 1793 |
+
|
| 1794 |
+
@pytest.mark.parametrize("indices", [None, [1, 3]])
|
| 1795 |
+
def test_check_method_params(indices):
|
| 1796 |
+
X = np.random.randn(4, 2)
|
| 1797 |
+
_params = {
|
| 1798 |
+
"list": [1, 2, 3, 4],
|
| 1799 |
+
"array": np.array([1, 2, 3, 4]),
|
| 1800 |
+
"sparse-col": sp.csc_matrix([1, 2, 3, 4]).T,
|
| 1801 |
+
"sparse-row": sp.csc_matrix([1, 2, 3, 4]),
|
| 1802 |
+
"scalar-int": 1,
|
| 1803 |
+
"scalar-str": "xxx",
|
| 1804 |
+
"None": None,
|
| 1805 |
+
}
|
| 1806 |
+
result = _check_method_params(X, params=_params, indices=indices)
|
| 1807 |
+
indices_ = indices if indices is not None else list(range(X.shape[0]))
|
| 1808 |
+
|
| 1809 |
+
for key in ["sparse-row", "scalar-int", "scalar-str", "None"]:
|
| 1810 |
+
assert result[key] is _params[key]
|
| 1811 |
+
|
| 1812 |
+
assert result["list"] == _safe_indexing(_params["list"], indices_)
|
| 1813 |
+
assert_array_equal(result["array"], _safe_indexing(_params["array"], indices_))
|
| 1814 |
+
assert_allclose_dense_sparse(
|
| 1815 |
+
result["sparse-col"], _safe_indexing(_params["sparse-col"], indices_)
|
| 1816 |
+
)
|
| 1817 |
+
|
| 1818 |
+
|
| 1819 |
+
@pytest.mark.parametrize("sp_format", [True, "csr", "csc", "coo", "bsr"])
|
| 1820 |
+
def test_check_sparse_pandas_sp_format(sp_format):
|
| 1821 |
+
# check_array converts pandas dataframe with only sparse arrays into
|
| 1822 |
+
# sparse matrix
|
| 1823 |
+
pd = pytest.importorskip("pandas")
|
| 1824 |
+
sp_mat = _sparse_random_matrix(10, 3)
|
| 1825 |
+
|
| 1826 |
+
sdf = pd.DataFrame.sparse.from_spmatrix(sp_mat)
|
| 1827 |
+
result = check_array(sdf, accept_sparse=sp_format)
|
| 1828 |
+
|
| 1829 |
+
if sp_format is True:
|
| 1830 |
+
# by default pandas converts to coo when accept_sparse is True
|
| 1831 |
+
sp_format = "coo"
|
| 1832 |
+
|
| 1833 |
+
assert sp.issparse(result)
|
| 1834 |
+
assert result.format == sp_format
|
| 1835 |
+
assert_allclose_dense_sparse(sp_mat, result)
|
| 1836 |
+
|
| 1837 |
+
|
| 1838 |
+
@pytest.mark.parametrize(
|
| 1839 |
+
"ntype1, ntype2",
|
| 1840 |
+
[
|
| 1841 |
+
("longdouble", "float16"),
|
| 1842 |
+
("float16", "float32"),
|
| 1843 |
+
("float32", "double"),
|
| 1844 |
+
("int16", "int32"),
|
| 1845 |
+
("int32", "long"),
|
| 1846 |
+
("byte", "uint16"),
|
| 1847 |
+
("ushort", "uint32"),
|
| 1848 |
+
("uint32", "uint64"),
|
| 1849 |
+
("uint8", "int8"),
|
| 1850 |
+
],
|
| 1851 |
+
)
|
| 1852 |
+
def test_check_pandas_sparse_mixed_dtypes(ntype1, ntype2):
|
| 1853 |
+
"""Check that pandas dataframes having sparse extension arrays with mixed dtypes
|
| 1854 |
+
works."""
|
| 1855 |
+
pd = pytest.importorskip("pandas")
|
| 1856 |
+
df = pd.DataFrame(
|
| 1857 |
+
{
|
| 1858 |
+
"col1": pd.arrays.SparseArray([0, 1, 0], dtype=ntype1, fill_value=0),
|
| 1859 |
+
"col2": pd.arrays.SparseArray([1, 0, 1], dtype=ntype2, fill_value=0),
|
| 1860 |
+
}
|
| 1861 |
+
)
|
| 1862 |
+
check_array(df, accept_sparse=["csr", "csc"])
|
| 1863 |
+
|
| 1864 |
+
|
| 1865 |
+
@pytest.mark.parametrize(
|
| 1866 |
+
"ntype1, ntype2, expected_subtype",
|
| 1867 |
+
[
|
| 1868 |
+
("double", "longdouble", np.floating),
|
| 1869 |
+
("single", "float32", np.floating),
|
| 1870 |
+
("double", "float64", np.floating),
|
| 1871 |
+
("int8", "byte", np.integer),
|
| 1872 |
+
("short", "int16", np.integer),
|
| 1873 |
+
("intc", "int32", np.integer),
|
| 1874 |
+
("intp", "long", np.integer),
|
| 1875 |
+
("int", "long", np.integer),
|
| 1876 |
+
("int64", "longlong", np.integer),
|
| 1877 |
+
("int_", "intp", np.integer),
|
| 1878 |
+
("ubyte", "uint8", np.unsignedinteger),
|
| 1879 |
+
("uint16", "ushort", np.unsignedinteger),
|
| 1880 |
+
("uintc", "uint32", np.unsignedinteger),
|
| 1881 |
+
("uint", "uint64", np.unsignedinteger),
|
| 1882 |
+
("uintp", "ulonglong", np.unsignedinteger),
|
| 1883 |
+
],
|
| 1884 |
+
)
|
| 1885 |
+
def test_check_pandas_sparse_valid(ntype1, ntype2, expected_subtype):
|
| 1886 |
+
# check that we support the conversion of sparse dataframe with mixed
|
| 1887 |
+
# type which can be converted safely.
|
| 1888 |
+
pd = pytest.importorskip("pandas")
|
| 1889 |
+
df = pd.DataFrame(
|
| 1890 |
+
{
|
| 1891 |
+
"col1": pd.arrays.SparseArray([0, 1, 0], dtype=ntype1, fill_value=0),
|
| 1892 |
+
"col2": pd.arrays.SparseArray([1, 0, 1], dtype=ntype2, fill_value=0),
|
| 1893 |
+
}
|
| 1894 |
+
)
|
| 1895 |
+
arr = check_array(df, accept_sparse=["csr", "csc"])
|
| 1896 |
+
assert np.issubdtype(arr.dtype, expected_subtype)
|
| 1897 |
+
|
| 1898 |
+
|
| 1899 |
+
@pytest.mark.parametrize(
|
| 1900 |
+
"constructor_name",
|
| 1901 |
+
["list", "tuple", "array", "dataframe", "sparse_csr", "sparse_csc"],
|
| 1902 |
+
)
|
| 1903 |
+
def test_num_features(constructor_name):
|
| 1904 |
+
"""Check _num_features for array-likes."""
|
| 1905 |
+
X = [[1, 2, 3], [4, 5, 6]]
|
| 1906 |
+
X = _convert_container(X, constructor_name)
|
| 1907 |
+
assert _num_features(X) == 3
|
| 1908 |
+
|
| 1909 |
+
|
| 1910 |
+
@pytest.mark.parametrize(
|
| 1911 |
+
"X",
|
| 1912 |
+
[
|
| 1913 |
+
[1, 2, 3],
|
| 1914 |
+
["a", "b", "c"],
|
| 1915 |
+
[False, True, False],
|
| 1916 |
+
[1.0, 3.4, 4.0],
|
| 1917 |
+
[{"a": 1}, {"b": 2}, {"c": 3}],
|
| 1918 |
+
],
|
| 1919 |
+
ids=["int", "str", "bool", "float", "dict"],
|
| 1920 |
+
)
|
| 1921 |
+
@pytest.mark.parametrize("constructor_name", ["list", "tuple", "array", "series"])
|
| 1922 |
+
def test_num_features_errors_1d_containers(X, constructor_name):
|
| 1923 |
+
X = _convert_container(X, constructor_name)
|
| 1924 |
+
if constructor_name == "array":
|
| 1925 |
+
expected_type_name = "numpy.ndarray"
|
| 1926 |
+
elif constructor_name == "series":
|
| 1927 |
+
expected_type_name = "pandas.*Series"
|
| 1928 |
+
else:
|
| 1929 |
+
expected_type_name = constructor_name
|
| 1930 |
+
message = (
|
| 1931 |
+
f"Unable to find the number of features from X of type {expected_type_name}"
|
| 1932 |
+
)
|
| 1933 |
+
if hasattr(X, "shape"):
|
| 1934 |
+
message += re.escape(" with shape (3,)")
|
| 1935 |
+
elif isinstance(X[0], str):
|
| 1936 |
+
message += " where the samples are of type str"
|
| 1937 |
+
elif isinstance(X[0], dict):
|
| 1938 |
+
message += " where the samples are of type dict"
|
| 1939 |
+
with pytest.raises(TypeError, match=message):
|
| 1940 |
+
_num_features(X)
|
| 1941 |
+
|
| 1942 |
+
|
| 1943 |
+
@pytest.mark.parametrize("X", [1, "b", False, 3.0], ids=["int", "str", "bool", "float"])
|
| 1944 |
+
def test_num_features_errors_scalars(X):
|
| 1945 |
+
msg = f"Unable to find the number of features from X of type {type(X).__qualname__}"
|
| 1946 |
+
with pytest.raises(TypeError, match=msg):
|
| 1947 |
+
_num_features(X)
|
| 1948 |
+
|
| 1949 |
+
|
| 1950 |
+
@pytest.mark.parametrize(
|
| 1951 |
+
"names",
|
| 1952 |
+
[list(range(2)), range(2), None, [["a", "b"], ["c", "d"]]],
|
| 1953 |
+
ids=["list-int", "range", "default", "MultiIndex"],
|
| 1954 |
+
)
|
| 1955 |
+
def test_get_feature_names_pandas_with_ints_no_warning(names):
|
| 1956 |
+
"""Get feature names with pandas dataframes without warning.
|
| 1957 |
+
|
| 1958 |
+
Column names with consistent dtypes will not warn, such as int or MultiIndex.
|
| 1959 |
+
"""
|
| 1960 |
+
pd = pytest.importorskip("pandas")
|
| 1961 |
+
X = pd.DataFrame([[1, 2], [4, 5], [5, 6]], columns=names)
|
| 1962 |
+
|
| 1963 |
+
with warnings.catch_warnings():
|
| 1964 |
+
warnings.simplefilter("error", FutureWarning)
|
| 1965 |
+
names = _get_feature_names(X)
|
| 1966 |
+
assert names is None
|
| 1967 |
+
|
| 1968 |
+
|
| 1969 |
+
def test_get_feature_names_pandas():
|
| 1970 |
+
"""Get feature names with pandas dataframes."""
|
| 1971 |
+
pd = pytest.importorskip("pandas")
|
| 1972 |
+
columns = [f"col_{i}" for i in range(3)]
|
| 1973 |
+
X = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=columns)
|
| 1974 |
+
feature_names = _get_feature_names(X)
|
| 1975 |
+
|
| 1976 |
+
assert_array_equal(feature_names, columns)
|
| 1977 |
+
|
| 1978 |
+
|
| 1979 |
+
@pytest.mark.parametrize(
|
| 1980 |
+
"constructor_name, minversion",
|
| 1981 |
+
[("pyarrow", "12.0.0"), ("dataframe", "1.5.0"), ("polars", "0.18.2")],
|
| 1982 |
+
)
|
| 1983 |
+
def test_get_feature_names_dataframe_protocol(constructor_name, minversion):
|
| 1984 |
+
"""Uses the dataframe exchange protocol to get feature names."""
|
| 1985 |
+
data = [[1, 4, 2], [3, 3, 6]]
|
| 1986 |
+
columns = ["col_0", "col_1", "col_2"]
|
| 1987 |
+
df = _convert_container(
|
| 1988 |
+
data, constructor_name, columns_name=columns, minversion=minversion
|
| 1989 |
+
)
|
| 1990 |
+
feature_names = _get_feature_names(df)
|
| 1991 |
+
|
| 1992 |
+
assert_array_equal(feature_names, columns)
|
| 1993 |
+
|
| 1994 |
+
|
| 1995 |
+
def test_get_feature_names_numpy():
|
| 1996 |
+
"""Get feature names return None for numpy arrays."""
|
| 1997 |
+
X = np.array([[1, 2, 3], [4, 5, 6]])
|
| 1998 |
+
names = _get_feature_names(X)
|
| 1999 |
+
assert names is None
|
| 2000 |
+
|
| 2001 |
+
|
| 2002 |
+
@pytest.mark.parametrize(
|
| 2003 |
+
"names, dtypes",
|
| 2004 |
+
[
|
| 2005 |
+
(["a", 1], "['int', 'str']"),
|
| 2006 |
+
(["pizza", ["a", "b"]], "['list', 'str']"),
|
| 2007 |
+
],
|
| 2008 |
+
ids=["int-str", "list-str"],
|
| 2009 |
+
)
|
| 2010 |
+
def test_get_feature_names_invalid_dtypes(names, dtypes):
|
| 2011 |
+
"""Get feature names errors when the feature names have mixed dtypes"""
|
| 2012 |
+
pd = pytest.importorskip("pandas")
|
| 2013 |
+
X = pd.DataFrame([[1, 2], [4, 5], [5, 6]], columns=names)
|
| 2014 |
+
|
| 2015 |
+
msg = re.escape(
|
| 2016 |
+
"Feature names are only supported if all input features have string names, "
|
| 2017 |
+
f"but your input has {dtypes} as feature name / column name types. "
|
| 2018 |
+
"If you want feature names to be stored and validated, you must convert "
|
| 2019 |
+
"them all to strings, by using X.columns = X.columns.astype(str) for "
|
| 2020 |
+
"example. Otherwise you can remove feature / column names from your input "
|
| 2021 |
+
"data, or convert them all to a non-string data type."
|
| 2022 |
+
)
|
| 2023 |
+
with pytest.raises(TypeError, match=msg):
|
| 2024 |
+
names = _get_feature_names(X)
|
| 2025 |
+
|
| 2026 |
+
|
| 2027 |
+
class PassthroughTransformer(BaseEstimator):
|
| 2028 |
+
def fit(self, X, y=None):
|
| 2029 |
+
validate_data(self, X, reset=True)
|
| 2030 |
+
return self
|
| 2031 |
+
|
| 2032 |
+
def transform(self, X):
|
| 2033 |
+
return X
|
| 2034 |
+
|
| 2035 |
+
def get_feature_names_out(self, input_features=None):
|
| 2036 |
+
return _check_feature_names_in(self, input_features)
|
| 2037 |
+
|
| 2038 |
+
|
| 2039 |
+
def test_check_feature_names_in():
|
| 2040 |
+
"""Check behavior of check_feature_names_in for arrays."""
|
| 2041 |
+
X = np.array([[0.0, 1.0, 2.0]])
|
| 2042 |
+
est = PassthroughTransformer().fit(X)
|
| 2043 |
+
|
| 2044 |
+
names = est.get_feature_names_out()
|
| 2045 |
+
assert_array_equal(names, ["x0", "x1", "x2"])
|
| 2046 |
+
|
| 2047 |
+
incorrect_len_names = ["x10", "x1"]
|
| 2048 |
+
with pytest.raises(ValueError, match="input_features should have length equal to"):
|
| 2049 |
+
est.get_feature_names_out(incorrect_len_names)
|
| 2050 |
+
|
| 2051 |
+
# remove n_feature_in_
|
| 2052 |
+
del est.n_features_in_
|
| 2053 |
+
with pytest.raises(ValueError, match="Unable to generate feature names"):
|
| 2054 |
+
est.get_feature_names_out()
|
| 2055 |
+
|
| 2056 |
+
|
| 2057 |
+
def test_check_feature_names_in_pandas():
|
| 2058 |
+
"""Check behavior of check_feature_names_in for pandas dataframes."""
|
| 2059 |
+
pd = pytest.importorskip("pandas")
|
| 2060 |
+
names = ["a", "b", "c"]
|
| 2061 |
+
df = pd.DataFrame([[0.0, 1.0, 2.0]], columns=names)
|
| 2062 |
+
est = PassthroughTransformer().fit(df)
|
| 2063 |
+
|
| 2064 |
+
names = est.get_feature_names_out()
|
| 2065 |
+
assert_array_equal(names, ["a", "b", "c"])
|
| 2066 |
+
|
| 2067 |
+
with pytest.raises(ValueError, match="input_features is not equal to"):
|
| 2068 |
+
est.get_feature_names_out(["x1", "x2", "x3"])
|
| 2069 |
+
|
| 2070 |
+
|
| 2071 |
+
def test_check_response_method_unknown_method():
|
| 2072 |
+
"""Check the error message when passing an unknown response method."""
|
| 2073 |
+
err_msg = (
|
| 2074 |
+
"RandomForestRegressor has none of the following attributes: unknown_method."
|
| 2075 |
+
)
|
| 2076 |
+
with pytest.raises(AttributeError, match=err_msg):
|
| 2077 |
+
_check_response_method(RandomForestRegressor(), "unknown_method")
|
| 2078 |
+
|
| 2079 |
+
|
| 2080 |
+
@pytest.mark.parametrize(
|
| 2081 |
+
"response_method", ["decision_function", "predict_proba", "predict"]
|
| 2082 |
+
)
|
| 2083 |
+
def test_check_response_method_not_supported_response_method(response_method):
|
| 2084 |
+
"""Check the error message when a response method is not supported by the
|
| 2085 |
+
estimator."""
|
| 2086 |
+
err_msg = (
|
| 2087 |
+
f"EstimatorWithFit has none of the following attributes: {response_method}."
|
| 2088 |
+
)
|
| 2089 |
+
with pytest.raises(AttributeError, match=err_msg):
|
| 2090 |
+
_check_response_method(EstimatorWithFit(), response_method)
|
| 2091 |
+
|
| 2092 |
+
|
| 2093 |
+
def test_check_response_method_list_str():
|
| 2094 |
+
"""Check that we can pass a list of ordered method."""
|
| 2095 |
+
method_implemented = ["predict_proba"]
|
| 2096 |
+
my_estimator = _MockEstimatorOnOffPrediction(method_implemented)
|
| 2097 |
+
|
| 2098 |
+
X = "mocking_data"
|
| 2099 |
+
|
| 2100 |
+
# raise an error when no methods are defined
|
| 2101 |
+
response_method = ["decision_function", "predict"]
|
| 2102 |
+
err_msg = (
|
| 2103 |
+
"_MockEstimatorOnOffPrediction has none of the following attributes: "
|
| 2104 |
+
f"{', '.join(response_method)}."
|
| 2105 |
+
)
|
| 2106 |
+
with pytest.raises(AttributeError, match=err_msg):
|
| 2107 |
+
_check_response_method(my_estimator, response_method)(X)
|
| 2108 |
+
|
| 2109 |
+
# check that we don't get issue when one of the method is defined
|
| 2110 |
+
response_method = ["decision_function", "predict_proba"]
|
| 2111 |
+
method_name_predicting = _check_response_method(my_estimator, response_method)(X)
|
| 2112 |
+
assert method_name_predicting == "predict_proba"
|
| 2113 |
+
|
| 2114 |
+
# check the order of the methods returned
|
| 2115 |
+
method_implemented = ["predict_proba", "predict"]
|
| 2116 |
+
my_estimator = _MockEstimatorOnOffPrediction(method_implemented)
|
| 2117 |
+
response_method = ["decision_function", "predict", "predict_proba"]
|
| 2118 |
+
method_name_predicting = _check_response_method(my_estimator, response_method)(X)
|
| 2119 |
+
assert method_name_predicting == "predict"
|
| 2120 |
+
|
| 2121 |
+
|
| 2122 |
+
def test_boolean_series_remains_boolean():
|
| 2123 |
+
"""Regression test for gh-25145"""
|
| 2124 |
+
pd = importorskip("pandas")
|
| 2125 |
+
res = check_array(pd.Series([True, False]), ensure_2d=False)
|
| 2126 |
+
expected = np.array([True, False])
|
| 2127 |
+
|
| 2128 |
+
assert res.dtype == expected.dtype
|
| 2129 |
+
assert_array_equal(res, expected)
|
| 2130 |
+
|
| 2131 |
+
|
| 2132 |
+
@pytest.mark.parametrize("input_values", [[0, 1, 0, 1, 0, np.nan], [0, 1, 0, 1, 0, 1]])
|
| 2133 |
+
def test_pandas_array_returns_ndarray(input_values):
|
| 2134 |
+
"""Check pandas array with extensions dtypes returns a numeric ndarray.
|
| 2135 |
+
|
| 2136 |
+
Non-regression test for gh-25637.
|
| 2137 |
+
"""
|
| 2138 |
+
pd = importorskip("pandas")
|
| 2139 |
+
input_series = pd.array(input_values, dtype="Int32")
|
| 2140 |
+
result = check_array(
|
| 2141 |
+
input_series,
|
| 2142 |
+
dtype=None,
|
| 2143 |
+
ensure_2d=False,
|
| 2144 |
+
allow_nd=False,
|
| 2145 |
+
ensure_all_finite=False,
|
| 2146 |
+
)
|
| 2147 |
+
assert np.issubdtype(result.dtype.kind, np.floating)
|
| 2148 |
+
assert_allclose(result, input_values)
|
| 2149 |
+
|
| 2150 |
+
|
| 2151 |
+
@skip_if_array_api_compat_not_configured
|
| 2152 |
+
def test_check_array_array_api_has_non_finite():
|
| 2153 |
+
"""Checks that Array API arrays checks non-finite correctly."""
|
| 2154 |
+
xp = pytest.importorskip("array_api_strict")
|
| 2155 |
+
|
| 2156 |
+
X_nan = xp.asarray([[xp.nan, 1, 0], [0, xp.nan, 3]], dtype=xp.float32)
|
| 2157 |
+
with config_context(array_api_dispatch=True):
|
| 2158 |
+
with pytest.raises(ValueError, match="Input contains NaN."):
|
| 2159 |
+
check_array(X_nan)
|
| 2160 |
+
|
| 2161 |
+
X_inf = xp.asarray([[xp.inf, 1, 0], [0, xp.inf, 3]], dtype=xp.float32)
|
| 2162 |
+
with config_context(array_api_dispatch=True):
|
| 2163 |
+
with pytest.raises(ValueError, match="infinity or a value too large"):
|
| 2164 |
+
check_array(X_inf)
|
| 2165 |
+
|
| 2166 |
+
|
| 2167 |
+
@pytest.mark.parametrize(
|
| 2168 |
+
"extension_dtype, regular_dtype",
|
| 2169 |
+
[
|
| 2170 |
+
("boolean", "bool"),
|
| 2171 |
+
("Int64", "int64"),
|
| 2172 |
+
("Float64", "float64"),
|
| 2173 |
+
("category", "object"),
|
| 2174 |
+
],
|
| 2175 |
+
)
|
| 2176 |
+
@pytest.mark.parametrize("include_object", [True, False])
|
| 2177 |
+
def test_check_array_multiple_extensions(
|
| 2178 |
+
extension_dtype, regular_dtype, include_object
|
| 2179 |
+
):
|
| 2180 |
+
"""Check pandas extension arrays give the same result as non-extension arrays."""
|
| 2181 |
+
pd = pytest.importorskip("pandas")
|
| 2182 |
+
X_regular = pd.DataFrame(
|
| 2183 |
+
{
|
| 2184 |
+
"a": pd.Series([1, 0, 1, 0], dtype=regular_dtype),
|
| 2185 |
+
"c": pd.Series([9, 8, 7, 6], dtype="int64"),
|
| 2186 |
+
}
|
| 2187 |
+
)
|
| 2188 |
+
if include_object:
|
| 2189 |
+
X_regular["b"] = pd.Series(["a", "b", "c", "d"], dtype="object")
|
| 2190 |
+
|
| 2191 |
+
X_extension = X_regular.assign(a=X_regular["a"].astype(extension_dtype))
|
| 2192 |
+
|
| 2193 |
+
X_regular_checked = check_array(X_regular, dtype=None)
|
| 2194 |
+
X_extension_checked = check_array(X_extension, dtype=None)
|
| 2195 |
+
assert_array_equal(X_regular_checked, X_extension_checked)
|
| 2196 |
+
|
| 2197 |
+
|
| 2198 |
+
def test_num_samples_dataframe_protocol():
|
| 2199 |
+
"""Use the DataFrame interchange protocol to get n_samples from polars."""
|
| 2200 |
+
pl = pytest.importorskip("polars")
|
| 2201 |
+
|
| 2202 |
+
df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 2203 |
+
assert _num_samples(df) == 3
|
| 2204 |
+
|
| 2205 |
+
|
| 2206 |
+
@pytest.mark.parametrize(
|
| 2207 |
+
"sparse_container",
|
| 2208 |
+
CSR_CONTAINERS + CSC_CONTAINERS + COO_CONTAINERS + DIA_CONTAINERS,
|
| 2209 |
+
)
|
| 2210 |
+
@pytest.mark.parametrize("output_format", ["csr", "csc", "coo"])
|
| 2211 |
+
def test_check_array_dia_to_int32_indexed_csr_csc_coo(sparse_container, output_format):
|
| 2212 |
+
"""Check the consistency of the indices dtype with sparse matrices/arrays."""
|
| 2213 |
+
X = sparse_container([[0, 1], [1, 0]], dtype=np.float64)
|
| 2214 |
+
|
| 2215 |
+
# Explicitly set the dtype of the indexing arrays
|
| 2216 |
+
if hasattr(X, "offsets"): # DIA matrix
|
| 2217 |
+
X.offsets = X.offsets.astype(np.int32)
|
| 2218 |
+
elif hasattr(X, "row") and hasattr(X, "col"): # COO matrix
|
| 2219 |
+
X.row = X.row.astype(np.int32)
|
| 2220 |
+
elif hasattr(X, "indices") and hasattr(X, "indptr"): # CSR or CSC matrix
|
| 2221 |
+
X.indices = X.indices.astype(np.int32)
|
| 2222 |
+
X.indptr = X.indptr.astype(np.int32)
|
| 2223 |
+
|
| 2224 |
+
X_checked = check_array(X, accept_sparse=output_format)
|
| 2225 |
+
if output_format == "coo":
|
| 2226 |
+
assert X_checked.row.dtype == np.int32
|
| 2227 |
+
assert X_checked.col.dtype == np.int32
|
| 2228 |
+
else: # output_format in ["csr", "csc"]
|
| 2229 |
+
assert X_checked.indices.dtype == np.int32
|
| 2230 |
+
assert X_checked.indptr.dtype == np.int32
|
| 2231 |
+
|
| 2232 |
+
|
| 2233 |
+
@pytest.mark.parametrize("sequence", [[np.array(1), np.array(2)], [[1, 2], [3, 4]]])
|
| 2234 |
+
def test_to_object_array(sequence):
|
| 2235 |
+
out = _to_object_array(sequence)
|
| 2236 |
+
assert isinstance(out, np.ndarray)
|
| 2237 |
+
assert out.dtype.kind == "O"
|
| 2238 |
+
assert out.ndim == 1
|
| 2239 |
+
|
| 2240 |
+
|
| 2241 |
+
def test_column_or_1d():
|
| 2242 |
+
EXAMPLES = [
|
| 2243 |
+
("binary", ["spam", "egg", "spam"]),
|
| 2244 |
+
("binary", [0, 1, 0, 1]),
|
| 2245 |
+
("continuous", np.arange(10) / 20.0),
|
| 2246 |
+
("multiclass", [1, 2, 3]),
|
| 2247 |
+
("multiclass", [0, 1, 2, 2, 0]),
|
| 2248 |
+
("multiclass", [[1], [2], [3]]),
|
| 2249 |
+
("multilabel-indicator", [[0, 1, 0], [0, 0, 1]]),
|
| 2250 |
+
("multiclass-multioutput", [[1, 2, 3]]),
|
| 2251 |
+
("multiclass-multioutput", [[1, 1], [2, 2], [3, 1]]),
|
| 2252 |
+
("multiclass-multioutput", [[5, 1], [4, 2], [3, 1]]),
|
| 2253 |
+
("multiclass-multioutput", [[1, 2, 3]]),
|
| 2254 |
+
("continuous-multioutput", np.arange(30).reshape((-1, 3))),
|
| 2255 |
+
]
|
| 2256 |
+
|
| 2257 |
+
for y_type, y in EXAMPLES:
|
| 2258 |
+
if y_type in ["binary", "multiclass", "continuous"]:
|
| 2259 |
+
assert_array_equal(column_or_1d(y), np.ravel(y))
|
| 2260 |
+
else:
|
| 2261 |
+
with pytest.raises(ValueError):
|
| 2262 |
+
column_or_1d(y)
|
| 2263 |
+
|
| 2264 |
+
|
| 2265 |
+
def test_check_array_writeable_np():
|
| 2266 |
+
"""Check the behavior of check_array when a writeable array is requested
|
| 2267 |
+
without copy if possible, on numpy arrays.
|
| 2268 |
+
"""
|
| 2269 |
+
X = np.random.uniform(size=(10, 10))
|
| 2270 |
+
|
| 2271 |
+
out = check_array(X, copy=False, force_writeable=True)
|
| 2272 |
+
# X is already writeable, no copy is needed
|
| 2273 |
+
assert np.may_share_memory(out, X)
|
| 2274 |
+
assert out.flags.writeable
|
| 2275 |
+
|
| 2276 |
+
X.flags.writeable = False
|
| 2277 |
+
|
| 2278 |
+
out = check_array(X, copy=False, force_writeable=True)
|
| 2279 |
+
# X is not writeable, a copy is made
|
| 2280 |
+
assert not np.may_share_memory(out, X)
|
| 2281 |
+
assert out.flags.writeable
|
| 2282 |
+
|
| 2283 |
+
|
| 2284 |
+
def test_check_array_writeable_mmap():
|
| 2285 |
+
"""Check the behavior of check_array when a writeable array is requested
|
| 2286 |
+
without copy if possible, on a memory-map.
|
| 2287 |
+
|
| 2288 |
+
A common situation is when a meta-estimators run in parallel using multiprocessing
|
| 2289 |
+
with joblib, which creates read-only memory-maps of large arrays.
|
| 2290 |
+
"""
|
| 2291 |
+
X = np.random.uniform(size=(10, 10))
|
| 2292 |
+
|
| 2293 |
+
mmap = create_memmap_backed_data(X, mmap_mode="w+")
|
| 2294 |
+
out = check_array(mmap, copy=False, force_writeable=True)
|
| 2295 |
+
# mmap is already writeable, no copy is needed
|
| 2296 |
+
assert np.may_share_memory(out, mmap)
|
| 2297 |
+
assert out.flags.writeable
|
| 2298 |
+
|
| 2299 |
+
mmap = create_memmap_backed_data(X, mmap_mode="r")
|
| 2300 |
+
out = check_array(mmap, copy=False, force_writeable=True)
|
| 2301 |
+
# mmap is read-only, a copy is made
|
| 2302 |
+
assert not np.may_share_memory(out, mmap)
|
| 2303 |
+
assert out.flags.writeable
|
| 2304 |
+
|
| 2305 |
+
|
| 2306 |
+
def test_check_array_writeable_df():
|
| 2307 |
+
"""Check the behavior of check_array when a writeable array is requested
|
| 2308 |
+
without copy if possible, on a dataframe.
|
| 2309 |
+
"""
|
| 2310 |
+
pd = pytest.importorskip("pandas")
|
| 2311 |
+
|
| 2312 |
+
X = np.random.uniform(size=(10, 10))
|
| 2313 |
+
df = pd.DataFrame(X, copy=False)
|
| 2314 |
+
|
| 2315 |
+
out = check_array(df, copy=False, force_writeable=True)
|
| 2316 |
+
# df is backed by a writeable array, no copy is needed
|
| 2317 |
+
assert np.may_share_memory(out, df)
|
| 2318 |
+
assert out.flags.writeable
|
| 2319 |
+
|
| 2320 |
+
X.flags.writeable = False
|
| 2321 |
+
df = pd.DataFrame(X, copy=False)
|
| 2322 |
+
|
| 2323 |
+
out = check_array(df, copy=False, force_writeable=True)
|
| 2324 |
+
# df is backed by a read-only array, a copy is made
|
| 2325 |
+
assert not np.may_share_memory(out, df)
|
| 2326 |
+
assert out.flags.writeable
|
| 2327 |
+
|
| 2328 |
+
|
| 2329 |
+
@skip_if_array_api_compat_not_configured
|
| 2330 |
+
def test_check_array_on_sparse_inputs_with_array_api_enabled():
|
| 2331 |
+
X_sp = sp.csr_array([[0, 1, 0], [1, 0, 1]])
|
| 2332 |
+
with config_context(array_api_dispatch=True):
|
| 2333 |
+
assert sp.issparse(check_array(X_sp, accept_sparse=True))
|
| 2334 |
+
|
| 2335 |
+
with pytest.raises(TypeError):
|
| 2336 |
+
check_array(X_sp)
|
| 2337 |
+
|
| 2338 |
+
|
| 2339 |
+
@pytest.mark.parametrize(
|
| 2340 |
+
["X", "estimator", "expected_error_message"],
|
| 2341 |
+
[
|
| 2342 |
+
(
|
| 2343 |
+
np.array([[[1, 2], [3, 4]], [[1, 2], [3, 4]]]),
|
| 2344 |
+
RandomForestRegressor(),
|
| 2345 |
+
"Found array with dim 3, while dim <= 2 is required by "
|
| 2346 |
+
"RandomForestRegressor.",
|
| 2347 |
+
),
|
| 2348 |
+
(
|
| 2349 |
+
np.array([[[1, 2], [3, 4]], [[1, 2], [3, 4]]]),
|
| 2350 |
+
None,
|
| 2351 |
+
"Found array with dim 3, while dim <= 2 is required.",
|
| 2352 |
+
),
|
| 2353 |
+
],
|
| 2354 |
+
)
|
| 2355 |
+
def test_check_array_allow_nd_errors(X, estimator, expected_error_message):
|
| 2356 |
+
with pytest.raises(ValueError, match=expected_error_message):
|
| 2357 |
+
check_array(X, estimator=estimator)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/tests/test_weight_vector.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from sklearn.utils._weight_vector import (
|
| 5 |
+
WeightVector32,
|
| 6 |
+
WeightVector64,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@pytest.mark.parametrize(
|
| 11 |
+
"dtype, WeightVector",
|
| 12 |
+
[
|
| 13 |
+
(np.float32, WeightVector32),
|
| 14 |
+
(np.float64, WeightVector64),
|
| 15 |
+
],
|
| 16 |
+
)
|
| 17 |
+
def test_type_invariance(dtype, WeightVector):
|
| 18 |
+
"""Check the `dtype` consistency of `WeightVector`."""
|
| 19 |
+
weights = np.random.rand(100).astype(dtype)
|
| 20 |
+
average_weights = np.random.rand(100).astype(dtype)
|
| 21 |
+
|
| 22 |
+
weight_vector = WeightVector(weights, average_weights)
|
| 23 |
+
|
| 24 |
+
assert np.asarray(weight_vector.w).dtype is np.dtype(dtype)
|
| 25 |
+
assert np.asarray(weight_vector.aw).dtype is np.dtype(dtype)
|
loan-advisor-agent/.venv/Lib/site-packages/sklearn/utils/validation.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|