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_ohe_infrequent_two_levels_user_cats_one_frequent(kwargs):
"""'a' is the only frequent category, all other categories are infrequent."""
X_train = np.array([["a"] * 5 + ["e"] * 30], dtype=object).T
ohe = OneHotEncoder(
categories=[["c", "d", "a", "b"]],
sparse_output=False,
... | 'a' is the only frequent category, all other categories are infrequent. | test_ohe_infrequent_two_levels_user_cats_one_frequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_two_levels_user_cats():
"""Test that the order of the categories provided by a user is respected."""
X_train = np.array(
[["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object
).T
ohe = OneHotEncoder(
categories=[["c", "d", "a", "b"]],
sparse_outp... | Test that the order of the categories provided by a user is respected. | test_ohe_infrequent_two_levels_user_cats | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_three_levels_user_cats():
"""Test that the order of the categories provided by a user is respected.
In this case 'c' is encoded as the first category and 'b' is encoded
as the second one."""
X_train = np.array(
[["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=obj... | Test that the order of the categories provided by a user is respected.
In this case 'c' is encoded as the first category and 'b' is encoded
as the second one. | test_ohe_infrequent_three_levels_user_cats | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_mixed():
"""Test infrequent categories where feature 0 has infrequent categories,
and feature 1 does not."""
# X[:, 0] 1 and 2 are infrequent
# X[:, 1] nothing is infrequent
X = np.c_[[0, 1, 3, 3, 3, 3, 2, 0, 3], [0, 0, 0, 0, 1, 1, 1, 1, 1]]
ohe = OneHotEncoder(max_cate... | Test infrequent categories where feature 0 has infrequent categories,
and feature 1 does not. | test_ohe_infrequent_mixed | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_multiple_categories():
"""Test infrequent categories with feature matrix with 3 features."""
X = np.c_[
[0, 1, 3, 3, 3, 3, 2, 0, 3],
[0, 0, 5, 1, 1, 10, 5, 5, 0],
[1, 0, 1, 0, 1, 0, 1, 0, 1],
]
ohe = OneHotEncoder(
categories="auto", max_categori... | Test infrequent categories with feature matrix with 3 features. | test_ohe_infrequent_multiple_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_multiple_categories_dtypes():
"""Test infrequent categories with a pandas dataframe with multiple dtypes."""
pd = pytest.importorskip("pandas")
X = pd.DataFrame(
{
"str": ["a", "f", "c", "f", "f", "a", "c", "b", "b"],
"int": [5, 3, 0, 10, 10, 12, 0, 3... | Test infrequent categories with a pandas dataframe with multiple dtypes. | test_ohe_infrequent_multiple_categories_dtypes | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_one_level_errors(kwargs):
"""All user provided categories are infrequent."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 2]).T
ohe = OneHotEncoder(
handle_unknown="infrequent_if_exist", sparse_output=False, **kwargs
)
ohe.fit(X_train)
X_tra... | All user provided categories are infrequent. | test_ohe_infrequent_one_level_errors | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_user_cats_unknown_training_errors(kwargs):
"""All user provided categories are infrequent."""
X_train = np.array([["e"] * 3], dtype=object).T
ohe = OneHotEncoder(
categories=[["c", "d", "a", "b"]],
sparse_output=False,
handle_unknown="infrequent_if_exist",
... | All user provided categories are infrequent. | test_ohe_infrequent_user_cats_unknown_training_errors | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_encoders_string_categories(input_dtype, category_dtype, array_type):
"""Check that encoding work with object, unicode, and byte string dtypes.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/15616
https://github.com/scikit-learn/scikit-learn/issues/15726
https:/... | Check that encoding work with object, unicode, and byte string dtypes.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/15616
https://github.com/scikit-learn/scikit-learn/issues/15726
https://github.com/scikit-learn/scikit-learn/issues/19677
| test_encoders_string_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_mixed_string_bytes_categoricals():
"""Check that this mixture of predefined categories and X raises an error.
Categories defined as bytes can not easily be compared to data that is
a string.
"""
# data as unicode
X = np.array([["b"], ["a"]], dtype="U")
# predefined categories as by... | Check that this mixture of predefined categories and X raises an error.
Categories defined as bytes can not easily be compared to data that is
a string.
| test_mixed_string_bytes_categoricals | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_drop_first_handle_unknown_ignore_warns(handle_unknown):
"""Check drop='first' and handle_unknown='ignore'/'infrequent_if_exist'
during transform."""
X = [["a", 0], ["b", 2], ["b", 1]]
ohe = OneHotEncoder(
drop="first", sparse_output=False, handle_unknown=handle_unknown
)
X_... | Check drop='first' and handle_unknown='ignore'/'infrequent_if_exist'
during transform. | test_ohe_drop_first_handle_unknown_ignore_warns | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_drop_if_binary_handle_unknown_ignore_warns(handle_unknown):
"""Check drop='if_binary' and handle_unknown='ignore' during transform."""
X = [["a", 0], ["b", 2], ["b", 1]]
ohe = OneHotEncoder(
drop="if_binary", sparse_output=False, handle_unknown=handle_unknown
)
X_trans = ohe.fi... | Check drop='if_binary' and handle_unknown='ignore' during transform. | test_ohe_drop_if_binary_handle_unknown_ignore_warns | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_drop_first_explicit_categories(handle_unknown):
"""Check drop='first' and handle_unknown='ignore'/'infrequent_if_exist'
during fit with categories passed in."""
X = [["a", 0], ["b", 2], ["b", 1]]
ohe = OneHotEncoder(
drop="first",
sparse_output=False,
handle_unknow... | Check drop='first' and handle_unknown='ignore'/'infrequent_if_exist'
during fit with categories passed in. | test_ohe_drop_first_explicit_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_more_informative_error_message():
"""Raise informative error message when pandas output and sparse_output=True."""
pd = pytest.importorskip("pandas")
df = pd.DataFrame({"a": [1, 2, 3], "b": ["z", "b", "b"]}, columns=["a", "b"])
ohe = OneHotEncoder(sparse_output=True)
ohe.set_output(tra... | Raise informative error message when pandas output and sparse_output=True. | test_ohe_more_informative_error_message | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_passthrough_missing_values_float_errors_dtype():
"""Test ordinal encoder with nan passthrough fails when dtype=np.int32."""
X = np.array([[np.nan, 3.0, 1.0, 3.0]]).T
oe = OrdinalEncoder(dtype=np.int32)
msg = (
r"There are missing values in features \[0\]. For OrdinalEn... | Test ordinal encoder with nan passthrough fails when dtype=np.int32. | test_ordinal_encoder_passthrough_missing_values_float_errors_dtype | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_passthrough_missing_values_float(encoded_missing_value):
"""Test ordinal encoder with nan on float dtypes."""
X = np.array([[np.nan, 3.0, 1.0, 3.0]], dtype=np.float64).T
oe = OrdinalEncoder(encoded_missing_value=encoded_missing_value).fit(X)
assert len(oe.categories_) == 1
... | Test ordinal encoder with nan on float dtypes. | test_ordinal_encoder_passthrough_missing_values_float | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_missing_value_support_pandas_categorical(
pd_nan_type, encoded_missing_value
):
"""Check ordinal encoder is compatible with pandas."""
# checks pandas dataframe with categorical features
pd = pytest.importorskip("pandas")
pd_missing_value = pd.NA if pd_nan_type == "pd.NA" e... | Check ordinal encoder is compatible with pandas. | test_ordinal_encoder_missing_value_support_pandas_categorical | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_specified_categories_missing_passthrough(
X, X2, cats, cat_dtype
):
"""Test ordinal encoder for specified categories."""
oe = OrdinalEncoder(categories=cats)
exp = np.array([[0.0], [np.nan]])
assert_array_equal(oe.fit_transform(X), exp)
# manually specified categories sh... | Test ordinal encoder for specified categories. | test_ordinal_encoder_specified_categories_missing_passthrough | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_encoder_duplicate_specified_categories(Encoder):
"""Test encoder for specified categories have duplicate values.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27088
"""
cats = [np.array(["a", "b", "a"], dtype=object)]
enc = Encoder(categories=cats)
X ... | Test encoder for specified categories have duplicate values.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27088
| test_encoder_duplicate_specified_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_handle_missing_and_unknown(X, expected_X_trans, X_test):
"""Test the interaction between missing values and handle_unknown"""
oe = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1)
X_trans = oe.fit_transform(X)
assert_allclose(X_trans, expected_X_trans)
... | Test the interaction between missing values and handle_unknown | test_ordinal_encoder_handle_missing_and_unknown | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_sparse(csr_container):
"""Check that we raise proper error with sparse input in OrdinalEncoder.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19878
"""
X = np.array([[3, 2, 1], [0, 1, 1]])
X_sparse = csr_container(X)
encoder = OrdinalE... | Check that we raise proper error with sparse input in OrdinalEncoder.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19878
| test_ordinal_encoder_sparse | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_fit_with_unseen_category():
"""Check OrdinalEncoder.fit works with unseen category when
`handle_unknown="use_encoded_value"`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19872
"""
X = np.array([0, 0, 1, 0, 2, 5])[:, np.newaxis]
oe = O... | Check OrdinalEncoder.fit works with unseen category when
`handle_unknown="use_encoded_value"`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19872
| test_ordinal_encoder_fit_with_unseen_category | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_handle_unknown_string_dtypes(X_train, X_test):
"""Checks that `OrdinalEncoder` transforms string dtypes.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19872
"""
enc = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-9)
enc.... | Checks that `OrdinalEncoder` transforms string dtypes.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19872
| test_ordinal_encoder_handle_unknown_string_dtypes | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_python_integer():
"""Check that `OrdinalEncoder` accepts Python integers that are potentially
larger than 64 bits.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20721
"""
X = np.array(
[
44253463435747313673,
... | Check that `OrdinalEncoder` accepts Python integers that are potentially
larger than 64 bits.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/20721
| test_ordinal_encoder_python_integer | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_features_names_out_pandas():
"""Check feature names out is same as the input."""
pd = pytest.importorskip("pandas")
names = ["b", "c", "a"]
X = pd.DataFrame([[1, 2, 3]], columns=names)
enc = OrdinalEncoder().fit(X)
feature_names_out = enc.get_feature_names_out()
as... | Check feature names out is same as the input. | test_ordinal_encoder_features_names_out_pandas | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_unknown_missing_interaction():
"""Check interactions between encode_unknown and missing value encoding."""
X = np.array([["a"], ["b"], [np.nan]], dtype=object)
oe = OrdinalEncoder(
handle_unknown="use_encoded_value",
unknown_value=np.nan,
encoded_missing_va... | Check interactions between encode_unknown and missing value encoding. | test_ordinal_encoder_unknown_missing_interaction | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_encoded_missing_value_error(with_pandas):
"""Check OrdinalEncoder errors when encoded_missing_value is used by
an known category."""
X = np.array([["a", "dog"], ["b", "cat"], ["c", np.nan]], dtype=object)
# The 0-th feature has no missing values so it is not included in the lis... | Check OrdinalEncoder errors when encoded_missing_value is used by
an known category. | test_ordinal_encoder_encoded_missing_value_error | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_unknown_missing_interaction_both_nan(
X_train, X_test_trans_expected, X_roundtrip_expected
):
"""Check transform when unknown_value and encoded_missing_value is nan.
Non-regression test for #24082.
"""
oe = OrdinalEncoder(
handle_unknown="use_encoded_value",
... | Check transform when unknown_value and encoded_missing_value is nan.
Non-regression test for #24082.
| test_ordinal_encoder_unknown_missing_interaction_both_nan | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_predefined_categories_dtype():
"""Check that the categories_ dtype is `object` for string categories
Regression test for gh-25171.
"""
categories = [["as", "mmas", "eas", "ras", "acs"], ["1", "2"]]
enc = OneHotEncoder(categories=categories)
enc.fit([["as", "1"]])
assert len(cate... | Check that the categories_ dtype is `object` for string categories
Regression test for gh-25171.
| test_predefined_categories_dtype | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_missing_unknown_encoding_max():
"""Check missing value or unknown encoding can equal the cardinality."""
X = np.array([["dog"], ["cat"], [np.nan]], dtype=object)
X_trans = OrdinalEncoder(encoded_missing_value=2).fit_transform(X)
assert_allclose(X_trans, [[1], [0], [2]])
enc... | Check missing value or unknown encoding can equal the cardinality. | test_ordinal_encoder_missing_unknown_encoding_max | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_drop_idx_infrequent_categories():
"""Check drop_idx is defined correctly with infrequent categories.
Non-regression test for gh-25550.
"""
X = np.array(
[["a"] * 2 + ["b"] * 4 + ["c"] * 4 + ["d"] * 4 + ["e"] * 4], dtype=object
).T
ohe = OneHotEncoder(min_frequency=4, sparse_out... | Check drop_idx is defined correctly with infrequent categories.
Non-regression test for gh-25550.
| test_drop_idx_infrequent_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_infrequent_three_levels(kwargs):
"""Test parameters for grouping 'a', and 'd' into the infrequent category."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T
ordinal = OrdinalEncoder(
handle_unknown="use_encoded_value", unknown_value=-1, **kwargs
... | Test parameters for grouping 'a', and 'd' into the infrequent category. | test_ordinal_encoder_infrequent_three_levels | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_infrequent_three_levels_user_cats():
"""Test that the order of the categories provided by a user is respected.
In this case 'c' is encoded as the first category and 'b' is encoded
as the second one.
"""
X_train = np.array(
[["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d... | Test that the order of the categories provided by a user is respected.
In this case 'c' is encoded as the first category and 'b' is encoded
as the second one.
| test_ordinal_encoder_infrequent_three_levels_user_cats | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_infrequent_mixed():
"""Test when feature 0 has infrequent categories and feature 1 does not."""
X = np.column_stack(([0, 1, 3, 3, 3, 3, 2, 0, 3], [0, 0, 0, 0, 1, 1, 1, 1, 1]))
ordinal = OrdinalEncoder(max_categories=3).fit(X)
assert_array_equal(ordinal.infrequent_categories_[... | Test when feature 0 has infrequent categories and feature 1 does not. | test_ordinal_encoder_infrequent_mixed | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_infrequent_multiple_categories_dtypes():
"""Test infrequent categories with a pandas DataFrame with multiple dtypes."""
pd = pytest.importorskip("pandas")
categorical_dtype = pd.CategoricalDtype(["bird", "cat", "dog", "snake"])
X = pd.DataFrame(
{
"str": ["a... | Test infrequent categories with a pandas DataFrame with multiple dtypes. | test_ordinal_encoder_infrequent_multiple_categories_dtypes | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_infrequent_custom_mapping():
"""Check behavior of unknown_value and encoded_missing_value with infrequent."""
X_train = np.array(
[["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3 + [np.nan]], dtype=object
).T
ordinal = OrdinalEncoder(
handle_unknown="use_encoded... | Check behavior of unknown_value and encoded_missing_value with infrequent. | test_ordinal_encoder_infrequent_custom_mapping | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_all_frequent(kwargs):
"""All categories are considered frequent have same encoding as default encoder."""
X_train = np.array(
[["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object
).T
adjusted_encoder = OrdinalEncoder(
**kwargs, handle_unknown="use_enc... | All categories are considered frequent have same encoding as default encoder. | test_ordinal_encoder_all_frequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_all_infrequent(kwargs):
"""When all categories are infrequent, they are all encoded as zero."""
X_train = np.array(
[["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object
).T
encoder = OrdinalEncoder(
**kwargs, handle_unknown="use_encoded_value", unknown... | When all categories are infrequent, they are all encoded as zero. | test_ordinal_encoder_all_infrequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_missing_appears_frequent():
"""Check behavior when missing value appears frequently."""
X = np.array(
[[np.nan] * 20 + ["dog"] * 10 + ["cat"] * 5 + ["snake"] + ["deer"]],
dtype=object,
).T
ordinal = OrdinalEncoder(max_categories=3).fit(X)
X_test = np.array([... | Check behavior when missing value appears frequently. | test_ordinal_encoder_missing_appears_frequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ordinal_encoder_missing_appears_infrequent():
"""Check behavior when missing value appears infrequently."""
# feature 0 has infrequent categories
# feature 1 has no infrequent categories
X = np.array(
[
[np.nan] + ["dog"] * 10 + ["cat"] * 5 + ["snake"] + ["deer"],
... | Check behavior when missing value appears infrequently. | test_ordinal_encoder_missing_appears_infrequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_encoder_not_fitted(Encoder):
"""Check that we raise a `NotFittedError` by calling transform before fit with
the encoders.
One could expect that the passing the `categories` argument to the encoder
would make it stateless. However, `fit` is making a couple of check, such as the
position of ... | Check that we raise a `NotFittedError` by calling transform before fit with
the encoders.
One could expect that the passing the `categories` argument to the encoder
would make it stateless. However, `fit` is making a couple of check, such as the
position of `np.nan`.
| test_encoder_not_fitted | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_function_transformer_raise_error_with_mixed_dtype(X_type):
"""Check that `FunctionTransformer.check_inverse` raises error on mixed dtype."""
mapping = {"one": 1, "two": 2, "three": 3, 5: "five", 6: "six"}
inverse_mapping = {value: key for key, value in mapping.items()}
dtype = "object"
dat... | Check that `FunctionTransformer.check_inverse` raises error on mixed dtype. | test_function_transformer_raise_error_with_mixed_dtype | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_function_transformer_support_all_nummerical_dataframes_check_inverse_True():
"""Check support for dataframes with only numerical values."""
pd = pytest.importorskip("pandas")
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
transformer = FunctionTransformer(
func=lambda x: x + 2, in... | Check support for dataframes with only numerical values. | test_function_transformer_support_all_nummerical_dataframes_check_inverse_True | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_function_transformer_with_dataframe_and_check_inverse_True():
"""Check error is raised when check_inverse=True.
Non-regresion test for gh-25261.
"""
pd = pytest.importorskip("pandas")
transformer = FunctionTransformer(
func=lambda x: x, inverse_func=lambda x: x, check_inverse=True
... | Check error is raised when check_inverse=True.
Non-regresion test for gh-25261.
| test_function_transformer_with_dataframe_and_check_inverse_True | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_function_transformer_validate_inverse():
"""Test that function transformer does not reset estimator in
`inverse_transform`."""
def add_constant_feature(X):
X_one = np.ones((X.shape[0], 1))
return np.concatenate((X, X_one), axis=1)
def inverse_add_constant(X):
return X[... | Test that function transformer does not reset estimator in
`inverse_transform`. | test_function_transformer_validate_inverse | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_get_feature_names_out_dataframe_with_string_data(
feature_names_out, expected, in_pipeline
):
"""Check that get_feature_names_out works with DataFrames with string data."""
pd = pytest.importorskip("pandas")
X = pd.DataFrame({"pet": ["dog", "cat"], "color": ["red", "green"]})
def func(X):
... | Check that get_feature_names_out works with DataFrames with string data. | test_get_feature_names_out_dataframe_with_string_data | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_set_output_func():
"""Check behavior of set_output with different settings."""
pd = pytest.importorskip("pandas")
X = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 100]})
ft = FunctionTransformer(np.log, feature_names_out="one-to-one")
# no warning is raised when feature_names_out is defin... | Check behavior of set_output with different settings. | test_set_output_func | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_consistence_column_name_between_steps():
"""Check that we have a consistence between the feature names out of
`FunctionTransformer` and the feature names in of the next step in the pipeline.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27695
"""
pd = pyt... | Check that we have a consistence between the feature names out of
`FunctionTransformer` and the feature names in of the next step in the pipeline.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27695
| test_consistence_column_name_between_steps | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_function_transformer_overwrite_column_names(dataframe_lib, transform_output):
"""Check that we overwrite the column names when we should."""
lib = pytest.importorskip(dataframe_lib)
if transform_output != "numpy":
pytest.importorskip(transform_output)
df = lib.DataFrame({"a": [1, 2, 3]... | Check that we overwrite the column names when we should. | test_function_transformer_overwrite_column_names | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_function_transformer_overwrite_column_names_numerical(feature_names_out):
"""Check the same as `test_function_transformer_overwrite_column_names`
but for the specific case of pandas where column names can be numerical."""
pd = pytest.importorskip("pandas")
df = pd.DataFrame({0: [1, 2, 3], 1: [... | Check the same as `test_function_transformer_overwrite_column_names`
but for the specific case of pandas where column names can be numerical. | test_function_transformer_overwrite_column_names_numerical | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_function_transformer_error_column_inconsistent(
dataframe_lib, feature_names_out
):
"""Check that we raise an error when `func` returns a dataframe with new
column names that become inconsistent with `get_feature_names_out`."""
lib = pytest.importorskip(dataframe_lib)
df = lib.DataFrame({"... | Check that we raise an error when `func` returns a dataframe with new
column names that become inconsistent with `get_feature_names_out`. | test_function_transformer_error_column_inconsistent | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_function_transformer.py | BSD-3-Clause |
def test_label_binarizer_pandas_nullable(dtype, unique_first):
"""Checks that LabelBinarizer works with pandas nullable dtypes.
Non-regression test for gh-25637.
"""
pd = pytest.importorskip("pandas")
y_true = pd.Series([1, 0, 0, 1, 0, 1, 1, 0, 1], dtype=dtype)
if unique_first:
# Calli... | Checks that LabelBinarizer works with pandas nullable dtypes.
Non-regression test for gh-25637.
| test_label_binarizer_pandas_nullable | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_label.py | BSD-3-Clause |
def test_nan_label_encoder():
"""Check that label encoder encodes nans in transform.
Non-regression test for #22628.
"""
le = LabelEncoder()
le.fit(["a", "a", "b", np.nan])
y_trans = le.transform([np.nan])
assert_array_equal(y_trans, [2]) | Check that label encoder encodes nans in transform.
Non-regression test for #22628.
| test_nan_label_encoder | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_label.py | BSD-3-Clause |
def test_label_encoders_do_not_have_set_output(encoder):
"""Check that label encoders do not define set_output and work with y as a kwarg.
Non-regression test for #26854.
"""
assert not hasattr(encoder, "set_output")
y_encoded_with_kwarg = encoder.fit_transform(y=["a", "b", "c"])
y_encoded_posi... | Check that label encoders do not define set_output and work with y as a kwarg.
Non-regression test for #26854.
| test_label_encoders_do_not_have_set_output | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_label.py | BSD-3-Clause |
def test_polynomial_and_spline_array_order(est):
"""Test that output array has the given order."""
X = np.arange(10).reshape(5, 2)
def is_c_contiguous(a):
return np.isfortran(a.T)
assert is_c_contiguous(est().fit_transform(X))
assert is_c_contiguous(est(order="C").fit_transform(X))
ass... | Test that output array has the given order. | test_polynomial_and_spline_array_order | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_input_validation(params, err_msg):
"""Test that we raise errors for invalid input in SplineTransformer."""
X = [[1], [2]]
with pytest.raises(ValueError, match=err_msg):
SplineTransformer(**params).fit(X) | Test that we raise errors for invalid input in SplineTransformer. | test_spline_transformer_input_validation | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_integer_knots(extrapolation):
"""Test that SplineTransformer accepts integer value knot positions."""
X = np.arange(20).reshape(10, 2)
knots = [[0, 1], [1, 2], [5, 5], [11, 10], [12, 11]]
_ = SplineTransformer(
degree=3, knots=knots, extrapolation=extrapolation
).... | Test that SplineTransformer accepts integer value knot positions. | test_spline_transformer_integer_knots | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_feature_names():
"""Test that SplineTransformer generates correct features name."""
X = np.arange(20).reshape(10, 2)
splt = SplineTransformer(n_knots=3, degree=3, include_bias=True).fit(X)
feature_names = splt.get_feature_names_out()
assert_array_equal(
feature_na... | Test that SplineTransformer generates correct features name. | test_spline_transformer_feature_names | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_split_transform_feature_names_extrapolation_degree(extrapolation, degree):
"""Test feature names are correct for different extrapolations and degree.
Non-regression test for gh-25292.
"""
X = np.arange(20).reshape(10, 2)
splt = SplineTransformer(degree=degree, extrapolation=extrapolation).... | Test feature names are correct for different extrapolations and degree.
Non-regression test for gh-25292.
| test_split_transform_feature_names_extrapolation_degree | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_unity_decomposition(degree, n_knots, knots, extrapolation):
"""Test that B-splines are indeed a decomposition of unity.
Splines basis functions must sum up to 1 per row, if we stay in between boundaries.
"""
X = np.linspace(0, 1, 100)[:, None]
# make the boundaries 0 and... | Test that B-splines are indeed a decomposition of unity.
Splines basis functions must sum up to 1 per row, if we stay in between boundaries.
| test_spline_transformer_unity_decomposition | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_linear_regression(bias, intercept):
"""Test that B-splines fit a sinusodial curve pretty well."""
X = np.linspace(0, 10, 100)[:, None]
y = np.sin(X[:, 0]) + 2 # +2 to avoid the value 0 in assert_allclose
pipe = Pipeline(
steps=[
(
"spline"... | Test that B-splines fit a sinusodial curve pretty well. | test_spline_transformer_linear_regression | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_get_base_knot_positions(
knots, n_knots, sample_weight, expected_knots
):
"""Check the behaviour to find knot positions with and without sample_weight."""
X = np.array([[0, 2], [0, 2], [2, 2], [3, 3], [4, 6], [5, 8], [6, 14]])
base_knots = SplineTransformer._get_base_knot_pos... | Check the behaviour to find knot positions with and without sample_weight. | test_spline_transformer_get_base_knot_positions | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_periodic_linear_regression(bias, intercept):
"""Test that B-splines fit a periodic curve pretty well."""
# "+ 3" to avoid the value 0 in assert_allclose
def f(x):
return np.sin(2 * np.pi * x) - np.sin(8 * np.pi * x) + 3
X = np.linspace(0, 1, 101)[:, None]
pipe =... | Test that B-splines fit a periodic curve pretty well. | test_spline_transformer_periodic_linear_regression | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_periodic_spline_backport():
"""Test that the backport of extrapolate="periodic" works correctly"""
X = np.linspace(-2, 3.5, 10)[:, None]
degree = 2
# Use periodic extrapolation backport in SplineTransformer
transformer = SplineTransformer(
degree=degree, extrapol... | Test that the backport of extrapolate="periodic" works correctly | test_spline_transformer_periodic_spline_backport | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_periodic_splines_periodicity():
"""Test if shifted knots result in the same transformation up to permutation."""
X = np.linspace(0, 10, 101)[:, None]
transformer_1 = SplineTransformer(
degree=3,
extrapolation="periodic",
knots=[[0.0], [1.0], [3.0], [4.0],... | Test if shifted knots result in the same transformation up to permutation. | test_spline_transformer_periodic_splines_periodicity | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_periodic_splines_smoothness(degree):
"""Test that spline transformation is smooth at first / last knot."""
X = np.linspace(-2, 10, 10_000)[:, None]
transformer = SplineTransformer(
degree=degree,
extrapolation="periodic",
knots=[[0.0], [1.0], [3.0], [4.0]... | Test that spline transformation is smooth at first / last knot. | test_spline_transformer_periodic_splines_smoothness | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_extrapolation(bias, intercept, degree):
"""Test that B-spline extrapolation works correctly."""
# we use a straight line for that
X = np.linspace(-1, 1, 100)[:, None]
y = X.squeeze()
# 'constant'
pipe = Pipeline(
[
[
"spline",
... | Test that B-spline extrapolation works correctly. | test_spline_transformer_extrapolation | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_kbindiscretizer(global_random_seed):
"""Test that a B-spline of degree=0 is equivalent to KBinsDiscretizer."""
rng = np.random.RandomState(global_random_seed)
X = rng.randn(200).reshape(200, 1)
n_bins = 5
n_knots = n_bins + 1
splt = SplineTransformer(
n_knots... | Test that a B-spline of degree=0 is equivalent to KBinsDiscretizer. | test_spline_transformer_kbindiscretizer | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_spline_transformer_n_features_out(
n_knots, include_bias, degree, extrapolation, sparse_output
):
"""Test that transform results in n_features_out_ features."""
splt = SplineTransformer(
n_knots=n_knots,
degree=degree,
include_bias=include_bias,
extrapolation=extrapo... | Test that transform results in n_features_out_ features. | test_spline_transformer_n_features_out | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_polynomial_features_input_validation(params, err_msg):
"""Test that we raise errors for invalid input in PolynomialFeatures."""
X = [[1], [2]]
with pytest.raises(ValueError, match=err_msg):
PolynomialFeatures(**params).fit(X) | Test that we raise errors for invalid input in PolynomialFeatures. | test_polynomial_features_input_validation | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_polynomial_features_one_feature(
single_feature_degree3,
degree,
include_bias,
interaction_only,
indices,
X_container,
):
"""Test PolynomialFeatures on single feature up to degree 3."""
X, P = single_feature_degree3
if X_container is not None:
X = X_container(X)
... | Test PolynomialFeatures on single feature up to degree 3. | test_polynomial_features_one_feature | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_polynomial_features_two_features(
two_features_degree3,
degree,
include_bias,
interaction_only,
indices,
X_container,
):
"""Test PolynomialFeatures on 2 features up to degree 3."""
X, P = two_features_degree3
if X_container is not None:
X = X_container(X)
tf = Po... | Test PolynomialFeatures on 2 features up to degree 3. | test_polynomial_features_two_features | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_csr_polynomial_expansion_index_overflow_non_regression(
interaction_only, include_bias, csr_container
):
"""Check the automatic index dtype promotion to `np.int64` when needed.
This ensures that sufficiently large input configurations get
properly promoted to use `np.int64` for index and indpt... | Check the automatic index dtype promotion to `np.int64` when needed.
This ensures that sufficiently large input configurations get
properly promoted to use `np.int64` for index and indptr representation
while preserving data integrity. Non-regression test for gh-16803.
Note that this is only possible ... | test_csr_polynomial_expansion_index_overflow_non_regression | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_csr_polynomial_expansion_index_overflow(
degree, n_features, interaction_only, include_bias, csr_container
):
"""Tests known edge-cases to the dtype promotion strategy and custom
Cython code, including a current bug in the upstream
`scipy.sparse.hstack`.
"""
data = [1.0]
# Use int32... | Tests known edge-cases to the dtype promotion strategy and custom
Cython code, including a current bug in the upstream
`scipy.sparse.hstack`.
| test_csr_polynomial_expansion_index_overflow | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def test_polynomial_features_behaviour_on_zero_degree(sparse_container):
"""Check that PolynomialFeatures raises error when degree=0 and include_bias=False,
and output a single constant column when include_bias=True
"""
X = np.ones((10, 2))
poly = PolynomialFeatures(degree=0, include_bias=False)
... | Check that PolynomialFeatures raises error when degree=0 and include_bias=False,
and output a single constant column when include_bias=True
| test_polynomial_features_behaviour_on_zero_degree | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_polynomial.py | BSD-3-Clause |
def _encode_target(X_ordinal, y_numeric, n_categories, smooth):
"""Simple Python implementation of target encoding."""
cur_encodings = np.zeros(n_categories, dtype=np.float64)
y_mean = np.mean(y_numeric)
if smooth == "auto":
y_variance = np.var(y_numeric)
for c in range(n_categories):
... | Simple Python implementation of target encoding. | _encode_target | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_target_encoder.py | BSD-3-Clause |
def test_encoding(categories, unknown_value, global_random_seed, smooth, target_type):
"""Check encoding for binary and continuous targets.
Compare the values returned by `TargetEncoder.fit_transform` against the
expected encodings for cv splits from a naive reference Python
implementation in _encode_t... | Check encoding for binary and continuous targets.
Compare the values returned by `TargetEncoder.fit_transform` against the
expected encodings for cv splits from a naive reference Python
implementation in _encode_target.
| test_encoding | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_target_encoder.py | BSD-3-Clause |
def test_custom_categories(X, categories, smooth):
"""Custom categories with unknown categories that are not in training data."""
rng = np.random.RandomState(0)
y = rng.uniform(low=-10, high=20, size=X.shape[0])
enc = TargetEncoder(categories=categories, smooth=smooth, random_state=0).fit(X, y)
# T... | Custom categories with unknown categories that are not in training data. | test_custom_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_target_encoder.py | BSD-3-Clause |
def test_use_regression_target():
"""Check inferred and specified `target_type` on regression target."""
X = np.array([[0, 1, 0, 1, 0, 1]]).T
y = np.array([1.0, 2.0, 3.0, 2.0, 3.0, 4.0])
enc = TargetEncoder(cv=2)
with pytest.warns(
UserWarning,
match=re.escape(
"The leas... | Check inferred and specified `target_type` on regression target. | test_use_regression_target | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_target_encoder.py | BSD-3-Clause |
def test_multiple_features_quick(to_pandas, smooth, target_type):
"""Check target encoder with multiple features."""
X_ordinal = np.array(
[[1, 1], [0, 1], [1, 1], [2, 1], [1, 0], [0, 1], [1, 0], [0, 0]], dtype=np.int64
)
if target_type == "binary-str":
y_train = np.array(["a", "b", "a",... | Check target encoder with multiple features. | test_multiple_features_quick | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_target_encoder.py | BSD-3-Clause |
def test_constant_target_and_feature(y, y_mean, smooth):
"""Check edge case where feature and target is constant."""
X = np.array([[1] * 20]).T
n_samples = X.shape[0]
enc = TargetEncoder(cv=2, smooth=smooth, random_state=0)
X_trans = enc.fit_transform(X, y)
assert_allclose(X_trans, np.repeat([[... | Check edge case where feature and target is constant. | test_constant_target_and_feature | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_target_encoder.py | BSD-3-Clause |
def test_smooth_zero():
"""Check edge case with zero smoothing and cv does not contain category."""
X = np.array([[0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]).T
y = np.array([2.1, 4.3, 1.2, 3.1, 1.0, 9.0, 10.3, 14.2, 13.3, 15.0])
enc = TargetEncoder(smooth=0.0, shuffle=False, cv=2)
X_trans = enc.fit_transform(... | Check edge case with zero smoothing and cv does not contain category. | test_smooth_zero | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_target_encoder.py | BSD-3-Clause |
def test_pandas_copy_on_write():
"""
Test target-encoder cython code when y is read-only.
The numpy array underlying df["y"] is read-only when copy-on-write is enabled.
Non-regression test for gh-27879.
"""
pd = pytest.importorskip("pandas", minversion="2.0")
with pd.option_context("mode.co... |
Test target-encoder cython code when y is read-only.
The numpy array underlying df["y"] is read-only when copy-on-write is enabled.
Non-regression test for gh-27879.
| test_pandas_copy_on_write | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_target_encoder.py | BSD-3-Clause |
def predict(self, X):
"""Perform inductive inference across the model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix.
Returns
-------
y : ndarray of shape (n_samples,)
Predictions for input data.
... | Perform inductive inference across the model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix.
Returns
-------
y : ndarray of shape (n_samples,)
Predictions for input data.
| predict | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_label_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_label_propagation.py | BSD-3-Clause |
def predict_proba(self, X):
"""Predict probability for each possible outcome.
Compute the probability estimates for each single sample in X
and each possible outcome seen during training (categorical
distribution).
Parameters
----------
X : array-like of shape (... | Predict probability for each possible outcome.
Compute the probability estimates for each single sample in X
and each possible outcome seen during training (categorical
distribution).
Parameters
----------
X : array-like of shape (n_samples, n_features)
The ... | predict_proba | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_label_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_label_propagation.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit a semi-supervised label propagation model to X.
The input samples (labeled and unlabeled) are provided by matrix X,
and target labels are provided by matrix y. We conventionally apply the
label -1 to unlabeled samples in matrix y in a semi-supervised
... | Fit a semi-supervised label propagation model to X.
The input samples (labeled and unlabeled) are provided by matrix X,
and target labels are provided by matrix y. We conventionally apply the
label -1 to unlabeled samples in matrix y in a semi-supervised
classification.
Paramet... | fit | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_label_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_label_propagation.py | BSD-3-Clause |
def _build_graph(self):
"""Matrix representing a fully connected graph between each sample
This basic implementation creates a non-stochastic affinity matrix, so
class distributions will exceed 1 (normalization may be desired).
"""
if self.kernel == "knn":
self.nn_fi... | Matrix representing a fully connected graph between each sample
This basic implementation creates a non-stochastic affinity matrix, so
class distributions will exceed 1 (normalization may be desired).
| _build_graph | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_label_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_label_propagation.py | BSD-3-Clause |
def _build_graph(self):
"""Graph matrix for Label Spreading computes the graph laplacian"""
# compute affinity matrix (or gram matrix)
if self.kernel == "knn":
self.nn_fit = None
n_samples = self.X_.shape[0]
affinity_matrix = self._get_kernel(self.X_)
laplacia... | Graph matrix for Label Spreading computes the graph laplacian | _build_graph | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_label_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_label_propagation.py | BSD-3-Clause |
def _get_estimator(self):
"""Get the estimator.
Returns
-------
estimator_ : estimator object
The cloned estimator object.
"""
# TODO(1.8): remove and only keep clone(self.estimator)
if self.estimator is None and self.base_estimator != "deprecated":
... | Get the estimator.
Returns
-------
estimator_ : estimator object
The cloned estimator object.
| _get_estimator | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_self_training.py | BSD-3-Clause |
def fit(self, X, y, **params):
"""
Fit self-training classifier using `X`, `y` as training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
y : {array-like, sparse matrix} of shape (n_s... |
Fit self-training classifier using `X`, `y` as training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
y : {array-like, sparse matrix} of shape (n_samples,)
Array representing th... | fit | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_self_training.py | BSD-3-Clause |
def predict(self, X, **params):
"""Predict the classes of `X`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
**params : dict of str -> object
Parameters to pass to the underlying estim... | Predict the classes of `X`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
**params : dict of str -> object
Parameters to pass to the underlying estimator's ``predict`` method.
.. ... | predict | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_self_training.py | BSD-3-Clause |
def predict_proba(self, X, **params):
"""Predict probability for each possible outcome.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
**params : dict of str -> object
Parameters to pas... | Predict probability for each possible outcome.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
**params : dict of str -> object
Parameters to pass to the underlying estimator's
``pre... | predict_proba | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_self_training.py | BSD-3-Clause |
def decision_function(self, X, **params):
"""Call decision function of the `estimator`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
**params : dict of str -> object
Parameters to pas... | Call decision function of the `estimator`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
**params : dict of str -> object
Parameters to pass to the underlying estimator's
``decisio... | decision_function | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_self_training.py | BSD-3-Clause |
def predict_log_proba(self, X, **params):
"""Predict log probability for each possible outcome.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
**params : dict of str -> object
Parameter... | Predict log probability for each possible outcome.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
**params : dict of str -> object
Parameters to pass to the underlying estimator's
`... | predict_log_proba | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_self_training.py | BSD-3-Clause |
def score(self, X, y, **params):
"""Call score on the `estimator`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
y : array-like of shape (n_samples,)
Array representing the labels.
... | Call score on the `estimator`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Array representing the data.
y : array-like of shape (n_samples,)
Array representing the labels.
**params : dict of str -> object
... | score | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_self_training.py | BSD-3-Clause |
def get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.6
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.met... | Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.6
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating... | get_metadata_routing | python | scikit-learn/scikit-learn | sklearn/semi_supervised/_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/_self_training.py | BSD-3-Clause |
def test_self_training_estimator_attribute_error():
"""Check that we raise the proper AttributeErrors when the `estimator`
does not implement the `predict_proba` method, which is called from within
`fit`, or `decision_function`, which is decorated with `available_if`.
Non-regression test for:
https... | Check that we raise the proper AttributeErrors when the `estimator`
does not implement the `predict_proba` method, which is called from within
`fit`, or `decision_function`, which is decorated with `available_if`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28108
| test_self_training_estimator_attribute_error | python | scikit-learn/scikit-learn | sklearn/semi_supervised/tests/test_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/tests/test_self_training.py | BSD-3-Clause |
def test_routing_passed_metadata_not_supported(method):
"""Test that the right error message is raised when metadata is passed while
not supported when `enable_metadata_routing=False`."""
est = SelfTrainingClassifier(estimator=SimpleEstimator())
with pytest.raises(
ValueError, match="is only sup... | Test that the right error message is raised when metadata is passed while
not supported when `enable_metadata_routing=False`. | test_routing_passed_metadata_not_supported | python | scikit-learn/scikit-learn | sklearn/semi_supervised/tests/test_self_training.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/semi_supervised/tests/test_self_training.py | BSD-3-Clause |
def _one_vs_one_coef(dual_coef, n_support, support_vectors):
"""Generate primal coefficients from dual coefficients
for the one-vs-one multi class LibSVM in the case
of a linear kernel."""
# get 1vs1 weights for all n*(n-1) classifiers.
# this is somewhat messy.
# shape of dual_coef_ is nSV * (... | Generate primal coefficients from dual coefficients
for the one-vs-one multi class LibSVM in the case
of a linear kernel. | _one_vs_one_coef | python | scikit-learn/scikit-learn | sklearn/svm/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None):
"""Fit the SVM model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) \
or (n_samples, n_samples)
Training vectors, where `n_samples` is the n... | Fit the SVM model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where `n_samples` is the number of samples
and `n_features` is the n... | fit | python | scikit-learn/scikit-learn | sklearn/svm/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.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.