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_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 |
def test_get_feature_names_pandas():
"""Get feature names with pandas dataframes."""
pd = pytest.importorskip("pandas")
columns = [f"col_{i}" for i in range(3)]
X = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=columns)
feature_names = _get_feature_names(X)
assert_array_equal(feature_names, colu... | Get feature names with pandas dataframes. | test_get_feature_names_pandas | 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_is_pandas_df():
"""Check behavior of is_pandas_df when pandas is installed."""
pd = pytest.importorskip("pandas")
df = pd.DataFrame([[1, 2, 3]])
assert _is_pandas_df(df)
assert not _is_pandas_df(np.asarray([1, 2, 3]))
assert not _is_pandas_df(1) | Check behavior of is_pandas_df when pandas is installed. | test_is_pandas_df | 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_is_pandas_df_pandas_not_installed(hide_available_pandas):
"""Check _is_pandas_df when pandas is not installed."""
assert not _is_pandas_df(np.asarray([1, 2, 3]))
assert not _is_pandas_df(1) | Check _is_pandas_df when pandas is not installed. | test_is_pandas_df_pandas_not_installed | 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_is_polars_df_for_duck_typed_polars_dataframe():
"""Check _is_polars_df for object that looks like a polars dataframe"""
class NotAPolarsDataFrame:
def __init__(self):
self.columns = [1, 2, 3]
self.schema = "my_schema"
not_a_polars_df = NotAPolarsDataFrame()
ass... | Check _is_polars_df for object that looks like a polars dataframe | test_is_polars_df_for_duck_typed_polars_dataframe | 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_numpy():
"""Get feature names return None for numpy arrays."""
X = np.array([[1, 2, 3], [4, 5, 6]])
names = _get_feature_names(X)
assert names is None | Get feature names return None for numpy arrays. | test_get_feature_names_numpy | 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_invalid_dtypes(names, dtypes):
"""Get feature names errors when the feature names have mixed dtypes"""
pd = pytest.importorskip("pandas")
X = pd.DataFrame([[1, 2], [4, 5], [5, 6]], columns=names)
msg = re.escape(
"Feature names are only supported if all input features... | Get feature names errors when the feature names have mixed dtypes | test_get_feature_names_invalid_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_check_feature_names_in_pandas():
"""Check behavior of check_feature_names_in for pandas dataframes."""
pd = pytest.importorskip("pandas")
names = ["a", "b", "c"]
df = pd.DataFrame([[0.0, 1.0, 2.0]], columns=names)
est = PassthroughTransformer().fit(df)
names = est.get_feature_names_out... | Check behavior of check_feature_names_in for pandas dataframes. | test_check_feature_names_in_pandas | 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_response_method_unknown_method():
"""Check the error message when passing an unknown response method."""
err_msg = (
"RandomForestRegressor has none of the following attributes: unknown_method."
)
with pytest.raises(AttributeError, match=err_msg):
_check_response_method(Ra... | Check the error message when passing an unknown response method. | test_check_response_method_unknown_method | 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_response_method_not_supported_response_method(response_method):
"""Check the error message when a response method is not supported by the
estimator."""
err_msg = (
f"EstimatorWithFit has none of the following attributes: {response_method}."
)
with pytest.raises(AttributeError,... | Check the error message when a response method is not supported by the
estimator. | test_check_response_method_not_supported_response_method | 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_response_method_list_str():
"""Check that we can pass a list of ordered method."""
method_implemented = ["predict_proba"]
my_estimator = _MockEstimatorOnOffPrediction(method_implemented)
X = "mocking_data"
# raise an error when no methods are defined
response_method = ["decision... | Check that we can pass a list of ordered method. | test_check_response_method_list_str | 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_pandas_array_returns_ndarray(input_values):
"""Check pandas array with extensions dtypes returns a numeric ndarray.
Non-regression test for gh-25637.
"""
pd = importorskip("pandas")
input_series = pd.array(input_values, dtype="Int32")
result = check_array(
input_series,
... | Check pandas array with extensions dtypes returns a numeric ndarray.
Non-regression test for gh-25637.
| test_pandas_array_returns_ndarray | 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_array_api_has_non_finite():
"""Checks that Array API arrays checks non-finite correctly."""
xp = pytest.importorskip("array_api_strict")
X_nan = xp.asarray([[xp.nan, 1, 0], [0, xp.nan, 3]], dtype=xp.float32)
with config_context(array_api_dispatch=True):
with pytest.raises(V... | Checks that Array API arrays checks non-finite correctly. | test_check_array_array_api_has_non_finite | 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_multiple_extensions(
extension_dtype, regular_dtype, include_object
):
"""Check pandas extension arrays give the same result as non-extension arrays."""
pd = pytest.importorskip("pandas")
X_regular = pd.DataFrame(
{
"a": pd.Series([1, 0, 1, 0], dtype=regular_dtyp... | Check pandas extension arrays give the same result as non-extension arrays. | test_check_array_multiple_extensions | 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_num_samples_dataframe_protocol():
"""Use the DataFrame interchange protocol to get n_samples from polars."""
pl = pytest.importorskip("polars")
df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
assert _num_samples(df) == 3 | Use the DataFrame interchange protocol to get n_samples from polars. | test_num_samples_dataframe_protocol | 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_dia_to_int32_indexed_csr_csc_coo(sparse_container, output_format):
"""Check the consistency of the indices dtype with sparse matrices/arrays."""
X = sparse_container([[0, 1], [1, 0]], dtype=np.float64)
# Explicitly set the dtype of the indexing arrays
if hasattr(X, "offsets"): # D... | Check the consistency of the indices dtype with sparse matrices/arrays. | test_check_array_dia_to_int32_indexed_csr_csc_coo | 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__is_polars_df():
"""Check that _is_polars_df return False for non-dataframe objects."""
class LooksLikePolars:
def __init__(self):
self.columns = ["a", "b"]
self.schema = ["a", "b"]
assert not _is_polars_df(LooksLikePolars()) | Check that _is_polars_df return False for non-dataframe objects. | test__is_polars_df | 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_writeable_np():
"""Check the behavior of check_array when a writeable array is requested
without copy if possible, on numpy arrays.
"""
X = np.random.uniform(size=(10, 10))
out = check_array(X, copy=False, force_writeable=True)
# X is already writeable, no copy is needed
... | Check the behavior of check_array when a writeable array is requested
without copy if possible, on numpy arrays.
| test_check_array_writeable_np | 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_writeable_mmap():
"""Check the behavior of check_array when a writeable array is requested
without copy if possible, on a memory-map.
A common situation is when a meta-estimators run in parallel using multiprocessing
with joblib, which creates read-only memory-maps of large arrays.... | Check the behavior of check_array when a writeable array is requested
without copy if possible, on a memory-map.
A common situation is when a meta-estimators run in parallel using multiprocessing
with joblib, which creates read-only memory-maps of large arrays.
| test_check_array_writeable_mmap | 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_writeable_df():
"""Check the behavior of check_array when a writeable array is requested
without copy if possible, on a dataframe.
"""
pd = pytest.importorskip("pandas")
X = np.random.uniform(size=(10, 10))
df = pd.DataFrame(X, copy=False)
out = check_array(df, copy=Fa... | Check the behavior of check_array when a writeable array is requested
without copy if possible, on a dataframe.
| test_check_array_writeable_df | 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_type_invariance(dtype, WeightVector):
"""Check the `dtype` consistency of `WeightVector`."""
weights = np.random.rand(100).astype(dtype)
average_weights = np.random.rand(100).astype(dtype)
weight_vector = WeightVector(weights, average_weights)
assert np.asarray(weight_vector.w).dtype is n... | Check the `dtype` consistency of `WeightVector`. | test_type_invariance | python | scikit-learn/scikit-learn | sklearn/utils/tests/test_weight_vector.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_weight_vector.py | BSD-3-Clause |
def _get_doc_link(self):
"""Generates a link to the API documentation for a given estimator.
This method generates the link to the estimator's documentation page
by using the template defined by the attribute `_doc_link_template`.
Returns
-------
url : str
T... | Generates a link to the API documentation for a given estimator.
This method generates the link to the estimator's documentation page
by using the template defined by the attribute `_doc_link_template`.
Returns
-------
url : str
The URL to the API documentation for ... | _get_doc_link | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/base.py | BSD-3-Clause |
def _repr_html_(self):
"""HTML representation of estimator.
This is redundant with the logic of `_repr_mimebundle_`. The latter
should be favored in the long term, `_repr_html_` is only
implemented for consumers who do not interpret `_repr_mimbundle_`.
"""
if get_config()... | HTML representation of estimator.
This is redundant with the logic of `_repr_mimebundle_`. The latter
should be favored in the long term, `_repr_html_` is only
implemented for consumers who do not interpret `_repr_mimbundle_`.
| _repr_html_ | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/base.py | BSD-3-Clause |
def _repr_mimebundle_(self, **kwargs):
"""Mime bundle used by jupyter kernels to display estimator"""
output = {"text/plain": repr(self)}
if get_config()["display"] == "diagram":
output["text/html"] = self._html_repr()
return output | Mime bundle used by jupyter kernels to display estimator | _repr_mimebundle_ | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/base.py | BSD-3-Clause |
def _write_label_html(
out,
params,
name,
name_details,
name_caption=None,
doc_link_label=None,
outer_class="sk-label-container",
inner_class="sk-label",
checked=False,
doc_link="",
is_fitted_css_class="",
is_fitted_icon="",
param_prefix="",
):
"""Write labeled ht... | Write labeled html with or without a dropdown with named details.
Parameters
----------
out : file-like object
The file to write the HTML representation to.
params: str
If estimator has `get_params` method, this is the HTML representation
of the estimator's parameters and their ... | _write_label_html | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/estimator.py | BSD-3-Clause |
def _get_visual_block(estimator):
"""Generate information about how to display an estimator."""
if hasattr(estimator, "_sk_visual_block_"):
try:
return estimator._sk_visual_block_()
except Exception:
return _VisualBlock(
"single",
estimator... | Generate information about how to display an estimator. | _get_visual_block | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/estimator.py | BSD-3-Clause |
def _write_estimator_html(
out,
estimator,
estimator_label,
estimator_label_details,
is_fitted_css_class,
is_fitted_icon="",
first_call=False,
param_prefix="",
):
"""Write estimator to html in serial, parallel, or by itself (single).
For multiple estimators, this function is cal... | Write estimator to html in serial, parallel, or by itself (single).
For multiple estimators, this function is called recursively.
Parameters
----------
out : file-like object
The file to write the HTML representation to.
estimator : estimator object
The estimator to visualize.
... | _write_estimator_html | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/estimator.py | BSD-3-Clause |
def estimator_html_repr(estimator):
"""Build a HTML representation of an estimator.
Read more in the :ref:`User Guide <visualizing_composite_estimators>`.
Parameters
----------
estimator : estimator object
The estimator to visualize.
Returns
-------
html: str
HTML repr... | Build a HTML representation of an estimator.
Read more in the :ref:`User Guide <visualizing_composite_estimators>`.
Parameters
----------
estimator : estimator object
The estimator to visualize.
Returns
-------
html: str
HTML representation of estimator.
Examples
... | estimator_html_repr | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/estimator.py | BSD-3-Clause |
def _read_params(name, value, non_default_params):
"""Categorizes parameters as 'default' or 'user-set' and formats their values.
Escapes or truncates parameter values for display safety and readability.
"""
r = reprlib.Repr()
r.maxlist = 2 # Show only first 2 items of lists
r.maxtuple = 1 # S... | Categorizes parameters as 'default' or 'user-set' and formats their values.
Escapes or truncates parameter values for display safety and readability.
| _read_params | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/params.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/params.py | BSD-3-Clause |
def _params_html_repr(params):
"""Generate HTML representation of estimator parameters.
Creates an HTML table with parameter names and values, wrapped in a
collapsible details element. Parameters are styled differently based
on whether they are default or user-set values.
"""
HTML_TEMPLATE = ""... | Generate HTML representation of estimator parameters.
Creates an HTML table with parameter names and values, wrapped in a
collapsible details element. Parameters are styled differently based
on whether they are default or user-set values.
| _params_html_repr | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/params.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/params.py | BSD-3-Clause |
def test_fallback_exists():
"""Check that repr fallback is in the HTML."""
pca = PCA(n_components=10)
html_output = estimator_html_repr(pca)
assert (
f'<div class="sk-text-repr-fallback"><pre>{html.escape(str(pca))}'
in html_output
) | Check that repr fallback is in the HTML. | test_fallback_exists | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_show_arrow_pipeline():
"""Show arrow in pipeline for top level in pipeline"""
pipe = Pipeline([("scale", StandardScaler()), ("log_Reg", LogisticRegression())])
html_output = estimator_html_repr(pipe)
assert (
'class="sk-toggleable__label sk-toggleable__label-arrow">'
"<div><di... | Show arrow in pipeline for top level in pipeline | test_show_arrow_pipeline | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_invalid_parameters_in_stacking():
"""Invalidate stacking configuration uses default repr.
Non-regression test for #24009.
"""
stacker = StackingClassifier(estimators=[])
html_output = estimator_html_repr(stacker)
assert html.escape(str(stacker)) in html_output | Invalidate stacking configuration uses default repr.
Non-regression test for #24009.
| test_invalid_parameters_in_stacking | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_estimator_get_params_return_cls():
"""Check HTML repr works where a value in get_params is a class."""
class MyEstimator:
def get_params(self, deep=False):
return {"inner_cls": LogisticRegression}
est = MyEstimator()
assert "MyEstimator" in estimator_html_repr(est) | Check HTML repr works where a value in get_params is a class. | test_estimator_get_params_return_cls | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_estimator_html_repr_unfitted_vs_fitted():
"""Check that we have the information that the estimator is fitted or not in the
HTML representation.
"""
class MyEstimator(BaseEstimator):
def fit(self, X, y):
self.fitted_ = True
return self
X, y = load_iris(retur... | Check that we have the information that the estimator is fitted or not in the
HTML representation.
| test_estimator_html_repr_unfitted_vs_fitted | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_estimator_html_repr_fitted_icon(estimator):
"""Check that we are showing the fitted status icon only once."""
pattern = '<span class="sk-estimator-doc-link ">i<span>Not fitted</span></span>'
assert estimator_html_repr(estimator).count(pattern) == 1
X, y = load_iris(return_X_y=True)
estimato... | Check that we are showing the fitted status icon only once. | test_estimator_html_repr_fitted_icon | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_html_documentation_link_mixin_sklearn(mock_version):
"""Check the behaviour of the `_HTMLDocumentationLinkMixin` class for scikit-learn
default.
"""
# mock the `__version__` where the mixin is located
with patch("sklearn.utils._repr_html.base.__version__", mock_version):
mixin = _H... | Check the behaviour of the `_HTMLDocumentationLinkMixin` class for scikit-learn
default.
| test_html_documentation_link_mixin_sklearn | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_html_documentation_link_mixin_get_doc_link_instance(
module_path, expected_module
):
"""Check the behaviour of the `_get_doc_link` with various parameter."""
class FooBar(_HTMLDocumentationLinkMixin):
pass
FooBar.__module__ = module_path
est = FooBar()
# if we set `_doc_link`,... | Check the behaviour of the `_get_doc_link` with various parameter. | test_html_documentation_link_mixin_get_doc_link_instance | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_html_documentation_link_mixin_get_doc_link_class(module_path, expected_module):
"""Check the behaviour of the `_get_doc_link` when `_doc_link_module` and
`_doc_link_template` are defined at the class level and not at the instance
level."""
class FooBar(_HTMLDocumentationLinkMixin):
_do... | Check the behaviour of the `_get_doc_link` when `_doc_link_module` and
`_doc_link_template` are defined at the class level and not at the instance
level. | test_html_documentation_link_mixin_get_doc_link_class | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def set_non_utf8_locale():
"""Pytest fixture to set non utf-8 locale during the test.
The locale is set to the original one after the test has run.
"""
try:
locale.setlocale(locale.LC_CTYPE, "C")
except locale.Error:
pytest.skip("'C' locale is not available on this OS")
yield
... | Pytest fixture to set non utf-8 locale during the test.
The locale is set to the original one after the test has run.
| set_non_utf8_locale | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_estimator_html_repr_table():
"""Check that we add the table of parameters in the HTML representation."""
est = LogisticRegression(C=10.0, fit_intercept=False)
assert "parameters-table" in estimator_html_repr(est) | Check that we add the table of parameters in the HTML representation. | test_estimator_html_repr_table | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_estimator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_estimator.py | BSD-3-Clause |
def test_params_dict_content():
"""Check the behavior of the ParamsDict class."""
params = ParamsDict({"a": 1, "b": 2})
assert params["a"] == 1
assert params["b"] == 2
assert params.non_default == ()
params = ParamsDict({"a": 1, "b": 2}, non_default=("a",))
assert params["a"] == 1
asser... | Check the behavior of the ParamsDict class. | test_params_dict_content | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_params.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_params.py | BSD-3-Clause |
def test_read_params():
"""Check the behavior of the `_read_params` function."""
out = _read_params("a", 1, tuple())
assert out["param_type"] == "default"
assert out["param_name"] == "a"
assert out["param_value"] == "1"
# check non-default parameters
out = _read_params("a", 1, ("a",))
a... | Check the behavior of the `_read_params` function. | test_read_params | python | scikit-learn/scikit-learn | sklearn/utils/_repr_html/tests/test_params.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_repr_html/tests/test_params.py | BSD-3-Clause |
def _construct_instances(Estimator):
"""Construct Estimator instances if possible.
If parameter sets in INIT_PARAMS are provided, use them. If there are a list
of parameter sets, return one instance for each set.
"""
if Estimator in SKIPPED_ESTIMATORS:
msg = f"Can't instantiate estimator {E... | Construct Estimator instances if possible.
If parameter sets in INIT_PARAMS are provided, use them. If there are a list
of parameter sets, return one instance for each set.
| _construct_instances | python | scikit-learn/scikit-learn | sklearn/utils/_test_common/instance_generator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_test_common/instance_generator.py | BSD-3-Clause |
def _get_check_estimator_ids(obj):
"""Create pytest ids for checks.
When `obj` is an estimator, this returns the pprint version of the
estimator (with `print_changed_only=True`). When `obj` is a function, the
name of the function is returned with its keyword arguments.
`_get_check_estimator_ids` i... | Create pytest ids for checks.
When `obj` is an estimator, this returns the pprint version of the
estimator (with `print_changed_only=True`). When `obj` is a function, the
name of the function is returned with its keyword arguments.
`_get_check_estimator_ids` is designed to be used as the `id` in
`... | _get_check_estimator_ids | python | scikit-learn/scikit-learn | sklearn/utils/_test_common/instance_generator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_test_common/instance_generator.py | BSD-3-Clause |
def _yield_instances_for_check(check, estimator_orig):
"""Yield instances for a check.
For most estimators, this is a no-op.
For estimators which have an entry in PER_ESTIMATOR_CHECK_PARAMS, this will yield
an estimator for each parameter set in PER_ESTIMATOR_CHECK_PARAMS[estimator].
"""
# TOD... | Yield instances for a check.
For most estimators, this is a no-op.
For estimators which have an entry in PER_ESTIMATOR_CHECK_PARAMS, this will yield
an estimator for each parameter set in PER_ESTIMATOR_CHECK_PARAMS[estimator].
| _yield_instances_for_check | python | scikit-learn/scikit-learn | sklearn/utils/_test_common/instance_generator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_test_common/instance_generator.py | BSD-3-Clause |
def _get_expected_failed_checks(estimator):
"""Get the expected failed checks for all estimators in scikit-learn."""
failed_checks = PER_ESTIMATOR_XFAIL_CHECKS.get(type(estimator), {})
tags = get_tags(estimator)
# all xfail marks that depend on the instance, come here. As of now, we have only
# th... | Get the expected failed checks for all estimators in scikit-learn. | _get_expected_failed_checks | python | scikit-learn/scikit-learn | sklearn/utils/_test_common/instance_generator.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_test_common/instance_generator.py | BSD-3-Clause |
def process_tempita(fromfile, outfile=None):
"""Process tempita templated file and write out the result.
The template file is expected to end in `.c.tp` or `.pyx.tp`:
E.g. processing `template.c.in` generates `template.c`.
"""
with open(fromfile, "r", encoding="utf-8") as f:
template_conte... | Process tempita templated file and write out the result.
The template file is expected to end in `.c.tp` or `.pyx.tp`:
E.g. processing `template.c.in` generates `template.c`.
| process_tempita | python | scikit-learn/scikit-learn | sklearn/_build_utils/tempita.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_build_utils/tempita.py | BSD-3-Clause |
def includes(self, x):
"""Test whether all values of x are in interval range.
Parameters
----------
x : ndarray
Array whose elements are tested to be in interval range.
Returns
-------
result : bool
"""
if self.low_inclusive:
... | Test whether all values of x are in interval range.
Parameters
----------
x : ndarray
Array whose elements are tested to be in interval range.
Returns
-------
result : bool
| includes | python | scikit-learn/scikit-learn | sklearn/_loss/link.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/link.py | BSD-3-Clause |
def _inclusive_low_high(interval, dtype=np.float64):
"""Generate values low and high to be within the interval range.
This is used in tests only.
Returns
-------
low, high : tuple
The returned values low and high lie within the interval.
"""
eps = 10 * np.finfo(dtype).eps
if in... | Generate values low and high to be within the interval range.
This is used in tests only.
Returns
-------
low, high : tuple
The returned values low and high lie within the interval.
| _inclusive_low_high | python | scikit-learn/scikit-learn | sklearn/_loss/link.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/link.py | BSD-3-Clause |
def link(self, y_pred, out=None):
"""Compute the link function g(y_pred).
The link function maps (predicted) target values to raw predictions,
i.e. `g(y_pred) = raw_prediction`.
Parameters
----------
y_pred : array
Predicted target values.
out : arra... | Compute the link function g(y_pred).
The link function maps (predicted) target values to raw predictions,
i.e. `g(y_pred) = raw_prediction`.
Parameters
----------
y_pred : array
Predicted target values.
out : array
A location into which the resul... | link | python | scikit-learn/scikit-learn | sklearn/_loss/link.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/link.py | BSD-3-Clause |
def inverse(self, raw_prediction, out=None):
"""Compute the inverse link function h(raw_prediction).
The inverse link function maps raw predictions to predicted target
values, i.e. `h(raw_prediction) = y_pred`.
Parameters
----------
raw_prediction : array
Ra... | Compute the inverse link function h(raw_prediction).
The inverse link function maps raw predictions to predicted target
values, i.e. `h(raw_prediction) = y_pred`.
Parameters
----------
raw_prediction : array
Raw prediction values (in link space).
out : array... | inverse | python | scikit-learn/scikit-learn | sklearn/_loss/link.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/link.py | BSD-3-Clause |
def loss(
self,
y_true,
raw_prediction,
sample_weight=None,
loss_out=None,
n_threads=1,
):
"""Compute the pointwise loss value for each input.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)
Observed... | Compute the pointwise loss value for each input.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)
Observed, true target values.
raw_prediction : C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes)
R... | loss | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def loss_gradient(
self,
y_true,
raw_prediction,
sample_weight=None,
loss_out=None,
gradient_out=None,
n_threads=1,
):
"""Compute loss and gradient w.r.t. raw_prediction for each input.
Parameters
----------
y_true : C-contiguo... | Compute loss and gradient w.r.t. raw_prediction for each input.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)
Observed, true target values.
raw_prediction : C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes... | loss_gradient | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def gradient(
self,
y_true,
raw_prediction,
sample_weight=None,
gradient_out=None,
n_threads=1,
):
"""Compute gradient of loss w.r.t raw_prediction for each input.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)... | Compute gradient of loss w.r.t raw_prediction for each input.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)
Observed, true target values.
raw_prediction : C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes)
... | gradient | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def gradient_hessian(
self,
y_true,
raw_prediction,
sample_weight=None,
gradient_out=None,
hessian_out=None,
n_threads=1,
):
"""Compute gradient and hessian of loss w.r.t raw_prediction.
Parameters
----------
y_true : C-contigu... | Compute gradient and hessian of loss w.r.t raw_prediction.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)
Observed, true target values.
raw_prediction : C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes)
... | gradient_hessian | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def __call__(self, y_true, raw_prediction, sample_weight=None, n_threads=1):
"""Compute the weighted average loss.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)
Observed, true target values.
raw_prediction : C-contiguous array of shape (n_sa... | Compute the weighted average loss.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)
Observed, true target values.
raw_prediction : C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes)
Raw prediction ... | __call__ | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def fit_intercept_only(self, y_true, sample_weight=None):
"""Compute raw_prediction of an intercept-only model.
This can be used as initial estimates of predictions, i.e. before the
first iteration in fit.
Parameters
----------
y_true : array-like of shape (n_samples,)
... | Compute raw_prediction of an intercept-only model.
This can be used as initial estimates of predictions, i.e. before the
first iteration in fit.
Parameters
----------
y_true : array-like of shape (n_samples,)
Observed, true target values.
sample_weight : Non... | fit_intercept_only | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def init_gradient_and_hessian(self, n_samples, dtype=np.float64, order="F"):
"""Initialize arrays for gradients and hessians.
Unless hessians are constant, arrays are initialized with undefined values.
Parameters
----------
n_samples : int
The number of samples, usu... | Initialize arrays for gradients and hessians.
Unless hessians are constant, arrays are initialized with undefined values.
Parameters
----------
n_samples : int
The number of samples, usually passed to `fit()`.
dtype : {np.float64, np.float32}, default=np.float64
... | init_gradient_and_hessian | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def fit_intercept_only(self, y_true, sample_weight=None):
"""Compute raw_prediction of an intercept-only model.
This is the weighted median of the target, i.e. over the samples
axis=0.
"""
if sample_weight is None:
return np.median(y_true, axis=0)
else:
... | Compute raw_prediction of an intercept-only model.
This is the weighted median of the target, i.e. over the samples
axis=0.
| fit_intercept_only | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def predict_proba(self, raw_prediction):
"""Predict probabilities.
Parameters
----------
raw_prediction : array of shape (n_samples,) or (n_samples, 1)
Raw prediction values (in link space).
Returns
-------
proba : array of shape (n_samples, 2)
... | Predict probabilities.
Parameters
----------
raw_prediction : array of shape (n_samples,) or (n_samples, 1)
Raw prediction values (in link space).
Returns
-------
proba : array of shape (n_samples, 2)
Element-wise class probabilities.
| predict_proba | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def fit_intercept_only(self, y_true, sample_weight=None):
"""Compute raw_prediction of an intercept-only model.
This is the softmax of the weighted average of the target, i.e. over
the samples axis=0.
"""
out = np.zeros(self.n_classes, dtype=y_true.dtype)
eps = np.finfo(... | Compute raw_prediction of an intercept-only model.
This is the softmax of the weighted average of the target, i.e. over
the samples axis=0.
| fit_intercept_only | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def gradient_proba(
self,
y_true,
raw_prediction,
sample_weight=None,
gradient_out=None,
proba_out=None,
n_threads=1,
):
"""Compute gradient and class probabilities fow raw_prediction.
Parameters
----------
y_true : C-contiguou... | Compute gradient and class probabilities fow raw_prediction.
Parameters
----------
y_true : C-contiguous array of shape (n_samples,)
Observed, true target values.
raw_prediction : array of shape (n_samples, n_classes)
Raw prediction values (in link space).
... | gradient_proba | python | scikit-learn/scikit-learn | sklearn/_loss/loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/loss.py | BSD-3-Clause |
def test_interval_raises():
"""Test that interval with low > high raises ValueError."""
with pytest.raises(
ValueError, match="One must have low <= high; got low=1, high=0."
):
Interval(1, 0, False, False) | Test that interval with low > high raises ValueError. | test_interval_raises | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_link.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_link.py | BSD-3-Clause |
def random_y_true_raw_prediction(
loss, n_samples, y_bound=(-100, 100), raw_bound=(-5, 5), seed=42
):
"""Random generate y_true and raw_prediction in valid range."""
rng = np.random.RandomState(seed)
if loss.is_multiclass:
raw_prediction = np.empty((n_samples, loss.n_classes))
raw_predic... | Random generate y_true and raw_prediction in valid range. | random_y_true_raw_prediction | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def numerical_derivative(func, x, eps):
"""Helper function for numerical (first) derivatives."""
# For numerical derivatives, see
# https://en.wikipedia.org/wiki/Numerical_differentiation
# https://en.wikipedia.org/wiki/Finite_difference_coefficient
# We use central finite differences of accuracy 4.... | Helper function for numerical (first) derivatives. | numerical_derivative | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_loss_boundary(loss):
"""Test interval ranges of y_true and y_pred in losses."""
# make sure low and high are always within the interval, used for linspace
if loss.is_multiclass:
n_classes = 3 # default value
y_true = np.tile(np.linspace(0, n_classes - 1, num=n_classes), 3)
else... | Test interval ranges of y_true and y_pred in losses. | test_loss_boundary | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_loss_boundary_y_true(loss, y_true_success, y_true_fail):
"""Test boundaries of y_true for loss functions."""
for y in y_true_success:
assert loss.in_y_true_range(np.array([y]))
for y in y_true_fail:
assert not loss.in_y_true_range(np.array([y])) | Test boundaries of y_true for loss functions. | test_loss_boundary_y_true | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_loss_boundary_y_pred(loss, y_pred_success, y_pred_fail):
"""Test boundaries of y_pred for loss functions."""
for y in y_pred_success:
assert loss.in_y_pred_range(np.array([y]))
for y in y_pred_fail:
assert not loss.in_y_pred_range(np.array([y])) | Test boundaries of y_pred for loss functions. | test_loss_boundary_y_pred | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_loss_on_specific_values(
loss, y_true, raw_prediction, loss_true, gradient_true, hessian_true
):
"""Test losses, gradients and hessians at specific values."""
loss1 = loss(y_true=np.array([y_true]), raw_prediction=np.array([raw_prediction]))
grad1 = loss.gradient(
y_true=np.array([y_tru... | Test losses, gradients and hessians at specific values. | test_loss_on_specific_values | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_loss_dtype(
loss, readonly_memmap, dtype_in, dtype_out, sample_weight, out1, out2, n_threads
):
"""Test acceptance of dtypes, readonly and writeable arrays in loss functions.
Check that loss accepts if all input arrays are either all float32 or all
float64, and all output arrays are either all... | Test acceptance of dtypes, readonly and writeable arrays in loss functions.
Check that loss accepts if all input arrays are either all float32 or all
float64, and all output arrays are either all float32 or all float64.
Also check that input arrays can be readonly, e.g. memory mapped.
| test_loss_dtype | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_loss_same_as_C_functions(loss, sample_weight):
"""Test that Python and Cython functions return same results."""
y_true, raw_prediction = random_y_true_raw_prediction(
loss=loss,
n_samples=20,
y_bound=(-100, 100),
raw_bound=(-10, 10),
seed=42,
)
if sample_... | Test that Python and Cython functions return same results. | test_loss_same_as_C_functions | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_loss_gradients_are_the_same(loss, sample_weight, global_random_seed):
"""Test that loss and gradient are the same across different functions.
Also test that output arguments contain correct results.
"""
y_true, raw_prediction = random_y_true_raw_prediction(
loss=loss,
n_samples... | Test that loss and gradient are the same across different functions.
Also test that output arguments contain correct results.
| test_loss_gradients_are_the_same | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_sample_weight_multiplies(loss, sample_weight, global_random_seed):
"""Test sample weights in loss, gradients and hessians.
Make sure that passing sample weights to loss, gradient and hessian
computation methods is equivalent to multiplying by the weights.
"""
n_samples = 100
y_true, ra... | Test sample weights in loss, gradients and hessians.
Make sure that passing sample weights to loss, gradient and hessian
computation methods is equivalent to multiplying by the weights.
| test_sample_weight_multiplies | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_graceful_squeezing(loss):
"""Test that reshaped raw_prediction gives same results."""
y_true, raw_prediction = random_y_true_raw_prediction(
loss=loss,
n_samples=20,
y_bound=(-100, 100),
raw_bound=(-10, 10),
seed=42,
)
if raw_prediction.ndim == 1:
... | Test that reshaped raw_prediction gives same results. | test_graceful_squeezing | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_loss_of_perfect_prediction(loss, sample_weight):
"""Test value of perfect predictions.
Loss of y_pred = y_true plus constant_to_optimal_zero should sums up to
zero.
"""
if not loss.is_multiclass:
# Use small values such that exp(value) is not nan.
raw_prediction = np.array(... | Test value of perfect predictions.
Loss of y_pred = y_true plus constant_to_optimal_zero should sums up to
zero.
| test_loss_of_perfect_prediction | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def test_derivatives(loss, x0, y_true):
"""Test that gradients are zero at the minimum of the loss.
We check this on a single value/sample using Halley's method with the
first and second order derivatives computed by the Loss instance.
Note that methods of Loss instances operate on arrays while the new... | Test that gradients are zero at the minimum of the loss.
We check this on a single value/sample using Halley's method with the
first and second order derivatives computed by the Loss instance.
Note that methods of Loss instances operate on arrays while the newton
root finder expects a scalar or a one-e... | test_derivatives | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
def func(x: np.ndarray) -> np.ndarray:
"""Compute loss plus constant term.
The constant term is such that the minimum function value is zero,
which is required by the Newton method.
"""
return loss.loss(
y_true=y_true, raw_prediction=x
) + loss.constant_to_op... | Compute loss plus constant term.
The constant term is such that the minimum function value is zero,
which is required by the Newton method.
| func | python | scikit-learn/scikit-learn | sklearn/_loss/tests/test_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_loss/tests/test_loss.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.