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, columns)
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=minversion ) feature_names = _get_feature_names(df) assert_array_equal(feature_names, columns)
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() assert not _is_polars_df(not_a_polars_df)
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 have string names, " f"but your input has {dtypes} as feature name / column name types. " "If you want feature names to be stored and validated, you must convert " "them all to strings, by using X.columns = X.columns.astype(str) for " "example. Otherwise you can remove feature / column names from your input " "data, or convert them all to a non-string data type." ) with pytest.raises(TypeError, match=msg): names = _get_feature_names(X)
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() assert_array_equal(names, ["a", "b", "c"]) with pytest.raises(ValueError, match="input_features is not equal to"): est.get_feature_names_out(["x1", "x2", "x3"])
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(RandomForestRegressor(), "unknown_method")
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, match=err_msg): _check_response_method(EstimatorWithFit(), response_method)
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_function", "predict"] err_msg = ( "_MockEstimatorOnOffPrediction has none of the following attributes: " f"{', '.join(response_method)}." ) with pytest.raises(AttributeError, match=err_msg): _check_response_method(my_estimator, response_method)(X) # check that we don't get issue when one of the method is defined response_method = ["decision_function", "predict_proba"] method_name_predicting = _check_response_method(my_estimator, response_method)(X) assert method_name_predicting == "predict_proba" # check the order of the methods returned method_implemented = ["predict_proba", "predict"] my_estimator = _MockEstimatorOnOffPrediction(method_implemented) response_method = ["decision_function", "predict", "predict_proba"] method_name_predicting = _check_response_method(my_estimator, response_method)(X) assert method_name_predicting == "predict"
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, dtype=None, ensure_2d=False, allow_nd=False, ensure_all_finite=False, ) assert np.issubdtype(result.dtype.kind, np.floating) assert_allclose(result, input_values)
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(ValueError, match="Input contains NaN."): check_array(X_nan) X_inf = xp.asarray([[xp.inf, 1, 0], [0, xp.inf, 3]], dtype=xp.float32) with config_context(array_api_dispatch=True): with pytest.raises(ValueError, match="infinity or a value too large"): check_array(X_inf)
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_dtype), "c": pd.Series([9, 8, 7, 6], dtype="int64"), } ) if include_object: X_regular["b"] = pd.Series(["a", "b", "c", "d"], dtype="object") X_extension = X_regular.assign(a=X_regular["a"].astype(extension_dtype)) X_regular_checked = check_array(X_regular, dtype=None) X_extension_checked = check_array(X_extension, dtype=None) assert_array_equal(X_regular_checked, X_extension_checked)
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"): # DIA matrix X.offsets = X.offsets.astype(np.int32) elif hasattr(X, "row") and hasattr(X, "col"): # COO matrix X.row = X.row.astype(np.int32) elif hasattr(X, "indices") and hasattr(X, "indptr"): # CSR or CSC matrix X.indices = X.indices.astype(np.int32) X.indptr = X.indptr.astype(np.int32) X_checked = check_array(X, accept_sparse=output_format) if output_format == "coo": assert X_checked.row.dtype == np.int32 assert X_checked.col.dtype == np.int32 else: # output_format in ["csr", "csc"] assert X_checked.indices.dtype == np.int32 assert X_checked.indptr.dtype == np.int32
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 assert np.may_share_memory(out, X) assert out.flags.writeable X.flags.writeable = False out = check_array(X, copy=False, force_writeable=True) # X is not writeable, a copy is made assert not np.may_share_memory(out, X) assert out.flags.writeable
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. """ X = np.random.uniform(size=(10, 10)) mmap = create_memmap_backed_data(X, mmap_mode="w+") out = check_array(mmap, copy=False, force_writeable=True) # mmap is already writeable, no copy is needed assert np.may_share_memory(out, mmap) assert out.flags.writeable mmap = create_memmap_backed_data(X, mmap_mode="r") out = check_array(mmap, copy=False, force_writeable=True) # mmap is read-only, a copy is made assert not np.may_share_memory(out, mmap) assert out.flags.writeable
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=False, force_writeable=True) # df is backed by a writeable array, no copy is needed assert np.may_share_memory(out, df) assert out.flags.writeable X.flags.writeable = False df = pd.DataFrame(X, copy=False) out = check_array(df, copy=False, force_writeable=True) # df is backed by a read-only array, a copy is made assert not np.may_share_memory(out, df) assert out.flags.writeable
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 np.dtype(dtype) assert np.asarray(weight_vector.aw).dtype is np.dtype(dtype)
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 The URL to the API documentation for this estimator. If the estimator does not belong to module `_doc_link_module`, the empty string (i.e. `""`) is returned. """ if self.__class__.__module__.split(".")[0] != self._doc_link_module: return "" if self._doc_link_url_param_generator is None: estimator_name = self.__class__.__name__ # Construct the estimator's module name, up to the first private submodule. # This works because in scikit-learn all public estimators are exposed at # that level, even if they actually live in a private sub-module. estimator_module = ".".join( itertools.takewhile( lambda part: not part.startswith("_"), self.__class__.__module__.split("."), ) ) return self._doc_link_template.format( estimator_module=estimator_module, estimator_name=estimator_name ) return self._doc_link_template.format(**self._doc_link_url_param_generator())
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 this estimator. If the estimator does not belong to module `_doc_link_module`, the empty string (i.e. `""`) is returned.
_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()["display"] != "diagram": raise AttributeError( "_repr_html_ is only defined when the " "'display' configuration option is set to " "'diagram'" ) return self._repr_html_inner
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 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 values. When the estimator does not have `get_params`, it is an empty string. name : str The label for the estimator. It corresponds either to the estimator class name for a simple estimator or in the case of a `Pipeline` and `ColumnTransformer`, it corresponds to the name of the step. name_details : str The details to show as content in the dropdown part of the toggleable label. It can contain information such as non-default parameters or column information for `ColumnTransformer`. name_caption : str, default=None The caption below the name. If `None`, no caption will be created. doc_link_label : str, default=None The label for the documentation link. If provided, the label would be "Documentation for {doc_link_label}". Otherwise it will look for `name`. outer_class : {"sk-label-container", "sk-item"}, default="sk-label-container" The CSS class for the outer container. inner_class : {"sk-label", "sk-estimator"}, default="sk-label" The CSS class for the inner container. checked : bool, default=False Whether the dropdown is folded or not. With a single estimator, we intend to unfold the content. doc_link : str, default="" The link to the documentation for the estimator. If an empty string, no link is added to the diagram. This can be generated for an estimator if it uses the `_HTMLDocumentationLinkMixin`. is_fitted_css_class : {"", "fitted"} The CSS class to indicate whether or not the estimator is fitted. The empty string means that the estimator is not fitted and "fitted" means that the estimator is fitted. is_fitted_icon : str, default="" The HTML representation to show the fitted information in the diagram. An empty string means that no information is shown. param_prefix : str, default="" The prefix to prepend to parameter names for nested estimators. """ out.write( f'<div class="{outer_class}"><div' f' class="{inner_class} {is_fitted_css_class} sk-toggleable">' ) name = html.escape(name) if name_details is not None: name_details = html.escape(str(name_details)) checked_str = "checked" if checked else "" est_id = _ESTIMATOR_ID_COUNTER.get_id() if doc_link: doc_label = "<span>Online documentation</span>" if doc_link_label is not None: doc_label = f"<span>Documentation for {doc_link_label}</span>" elif name is not None: doc_label = f"<span>Documentation for {name}</span>" doc_link = ( f'<a class="sk-estimator-doc-link {is_fitted_css_class}"' f' rel="noreferrer" target="_blank" href="{doc_link}">?{doc_label}</a>' ) name_caption_div = ( "" if name_caption is None else f'<div class="caption">{html.escape(name_caption)}</div>' ) name_caption_div = f"<div><div>{name}</div>{name_caption_div}</div>" links_div = ( f"<div>{doc_link}{is_fitted_icon}</div>" if doc_link or is_fitted_icon else "" ) label_html = ( f'<label for="{est_id}" class="sk-toggleable__label {is_fitted_css_class} ' f'sk-toggleable__label-arrow">{name_caption_div}{links_div}</label>' ) fmt_str = ( f'<input class="sk-toggleable__control sk-hidden--visually" id="{est_id}" ' f'type="checkbox" {checked_str}>{label_html}<div ' f'class="sk-toggleable__content {is_fitted_css_class}" ' f'data-param-prefix="{html.escape(param_prefix)}">' ) if params: fmt_str = "".join([fmt_str, f"{params}</div>"]) elif name_details and ("Pipeline" not in name): fmt_str = "".join([fmt_str, f"<pre>{name_details}</pre></div>"]) out.write(fmt_str) else: out.write(f"<label>{name}</label>") out.write("</div></div>") # outer_class inner_class
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 values. When the estimator does not have `get_params`, it is an empty string. name : str The label for the estimator. It corresponds either to the estimator class name for a simple estimator or in the case of a `Pipeline` and `ColumnTransformer`, it corresponds to the name of the step. name_details : str The details to show as content in the dropdown part of the toggleable label. It can contain information such as non-default parameters or column information for `ColumnTransformer`. name_caption : str, default=None The caption below the name. If `None`, no caption will be created. doc_link_label : str, default=None The label for the documentation link. If provided, the label would be "Documentation for {doc_link_label}". Otherwise it will look for `name`. outer_class : {"sk-label-container", "sk-item"}, default="sk-label-container" The CSS class for the outer container. inner_class : {"sk-label", "sk-estimator"}, default="sk-label" The CSS class for the inner container. checked : bool, default=False Whether the dropdown is folded or not. With a single estimator, we intend to unfold the content. doc_link : str, default="" The link to the documentation for the estimator. If an empty string, no link is added to the diagram. This can be generated for an estimator if it uses the `_HTMLDocumentationLinkMixin`. is_fitted_css_class : {"", "fitted"} The CSS class to indicate whether or not the estimator is fitted. The empty string means that the estimator is not fitted and "fitted" means that the estimator is fitted. is_fitted_icon : str, default="" The HTML representation to show the fitted information in the diagram. An empty string means that no information is shown. param_prefix : str, default="" The prefix to prepend to parameter names for nested estimators.
_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, names=estimator.__class__.__name__, name_details=str(estimator), ) if isinstance(estimator, str): return _VisualBlock( "single", estimator, names=estimator, name_details=estimator ) elif estimator is None: return _VisualBlock("single", estimator, names="None", name_details="None") # check if estimator looks like a meta estimator (wraps estimators) if hasattr(estimator, "get_params") and not isclass(estimator): estimators = [ (key, est) for key, est in estimator.get_params(deep=False).items() if hasattr(est, "get_params") and hasattr(est, "fit") and not isclass(est) ] if estimators: return _VisualBlock( "parallel", [est for _, est in estimators], names=[f"{key}: {est.__class__.__name__}" for key, est in estimators], name_details=[str(est) for _, est in estimators], ) return _VisualBlock( "single", estimator, names=estimator.__class__.__name__, name_details=str(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 called recursively. Parameters ---------- out : file-like object The file to write the HTML representation to. estimator : estimator object The estimator to visualize. estimator_label : str The label for the estimator. It corresponds either to the estimator class name for simple estimator or in the case of `Pipeline` and `ColumnTransformer`, it corresponds to the name of the step. estimator_label_details : str The details to show as content in the dropdown part of the toggleable label. It can contain information as non-default parameters or column information for `ColumnTransformer`. is_fitted_css_class : {"", "fitted"} The CSS class to indicate whether or not the estimator is fitted or not. The empty string means that the estimator is not fitted and "fitted" means that the estimator is fitted. is_fitted_icon : str, default="" The HTML representation to show the fitted information in the diagram. An empty string means that no information is shown. If the estimator to be shown is not the first estimator (i.e. `first_call=False`), `is_fitted_icon` is always an empty string. first_call : bool, default=False Whether this is the first time this function is called. param_prefix : str, default="" The prefix to prepend to parameter names for nested estimators. For example, in a pipeline this might be "pipeline__stepname__". """ if first_call: est_block = _get_visual_block(estimator) else: is_fitted_icon = "" with config_context(print_changed_only=True): est_block = _get_visual_block(estimator) # `estimator` can also be an instance of `_VisualBlock` if hasattr(estimator, "_get_doc_link"): doc_link = estimator._get_doc_link() else: doc_link = "" if est_block.kind in ("serial", "parallel"): dashed_wrapped = first_call or est_block.dash_wrapped dash_cls = " sk-dashed-wrapped" if dashed_wrapped else "" out.write(f'<div class="sk-item{dash_cls}">') if estimator_label: if hasattr(estimator, "get_params") and hasattr( estimator, "_get_params_html" ): params = estimator._get_params_html(deep=False)._repr_html_inner() else: params = "" _write_label_html( out, params, estimator_label, estimator_label_details, doc_link=doc_link, is_fitted_css_class=is_fitted_css_class, is_fitted_icon=is_fitted_icon, param_prefix=param_prefix, ) kind = est_block.kind out.write(f'<div class="sk-{kind}">') est_infos = zip(est_block.estimators, est_block.names, est_block.name_details) for est, name, name_details in est_infos: # Build the parameter prefix for nested estimators if param_prefix and hasattr(name, "split"): # If we already have a prefix, append the new component new_prefix = f"{param_prefix}{name.split(':')[0]}__" elif hasattr(name, "split"): # If this is the first level, start the prefix new_prefix = f"{name.split(':')[0]}__" if name else "" else: new_prefix = param_prefix if kind == "serial": _write_estimator_html( out, est, name, name_details, is_fitted_css_class=is_fitted_css_class, param_prefix=new_prefix, ) else: # parallel out.write('<div class="sk-parallel-item">') # wrap element in a serial visualblock serial_block = _VisualBlock("serial", [est], dash_wrapped=False) _write_estimator_html( out, serial_block, name, name_details, is_fitted_css_class=is_fitted_css_class, param_prefix=new_prefix, ) out.write("</div>") # sk-parallel-item out.write("</div></div>") elif est_block.kind == "single": if hasattr(estimator, "_get_params_html"): params = estimator._get_params_html()._repr_html_inner() else: params = "" _write_label_html( out, params, est_block.names, est_block.name_details, est_block.name_caption, est_block.doc_link_label, outer_class="sk-item", inner_class="sk-estimator", checked=first_call, doc_link=doc_link, is_fitted_css_class=is_fitted_css_class, is_fitted_icon=is_fitted_icon, param_prefix=param_prefix, )
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. estimator_label : str The label for the estimator. It corresponds either to the estimator class name for simple estimator or in the case of `Pipeline` and `ColumnTransformer`, it corresponds to the name of the step. estimator_label_details : str The details to show as content in the dropdown part of the toggleable label. It can contain information as non-default parameters or column information for `ColumnTransformer`. is_fitted_css_class : {"", "fitted"} The CSS class to indicate whether or not the estimator is fitted or not. The empty string means that the estimator is not fitted and "fitted" means that the estimator is fitted. is_fitted_icon : str, default="" The HTML representation to show the fitted information in the diagram. An empty string means that no information is shown. If the estimator to be shown is not the first estimator (i.e. `first_call=False`), `is_fitted_icon` is always an empty string. first_call : bool, default=False Whether this is the first time this function is called. param_prefix : str, default="" The prefix to prepend to parameter names for nested estimators. For example, in a pipeline this might be "pipeline__stepname__".
_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 representation of estimator. Examples -------- >>> from sklearn.utils._repr_html.estimator import estimator_html_repr >>> from sklearn.linear_model import LogisticRegression >>> estimator_html_repr(LogisticRegression()) '<style>#sk-container-id...' """ from sklearn.exceptions import NotFittedError from sklearn.utils.validation import check_is_fitted if not hasattr(estimator, "fit"): status_label = "<span>Not fitted</span>" is_fitted_css_class = "" else: try: check_is_fitted(estimator) status_label = "<span>Fitted</span>" is_fitted_css_class = "fitted" except NotFittedError: status_label = "<span>Not fitted</span>" is_fitted_css_class = "" is_fitted_icon = ( f'<span class="sk-estimator-doc-link {is_fitted_css_class}">' f"i{status_label}</span>" ) with closing(StringIO()) as out: container_id = _CONTAINER_ID_COUNTER.get_id() style_template = Template(_CSS_STYLE) style_with_id = style_template.substitute(id=container_id) estimator_str = str(estimator) # The fallback message is shown by default and loading the CSS sets # div.sk-text-repr-fallback to display: none to hide the fallback message. # # If the notebook is trusted, the CSS is loaded which hides the fallback # message. If the notebook is not trusted, then the CSS is not loaded and the # fallback message is shown by default. # # The reverse logic applies to HTML repr div.sk-container. # div.sk-container is hidden by default and the loading the CSS displays it. fallback_msg = ( "In a Jupyter environment, please rerun this cell to show the HTML" " representation or trust the notebook. <br />On GitHub, the" " HTML representation is unable to render, please try loading this page" " with nbviewer.org." ) html_template = ( f"<style>{style_with_id}</style>" f"<body>" f'<div id="{container_id}" class="sk-top-container">' '<div class="sk-text-repr-fallback">' f"<pre>{html.escape(estimator_str)}</pre><b>{fallback_msg}</b>" "</div>" '<div class="sk-container" hidden>' ) out.write(html_template) _write_estimator_html( out, estimator, estimator.__class__.__name__, estimator_str, first_call=True, is_fitted_css_class=is_fitted_css_class, is_fitted_icon=is_fitted_icon, ) with open(str(Path(__file__).parent / "estimator.js"), "r") as f: script = f.read() html_end = f"</div></div><script>{script}</script></body>" out.write(html_end) html_output = out.getvalue() return html_output
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 -------- >>> from sklearn.utils._repr_html.estimator import estimator_html_repr >>> from sklearn.linear_model import LogisticRegression >>> estimator_html_repr(LogisticRegression()) '<style>#sk-container-id...'
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 # Show only first item of tuples r.maxstring = 50 # Limit string length cleaned_value = html.escape(r.repr(value)) param_type = "user-set" if name in non_default_params else "default" return {"param_type": param_type, "param_name": name, "param_value": cleaned_value}
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 = """ <div class="estimator-table"> <details> <summary>Parameters</summary> <table class="parameters-table"> <tbody> {rows} </tbody> </table> </details> </div> """ ROW_TEMPLATE = """ <tr class="{param_type}"> <td><i class="copy-paste-icon" onclick="copyToClipboard('{param_name}', this.parentElement.nextElementSibling)" ></i></td> <td class="param">{param_name}&nbsp;</td> <td class="value">{param_value}</td> </tr> """ rows = [ ROW_TEMPLATE.format(**_read_params(name, value, params.non_default)) for name, value in params.items() ] return HTML_TEMPLATE.format(rows="\n".join(rows))
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><div>Pipeline</div></div>" in html_output )
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(return_X_y=True) estimator = MyEstimator() assert "<span>Not fitted</span>" in estimator_html_repr(estimator) estimator.fit(X, y) assert "<span>Fitted</span>" in estimator_html_repr(estimator)
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) estimator.fit(X, y) pattern = '<span class="sk-estimator-doc-link fitted">i<span>Fitted</span></span>' assert estimator_html_repr(estimator).count(pattern) == 1
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 = _HTMLDocumentationLinkMixin() assert mixin._doc_link_module == "sklearn" sklearn_version = parse_version(mock_version) # we need to parse the version manually to be sure that this test is passing in # other branches than `main` (that is "dev"). if sklearn_version.dev is None: version = f"{sklearn_version.major}.{sklearn_version.minor}" else: version = "dev" assert ( mixin._doc_link_template == f"https://scikit-learn.org/{version}/modules/generated/" "{estimator_module}.{estimator_name}.html" ) assert ( mixin._get_doc_link() == f"https://scikit-learn.org/{version}/modules/generated/" "sklearn.utils._HTMLDocumentationLinkMixin.html" )
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`, then we expect to infer a module and name for the estimator est._doc_link_module = "prefix" est._doc_link_template = ( "https://website.com/{estimator_module}.{estimator_name}.html" ) assert est._get_doc_link() == f"https://website.com/{expected_module}.FooBar.html"
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): _doc_link_module = "prefix" _doc_link_template = ( "https://website.com/{estimator_module}.{estimator_name}.html" ) FooBar.__module__ = module_path est = FooBar() assert est._get_doc_link() == f"https://website.com/{expected_module}.FooBar.html"
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 an empty string. mixin._doc_link_module = "xxx" assert mixin._get_doc_link() == ""
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 # Resets the locale to the original one. Python calls setlocale(LC_TYPE, "") # at startup according to # https://docs.python.org/3/library/locale.html#background-details-hints-tips-and-caveats. # This assumes that no other locale changes have been made. For some reason, # on some platforms, trying to restore locale with something like # locale.setlocale(locale.LC_CTYPE, locale.getlocale()) raises a # locale.Error: unsupported locale setting locale.setlocale(locale.LC_CTYPE, "")
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 assert params["b"] == 2 assert params.non_default == ("a",)
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",)) assert out["param_type"] == "user-set" assert out["param_name"] == "a" assert out["param_value"] == "1" # check that we escape html tags tag_injection = "<script>alert('xss')</script>" out = _read_params("a", tag_injection, tuple()) assert ( out["param_value"] == "&quot;&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&quot;" ) assert out["param_name"] == "a" assert out["param_type"] == "default"
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 {Estimator.__name__}" # raise additional warning to be shown by pytest warnings.warn(msg, SkipTestWarning) raise SkipTest(msg) if Estimator in INIT_PARAMS: param_sets = INIT_PARAMS[Estimator] if not isinstance(param_sets, list): param_sets = [param_sets] for params in param_sets: est = Estimator(**params) yield est else: yield 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.
_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` is designed to be used as the `id` in `pytest.mark.parametrize` where `check_estimator(..., generate_only=True)` is yielding estimators and checks. Parameters ---------- obj : estimator or function Items generated by `check_estimator`. Returns ------- id : str or None See Also -------- check_estimator """ if isfunction(obj): return obj.__name__ if isinstance(obj, partial): if not obj.keywords: return obj.func.__name__ kwstring = ",".join(["{}={}".format(k, v) for k, v in obj.keywords.items()]) return "{}({})".format(obj.func.__name__, kwstring) if hasattr(obj, "get_params"): with config_context(print_changed_only=True): return re.sub(r"\s", "", str(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` is designed to be used as the `id` in `pytest.mark.parametrize` where `check_estimator(..., generate_only=True)` is yielding estimators and checks. Parameters ---------- obj : estimator or function Items generated by `check_estimator`. Returns ------- id : str or None See Also -------- check_estimator
_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]. """ # TODO(devtools): enable this behavior for third party estimators as well if type(estimator_orig) not in PER_ESTIMATOR_CHECK_PARAMS: yield estimator_orig return check_params = PER_ESTIMATOR_CHECK_PARAMS[type(estimator_orig)] try: check_name = check.__name__ except AttributeError: # partial tests check_name = check.func.__name__ if check_name not in check_params: yield estimator_orig return param_set = check_params[check_name] if isinstance(param_set, dict): param_set = [param_set] for params in param_set: estimator = clone(estimator_orig) estimator.set_params(**params) yield estimator
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 # these two cases. if type(estimator) in [KNeighborsClassifier, KNeighborsRegressor]: if tags.input_tags.pairwise: failed_checks.update( { "check_n_features_in_after_fitting": "FIXME", "check_dataframe_column_names_consistency": "FIXME", } ) if type(estimator) == LinearRegression: # TODO: remove when scipy min version >= 1.16 # Regression introduced in scipy 1.15 and fixed in 1.16, see # https://github.com/scipy/scipy/issues/22791 if ( parse_version("1.15.0") <= sp_base_version < parse_version("1.16") and _IS_32BIT ): failed_checks.update( { "check_sample_weight_equivalence_on_dense_data": ( "Issue #31098. Fails on 32-bit platforms with recent scipy." ), "check_sample_weight_equivalence_on_sparse_data": ( "Issue #31098. Fails on 32-bit platforms with recent scipy." ), } ) return failed_checks
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_content = f.read() template = tempita.Template(template_content) content = template.substitute() with open(outfile, "w", encoding="utf-8") as f: f.write(content)
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: low = np.greater_equal(x, self.low) else: low = np.greater(x, self.low) if not np.all(low): return False if self.high_inclusive: high = np.less_equal(x, self.high) else: high = np.less(x, self.high) # Note: np.all returns numpy.bool_ return bool(np.all(high))
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 interval.low == -np.inf: low = -1e10 elif interval.low < 0: low = interval.low * (1 - eps) + eps else: low = interval.low * (1 + eps) + eps if interval.high == np.inf: high = 1e10 elif interval.high < 0: high = interval.high * (1 + eps) - eps else: high = interval.high * (1 - eps) - eps return low, high
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 : array A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. Returns ------- out : array Output array, element-wise link function. """
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 result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. Returns ------- out : array Output array, element-wise link function.
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 Raw prediction values (in link space). out : array A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. Returns ------- out : array Output array, element-wise inverse link function. """
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 A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. Returns ------- out : array Output array, element-wise inverse link function.
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, true target values. raw_prediction : C-contiguous array of shape (n_samples,) or array of \ shape (n_samples, n_classes) Raw prediction values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. loss_out : None or C-contiguous array of shape (n_samples,) A location into which the result is stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- loss : array of shape (n_samples,) Element-wise loss function. """ if loss_out is None: loss_out = np.empty_like(y_true) # Be graceful to shape (n_samples, 1) -> (n_samples,) if raw_prediction.ndim == 2 and raw_prediction.shape[1] == 1: raw_prediction = raw_prediction.squeeze(1) self.closs.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=loss_out, n_threads=n_threads, ) return loss_out
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) Raw prediction values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. loss_out : None or C-contiguous array of shape (n_samples,) A location into which the result is stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- loss : array of shape (n_samples,) Element-wise loss function.
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-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 values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. loss_out : None or C-contiguous array of shape (n_samples,) A location into which the loss is stored. If None, a new array might be created. gradient_out : None or C-contiguous array of shape (n_samples,) or array \ of shape (n_samples, n_classes) A location into which the gradient is stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- loss : array of shape (n_samples,) Element-wise loss function. gradient : array of shape (n_samples,) or (n_samples, n_classes) Element-wise gradients. """ if loss_out is None: if gradient_out is None: loss_out = np.empty_like(y_true) gradient_out = np.empty_like(raw_prediction) else: loss_out = np.empty_like(y_true, dtype=gradient_out.dtype) elif gradient_out is None: gradient_out = np.empty_like(raw_prediction, dtype=loss_out.dtype) # Be graceful to shape (n_samples, 1) -> (n_samples,) if raw_prediction.ndim == 2 and raw_prediction.shape[1] == 1: raw_prediction = raw_prediction.squeeze(1) if gradient_out.ndim == 2 and gradient_out.shape[1] == 1: gradient_out = gradient_out.squeeze(1) self.closs.loss_gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=loss_out, gradient_out=gradient_out, n_threads=n_threads, ) return loss_out, gradient_out
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) Raw prediction values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. loss_out : None or C-contiguous array of shape (n_samples,) A location into which the loss is stored. If None, a new array might be created. gradient_out : None or C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes) A location into which the gradient is stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- loss : array of shape (n_samples,) Element-wise loss function. gradient : array of shape (n_samples,) or (n_samples, n_classes) Element-wise gradients.
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,) Observed, true target values. raw_prediction : C-contiguous array of shape (n_samples,) or array of \ shape (n_samples, n_classes) Raw prediction values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. gradient_out : None or C-contiguous array of shape (n_samples,) or array \ of shape (n_samples, n_classes) A location into which the result is stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- gradient : array of shape (n_samples,) or (n_samples, n_classes) Element-wise gradients. """ if gradient_out is None: gradient_out = np.empty_like(raw_prediction) # Be graceful to shape (n_samples, 1) -> (n_samples,) if raw_prediction.ndim == 2 and raw_prediction.shape[1] == 1: raw_prediction = raw_prediction.squeeze(1) if gradient_out.ndim == 2 and gradient_out.shape[1] == 1: gradient_out = gradient_out.squeeze(1) self.closs.gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=gradient_out, n_threads=n_threads, ) return gradient_out
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) Raw prediction values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. gradient_out : None or C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes) A location into which the result is stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- gradient : array of shape (n_samples,) or (n_samples, n_classes) Element-wise gradients.
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-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 values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. gradient_out : None or C-contiguous array of shape (n_samples,) or array \ of shape (n_samples, n_classes) A location into which the gradient is stored. If None, a new array might be created. hessian_out : None or C-contiguous array of shape (n_samples,) or array \ of shape (n_samples, n_classes) A location into which the hessian is stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- gradient : arrays of shape (n_samples,) or (n_samples, n_classes) Element-wise gradients. hessian : arrays of shape (n_samples,) or (n_samples, n_classes) Element-wise hessians. """ if gradient_out is None: if hessian_out is None: gradient_out = np.empty_like(raw_prediction) hessian_out = np.empty_like(raw_prediction) else: gradient_out = np.empty_like(hessian_out) elif hessian_out is None: hessian_out = np.empty_like(gradient_out) # Be graceful to shape (n_samples, 1) -> (n_samples,) if raw_prediction.ndim == 2 and raw_prediction.shape[1] == 1: raw_prediction = raw_prediction.squeeze(1) if gradient_out.ndim == 2 and gradient_out.shape[1] == 1: gradient_out = gradient_out.squeeze(1) if hessian_out.ndim == 2 and hessian_out.shape[1] == 1: hessian_out = hessian_out.squeeze(1) self.closs.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=gradient_out, hessian_out=hessian_out, n_threads=n_threads, ) return gradient_out, hessian_out
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) Raw prediction values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. gradient_out : None or C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes) A location into which the gradient is stored. If None, a new array might be created. hessian_out : None or C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes) A location into which the hessian is stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- gradient : arrays of shape (n_samples,) or (n_samples, n_classes) Element-wise gradients. hessian : arrays of shape (n_samples,) or (n_samples, n_classes) Element-wise hessians.
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_samples,) or array of \ shape (n_samples, n_classes) Raw prediction values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- loss : float Mean or averaged loss function. """ return np.average( self.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=None, loss_out=None, n_threads=n_threads, ), weights=sample_weight, )
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 values (in link space). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- loss : float Mean or averaged loss function.
__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,) Observed, true target values. sample_weight : None or array of shape (n_samples,) Sample weights. Returns ------- raw_prediction : numpy scalar or array of shape (n_classes,) Raw predictions of an intercept-only model. """ # As default, take weighted average of the target over the samples # axis=0 and then transform into link-scale (raw_prediction). y_pred = np.average(y_true, weights=sample_weight, axis=0) eps = 10 * np.finfo(y_pred.dtype).eps if self.interval_y_pred.low == -np.inf: a_min = None elif self.interval_y_pred.low_inclusive: a_min = self.interval_y_pred.low else: a_min = self.interval_y_pred.low + eps if self.interval_y_pred.high == np.inf: a_max = None elif self.interval_y_pred.high_inclusive: a_max = self.interval_y_pred.high else: a_max = self.interval_y_pred.high - eps if a_min is None and a_max is None: return self.link.link(y_pred) else: return self.link.link(np.clip(y_pred, a_min, a_max))
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 : None or array of shape (n_samples,) Sample weights. Returns ------- raw_prediction : numpy scalar or array of shape (n_classes,) Raw predictions of an intercept-only model.
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, usually passed to `fit()`. dtype : {np.float64, np.float32}, default=np.float64 The dtype of the arrays gradient and hessian. order : {'C', 'F'}, default='F' Order of the arrays gradient and hessian. The default 'F' makes the arrays contiguous along samples. Returns ------- gradient : C-contiguous array of shape (n_samples,) or array of shape \ (n_samples, n_classes) Empty array (allocated but not initialized) to be used as argument gradient_out. hessian : C-contiguous array of shape (n_samples,), array of shape (n_samples, n_classes) or shape (1,) Empty (allocated but not initialized) array to be used as argument hessian_out. If constant_hessian is True (e.g. `HalfSquaredError`), the array is initialized to ``1``. """ if dtype not in (np.float32, np.float64): raise ValueError( "Valid options for 'dtype' are np.float32 and np.float64. " f"Got dtype={dtype} instead." ) if self.is_multiclass: shape = (n_samples, self.n_classes) else: shape = (n_samples,) gradient = np.empty(shape=shape, dtype=dtype, order=order) if self.constant_hessian: # If the hessians are constant, we consider them equal to 1. # - This is correct for HalfSquaredError # - For AbsoluteError, hessians are actually 0, but they are # always ignored anyway. hessian = np.ones(shape=(1,), dtype=dtype) else: hessian = np.empty(shape=shape, dtype=dtype, order=order) return gradient, hessian
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 The dtype of the arrays gradient and hessian. order : {'C', 'F'}, default='F' Order of the arrays gradient and hessian. The default 'F' makes the arrays contiguous along samples. Returns ------- gradient : C-contiguous array of shape (n_samples,) or array of shape (n_samples, n_classes) Empty array (allocated but not initialized) to be used as argument gradient_out. hessian : C-contiguous array of shape (n_samples,), array of shape (n_samples, n_classes) or shape (1,) Empty (allocated but not initialized) array to be used as argument hessian_out. If constant_hessian is True (e.g. `HalfSquaredError`), the array is initialized to ``1``.
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: return _weighted_percentile(y_true, sample_weight, 50)
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.quantile, axis=0) else: return _weighted_percentile( y_true, sample_weight, 100 * self.closs.quantile )
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 to the residual y_true - raw_prediction. An estimator like # HistGradientBoostingRegressor might then call it on the residual, e.g. # fit_intercept_only(y_true - raw_prediction). if sample_weight is None: median = np.percentile(y_true, 50, axis=0) else: median = _weighted_percentile(y_true, sample_weight, 50) diff = y_true - median term = np.sign(diff) * np.minimum(self.closs.delta, np.abs(diff)) return median + np.average(term, weights=sample_weight)
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) Element-wise class probabilities. """ # Be graceful to shape (n_samples, 1) -> (n_samples,) if raw_prediction.ndim == 2 and raw_prediction.shape[1] == 1: raw_prediction = raw_prediction.squeeze(1) proba = np.empty((raw_prediction.shape[0], 2), dtype=raw_prediction.dtype) proba[:, 1] = self.link.inverse(raw_prediction) proba[:, 0] = 1 - proba[:, 1] return proba
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(y_true.dtype).eps for k in range(self.n_classes): out[k] = np.average(y_true == k, weights=sample_weight, axis=0) out[k] = np.clip(out[k], eps, 1 - eps) return self.link.link(out[None, :]).reshape(-1)
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-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). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. gradient_out : None or array of shape (n_samples, n_classes) A location into which the gradient is stored. If None, a new array might be created. proba_out : None or array of shape (n_samples, n_classes) A location into which the class probabilities are stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- gradient : array of shape (n_samples, n_classes) Element-wise gradients. proba : array of shape (n_samples, n_classes) Element-wise class probabilities. """ if gradient_out is None: if proba_out is None: gradient_out = np.empty_like(raw_prediction) proba_out = np.empty_like(raw_prediction) else: gradient_out = np.empty_like(proba_out) elif proba_out is None: proba_out = np.empty_like(gradient_out) self.closs.gradient_proba( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=gradient_out, proba_out=proba_out, n_threads=n_threads, ) return gradient_out, proba_out
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). sample_weight : None or C-contiguous array of shape (n_samples,) Sample weights. gradient_out : None or array of shape (n_samples, n_classes) A location into which the gradient is stored. If None, a new array might be created. proba_out : None or array of shape (n_samples, n_classes) A location into which the class probabilities are stored. If None, a new array might be created. n_threads : int, default=1 Might use openmp thread parallelism. Returns ------- gradient : array of shape (n_samples, n_classes) Element-wise gradients. proba : array of shape (n_samples, n_classes) Element-wise class probabilities.
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) Element-wise class probabilities. """ # Be graceful to shape (n_samples, 1) -> (n_samples,) if raw_prediction.ndim == 2 and raw_prediction.shape[1] == 1: raw_prediction = raw_prediction.squeeze(1) proba = np.empty((raw_prediction.shape[0], 2), dtype=raw_prediction.dtype) proba[:, 1] = self.link.inverse(raw_prediction) proba[:, 0] = 1 - proba[:, 1] return proba
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_prediction.flat[:] = rng.uniform( low=raw_bound[0], high=raw_bound[1], size=n_samples * loss.n_classes, ) y_true = np.arange(n_samples).astype(float) % loss.n_classes else: # If link is identity, we must respect the interval of y_pred: if isinstance(loss.link, IdentityLink): low, high = _inclusive_low_high(loss.interval_y_pred) low = np.amax([low, raw_bound[0]]) high = np.amin([high, raw_bound[1]]) raw_bound = (low, high) raw_prediction = rng.uniform( low=raw_bound[0], high=raw_bound[1], size=n_samples ) # generate a y_true in valid range low, high = _inclusive_low_high(loss.interval_y_true) low = max(low, y_bound[0]) high = min(high, y_bound[1]) y_true = rng.uniform(low, high, size=n_samples) # set some values at special boundaries if loss.interval_y_true.low == 0 and loss.interval_y_true.low_inclusive: y_true[:: (n_samples // 3)] = 0 if loss.interval_y_true.high == 1 and loss.interval_y_true.high_inclusive: y_true[1 :: (n_samples // 3)] = 1 return y_true, raw_prediction
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. h = np.full_like(x, fill_value=eps) f_minus_2h = func(x - 2 * h) f_minus_1h = func(x - h) f_plus_1h = func(x + h) f_plus_2h = func(x + 2 * h) return (-f_plus_2h + 8 * f_plus_1h - 8 * f_minus_1h + f_minus_2h) / (12.0 * eps)
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: low, high = _inclusive_low_high(loss.interval_y_true) y_true = np.linspace(low, high, num=10) # add boundaries if they are included if loss.interval_y_true.low_inclusive: y_true = np.r_[y_true, loss.interval_y_true.low] if loss.interval_y_true.high_inclusive: y_true = np.r_[y_true, loss.interval_y_true.high] assert loss.in_y_true_range(y_true) n = y_true.shape[0] low, high = _inclusive_low_high(loss.interval_y_pred) if loss.is_multiclass: y_pred = np.empty((n, n_classes)) y_pred[:, 0] = np.linspace(low, high, num=n) y_pred[:, 1] = 0.5 * (1 - y_pred[:, 0]) y_pred[:, 2] = 0.5 * (1 - y_pred[:, 0]) else: y_pred = np.linspace(low, high, num=n) assert loss.in_y_pred_range(y_pred) # calculating losses should not fail raw_prediction = loss.link.link(y_pred) loss.loss(y_true=y_true, raw_prediction=raw_prediction)
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_true]), raw_prediction=np.array([raw_prediction]) ) loss2, grad2 = loss.loss_gradient( y_true=np.array([y_true]), raw_prediction=np.array([raw_prediction]) ) grad3, hess = loss.gradient_hessian( y_true=np.array([y_true]), raw_prediction=np.array([raw_prediction]) ) assert loss1 == approx(loss_true, rel=1e-15, abs=1e-15) assert loss2 == approx(loss_true, rel=1e-15, abs=1e-15) if gradient_true is not None: assert grad1 == approx(gradient_true, rel=1e-15, abs=1e-15) assert grad2 == approx(gradient_true, rel=1e-15, abs=1e-15) assert grad3 == approx(gradient_true, rel=1e-15, abs=1e-15) if hessian_true is not None: assert hess == approx(hessian_true, rel=1e-15, abs=1e-15)
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 float32 or all float64. Also check that input arrays can be readonly, e.g. memory mapped. """ loss = loss() # generate a y_true and raw_prediction in valid range n_samples = 5 y_true, raw_prediction = random_y_true_raw_prediction( loss=loss, n_samples=n_samples, y_bound=(-100, 100), raw_bound=(-10, 10), seed=42, ) y_true = y_true.astype(dtype_in) raw_prediction = raw_prediction.astype(dtype_in) if sample_weight is not None: sample_weight = np.array([2.0] * n_samples, dtype=dtype_in) if out1 is not None: out1 = np.empty_like(y_true, dtype=dtype_out) if out2 is not None: out2 = np.empty_like(raw_prediction, dtype=dtype_out) if readonly_memmap: y_true = create_memmap_backed_data(y_true) raw_prediction = create_memmap_backed_data(raw_prediction) if sample_weight is not None: sample_weight = create_memmap_backed_data(sample_weight) l = loss.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=out1, n_threads=n_threads, ) assert l is out1 if out1 is not None else True g = loss.gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out2, n_threads=n_threads, ) assert g is out2 if out2 is not None else True l, g = loss.loss_gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=out1, gradient_out=out2, n_threads=n_threads, ) assert l is out1 if out1 is not None else True assert g is out2 if out2 is not None else True if out1 is not None and loss.is_multiclass: out1 = np.empty_like(raw_prediction, dtype=dtype_out) g, h = loss.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out1, hessian_out=out2, n_threads=n_threads, ) assert g is out1 if out1 is not None else True assert h is out2 if out2 is not None else True loss(y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight) loss.fit_intercept_only(y_true=y_true, sample_weight=sample_weight) loss.constant_to_optimal_zero(y_true=y_true, sample_weight=sample_weight) if hasattr(loss, "predict_proba"): loss.predict_proba(raw_prediction=raw_prediction) if hasattr(loss, "gradient_proba"): g, p = loss.gradient_proba( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out1, proba_out=out2, n_threads=n_threads, ) assert g is out1 if out1 is not None else True assert p is out2 if out2 is not None else True
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_weight == "range": sample_weight = np.linspace(1, y_true.shape[0], num=y_true.shape[0]) out_l1 = np.empty_like(y_true) out_l2 = np.empty_like(y_true) out_g1 = np.empty_like(raw_prediction) out_g2 = np.empty_like(raw_prediction) out_h1 = np.empty_like(raw_prediction) out_h2 = np.empty_like(raw_prediction) loss.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=out_l1, ) loss.closs.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=out_l2, ) assert_allclose(out_l1, out_l2) loss.gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out_g1, ) loss.closs.gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out_g2, ) assert_allclose(out_g1, out_g2) loss.closs.loss_gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=out_l1, gradient_out=out_g1, ) loss.closs.loss_gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=out_l2, gradient_out=out_g2, ) assert_allclose(out_l1, out_l2) assert_allclose(out_g1, out_g2) loss.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out_g1, hessian_out=out_h1, ) loss.closs.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out_g2, hessian_out=out_h2, ) assert_allclose(out_g1, out_g2) assert_allclose(out_h1, out_h2)
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=20, y_bound=(-100, 100), raw_bound=(-10, 10), seed=global_random_seed, ) if sample_weight == "range": sample_weight = np.linspace(1, y_true.shape[0], num=y_true.shape[0]) out_l1 = np.empty_like(y_true) out_l2 = np.empty_like(y_true) out_g1 = np.empty_like(raw_prediction) out_g2 = np.empty_like(raw_prediction) out_g3 = np.empty_like(raw_prediction) out_h3 = np.empty_like(raw_prediction) l1 = loss.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=out_l1, ) g1 = loss.gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out_g1, ) l2, g2 = loss.loss_gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, loss_out=out_l2, gradient_out=out_g2, ) g3, h3 = loss.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out_g3, hessian_out=out_h3, ) assert_allclose(l1, l2) assert_array_equal(l1, out_l1) assert np.shares_memory(l1, out_l1) assert_array_equal(l2, out_l2) assert np.shares_memory(l2, out_l2) assert_allclose(g1, g2) assert_allclose(g1, g3) assert_array_equal(g1, out_g1) assert np.shares_memory(g1, out_g1) assert_array_equal(g2, out_g2) assert np.shares_memory(g2, out_g2) assert_array_equal(g3, out_g3) assert np.shares_memory(g3, out_g3) if hasattr(loss, "gradient_proba"): assert loss.is_multiclass # only for HalfMultinomialLoss out_g4 = np.empty_like(raw_prediction) out_proba = np.empty_like(raw_prediction) g4, proba = loss.gradient_proba( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, gradient_out=out_g4, proba_out=out_proba, ) assert_allclose(g1, out_g4) assert_allclose(g1, g4) assert_allclose(proba, out_proba) assert_allclose(np.sum(proba, axis=1), 1, rtol=1e-11)
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, raw_prediction = random_y_true_raw_prediction( loss=loss, n_samples=n_samples, y_bound=(-100, 100), raw_bound=(-5, 5), seed=global_random_seed, ) if sample_weight == "ones": sample_weight = np.ones(shape=n_samples, dtype=np.float64) else: rng = np.random.RandomState(global_random_seed) sample_weight = rng.normal(size=n_samples).astype(np.float64) assert_allclose( loss.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, ), sample_weight * loss.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=None, ), ) losses, gradient = loss.loss_gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=None, ) losses_sw, gradient_sw = loss.loss_gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, ) assert_allclose(losses * sample_weight, losses_sw) if not loss.is_multiclass: assert_allclose(gradient * sample_weight, gradient_sw) else: assert_allclose(gradient * sample_weight[:, None], gradient_sw) gradient, hessian = loss.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction, sample_weight=None, ) gradient_sw, hessian_sw = loss.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, ) if not loss.is_multiclass: assert_allclose(gradient * sample_weight, gradient_sw) assert_allclose(hessian * sample_weight, hessian_sw) else: assert_allclose(gradient * sample_weight[:, None], gradient_sw) assert_allclose(hessian * sample_weight[:, None], hessian_sw)
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: raw_prediction_2d = raw_prediction[:, None] assert_allclose( loss.loss(y_true=y_true, raw_prediction=raw_prediction_2d), loss.loss(y_true=y_true, raw_prediction=raw_prediction), ) assert_allclose( loss.loss_gradient(y_true=y_true, raw_prediction=raw_prediction_2d), loss.loss_gradient(y_true=y_true, raw_prediction=raw_prediction), ) assert_allclose( loss.gradient(y_true=y_true, raw_prediction=raw_prediction_2d), loss.gradient(y_true=y_true, raw_prediction=raw_prediction), ) assert_allclose( loss.gradient_hessian(y_true=y_true, raw_prediction=raw_prediction_2d), loss.gradient_hessian(y_true=y_true, raw_prediction=raw_prediction), )
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([-10, -0.1, 0, 0.1, 3, 10]) # If link is identity, we must respect the interval of y_pred: if isinstance(loss.link, IdentityLink): eps = 1e-10 low = loss.interval_y_pred.low if not loss.interval_y_pred.low_inclusive: low = low + eps high = loss.interval_y_pred.high if not loss.interval_y_pred.high_inclusive: high = high - eps raw_prediction = np.clip(raw_prediction, low, high) y_true = loss.link.inverse(raw_prediction) else: # HalfMultinomialLoss y_true = np.arange(loss.n_classes).astype(float) # raw_prediction with entries -exp(10), but +exp(10) on the diagonal # this is close enough to np.inf which would produce nan raw_prediction = np.full( shape=(loss.n_classes, loss.n_classes), fill_value=-np.exp(10), dtype=float, ) raw_prediction.flat[:: loss.n_classes + 1] = np.exp(10) if sample_weight == "range": sample_weight = np.linspace(1, y_true.shape[0], num=y_true.shape[0]) loss_value = loss.loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, ) constant_term = loss.constant_to_optimal_zero( y_true=y_true, sample_weight=sample_weight ) # Comparing loss_value + constant_term to zero would result in large # round-off errors. assert_allclose(loss_value, -constant_term, atol=1e-14, rtol=1e-15)
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_true, raw_prediction = random_y_true_raw_prediction( loss=loss, n_samples=n_samples, y_bound=(-100, 100), raw_bound=(-5, 5), seed=global_random_seed, ) if sample_weight == "range": sample_weight = np.linspace(1, y_true.shape[0], num=y_true.shape[0]) g, h = loss.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, ) assert g.shape == raw_prediction.shape assert h.shape == raw_prediction.shape if not loss.is_multiclass: def loss_func(x): return loss.loss( y_true=y_true, raw_prediction=x, sample_weight=sample_weight, ) g_numeric = numerical_derivative(loss_func, raw_prediction, eps=1e-6) assert_allclose(g, g_numeric, rtol=5e-6, atol=1e-10) def grad_func(x): return loss.gradient( y_true=y_true, raw_prediction=x, sample_weight=sample_weight, ) h_numeric = numerical_derivative(grad_func, raw_prediction, eps=1e-6) if loss.approx_hessian: # TODO: What could we test if loss.approx_hessian? pass else: assert_allclose(h, h_numeric, rtol=5e-6, atol=1e-10) else: # For multiclass loss, we should only change the predictions of the # class for which the derivative is taken for, e.g. offset[:, k] = eps # for class k. # As a softmax is computed, offsetting the whole array by a constant # would have no effect on the probabilities, and thus on the loss. for k in range(loss.n_classes): def loss_func(x): raw = raw_prediction.copy() raw[:, k] = x return loss.loss( y_true=y_true, raw_prediction=raw, sample_weight=sample_weight, ) g_numeric = numerical_derivative(loss_func, raw_prediction[:, k], eps=1e-5) assert_allclose(g[:, k], g_numeric, rtol=5e-6, atol=1e-10) def grad_func(x): raw = raw_prediction.copy() raw[:, k] = x return loss.gradient( y_true=y_true, raw_prediction=raw, sample_weight=sample_weight, )[:, k] h_numeric = numerical_derivative(grad_func, raw_prediction[:, k], eps=1e-6) if loss.approx_hessian: # TODO: What could we test if loss.approx_hessian? pass else: assert_allclose(h[:, k], h_numeric, rtol=5e-6, atol=1e-10)
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 newton root finder expects a scalar or a one-element array for this purpose. """ loss = _LOSSES[loss](sample_weight=None) y_true = np.array([y_true], dtype=np.float64) x0 = np.array([x0], dtype=np.float64) 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_optimal_zero(y_true=y_true) def fprime(x: np.ndarray) -> np.ndarray: return loss.gradient(y_true=y_true, raw_prediction=x) def fprime2(x: np.ndarray) -> np.ndarray: return loss.gradient_hessian(y_true=y_true, raw_prediction=x)[1] optimum = newton( func, x0=x0, fprime=fprime, fprime2=fprime2, maxiter=100, tol=5e-8, ) # Need to ravel arrays because assert_allclose requires matching # dimensions. y_true = y_true.ravel() optimum = optimum.ravel() assert_allclose(loss.link.inverse(optimum), y_true) assert_allclose(func(optimum), 0, atol=1e-14) assert_allclose(loss.gradient(y_true=y_true, raw_prediction=optimum), 0, atol=5e-7)
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-element array for this purpose.
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_optimal_zero(y_true=y_true)
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: y_true = np.arange(n_samples).astype(np.float64) % loss.n_classes y_true[::5] = 0 # exceedance of class 0 if sample_weight == "range": sample_weight = np.linspace(0.1, 2, num=n_samples) a = loss.fit_intercept_only(y_true=y_true, sample_weight=sample_weight) # find minimum by optimization def fun(x): if not loss.is_multiclass: raw_prediction = np.full(shape=(n_samples), fill_value=x) else: raw_prediction = np.ascontiguousarray( np.broadcast_to(x, shape=(n_samples, loss.n_classes)) ) return loss( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, ) if not loss.is_multiclass: opt = minimize_scalar(fun, tol=1e-7, options={"maxiter": 100}) grad = loss.gradient( y_true=y_true, raw_prediction=np.full_like(y_true, a), sample_weight=sample_weight, ) assert a.shape == tuple() # scalar assert a.dtype == y_true.dtype assert_all_finite(a) a == approx(opt.x, rel=1e-7) grad.sum() == approx(0, abs=1e-12) else: # The constraint corresponds to sum(raw_prediction) = 0. Without it, we would # need to apply loss.symmetrize_raw_prediction to opt.x before comparing. opt = minimize( fun, np.zeros((loss.n_classes)), tol=1e-13, options={"maxiter": 100}, method="SLSQP", constraints=LinearConstraint(np.ones((1, loss.n_classes)), 0, 0), ) grad = loss.gradient( y_true=y_true, raw_prediction=np.tile(a, (n_samples, 1)), sample_weight=sample_weight, ) assert a.dtype == y_true.dtype assert_all_finite(a) assert_allclose(a, opt.x, rtol=5e-6, atol=1e-12) assert_allclose(grad.sum(axis=0), 0, atol=1e-12)
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.random.RandomState(global_random_seed) if random_dist == "binomial": y_train = rng.binomial(1, 0.5, size=100) else: y_train = getattr(rng, random_dist)(size=100) baseline_prediction = loss.fit_intercept_only(y_true=y_train) # Make sure baseline prediction is the expected functional=func, e.g. mean # or median. assert_all_finite(baseline_prediction) assert baseline_prediction == approx(loss.link.link(func(y_train))) assert loss.link.inverse(baseline_prediction) == approx(func(y_train)) if isinstance(loss, IdentityLink): assert_allclose(loss.link.inverse(baseline_prediction), baseline_prediction) # Test baseline at boundary if loss.interval_y_true.low_inclusive: y_train.fill(loss.interval_y_true.low) baseline_prediction = loss.fit_intercept_only(y_true=y_train) assert_all_finite(baseline_prediction) if loss.interval_y_true.high_inclusive: y_train.fill(loss.interval_y_true.high) baseline_prediction = loss.fit_intercept_only(y_true=y_train) assert_all_finite(baseline_prediction)
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 = softmax and link function = log - symmetry term. y_train = rng.randint(0, n_classes + 1, size=100).astype(np.float64) baseline_prediction = loss.fit_intercept_only(y_true=y_train) assert baseline_prediction.shape == (n_classes,) p = np.zeros(n_classes, dtype=y_train.dtype) for k in range(n_classes): p[k] = (y_train == k).mean() assert_allclose(baseline_prediction, np.log(p) - np.mean(np.log(p))) assert_allclose(baseline_prediction[None, :], loss.link.link(p[None, :])) for y_train in (np.zeros(shape=10), np.ones(shape=10)): y_train = y_train.astype(np.float64) baseline_prediction = loss.fit_intercept_only(y_true=y_train) assert baseline_prediction.dtype == y_train.dtype assert_all_finite(baseline_prediction)
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_gradient`. """ n_samples = 100 n_classes = 5 loss = HalfMultinomialLoss(n_classes=n_classes) y_true, raw_prediction = random_y_true_raw_prediction( loss=loss, n_samples=n_samples, seed=global_random_seed, ) sample_weight = np.linspace(0.1, 2, num=n_samples) grad1 = loss.closs._test_cy_gradient( y_true=y_true, raw_prediction=raw_prediction, # needs to be C-contiguous sample_weight=sample_weight, ) grad2 = loss.gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=sample_weight, ) assert_allclose(grad1, grad2)
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.randint(0, 2, size=n_samples).astype(np.float64) raw_prediction = rng.normal(size=n_samples) raw_multinom = np.empty((n_samples, 2)) raw_multinom[:, 0] = -0.5 * raw_prediction raw_multinom[:, 1] = 0.5 * raw_prediction assert_allclose( binom.loss(y_true=y_train, raw_prediction=raw_prediction), multinom.loss(y_true=y_train, raw_prediction=raw_multinom), )
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): -loglike(z, f) = log(1 + exp(-2 * z * f)) Note: - ESL 2*f = raw_prediction, hence the factor 2 of ESL disappears. - Deviance = -2*loglike + .., but HalfBinomialLoss is half of the deviance, hence the factor of 2 cancels in the comparison. """ def alt_loss(y, raw_pred): z = 2 * y - 1 return np.mean(np.log(1 + np.exp(-z * raw_pred))) def alt_gradient(y, raw_pred): # alternative gradient formula according to ESL z = 2 * y - 1 return -z / (1 + np.exp(z * raw_pred)) bin_loss = HalfBinomialLoss() y_true = y_true.astype(global_dtype) y_pred = y_pred.astype(global_dtype) datum = (y_true, y_pred) assert bin_loss(*datum) == approx(alt_loss(*datum)) assert_allclose(bin_loss.gradient(*datum), alt_gradient(*datum))
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_prediction, hence the factor 2 of ESL disappears. - Deviance = -2*loglike + .., but HalfBinomialLoss is half of the deviance, hence the factor of 2 cancels in the comparison.
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=global_random_seed, ) if hasattr(loss, "predict_proba"): proba = loss.predict_proba(raw_prediction) assert proba.shape == (n_samples, loss.n_classes) assert np.sum(proba, axis=1) == approx(1, rel=1e-11) if hasattr(loss, "gradient_proba"): for grad, proba in ( (None, None), (None, np.empty_like(raw_prediction)), (np.empty_like(raw_prediction), None), (np.empty_like(raw_prediction), np.empty_like(raw_prediction)), ): grad, proba = loss.gradient_proba( y_true=y_true, raw_prediction=raw_prediction, sample_weight=None, gradient_out=grad, proba_out=proba, ) assert proba.shape == (n_samples, loss.n_classes) assert np.sum(proba, axis=1) == approx(1, rel=1e-11) assert_allclose( grad, loss.gradient( y_true=y_true, raw_prediction=raw_prediction, sample_weight=None, gradient_out=None, ), )
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_weight == "range": sample_weight = np.ones(n_samples) loss = loss(sample_weight=sample_weight) gradient, hessian = loss.init_gradient_and_hessian( n_samples=n_samples, dtype=dtype, order=order, ) if loss.constant_hessian: assert gradient.shape == (n_samples,) assert hessian.shape == (1,) elif loss.is_multiclass: assert gradient.shape == (n_samples, loss.n_classes) assert hessian.shape == (n_samples, loss.n_classes) else: assert hessian.shape == (n_samples,) assert hessian.shape == (n_samples,) assert gradient.dtype == dtype assert hessian.dtype == dtype if order == "C": assert gradient.flags.c_contiguous assert hessian.flags.c_contiguous else: assert gradient.flags.f_contiguous assert hessian.flags.f_contiguous
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) unpickled_loss = pickle.loads(pickled_loss) assert loss(y_true=y_true, raw_prediction=raw_prediction) == approx( unpickled_loss(y_true=y_true, raw_prediction=raw_prediction) )
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( loss=half_tweedie_log, n_samples=n_samples, seed=42 ) y_pred = half_tweedie_log.link.inverse(raw_prediction) # exp(raw_prediction) # Let's compare the loss values, up to some constant term that is dropped # in HalfTweedieLoss but not in HalfTweedieLossIdentity. loss_log = half_tweedie_log.loss( y_true=y_true, raw_prediction=raw_prediction ) + half_tweedie_log.constant_to_optimal_zero(y_true) loss_identity = half_tweedie_identity.loss( y_true=y_true, raw_prediction=y_pred ) + half_tweedie_identity.constant_to_optimal_zero(y_true) # Note that HalfTweedieLoss ignores different constant terms than # HalfTweedieLossIdentity. Constant terms means terms not depending on # raw_prediction. By adding these terms, `constant_to_optimal_zero`, both losses # give the same values. assert_allclose(loss_log, loss_identity) # For gradients and hessians, the constant terms do not matter. We have, however, # to account for the chain rule, i.e. with x=raw_prediction # gradient_log(x) = d/dx loss_log(x) # = d/dx loss_identity(exp(x)) # = exp(x) * gradient_identity(exp(x)) # Similarly, # hessian_log(x) = exp(x) * gradient_identity(exp(x)) # + exp(x)**2 * hessian_identity(x) gradient_log, hessian_log = half_tweedie_log.gradient_hessian( y_true=y_true, raw_prediction=raw_prediction ) gradient_identity, hessian_identity = half_tweedie_identity.gradient_hessian( y_true=y_true, raw_prediction=y_pred ) assert_allclose(gradient_log, y_pred * gradient_identity) assert_allclose( hessian_log, y_pred * gradient_identity + y_pred**2 * hessian_identity )
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', 'title', 'article']: val = item.get(key, None) if val is not None: metadata.append(encoder.__dict__[f'begin_{key}']) metadata.extend(encoder.encode(val)) metadata.append(encoder.__dict__[f'end_{key}']) return metadata
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 actual input function.""" batch_size = params["batch_size"] name_to_features = { "input_ids": tf.FixedLenFeature([seq_length + 1], tf.int64), } # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. if is_training: d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files)) d = d.repeat() d = d.shuffle(buffer_size=len(input_files)) # `cycle_length` is the number of parallel files that get read. cycle_length = min(num_cpu_threads, len(input_files)) # `sloppy` mode means that the interleaving is not exact. This adds # even more randomness to the training pipeline. d = d.apply( tf.data.experimental.parallel_interleave( tf.data.TFRecordDataset, sloppy=is_training, cycle_length=cycle_length)) d = d.shuffle(buffer_size=100) else: d = tf.data.TFRecordDataset(input_files) # If we evaluate for a fixed number of steps we don't want to encounter # out-of-range exceptions. if evaluate_for_fixed_number_of_steps: d = d.repeat() # We must `drop_remainder` on training because the TPU requires fixed # size dimensions. For eval, we assume we are evaluating on the CPU or GPU # and we *don't* want to drop the remainder, otherwise we wont cover # every sample. d = d.apply( tf.data.experimental.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, num_parallel_batches=num_cpu_threads, drop_remainder=True)) return d return input_fn
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_map = {label: i for i, label in enumerate(labels)} for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: tf.logging.info("Writing example %d of %d" % (ex_index, len(examples))) # begin_summary is our [CLS] token tokens = example['ids'] + [encoder.begin_summary] if len(tokens) > max_seq_length: if chop_from_front_if_needed: tokens = tokens[-max_seq_length:] else: tokens = example['ids'][:(max_seq_length-1)] + [encoder.begin_summary] elif len(tokens) < max_seq_length: tokens.extend([encoder.padding] * (max_seq_length - len(tokens))) features = collections.OrderedDict() features['input_ids'] = tf.train.Feature(int64_list=tf.train.Int64List(value=tokens)) features['label_ids'] = tf.train.Feature(int64_list=tf.train.Int64List(value=[label_map[example['label']]])) features['is_real_example'] = tf.train.Feature(int64_list=tf.train.Int64List(value=[1])) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writer.write(tf_example.SerializeToString()) if pad_extra_examples: for x in range(len(examples) % batch_size): features = collections.OrderedDict() features['input_ids'] = tf.train.Feature(int64_list=tf.train.Int64List(value=[0]*max_seq_length)) features['label_ids'] = tf.train.Feature(int64_list=tf.train.Int64List(value=[0])) features['is_real_example'] = tf.train.Feature(int64_list=tf.train.Int64List(value=[0])) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writer.write(tf_example.SerializeToString()) writer.close()
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_length], tf.int64), "label_ids": tf.FixedLenFeature([], tf.int64), "is_real_example": tf.FixedLenFeature([], tf.int64), } def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: d = d.repeat() d = d.shuffle(buffer_size=buffer_size) d = d.apply( tf.data.experimental.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn
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_dropout_prob=0.1, max_position_embeddings=512, initializer_range=0.02): """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 the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. hidden_dropout_prob: The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). initializer_range: The stdev of the truncated_normal_initializer for initializing all weight matrices. """ self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.pad_token_id = 0
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 the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. hidden_dropout_prob: The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). initializer_range: The stdev of the truncated_normal_initializer for initializing all weight matrices.
__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