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_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 |
def test_weighted_percentile_all_nan_column():
"""Check that nans are ignored in general, except for all NaN columns."""
array = np.array(
[
[np.nan, 5],
[np.nan, 1],
[np.nan, np.nan],
[np.nan, np.nan],
[np.nan, 2],
[np.nan, np.nan... | Check that nans are ignored in general, except for all NaN columns. | test_weighted_percentile_all_nan_column | 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_like_numpy_quantile(percentile, global_random_seed):
"""Check that _weighted_percentile delivers equivalent results as np.quantile
with weights."""
rng = np.random.RandomState(global_random_seed)
array = rng.rand(10, 100)
sample_weight = rng.randint(1, 6, size=(10, 100)... | Check that _weighted_percentile delivers equivalent results as np.quantile
with weights. | test_weighted_percentile_like_numpy_quantile | 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_like_numpy_nanquantile(percentile, global_random_seed):
"""Check that _weighted_percentile delivers equivalent results as np.nanquantile
with weights."""
rng = np.random.RandomState(global_random_seed)
array_with_nans = rng.rand(10, 100)
array_with_nans[rng.rand(*array_... | Check that _weighted_percentile delivers equivalent results as np.nanquantile
with weights. | test_weighted_percentile_like_numpy_nanquantile | 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_no___sklearn_tags__with_more_tags():
"""Test that calling `get_tags` on a class that defines `_more_tags` but not
`__sklearn_tags__` raises an error.
"""
class MoreTagsEstimator(BaseEstimator):
def _more_tags(self):
return {"requires_y": True} # pragma: no cover
with ... | Test that calling `get_tags` on a class that defines `_more_tags` but not
`__sklearn_tags__` raises an error.
| test_no___sklearn_tags__with_more_tags | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_tags.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_tags.py | BSD-3-Clause |
def test_tags_no_sklearn_tags_concrete_implementation():
"""Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/30479
Either the estimator doesn't implement `__sklearn_tags` or there is no class
implementing `__sklearn_tags__` without calling `super().__sklearn_tags__()` in
... | Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/30479
Either the estimator doesn't implement `__sklearn_tags` or there is no class
implementing `__sklearn_tags__` without calling `super().__sklearn_tags__()` in
its mro. Thus, we raise a warning and request to inherit from
... | test_tags_no_sklearn_tags_concrete_implementation | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_tags.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_tags.py | BSD-3-Clause |
def score(self, X):
"""This is available only if delegate has score.
Parameters
---------
y : ndarray
Parameter y
""" | This is available only if delegate has score.
Parameters
---------
y : ndarray
Parameter y
| score | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_testing.py | BSD-3-Clause |
def test_convert_container(
constructor_name,
container_type,
dtype,
superdtype,
):
"""Check that we convert the container to the right type of array with the
right data type."""
if constructor_name in (
"dataframe",
"index",
"polars",
"polars_series",
... | Check that we convert the container to the right type of array with the
right data type. | test_convert_container | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_testing.py | BSD-3-Clause |
def test_attach_unique_not_ndarray():
"""Test that when not np.ndarray, we don't touch the array."""
arr = [1, 2, 2, 3, 4, 4, 5]
arr_ = attach_unique(arr)
assert arr_ is arr | Test that when not np.ndarray, we don't touch the array. | test_attach_unique_not_ndarray | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_unique.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_unique.py | BSD-3-Clause |
def test_attach_unique_returns_view():
"""Test that attach_unique returns a view of the array."""
arr = np.array([1, 2, 2, 3, 4, 4, 5])
arr_ = attach_unique(arr)
assert arr_.base is arr | Test that attach_unique returns a view of the array. | test_attach_unique_returns_view | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_unique.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_unique.py | BSD-3-Clause |
def test_check_array_keeps_unique():
"""Test that check_array keeps the unique metadata."""
arr = np.array([[1, 2, 2, 3, 4, 4, 5]])
arr_ = attach_unique(arr)
arr_ = check_array(arr_)
assert_array_equal(arr_.dtype.metadata["unique"], np.array([1, 2, 3, 4, 5]))
assert_array_equal(arr_, arr) | Test that check_array keeps the unique metadata. | test_check_array_keeps_unique | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_unique.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_unique.py | BSD-3-Clause |
def test_check_array_series_err_msg():
"""
Check that we raise a proper error message when passing a Series and we expect a
2-dimensional container.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27498
"""
pd = pytest.importorskip("pandas")
ser = pd.Series(... |
Check that we raise a proper error message when passing a Series and we expect a
2-dimensional container.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27498
| test_check_array_series_err_msg | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_array_numeric_error(X):
"""Test that check_array errors when it receives an array of bytes/string
while a numeric dtype is required."""
expected_msg = r"dtype='numeric' is not compatible with arrays of bytes/strings"
with pytest.raises(ValueError, match=expected_msg):
check_array(... | Test that check_array errors when it receives an array of bytes/string
while a numeric dtype is required. | test_check_array_numeric_error | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_array_panadas_na_support_series():
"""Check check_array is correct with pd.NA in a series."""
pd = pytest.importorskip("pandas")
X_int64 = pd.Series([1, 2, pd.NA], dtype="Int64")
msg = "Input contains NaN"
with pytest.raises(ValueError, match=msg):
check_array(X_int64, ensur... | Check check_array is correct with pd.NA in a series. | test_check_array_panadas_na_support_series | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_is_fitted_stateless():
"""Check that check_is_fitted passes for stateless estimators."""
class StatelessEstimator(BaseEstimator):
def fit(self, **kwargs):
return self # pragma: no cover
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
... | Check that check_is_fitted passes for stateless estimators. | test_check_is_fitted_stateless | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_consistent_length():
"""Test that `check_consistent_length` raises on inconsistent lengths and wrong
input types trigger TypeErrors."""
check_consistent_length([1], [2], [3], [4], [5])
check_consistent_length([[1, 2], [[1, 2]]], [1, 2], ["a", "b"])
check_consistent_length([1], (2,), n... | Test that `check_consistent_length` raises on inconsistent lengths and wrong
input types trigger TypeErrors. | test_check_consistent_length | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_consistent_length_array_api(array_namespace, device, _):
"""Test that check_consistent_length works with different array types."""
xp = _array_api_for_tests(array_namespace, device)
with config_context(array_api_dispatch=True):
check_consistent_length(
xp.asarray([1, 2, 3... | Test that check_consistent_length works with different array types. | test_check_consistent_length_array_api | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_dataframe_with_only_bool():
"""Check that dataframe with bool return a boolean arrays."""
pd = importorskip("pandas")
df = pd.DataFrame({"bool": [True, False, True]})
array = check_array(df, dtype=None)
assert array.dtype == np.bool_
assert_array_equal(array, [[True], [False], [T... | Check that dataframe with bool return a boolean arrays. | test_check_dataframe_with_only_bool | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_dataframe_with_only_boolean():
"""Check that dataframe with boolean return a float array with dtype=None"""
pd = importorskip("pandas")
df = pd.DataFrame({"bool": pd.Series([True, False, True], dtype="boolean")})
array = check_array(df, dtype=None)
assert array.dtype == np.float64
... | Check that dataframe with boolean return a float array with dtype=None | test_check_dataframe_with_only_boolean | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_estimator_has(
estimator_name, estimator_value, delegates, expected_result, expected_exception
):
"""
Tests the _estimator_has function by verifying:
- Functionality with default and custom delegates.
- Raises ValueError if delegates are missing.
- Raises AttributeError if the specified... |
Tests the _estimator_has function by verifying:
- Functionality with default and custom delegates.
- Raises ValueError if delegates are missing.
- Raises AttributeError if the specified attribute is missing.
| test_estimator_has | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_scalar_valid(x):
"""Test that check_scalar returns no error/warning if valid inputs are
provided"""
with warnings.catch_warnings():
warnings.simplefilter("error")
scalar = check_scalar(
x,
"test_name",
target_type=numbers.Real,
m... | Test that check_scalar returns no error/warning if valid inputs are
provided | test_check_scalar_valid | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_scalar_invalid(
x, target_name, target_type, min_val, max_val, include_boundaries, err_msg
):
"""Test that check_scalar returns the right error if a wrong input is
given"""
with pytest.raises(Exception) as raised_error:
check_scalar(
x,
target_name,
... | Test that check_scalar returns the right error if a wrong input is
given | test_check_scalar_invalid | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_check_pandas_sparse_mixed_dtypes(ntype1, ntype2):
"""Check that pandas dataframes having sparse extension arrays with mixed dtypes
works."""
pd = pytest.importorskip("pandas")
df = pd.DataFrame(
{
"col1": pd.arrays.SparseArray([0, 1, 0], dtype=ntype1, fill_value=0),
... | Check that pandas dataframes having sparse extension arrays with mixed dtypes
works. | test_check_pandas_sparse_mixed_dtypes | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
def test_get_feature_names_pandas_with_ints_no_warning(names):
"""Get feature names with pandas dataframes without warning.
Column names with consistent dtypes will not warn, such as int or MultiIndex.
"""
pd = pytest.importorskip("pandas")
X = pd.DataFrame([[1, 2], [4, 5], [5, 6]], columns=names)
... | Get feature names with pandas dataframes without warning.
Column names with consistent dtypes will not warn, such as int or MultiIndex.
| test_get_feature_names_pandas_with_ints_no_warning | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_validation.py | BSD-3-Clause |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.