code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_get_namespace_ndarray_creation_device():
"""Check expected behavior with device and creation functions."""
X = numpy.asarray([1, 2, 3])
xp_out, _ = get_namespace(X)
full_array = xp_out.full(10, fill_value=2.0, device="cpu")
assert_allclose(full_array, [2.0] * 10)
with pytest.raises(Va... | Check expected behavior with device and creation functions. | test_get_namespace_ndarray_creation_device | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_array_api.py | BSD-3-Clause |
def test_asarray_with_order(array_api):
"""Test _asarray_with_order passes along order for NumPy arrays."""
xp = pytest.importorskip(array_api)
X = xp.asarray([1.2, 3.4, 5.1])
X_new = _asarray_with_order(X, order="F", xp=xp)
X_new_np = numpy.asarray(X_new)
assert X_new_np.flags["F_CONTIGUOUS"] | Test _asarray_with_order passes along order for NumPy arrays. | test_asarray_with_order | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_array_api.py | BSD-3-Clause |
def test_convert_estimator_to_array_api():
"""Convert estimator attributes to ArrayAPI arrays."""
xp = pytest.importorskip("array_api_strict")
X_np = numpy.asarray([[1.3, 4.5]])
est = SimpleEstimator().fit(X_np)
new_est = _estimator_with_converted_arrays(est, lambda array: xp.asarray(array))
a... | Convert estimator attributes to ArrayAPI arrays. | test_convert_estimator_to_array_api | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_array_api.py | BSD-3-Clause |
def test_bunch_attribute_deprecation():
"""Check that bunch raises deprecation message with `__getattr__`."""
bunch = Bunch()
values = np.asarray([1, 2, 3])
msg = (
"Key: 'values', is deprecated in 1.3 and will be "
"removed in 1.5. Please use 'grid_values' instead"
)
bunch._set_... | Check that bunch raises deprecation message with `__getattr__`. | test_bunch_attribute_deprecation | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_bunch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_bunch.py | BSD-3-Clause |
def test_get_chunk_n_rows_warns():
"""Check that warning is raised when working_memory is too low."""
row_bytes = 1024 * 1024 + 1
max_n_rows = None
working_memory = 1
expected = 1
warn_msg = (
"Could not adhere to working_memory config. Currently 1MiB, 2MiB required."
)
with pyt... | Check that warning is raised when working_memory is too low. | test_get_chunk_n_rows_warns | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_chunking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_chunking.py | BSD-3-Clause |
def test_class_weight_does_not_contains_more_classes():
"""Check that class_weight can contain more labels than in y.
Non-regression test for #22413
"""
tree = DecisionTreeClassifier(class_weight={0: 1, 1: 10, 2: 20})
# Does not raise
tree.fit([[0, 0, 1], [1, 0, 1], [1, 2, 0]], [0, 0, 1]) | Check that class_weight can contain more labels than in y.
Non-regression test for #22413
| test_class_weight_does_not_contains_more_classes | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_class_weight.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_class_weight.py | BSD-3-Clause |
def test_compute_sample_weight_sparse(csc_container):
"""Check that we can compute weight for sparse `y`."""
y = csc_container(np.asarray([[0], [1], [1]]))
sample_weight = compute_sample_weight("balanced", y)
assert_allclose(sample_weight, [1.5, 0.75, 0.75]) | Check that we can compute weight for sparse `y`. | test_compute_sample_weight_sparse | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_class_weight.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_class_weight.py | BSD-3-Clause |
def test_check_estimator_with_class_removed():
"""Test that passing a class instead of an instance fails."""
msg = "Passing a class was deprecated"
with raises(TypeError, match=msg):
check_estimator(LogisticRegression) | Test that passing a class instead of an instance fails. | test_check_estimator_with_class_removed | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_mutable_default_params():
"""Test that constructor cannot have mutable default parameters."""
msg = (
"Parameter 'p' of estimator 'HasMutableParameters' is of type "
"object which is not allowed"
)
# check that the "default_constructible" test checks for mutable parameters
c... | Test that constructor cannot have mutable default parameters. | test_mutable_default_params | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_set_params():
"""Check set_params doesn't fail and sets the right values."""
# check that values returned by get_params match set_params
msg = "get_params result does not match what was passed to set_params"
with raises(AssertionError, match=msg):
check_set_params("test", Modifies... | Check set_params doesn't fail and sets the right values. | test_check_set_params | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_estimator_not_fail_fast():
"""Check the contents of the results returned with on_fail!="raise".
This results should contain details about the observed failures, expected
or not.
"""
check_results = check_estimator(BaseEstimator(), on_fail=None)
assert isinstance(check_results, li... | Check the contents of the results returned with on_fail!="raise".
This results should contain details about the observed failures, expected
or not.
| test_check_estimator_not_fail_fast | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_estimator_sparse_tag():
"""Test that check_estimator_sparse_tag raises error when sparse tag is
misaligned."""
class EstimatorWithSparseConfig(BaseEstimator):
def __init__(self, tag_sparse, accept_sparse, fit_error=None):
self.tag_sparse = tag_sparse
self.acce... | Test that check_estimator_sparse_tag raises error when sparse tag is
misaligned. | test_check_estimator_sparse_tag | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def run_tests_without_pytest():
"""Runs the tests in this file without using pytest."""
main_module = sys.modules["__main__"]
test_functions = [
getattr(main_module, name)
for name in dir(main_module)
if name.startswith("test_")
]
test_cases = [unittest.FunctionTestCase(fn) f... | Runs the tests in this file without using pytest. | run_tests_without_pytest | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_xfail_count_with_no_fast_fail():
"""Test that the right number of xfail warnings are raised when on_fail is "warn".
It also checks the number of raised EstimatorCheckFailedWarning, and checks the
output of check_estimator.
"""
est = NuSVC()
expected_failed_checks = _get_expected_failed... | Test that the right number of xfail warnings are raised when on_fail is "warn".
It also checks the number of raised EstimatorCheckFailedWarning, and checks the
output of check_estimator.
| test_xfail_count_with_no_fast_fail | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_estimator_callback():
"""Test that the callback is called with the right arguments."""
call_count = {"xfail": 0, "skipped": 0, "passed": 0, "failed": 0}
def callback(
*,
estimator,
check_name,
exception,
status,
expected_to_fail,
expect... | Test that the callback is called with the right arguments. | test_check_estimator_callback | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_outlier_contamination():
"""Check the test for the contamination parameter in the outlier detectors."""
# Without any parameter constraints, the estimator will early exit the test by
# returning None.
class OutlierDetectorWithoutConstraint(OutlierMixin, BaseEstimator):
"""Outlier... | Check the test for the contamination parameter in the outlier detectors. | test_check_outlier_contamination | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_estimator_cloneable_error():
"""Check that the right error is raised when the estimator is not cloneable."""
class NotCloneable(BaseEstimator):
def __sklearn_clone__(self):
raise NotImplementedError("This estimator is not cloneable.")
estimator = NotCloneable()
msg =... | Check that the right error is raised when the estimator is not cloneable. | test_check_estimator_cloneable_error | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_estimator_repr_error():
"""Check that the right error is raised when the estimator does not have a repr."""
class NotRepr(BaseEstimator):
def __repr__(self):
raise NotImplementedError("This estimator does not have a repr.")
estimator = NotRepr()
msg = "Repr of .* failed wi... | Check that the right error is raised when the estimator does not have a repr. | test_estimator_repr_error | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_classifier_not_supporting_multiclass():
"""Check that when the estimator has the wrong tags.classifier_tags.multi_class
set, the test fails."""
class BadEstimator(BaseEstimator):
# we don't actually need to define the tag here since we're running the test
# manually, and Base... | Check that when the estimator has the wrong tags.classifier_tags.multi_class
set, the test fails. | test_check_classifier_not_supporting_multiclass | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_estimator_callback_with_fast_fail_error():
"""Check that check_estimator fails correctly with on_fail='raise' and callback."""
with raises(
ValueError, match="callback cannot be provided together with on_fail='raise'"
):
check_estimator(LogisticRegression(), on_fail="raise", c... | Check that check_estimator fails correctly with on_fail='raise' and callback. | test_check_estimator_callback_with_fast_fail_error | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_check_mixin_order():
"""Test that the check raises an error when the mixin order is incorrect."""
class BadEstimator(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
return self
msg = "TransformerMixin comes before/left side of BaseEstimator"
with raises(Asserti... | Test that the check raises an error when the mixin order is incorrect. | test_check_mixin_order | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_estimator_checks.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py | BSD-3-Clause |
def test_randomized_eigsh(dtype):
"""Test that `_randomized_eigsh` returns the appropriate components"""
rng = np.random.RandomState(42)
X = np.diag(np.array([1.0, -2.0, 0.0, 3.0], dtype=dtype))
# random rotation that preserves the eigenvalues of X
rand_rot = np.linalg.qr(rng.normal(size=X.shape))[... | Test that `_randomized_eigsh` returns the appropriate components | test_randomized_eigsh | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_extmath.py | BSD-3-Clause |
def test_randomized_eigsh_compared_to_others(k):
"""Check that `_randomized_eigsh` is similar to other `eigsh`
Tests that for a random PSD matrix, `_randomized_eigsh` provides results
comparable to LAPACK (scipy.linalg.eigh) and ARPACK
(scipy.sparse.linalg.eigsh).
Note: some versions of ARPACK do ... | Check that `_randomized_eigsh` is similar to other `eigsh`
Tests that for a random PSD matrix, `_randomized_eigsh` provides results
comparable to LAPACK (scipy.linalg.eigh) and ARPACK
(scipy.sparse.linalg.eigsh).
Note: some versions of ARPACK do not support k=n_features.
| test_randomized_eigsh_compared_to_others | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_extmath.py | BSD-3-Clause |
def test_randomized_eigsh_reconst_low_rank(n, rank):
"""Check that randomized_eigsh is able to reconstruct a low rank psd matrix
Tests that the decomposition provided by `_randomized_eigsh` leads to
orthonormal eigenvectors, and that a low rank PSD matrix can be effectively
reconstructed with good accu... | Check that randomized_eigsh is able to reconstruct a low rank psd matrix
Tests that the decomposition provided by `_randomized_eigsh` leads to
orthonormal eigenvectors, and that a low rank PSD matrix can be effectively
reconstructed with good accuracy using it.
| test_randomized_eigsh_reconst_low_rank | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_extmath.py | BSD-3-Clause |
def max_loading_is_positive(u, v):
"""
returns bool tuple indicating if the values maximising np.abs
are positive across all rows for u and across all columns for v.
"""
u_based = (np.abs(u).max(axis=0) == u.max(axis=0)).all()
v_based = (np.abs(v).max(axis=1) == v.max(axi... |
returns bool tuple indicating if the values maximising np.abs
are positive across all rows for u and across all columns for v.
| max_loading_is_positive | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_extmath.py | BSD-3-Clause |
def test_cartesian_mix_types(arrays, output_dtype):
"""Check that the cartesian product works with mixed types."""
output = cartesian(arrays)
assert output.dtype == output_dtype | Check that the cartesian product works with mixed types. | test_cartesian_mix_types | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_extmath.py | BSD-3-Clause |
def test_approximate_mode():
"""Make sure sklearn.utils.extmath._approximate_mode returns valid
results for cases where "class_counts * n_draws" is enough
to overflow 32-bit signed integer.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20774
"""
X = np.array([... | Make sure sklearn.utils.extmath._approximate_mode returns valid
results for cases where "class_counts * n_draws" is enough
to overflow 32-bit signed integer.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20774
| test_approximate_mode | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_extmath.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_extmath.py | BSD-3-Clause |
def test_smallest_admissible_index_dtype_without_checking_contents(
params, expected_dtype
):
"""Check the behaviour of `smallest_admissible_index_dtype` using the passed
arrays but without checking the contents of the arrays.
"""
assert _smallest_admissible_index_dtype(**params) == expected_dtype | Check the behaviour of `smallest_admissible_index_dtype` using the passed
arrays but without checking the contents of the arrays.
| test_smallest_admissible_index_dtype_without_checking_contents | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_fixes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_fixes.py | BSD-3-Clause |
def test_safe_indexing_list_axis_1_unsupported(indices):
"""Check that we raise a ValueError when axis=1 with input as list."""
X = [[1, 2], [4, 5], [7, 8]]
err_msg = "axis=1 is not supported for lists"
with pytest.raises(ValueError, match=err_msg):
_safe_indexing(X, indices, axis=1) | Check that we raise a ValueError when axis=1 with input as list. | test_safe_indexing_list_axis_1_unsupported | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_indexing.py | BSD-3-Clause |
def test_get_column_indices_interchange():
"""Check _get_column_indices for edge cases with the interchange"""
pl = pytest.importorskip("polars")
# Polars dataframes go down the interchange path.
df = pl.DataFrame([[1, 2, 3], [4, 5, 6]], schema=["a", "b", "c"])
key_results = [
(slice(1, No... | Check _get_column_indices for edge cases with the interchange | test_get_column_indices_interchange | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_indexing.py | BSD-3-Clause |
def test_available_if_methods_can_be_pickled():
"""Check that available_if methods can be pickled.
Non-regression test for #21344.
"""
return_value = 10
est = AvailableParameterEstimator(available=True, return_value=return_value)
pickled_bytes = pickle.dumps(est.available_func)
unpickled_fu... | Check that available_if methods can be pickled.
Non-regression test for #21344.
| test_available_if_methods_can_be_pickled | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_metaestimators.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_metaestimators.py | BSD-3-Clause |
def test_type_of_target_too_many_unique_classes():
"""Check that we raise a warning when the number of unique classes is greater than
50% of the number of samples.
We need to check that we don't raise if we have less than 20 samples.
"""
y = np.arange(25)
msg = r"The number of unique classes i... | Check that we raise a warning when the number of unique classes is greater than
50% of the number of samples.
We need to check that we don't raise if we have less than 20 samples.
| test_type_of_target_too_many_unique_classes | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_multiclass.py | BSD-3-Clause |
def test_type_of_target_pandas_nullable():
"""Check that type_of_target works with pandas nullable dtypes."""
pd = pytest.importorskip("pandas")
for dtype in ["Int32", "Float32"]:
y_true = pd.Series([1, 0, 2, 3, 4], dtype=dtype)
assert type_of_target(y_true) == "multiclass"
y_true ... | Check that type_of_target works with pandas nullable dtypes. | test_type_of_target_pandas_nullable | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_multiclass.py | BSD-3-Clause |
def test_unique_labels_pandas_nullable(dtype):
"""Checks that unique_labels work with pandas nullable dtypes.
Non-regression test for gh-25634.
"""
pd = pytest.importorskip("pandas")
y_true = pd.Series([1, 0, 0, 1, 0, 1, 1, 0, 1], dtype=dtype)
y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1... | Checks that unique_labels work with pandas nullable dtypes.
Non-regression test for gh-25634.
| test_unique_labels_pandas_nullable | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_multiclass.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_multiclass.py | BSD-3-Clause |
def test_newton_cg_verbosity(capsys, verbose):
"""Test the std output of verbose newton_cg solver."""
A = np.eye(2)
b = np.array([1, 2], dtype=float)
_newton_cg(
grad_hess=lambda x: (A @ x - b, lambda z: A @ z),
func=lambda x: 0.5 * x @ A @ x - b @ x,
grad=lambda x: A @ x - b,
... | Test the std output of verbose newton_cg solver. | test_newton_cg_verbosity | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_optimize.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_optimize.py | BSD-3-Clause |
def test_parallel_delayed_warnings():
"""Informative warnings should be raised when mixing sklearn and joblib API"""
# We should issue a warning when one wants to use sklearn.utils.fixes.Parallel
# with joblib.delayed. The config will not be propagated to the workers.
warn_msg = "`sklearn.utils.parallel... | Informative warnings should be raised when mixing sklearn and joblib API | test_parallel_delayed_warnings | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_parallel.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_parallel.py | BSD-3-Clause |
def test_dispatch_config_parallel(n_jobs):
"""Check that we properly dispatch the configuration in parallel processing.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/25239
"""
pd = pytest.importorskip("pandas")
iris = load_iris(as_frame=True)
class Transforme... | Check that we properly dispatch the configuration in parallel processing.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/25239
| test_dispatch_config_parallel | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_parallel.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_parallel.py | BSD-3-Clause |
def test_filter_warning_propagates(n_jobs, backend):
"""Check warning propagates to the job."""
with warnings.catch_warnings():
warnings.simplefilter("error", category=ConvergenceWarning)
with pytest.raises(ConvergenceWarning):
Parallel(n_jobs=n_jobs, backend=backend)(
... | Check warning propagates to the job. | test_filter_warning_propagates | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_parallel.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_parallel.py | BSD-3-Clause |
def test_check_warnings_threading():
"""Check that warnings filters are set correctly in the threading backend."""
with warnings.catch_warnings():
warnings.simplefilter("error", category=ConvergenceWarning)
filters = warnings.filters
assert ("error", None, ConvergenceWarning, None, 0) i... | Check that warnings filters are set correctly in the threading backend. | test_check_warnings_threading | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_parallel.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_parallel.py | BSD-3-Clause |
def test_interval_range(interval_type):
"""Check the range of values depending on closed."""
interval = Interval(interval_type, -2, 2, closed="left")
assert -2 in interval
assert 2 not in interval
interval = Interval(interval_type, -2, 2, closed="right")
assert -2 not in interval
assert 2 i... | Check the range of values depending on closed. | test_interval_range | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_interval_large_integers(interval_type):
"""Check that Interval constraint work with large integers.
non-regression test for #26648.
"""
interval = Interval(interval_type, 0, 2, closed="neither")
assert 2**65 not in interval
assert 2**128 not in interval
assert float(2**65) not in i... | Check that Interval constraint work with large integers.
non-regression test for #26648.
| test_interval_large_integers | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_interval_inf_in_bounds():
"""Check that inf is included iff a bound is closed and set to None.
Only valid for real intervals.
"""
interval = Interval(Real, 0, None, closed="right")
assert np.inf in interval
interval = Interval(Real, None, 0, closed="left")
assert -np.inf in interv... | Check that inf is included iff a bound is closed and set to None.
Only valid for real intervals.
| test_interval_inf_in_bounds | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_stroptions():
"""Sanity check for the StrOptions constraint"""
options = StrOptions({"a", "b", "c"}, deprecated={"c"})
assert options.is_satisfied_by("a")
assert options.is_satisfied_by("c")
assert not options.is_satisfied_by("d")
assert "'c' (deprecated)" in str(options) | Sanity check for the StrOptions constraint | test_stroptions | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_options():
"""Sanity check for the Options constraint"""
options = Options(Real, {-0.5, 0.5, np.inf}, deprecated={-0.5})
assert options.is_satisfied_by(-0.5)
assert options.is_satisfied_by(np.inf)
assert not options.is_satisfied_by(1.23)
assert "-0.5 (deprecated)" in str(options) | Sanity check for the Options constraint | test_options | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_instances_of_type_human_readable(type, expected_type_name):
"""Check the string representation of the _InstancesOf constraint."""
constraint = _InstancesOf(type)
assert str(constraint) == f"an instance of '{expected_type_name}'" | Check the string representation of the _InstancesOf constraint. | test_instances_of_type_human_readable | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_generate_invalid_param_val(constraint):
"""Check that the value generated does not satisfy the constraint"""
bad_value = generate_invalid_param_val(constraint)
assert not constraint.is_satisfied_by(bad_value) | Check that the value generated does not satisfy the constraint | test_generate_invalid_param_val | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_generate_invalid_param_val_2_intervals(integer_interval, real_interval):
"""Check that the value generated for an interval constraint does not satisfy any of
the interval constraints.
"""
bad_value = generate_invalid_param_val(constraint=real_interval)
assert not real_interval.is_satisfied_... | Check that the value generated for an interval constraint does not satisfy any of
the interval constraints.
| test_generate_invalid_param_val_2_intervals | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_make_constraint(constraint_declaration, expected_constraint_class):
"""Check that make_constraint dispatches to the appropriate constraint class"""
constraint = make_constraint(constraint_declaration)
assert constraint.__class__ is expected_constraint_class | Check that make_constraint dispatches to the appropriate constraint class | test_make_constraint | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_make_constraint_unknown():
"""Check that an informative error is raised when an unknown constraint is passed"""
with pytest.raises(ValueError, match="Unknown constraint"):
make_constraint("not a valid constraint") | Check that an informative error is raised when an unknown constraint is passed | test_make_constraint_unknown | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_validate_params():
"""Check that validate_params works no matter how the arguments are passed"""
with pytest.raises(
InvalidParameterError, match="The 'a' parameter of _func must be"
):
_func("wrong", c=1)
with pytest.raises(
InvalidParameterError, match="The 'b' parame... | Check that validate_params works no matter how the arguments are passed | test_validate_params | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_validate_params_missing_params():
"""Check that no error is raised when there are parameters without
constraints
"""
@validate_params({"a": [int]}, prefer_skip_nested_validation=True)
def func(a, b):
pass
func(1, 2) | Check that no error is raised when there are parameters without
constraints
| test_validate_params_missing_params | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_decorate_validated_function():
"""Check that validate_params functions can be decorated"""
decorated_function = deprecated()(_func)
with pytest.warns(FutureWarning, match="Function _func is deprecated"):
decorated_function(1, 2, c=3)
# outer decorator does not interfere with validatio... | Check that validate_params functions can be decorated | test_decorate_validated_function | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_validate_params_estimator():
"""Check that validate_params works with Estimator instances"""
# no validation in init
est = _Estimator("wrong")
with pytest.raises(
InvalidParameterError, match="The 'a' parameter of _Estimator must be"
):
est.fit() | Check that validate_params works with Estimator instances | test_validate_params_estimator | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_stroptions_deprecated_subset():
"""Check that the deprecated parameter must be a subset of options."""
with pytest.raises(ValueError, match="deprecated options must be a subset"):
StrOptions({"a", "b", "c"}, deprecated={"a", "d"}) | Check that the deprecated parameter must be a subset of options. | test_stroptions_deprecated_subset | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_hidden_constraint():
"""Check that internal constraints are not exposed in the error message."""
@validate_params(
{"param": [Hidden(list), dict]}, prefer_skip_nested_validation=True
)
def f(param):
pass
# list and dict are valid params
f({"a": 1, "b": 2, "c": 3})
... | Check that internal constraints are not exposed in the error message. | test_hidden_constraint | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_hidden_stroptions():
"""Check that we can have 2 StrOptions constraints, one being hidden."""
@validate_params(
{"param": [StrOptions({"auto"}), Hidden(StrOptions({"warn"}))]},
prefer_skip_nested_validation=True,
)
def f(param):
pass
# "auto" and "warn" are valid p... | Check that we can have 2 StrOptions constraints, one being hidden. | test_hidden_stroptions | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_validate_params_set_param_constraints_attribute():
"""Check that the validate_params decorator properly sets the parameter constraints
as attribute of the decorated function/method.
"""
assert hasattr(_func, "_skl_parameter_constraints")
assert hasattr(_Class()._method, "_skl_parameter_cons... | Check that the validate_params decorator properly sets the parameter constraints
as attribute of the decorated function/method.
| test_validate_params_set_param_constraints_attribute | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_boolean_constraint_deprecated_int():
"""Check that validate_params raise a deprecation message but still passes
validation when using an int for a parameter accepting a boolean.
"""
@validate_params({"param": ["boolean"]}, prefer_skip_nested_validation=True)
def f(param):
pass
... | Check that validate_params raise a deprecation message but still passes
validation when using an int for a parameter accepting a boolean.
| test_boolean_constraint_deprecated_int | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_no_validation():
"""Check that validation can be skipped for a parameter."""
@validate_params(
{"param1": [int, None], "param2": "no_validation"},
prefer_skip_nested_validation=True,
)
def f(param1=None, param2=None):
pass
# param1 is validated
with pytest.rais... | Check that validation can be skipped for a parameter. | test_no_validation | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_pandas_na_constraint_with_pd_na():
"""Add a specific test for checking support for `pandas.NA`."""
pd = pytest.importorskip("pandas")
na_constraint = _PandasNAConstraint()
assert na_constraint.is_satisfied_by(pd.NA)
assert not na_constraint.is_satisfied_by(np.array([1, 2, 3])) | Add a specific test for checking support for `pandas.NA`. | test_pandas_na_constraint_with_pd_na | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_iterable_not_string():
"""Check that a string does not satisfy the _IterableNotString constraint."""
constraint = _IterablesNotString()
assert constraint.is_satisfied_by([1, 2, 3])
assert constraint.is_satisfied_by(range(10))
assert not constraint.is_satisfied_by("some string") | Check that a string does not satisfy the _IterableNotString constraint. | test_iterable_not_string | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_cv_objects():
"""Check that the _CVObjects constraint accepts all current ways
to pass cv objects."""
constraint = _CVObjects()
assert constraint.is_satisfied_by(5)
assert constraint.is_satisfied_by(LeaveOneOut())
assert constraint.is_satisfied_by([([1, 2], [3, 4]), ([3, 4], [1, 2])])
... | Check that the _CVObjects constraint accepts all current ways
to pass cv objects. | test_cv_objects | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_third_party_estimator():
"""Check that the validation from a scikit-learn estimator inherited by a third
party estimator does not impose a match between the dict of constraints and the
parameters of the estimator.
"""
class ThirdPartyEstimator(_Estimator):
def __init__(self, b):
... | Check that the validation from a scikit-learn estimator inherited by a third
party estimator does not impose a match between the dict of constraints and the
parameters of the estimator.
| test_third_party_estimator | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_interval_real_not_int():
"""Check for the type RealNotInt in the Interval constraint."""
constraint = Interval(RealNotInt, 0, 1, closed="both")
assert constraint.is_satisfied_by(1.0)
assert not constraint.is_satisfied_by(1) | Check for the type RealNotInt in the Interval constraint. | test_interval_real_not_int | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_skip_param_validation():
"""Check that param validation can be skipped using config_context."""
@validate_params({"a": [int]}, prefer_skip_nested_validation=True)
def f(a):
pass
with pytest.raises(InvalidParameterError, match="The 'a' parameter"):
f(a="1")
# does not rais... | Check that param validation can be skipped using config_context. | test_skip_param_validation | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_skip_nested_validation(prefer_skip_nested_validation):
"""Check that nested validation can be skipped."""
@validate_params({"a": [int]}, prefer_skip_nested_validation=True)
def f(a):
pass
@validate_params(
{"b": [int]},
prefer_skip_nested_validation=prefer_skip_nested_... | Check that nested validation can be skipped. | test_skip_nested_validation | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_skip_nested_validation_and_config_context(
skip_parameter_validation, prefer_skip_nested_validation, expected_skipped
):
"""Check interaction between global skip and local skip."""
@validate_params(
{"a": [int]}, prefer_skip_nested_validation=prefer_skip_nested_validation
)
def g(a... | Check interaction between global skip and local skip. | test_skip_nested_validation_and_config_context | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_param_validation.py | BSD-3-Clause |
def test_validate_curve_kwargs_single_legend(
name, legend_metric, legend_metric_name, curve_kwargs
):
"""Check `_validate_curve_kwargs` returns correct kwargs for single legend entry."""
n_curves = 3
curve_kwargs_out = _BinaryClassifierCurveDisplayMixin._validate_curve_kwargs(
n_curves=n_curves... | Check `_validate_curve_kwargs` returns correct kwargs for single legend entry. | test_validate_curve_kwargs_single_legend | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_plotting.py | BSD-3-Clause |
def test_validate_curve_kwargs_multi_legend(name, legend_metric, legend_metric_name):
"""Check `_validate_curve_kwargs` returns correct kwargs for multi legend entry."""
n_curves = 3
curve_kwargs = [{"color": "red"}, {"color": "yellow"}, {"color": "blue"}]
curve_kwargs_out = _BinaryClassifierCurveDispla... | Check `_validate_curve_kwargs` returns correct kwargs for multi legend entry. | test_validate_curve_kwargs_multi_legend | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_plotting.py | BSD-3-Clause |
def test_validate_score_name(score_name, scoring, negate_score, expected_score_name):
"""Check that we return the right score name."""
assert (
_validate_score_name(score_name, scoring, negate_score) == expected_score_name
) | Check that we return the right score name. | test_validate_score_name | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_plotting.py | BSD-3-Clause |
def test_validate_style_kwargs(default_kwargs, user_kwargs, expected):
"""Check the behaviour of `validate_style_kwargs` with various type of entries."""
result = _validate_style_kwargs(default_kwargs, user_kwargs)
assert result == expected, (
"The validation of style keywords does not provide the e... | Check the behaviour of `validate_style_kwargs` with various type of entries. | test_validate_style_kwargs | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_plotting.py | BSD-3-Clause |
def test_get_response_values_regressor_error(response_method):
"""Check the error message with regressor an not supported response
method."""
my_estimator = _MockEstimatorOnOffPrediction(response_methods=[response_method])
X = "mocking_data", "mocking_target"
err_msg = f"{my_estimator.__class__.__na... | Check the error message with regressor an not supported response
method. | test_get_response_values_regressor_error | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_values_regressor(return_response_method_used):
"""Check the behaviour of `_get_response_values` with regressor."""
X, y = make_regression(n_samples=10, random_state=0)
regressor = LinearRegression().fit(X, y)
results = _get_response_values(
regressor,
X,
res... | Check the behaviour of `_get_response_values` with regressor. | test_get_response_values_regressor | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_values_outlier_detection(
response_method, return_response_method_used
):
"""Check the behaviour of `_get_response_values` with outlier detector."""
X, y = make_classification(n_samples=50, random_state=0)
outlier_detector = IsolationForest(random_state=0).fit(X, y)
results = _... | Check the behaviour of `_get_response_values` with outlier detector. | test_get_response_values_outlier_detection | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_values_classifier_unknown_pos_label(response_method):
"""Check that `_get_response_values` raises the proper error message with
classifier."""
X, y = make_classification(n_samples=10, n_classes=2, random_state=0)
classifier = LogisticRegression().fit(X, y)
# provide a `pos_lab... | Check that `_get_response_values` raises the proper error message with
classifier. | test_get_response_values_classifier_unknown_pos_label | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_values_classifier_inconsistent_y_pred_for_binary_proba(
response_method,
):
"""Check that `_get_response_values` will raise an error when `y_pred` has a
single class with `predict_proba`."""
X, y_two_class = make_classification(n_samples=10, n_classes=2, random_state=0)
y_singl... | Check that `_get_response_values` will raise an error when `y_pred` has a
single class with `predict_proba`. | test_get_response_values_classifier_inconsistent_y_pred_for_binary_proba | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_values_binary_classifier_decision_function(
return_response_method_used,
):
"""Check the behaviour of `_get_response_values` with `decision_function`
and binary classifier."""
X, y = make_classification(
n_samples=10,
n_classes=2,
weights=[0.3, 0.7],
... | Check the behaviour of `_get_response_values` with `decision_function`
and binary classifier. | test_get_response_values_binary_classifier_decision_function | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_values_binary_classifier_predict_proba(
return_response_method_used, response_method
):
"""Check that `_get_response_values` with `predict_proba` and binary
classifier."""
X, y = make_classification(
n_samples=10,
n_classes=2,
weights=[0.3, 0.7],
ran... | Check that `_get_response_values` with `predict_proba` and binary
classifier. | test_get_response_values_binary_classifier_predict_proba | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_error(estimator, X, y, err_msg, params):
"""Check that we raise the proper error messages in _get_response_values_binary."""
estimator.fit(X, y)
with pytest.raises(ValueError, match=err_msg):
_get_response_values_binary(estimator, X, **params) | Check that we raise the proper error messages in _get_response_values_binary. | test_get_response_error | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_values_multiclass(estimator, response_method):
"""Check that we can call `_get_response_values` with a multiclass estimator.
It should return the predictions untouched.
"""
estimator.fit(X, y)
predictions, pos_label = _get_response_values(
estimator, X, response_method=... | Check that we can call `_get_response_values` with a multiclass estimator.
It should return the predictions untouched.
| test_get_response_values_multiclass | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_get_response_values_with_response_list():
"""Check the behaviour of passing a list of responses to `_get_response_values`."""
classifier = LogisticRegression().fit(X_binary, y_binary)
# it should use `predict_proba`
y_pred, pos_label, response_method = _get_response_values(
classifier,... | Check the behaviour of passing a list of responses to `_get_response_values`. | test_get_response_values_with_response_list | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_response.py | BSD-3-Clause |
def test_pandas_adapter():
"""Check pandas adapter has expected behavior."""
pd = pytest.importorskip("pandas")
X_np = np.asarray([[1, 0, 3], [0, 0, 1]])
columns = np.asarray(["f0", "f1", "f2"], dtype=object)
index = np.asarray([0, 1])
X_df_orig = pd.DataFrame([[1, 2], [1, 3]], index=index)
... | Check pandas adapter has expected behavior. | test_pandas_adapter | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_polars_adapter():
"""Check Polars adapter has expected behavior."""
pl = pytest.importorskip("polars")
X_np = np.array([[1, 0, 3], [0, 0, 1]])
columns = ["f1", "f2", "f3"]
X_df_orig = pl.DataFrame(X_np, schema=columns, orient="row")
adapter = ADAPTERS_MANAGER.adapters["polars"]
X_c... | Check Polars adapter has expected behavior. | test_polars_adapter | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_set_output_method(dataframe_lib):
"""Check that the output is a dataframe."""
lib = pytest.importorskip(dataframe_lib)
X = np.asarray([[1, 0, 3], [0, 0, 1]])
est = EstimatorWithSetOutput().fit(X)
# transform=None is a no-op
est2 = est.set_output(transform=None)
assert est2 is est
... | Check that the output is a dataframe. | test_set_output_method | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_set_output_method_error():
"""Check transform fails with invalid transform."""
X = np.asarray([[1, 0, 3], [0, 0, 1]])
est = EstimatorWithSetOutput().fit(X)
est.set_output(transform="bad")
msg = "output config must be in"
with pytest.raises(ValueError, match=msg):
est.transform... | Check transform fails with invalid transform. | test_set_output_method_error | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_get_output_auto_wrap_false():
"""Check that auto_wrap_output_keys=None does not wrap."""
est = EstimatorWithSetOutputNoAutoWrap()
assert not hasattr(est, "set_output")
X = np.asarray([[1, 0, 3], [0, 0, 1]])
assert X is est.transform(X) | Check that auto_wrap_output_keys=None does not wrap. | test_get_output_auto_wrap_false | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_set_output_mixin_custom_mixin():
"""Check that multiple init_subclasses passes parameters up."""
class BothMixinEstimator(_SetOutputMixin, AnotherMixin, custom_parameter=123):
def transform(self, X, y=None):
return X
def get_feature_names_out(self, input_features=None):
... | Check that multiple init_subclasses passes parameters up. | test_set_output_mixin_custom_mixin | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_set_output_mro():
"""Check that multi-inheritance resolves to the correct class method.
Non-regression test gh-25293.
"""
class Base(_SetOutputMixin):
def transform(self, X):
return "Base"
class A(Base):
pass
class B(Base):
def transform(self, X):... | Check that multi-inheritance resolves to the correct class method.
Non-regression test gh-25293.
| test_set_output_mro | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_set_output_pandas_keep_index():
"""Check that set_output does not override index.
Non-regression test for gh-25730.
"""
pd = pytest.importorskip("pandas")
X = pd.DataFrame([[1, 2, 3], [4, 5, 6]], index=[0, 1])
est = EstimatorWithSetOutputIndex().set_output(transform="pandas")
est.... | Check that set_output does not override index.
Non-regression test for gh-25730.
| test_set_output_pandas_keep_index | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_set_output_named_tuple_out():
"""Check that namedtuples are kept by default."""
Output = namedtuple("Output", "X, Y")
X = np.asarray([[1, 2, 3]])
est = EstimatorReturnTuple(OutputTuple=Output)
X_trans = est.transform(X)
assert isinstance(X_trans, Output)
assert_array_equal(X_trans.... | Check that namedtuples are kept by default. | test_set_output_named_tuple_out | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_set_output_list_input(dataframe_lib):
"""Check set_output for list input.
Non-regression test for #27037.
"""
lib = pytest.importorskip(dataframe_lib)
X = [[0, 1, 2, 3], [4, 5, 6, 7]]
est = EstimatorWithListInput()
est.set_output(transform=dataframe_lib)
X_out = est.fit(X).tr... | Check set_output for list input.
Non-regression test for #27037.
| test_set_output_list_input | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_set_output.py | BSD-3-Clause |
def test_incr_mean_variance_axis_dim_mismatch(sparse_constructor):
"""Check that we raise proper error when axis=1 and the dimension mismatch.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/pull/18655
"""
n_samples, n_features = 60, 4
rng = np.random.RandomState(42)
X ... | Check that we raise proper error when axis=1 and the dimension mismatch.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/pull/18655
| test_incr_mean_variance_axis_dim_mismatch | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_sparsefuncs.py | BSD-3-Clause |
def centered_matrices(request):
"""Returns equivalent tuple[sp.linalg.LinearOperator, np.ndarray]."""
sparse_container = request.param
random_state = np.random.default_rng(42)
X_sparse = sparse_container(
sp.random(500, 100, density=0.1, format="csr", random_state=random_state)
)
X_den... | Returns equivalent tuple[sp.linalg.LinearOperator, np.ndarray]. | centered_matrices | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_sparsefuncs.py | BSD-3-Clause |
def test_weighted_percentile():
"""Check `weighted_percentile` on artificial data with obvious median."""
y = np.empty(102, dtype=np.float64)
y[:50] = 0
y[-51:] = 2
y[-1] = 100000
y[50] = 1
sw = np.ones(102, dtype=np.float64)
sw[-1] = 0.0
value = _weighted_percentile(y, sw, 50)
a... | Check `weighted_percentile` on artificial data with obvious median. | test_weighted_percentile | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_stats.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_stats.py | BSD-3-Clause |
def test_weighted_percentile_equal():
"""Check `weighted_percentile` with all weights equal to 1."""
y = np.empty(102, dtype=np.float64)
y.fill(0.0)
sw = np.ones(102, dtype=np.float64)
score = _weighted_percentile(y, sw, 50)
assert approx(score) == 0 | Check `weighted_percentile` with all weights equal to 1. | test_weighted_percentile_equal | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_stats.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_stats.py | BSD-3-Clause |
def test_weighted_percentile_zero_weight():
"""Check `weighted_percentile` with all weights equal to 0."""
y = np.empty(102, dtype=np.float64)
y.fill(1.0)
sw = np.ones(102, dtype=np.float64)
sw.fill(0.0)
value = _weighted_percentile(y, sw, 50)
assert approx(value) == 1.0 | Check `weighted_percentile` with all weights equal to 0. | test_weighted_percentile_zero_weight | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_stats.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_stats.py | BSD-3-Clause |
def test_weighted_percentile_zero_weight_zero_percentile():
"""Check `weighted_percentile(percentile_rank=0)` behaves correctly.
Ensures that (leading)zero-weight observations ignored when `percentile_rank=0`.
See #20528 for details.
"""
y = np.array([0, 1, 2, 3, 4, 5])
sw = np.array([0, 0, 1, ... | Check `weighted_percentile(percentile_rank=0)` behaves correctly.
Ensures that (leading)zero-weight observations ignored when `percentile_rank=0`.
See #20528 for details.
| test_weighted_percentile_zero_weight_zero_percentile | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_stats.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_stats.py | BSD-3-Clause |
def test_weighted_median_equal_weights(global_random_seed):
"""Checks `_weighted_percentile(percentile_rank=50)` is the same as `np.median`.
`sample_weights` are all 1s and the number of samples is odd.
When number of samples is odd, `_weighted_percentile` always falls on a single
observation (not betw... | Checks `_weighted_percentile(percentile_rank=50)` is the same as `np.median`.
`sample_weights` are all 1s and the number of samples is odd.
When number of samples is odd, `_weighted_percentile` always falls on a single
observation (not between 2 values, in which case the lower value would be taken)
and... | test_weighted_median_equal_weights | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_stats.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_stats.py | BSD-3-Clause |
def test_weighted_percentile_array_api_consistency(
global_random_seed, array_namespace, device, dtype_name, data, weights, percentile
):
"""Check `_weighted_percentile` gives consistent results with array API."""
if array_namespace == "array_api_strict":
try:
import array_api_strict
... | Check `_weighted_percentile` gives consistent results with array API. | test_weighted_percentile_array_api_consistency | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_stats.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_stats.py | BSD-3-Clause |
def test_weighted_percentile_nan_filtered(sample_weight_ndim, global_random_seed):
"""Test that calling _weighted_percentile on an array with nan values returns
the same results as calling _weighted_percentile on a filtered version of the data.
We test both with sample_weight of the same shape as the data a... | Test that calling _weighted_percentile on an array with nan values returns
the same results as calling _weighted_percentile on a filtered version of the data.
We test both with sample_weight of the same shape as the data and with
one-dimensional sample_weight. | test_weighted_percentile_nan_filtered | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_stats.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_stats.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.