code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_get_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_get_feature_names_dataframe_protocol(constructor_name, minversion):
"""Uses the dataframe exchange protocol to get feature names."""
data = [[1, 4, 2], [3, 3, 6]]
columns = ["col_0", "col_1", "col_2"]
df = _convert_container(
data, constructor_name, columns_name=columns, minversion=minv... | Uses the dataframe exchange protocol to get feature names. | test_get_feature_names_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_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 test_html_documentation_link_mixin_get_doc_link_out_of_library():
"""Check the behaviour of the `_get_doc_link` with various parameter."""
mixin = _HTMLDocumentationLinkMixin()
# if the `_doc_link_module` does not refer to the root module of the estimator
# (here the mixin), then we should return a... | Check the behaviour of the `_get_doc_link` with various parameter. | test_html_documentation_link_mixin_get_doc_link_out_of_library | 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 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.percentile(y_true, 100 * self.closs.quanti... | 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 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.
"""
# See formula before algo 4 in Friedman (2001), but we apply it to y_true,
# not t... | 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 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 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_gradients_hessians_numerically(loss, sample_weight, global_random_seed):
"""Test gradients and hessians with numerical derivatives.
Gradient should equal the numerical derivatives of the loss function.
Hessians should equal the numerical derivatives of gradients.
"""
n_samples = 20
y_t... | Test gradients and hessians with numerical derivatives.
Gradient should equal the numerical derivatives of the loss function.
Hessians should equal the numerical derivatives of gradients.
| test_gradients_hessians_numerically | 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 |
def test_loss_intercept_only(loss, sample_weight):
"""Test that fit_intercept_only returns the argmin of the loss.
Also test that the gradient is zero at the minimum.
"""
n_samples = 50
if not loss.is_multiclass:
y_true = loss.link.inverse(np.linspace(-4, 4, num=n_samples))
else:
... | Test that fit_intercept_only returns the argmin of the loss.
Also test that the gradient is zero at the minimum.
| test_loss_intercept_only | 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_specific_fit_intercept_only(loss, func, random_dist, global_random_seed):
"""Test that fit_intercept_only returns the correct functional.
We test the functional for specific, meaningful distributions, e.g.
squared error estimates the expectation of a probability distribution.
"""
rng = np.... | Test that fit_intercept_only returns the correct functional.
We test the functional for specific, meaningful distributions, e.g.
squared error estimates the expectation of a probability distribution.
| test_specific_fit_intercept_only | 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_multinomial_loss_fit_intercept_only():
"""Test that fit_intercept_only returns the mean functional for CCE."""
rng = np.random.RandomState(0)
n_classes = 4
loss = HalfMultinomialLoss(n_classes=n_classes)
# Same logic as test_specific_fit_intercept_only. Here inverse link
# function = so... | Test that fit_intercept_only returns the mean functional for CCE. | test_multinomial_loss_fit_intercept_only | 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_multinomial_cy_gradient(global_random_seed):
"""Test that Multinomial cy_gradient gives the same result as gradient.
CyHalfMultinomialLoss does not inherit from CyLossFunction and has a different API.
As a consequence, the functions like `loss` and `gradient` do not rely on `cy_loss`
and `cy_g... | Test that Multinomial cy_gradient gives the same result as gradient.
CyHalfMultinomialLoss does not inherit from CyLossFunction and has a different API.
As a consequence, the functions like `loss` and `gradient` do not rely on `cy_loss`
and `cy_gradient`.
| test_multinomial_cy_gradient | 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_binomial_and_multinomial_loss(global_random_seed):
"""Test that multinomial loss with n_classes = 2 is the same as binomial loss."""
rng = np.random.RandomState(global_random_seed)
n_samples = 20
binom = HalfBinomialLoss()
multinom = HalfMultinomialLoss(n_classes=2)
y_train = rng.randin... | Test that multinomial loss with n_classes = 2 is the same as binomial loss. | test_binomial_and_multinomial_loss | 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_binomial_vs_alternative_formulation(y_true, y_pred, global_dtype):
"""Test that both formulations of the binomial deviance agree.
Often, the binomial deviance or log loss is written in terms of a variable
z in {-1, +1}, but we use y in {0, 1}, hence z = 2 * y - 1.
ESL II Eq. (10.18):
... | Test that both formulations of the binomial deviance agree.
Often, the binomial deviance or log loss is written in terms of a variable
z in {-1, +1}, but we use y in {0, 1}, hence z = 2 * y - 1.
ESL II Eq. (10.18):
-loglike(z, f) = log(1 + exp(-2 * z * f))
Note:
- ESL 2*f = raw_predic... | test_binomial_vs_alternative_formulation | 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_predict_proba(loss, global_random_seed):
"""Test that predict_proba and gradient_proba work as expected."""
n_samples = 20
y_true, raw_prediction = random_y_true_raw_prediction(
loss=loss,
n_samples=n_samples,
y_bound=(-100, 100),
raw_bound=(-5, 5),
seed=glob... | Test that predict_proba and gradient_proba work as expected. | test_predict_proba | 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_init_gradient_and_hessians(loss, sample_weight, dtype, order):
"""Test that init_gradient_and_hessian works as expected.
passing sample_weight to a loss correctly influences the constant_hessian
attribute, and consequently the shape of the hessian array.
"""
n_samples = 5
if sample_wei... | Test that init_gradient_and_hessian works as expected.
passing sample_weight to a loss correctly influences the constant_hessian
attribute, and consequently the shape of the hessian array.
| test_init_gradient_and_hessians | 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_init_gradient_and_hessian_raises(loss, params, err_msg):
"""Test that init_gradient_and_hessian raises errors for invalid input."""
loss = loss()
with pytest.raises((ValueError, TypeError), match=err_msg):
gradient, hessian = loss.init_gradient_and_hessian(n_samples=5, **params) | Test that init_gradient_and_hessian raises errors for invalid input. | test_init_gradient_and_hessian_raises | 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_pickle(loss):
"""Test that losses can be pickled."""
n_samples = 20
y_true, raw_prediction = random_y_true_raw_prediction(
loss=loss,
n_samples=n_samples,
y_bound=(-100, 100),
raw_bound=(-5, 5),
seed=42,
)
pickled_loss = pickle.dumps(loss)
un... | Test that losses can be pickled. | test_loss_pickle | 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_tweedie_log_identity_consistency(p):
"""Test for identical losses when only the link function is different."""
half_tweedie_log = HalfTweedieLoss(power=p)
half_tweedie_identity = HalfTweedieLossIdentity(power=p)
n_samples = 10
y_true, raw_prediction = random_y_true_raw_prediction(
l... | Test for identical losses when only the link function is different. | test_tweedie_log_identity_consistency | 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 _flatten_and_tokenize_metadata(encoder, item):
"""
Turn the article into tokens
:param item: Contains things that need to be tokenized
fields are ['domain', 'date', 'authors', 'title', 'article', 'summary']
:return: dict
"""
metadata = []
for key in ['domain', 'date', 'authors', 'ti... |
Turn the article into tokens
:param item: Contains things that need to be tokenized
fields are ['domain', 'date', 'authors', 'title', 'article', 'summary']
:return: dict
| _flatten_and_tokenize_metadata | python | rowanz/grover | discrimination/run_discrimination.py | https://github.com/rowanz/grover/blob/master/discrimination/run_discrimination.py | Apache-2.0 |
def input_fn_builder(input_files,
seq_length,
is_training,
num_cpu_threads=4,
evaluate_for_fixed_number_of_steps=True):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
"""The actu... | Creates an `input_fn` closure to be passed to TPUEstimator. | input_fn_builder | python | rowanz/grover | lm/dataloader.py | https://github.com/rowanz/grover/blob/master/lm/dataloader.py | Apache-2.0 |
def classification_convert_examples_to_features(
examples, max_seq_length, batch_size, encoder, output_file, labels, pad_extra_examples=False,
chop_from_front_if_needed=True):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
label... | Convert a set of `InputExample`s to a TFRecord file. | classification_convert_examples_to_features | python | rowanz/grover | lm/dataloader.py | https://github.com/rowanz/grover/blob/master/lm/dataloader.py | Apache-2.0 |
def classification_input_fn_builder(input_file, seq_length, is_training,
drop_remainder,
buffer_size=100):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_... | Creates an `input_fn` closure to be passed to TPUEstimator. | classification_input_fn_builder | python | rowanz/grover | lm/dataloader.py | https://github.com/rowanz/grover/blob/master/lm/dataloader.py | Apache-2.0 |
def __init__(self,
vocab_size,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropou... | Constructs NewsConfig.
Args:
vocab_size: Vocabulary size of `inputs_ids` in `GroverModel`.
hidden_size: Size of the layers
num_hidden_layers: Number of hidden layers in the Transformer encoder.
num_attention_heads: Number of attention heads for each attention layer in
... | __init__ | python | rowanz/grover | lm/modeling.py | https://github.com/rowanz/grover/blob/master/lm/modeling.py | Apache-2.0 |
def from_dict(cls, json_object):
"""Constructs a `NewsConfig` from a Python dictionary of parameters."""
config = GroverConfig(vocab_size=None)
for (key, value) in six.iteritems(json_object):
config.__dict__[key] = value
return config | Constructs a `NewsConfig` from a Python dictionary of parameters. | from_dict | python | rowanz/grover | lm/modeling.py | https://github.com/rowanz/grover/blob/master/lm/modeling.py | Apache-2.0 |
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.