Skip to content

MAINT cleanup utils.__init__: move _to_object_array into utils.validation #28661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions sklearn/neighbors/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,14 @@
)
from ..metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS
from ..utils import (
_to_object_array,
check_array,
gen_even_slices,
)
from ..utils._param_validation import Interval, StrOptions, validate_params
from ..utils.fixes import parse_version, sp_base_version
from ..utils.multiclass import check_classification_targets
from ..utils.parallel import Parallel, delayed
from ..utils.validation import check_is_fitted, check_non_negative
from ..utils.validation import _to_object_array, check_is_fitted, check_non_negative
from ._ball_tree import BallTree
from ._kd_tree import KDTree

Expand Down
2 changes: 1 addition & 1 deletion sklearn/preprocessing/tests/test_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
_inverse_binarize_thresholding,
label_binarize,
)
from sklearn.utils import _to_object_array
from sklearn.utils._testing import assert_array_equal, ignore_warnings
from sklearn.utils.fixes import (
COO_CONTAINERS,
Expand All @@ -21,6 +20,7 @@
LIL_CONTAINERS,
)
from sklearn.utils.multiclass import type_of_target
from sklearn.utils.validation import _to_object_array

iris = datasets.load_iris()

Expand Down
36 changes: 0 additions & 36 deletions sklearn/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,39 +107,3 @@ def tosequence(x):
return x
else:
return list(x)


def _to_object_array(sequence):
"""Convert sequence to a 1-D NumPy array of object dtype.

numpy.array constructor has a similar use but it's output
is ambiguous. It can be 1-D NumPy array of object dtype if
the input is a ragged array, but if the input is a list of
equal length arrays, then the output is a 2D numpy.array.
_to_object_array solves this ambiguity by guarantying that
the output is a 1-D NumPy array of objects for any input.

Parameters
----------
sequence : array-like of shape (n_elements,)
The sequence to be converted.

Returns
-------
out : ndarray of shape (n_elements,), dtype=object
The converted sequence into a 1-D NumPy array of object dtype.

Examples
--------
>>> import numpy as np
>>> from sklearn.utils import _to_object_array
>>> _to_object_array([np.array([0]), np.array([1])])
array([array([0]), array([1])], dtype=object)
>>> _to_object_array([np.array([0]), np.array([1, 2])])
array([array([0]), array([1, 2])], dtype=object)
>>> _to_object_array([np.array([0]), np.array([1, 2])])
array([array([0]), array([1, 2])], dtype=object)
"""
out = np.empty(len(sequence), dtype=object)
out[:] = sequence
return out
9 changes: 0 additions & 9 deletions sklearn/utils/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import pytest

from sklearn.utils import (
_to_object_array,
check_random_state,
column_or_1d,
deprecated,
Expand Down Expand Up @@ -149,14 +148,6 @@ def test_deprecation_joblib_api(tmpdir):
del joblib.parallel.BACKENDS["failing"]


@pytest.mark.parametrize("sequence", [[np.array(1), np.array(2)], [[1, 2], [3, 4]]])
def test_to_object_array(sequence):
out = _to_object_array(sequence)
assert isinstance(out, np.ndarray)
assert out.dtype.kind == "O"
assert out.ndim == 1


def test__is_polars_df():
"""Check that _is_polars_df return False for non-dataframe objects."""

Expand Down
9 changes: 9 additions & 0 deletions sklearn/utils/tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
_is_polars_df,
_num_features,
_num_samples,
_to_object_array,
assert_all_finite,
check_consistent_length,
check_is_fitted,
Expand Down Expand Up @@ -2052,3 +2053,11 @@ def test_check_array_dia_to_int32_indexed_csr_csc_coo(sparse_container, output_f
else: # output_format in ["csr", "csc"]
assert X_checked.indices.dtype == np.int32
assert X_checked.indptr.dtype == np.int32


@pytest.mark.parametrize("sequence", [[np.array(1), np.array(2)], [[1, 2], [3, 4]]])
def test_to_object_array(sequence):
out = _to_object_array(sequence)
assert isinstance(out, np.ndarray)
assert out.dtype.kind == "O"
assert out.ndim == 1
36 changes: 36 additions & 0 deletions sklearn/utils/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2472,3 +2472,39 @@ def _check_pos_label_consistency(pos_label, y_true):
pos_label = 1

return pos_label


def _to_object_array(sequence):
"""Convert sequence to a 1-D NumPy array of object dtype.

numpy.array constructor has a similar use but it's output
is ambiguous. It can be 1-D NumPy array of object dtype if
the input is a ragged array, but if the input is a list of
equal length arrays, then the output is a 2D numpy.array.
_to_object_array solves this ambiguity by guarantying that
the output is a 1-D NumPy array of objects for any input.

Parameters
----------
sequence : array-like of shape (n_elements,)
The sequence to be converted.

Returns
-------
out : ndarray of shape (n_elements,), dtype=object
The converted sequence into a 1-D NumPy array of object dtype.

Examples
--------
>>> import numpy as np
>>> from sklearn.utils.validation import _to_object_array
>>> _to_object_array([np.array([0]), np.array([1])])
array([array([0]), array([1])], dtype=object)
>>> _to_object_array([np.array([0]), np.array([1, 2])])
array([array([0]), array([1, 2])], dtype=object)
>>> _to_object_array([np.array([0]), np.array([1, 2])])
array([array([0]), array([1, 2])], dtype=object)
"""
out = np.empty(len(sequence), dtype=object)
out[:] = sequence
return out