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 safe_mask(X, mask):
"""Return a mask which is safe to use on X.
Parameters
----------
X : {array-like, sparse matrix}
Data on which to apply mask.
mask : array-like
Mask to be used on X.
Returns
-------
mask : ndarray
Array that is safe to use on X.
Ex... | Return a mask which is safe to use on X.
Parameters
----------
X : {array-like, sparse matrix}
Data on which to apply mask.
mask : array-like
Mask to be used on X.
Returns
-------
mask : ndarray
Array that is safe to use on X.
Examples
--------
>>> fro... | safe_mask | python | scikit-learn/scikit-learn | sklearn/utils/_mask.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mask.py | BSD-3-Clause |
def axis0_safe_slice(X, mask, len_mask):
"""Return a mask which is safer to use on X than safe_mask.
This mask is safer than safe_mask since it returns an
empty array, when a sparse matrix is sliced with a boolean mask
with all False, instead of raising an unhelpful error in older
versions of SciPy... | Return a mask which is safer to use on X than safe_mask.
This mask is safer than safe_mask since it returns an
empty array, when a sparse matrix is sliced with a boolean mask
with all False, instead of raising an unhelpful error in older
versions of SciPy.
See: https://github.com/scipy/scipy/issue... | axis0_safe_slice | python | scikit-learn/scikit-learn | sklearn/utils/_mask.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mask.py | BSD-3-Clause |
def indices_to_mask(indices, mask_length):
"""Convert list of indices to boolean mask.
Parameters
----------
indices : list-like
List of integers treated as indices.
mask_length : int
Length of boolean mask to be generated.
This parameter must be greater than max(indices).
... | Convert list of indices to boolean mask.
Parameters
----------
indices : list-like
List of integers treated as indices.
mask_length : int
Length of boolean mask to be generated.
This parameter must be greater than max(indices).
Returns
-------
mask : 1d boolean nd-a... | indices_to_mask | python | scikit-learn/scikit-learn | sklearn/utils/_mask.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mask.py | BSD-3-Clause |
def _raise_for_params(params, owner, method, allow=None):
"""Raise an error if metadata routing is not enabled and params are passed.
.. versionadded:: 1.4
Parameters
----------
params : dict
The metadata passed to a method.
owner : object
The object to which the method belong... | Raise an error if metadata routing is not enabled and params are passed.
.. versionadded:: 1.4
Parameters
----------
params : dict
The metadata passed to a method.
owner : object
The object to which the method belongs.
method : str
The name of the method, e.g. "fit".
... | _raise_for_params | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _raise_for_unsupported_routing(obj, method, **kwargs):
"""Raise when metadata routing is enabled and metadata is passed.
This is used in meta-estimators which have not implemented metadata routing
to prevent silent bugs. There is no need to use this function if the
meta-estimator is not accepting a... | Raise when metadata routing is enabled and metadata is passed.
This is used in meta-estimators which have not implemented metadata routing
to prevent silent bugs. There is no need to use this function if the
meta-estimator is not accepting any metadata, especially in `fit`, since
if a meta-estimator ac... | _raise_for_unsupported_routing | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def get_metadata_routing(self):
"""Raise `NotImplementedError`.
This estimator does not support metadata routing yet."""
raise NotImplementedError(
f"{self.__class__.__name__} has not implemented metadata routing yet."
) | Raise `NotImplementedError`.
This estimator does not support metadata routing yet. | get_metadata_routing | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def request_is_alias(item):
"""Check if an item is a valid alias.
Values in ``VALID_REQUEST_VALUES`` are not considered aliases in this
context. Only a string which is a valid identifier is.
Parameters
----------
item : object
The given item to be checked if it can be an alias.
Re... | Check if an item is a valid alias.
Values in ``VALID_REQUEST_VALUES`` are not considered aliases in this
context. Only a string which is a valid identifier is.
Parameters
----------
item : object
The given item to be checked if it can be an alias.
Returns
-------
result : bool... | request_is_alias | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def add_request(
self,
*,
param,
alias,
):
"""Add request info for a metadata.
Parameters
----------
param : str
The property for which a request is set.
alias : str, or {True, False, None}
Specifies which metadata sho... | Add request info for a metadata.
Parameters
----------
param : str
The property for which a request is set.
alias : str, or {True, False, None}
Specifies which metadata should be routed to `param`
- str: the name (or alias) of metadata given to a me... | add_request | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _get_param_names(self, return_alias):
"""Get names of all metadata that can be consumed or routed by this method.
This method returns the names of all metadata, even the ``False``
ones.
Parameters
----------
return_alias : bool
Controls whether original ... | Get names of all metadata that can be consumed or routed by this method.
This method returns the names of all metadata, even the ``False``
ones.
Parameters
----------
return_alias : bool
Controls whether original or aliased names should be returned. If
`... | _get_param_names | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _check_warnings(self, *, params):
"""Check whether metadata is passed which is marked as WARN.
If any metadata is passed which is marked as WARN, a warning is raised.
Parameters
----------
params : dict
The metadata passed to a method.
"""
params... | Check whether metadata is passed which is marked as WARN.
If any metadata is passed which is marked as WARN, a warning is raised.
Parameters
----------
params : dict
The metadata passed to a method.
| _check_warnings | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _route_params(self, params, parent, caller):
"""Prepare the given parameters to be passed to the method.
The output of this method can be used directly as the input to the
corresponding method as extra props.
Parameters
----------
params : dict
A diction... | Prepare the given parameters to be passed to the method.
The output of this method can be used directly as the input to the
corresponding method as extra props.
Parameters
----------
params : dict
A dictionary of provided metadata.
parent : object
... | _route_params | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _consumes(self, params):
"""Check whether the given parameters are consumed by this method.
Parameters
----------
params : iterable of str
An iterable of parameters to check.
Returns
-------
consumed : set of str
A set of parameters w... | Check whether the given parameters are consumed by this method.
Parameters
----------
params : iterable of str
An iterable of parameters to check.
Returns
-------
consumed : set of str
A set of parameters which are consumed by this method.
... | _consumes | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _route_params(self, *, params, method, parent, caller):
"""Prepare the given parameters to be passed to the method.
The output of this method can be used directly as the input to the
corresponding method as extra keyword arguments to pass metadata.
Parameters
----------
... | Prepare the given parameters to be passed to the method.
The output of this method can be used directly as the input to the
corresponding method as extra keyword arguments to pass metadata.
Parameters
----------
params : dict
A dictionary of provided metadata.
... | _route_params | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _serialize(self):
"""Serialize the object.
Returns
-------
obj : dict
A serialized version of the instance in the form of a dictionary.
"""
output = dict()
for method in SIMPLE_METHODS:
mmr = getattr(self, method)
if len(mm... | Serialize the object.
Returns
-------
obj : dict
A serialized version of the instance in the form of a dictionary.
| _serialize | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def add(self, *, caller, callee):
"""Add a method mapping.
Parameters
----------
caller : str
Parent estimator's method name in which the ``callee`` is called.
callee : str
Child object's method name. This method is called in ``caller``.
Return... | Add a method mapping.
Parameters
----------
caller : str
Parent estimator's method name in which the ``callee`` is called.
callee : str
Child object's method name. This method is called in ``caller``.
Returns
-------
self : MethodMappin... | add | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _serialize(self):
"""Serialize the object.
Returns
-------
obj : list
A serialized version of the instance in the form of a list.
"""
result = list()
for route in self._routes:
result.append({"caller": route.caller, "callee": route.cal... | Serialize the object.
Returns
-------
obj : list
A serialized version of the instance in the form of a list.
| _serialize | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def add_self_request(self, obj):
"""Add `self` (as a consumer) to the routing.
This method is used if the router is also a consumer, and hence the
router itself needs to be included in the routing. The passed object
can be an estimator or a
:class:`~sklearn.utils.metadata_routin... | Add `self` (as a consumer) to the routing.
This method is used if the router is also a consumer, and hence the
router itself needs to be included in the routing. The passed object
can be an estimator or a
:class:`~sklearn.utils.metadata_routing.MetadataRequest`.
A router should... | add_self_request | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def add(self, *, method_mapping, **objs):
"""Add named objects with their corresponding method mapping.
Parameters
----------
method_mapping : MethodMapping
The mapping between the child and the parent's methods.
**objs : dict
A dictionary of objects fro... | Add named objects with their corresponding method mapping.
Parameters
----------
method_mapping : MethodMapping
The mapping between the child and the parent's methods.
**objs : dict
A dictionary of objects from which metadata is extracted by calling
... | add | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def consumes(self, method, params):
"""Check whether the given parameters are consumed by the given method.
.. versionadded:: 1.4
Parameters
----------
method : str
The name of the method to check.
params : iterable of str
An iterable of paramet... | Check whether the given parameters are consumed by the given method.
.. versionadded:: 1.4
Parameters
----------
method : str
The name of the method to check.
params : iterable of str
An iterable of parameters to check.
Returns
-------
... | consumes | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _get_param_names(self, *, method, return_alias, ignore_self_request):
"""Get names of all metadata that can be consumed or routed by specified \
method.
This method returns the names of all metadata, even the ``False``
ones.
Parameters
----------
method ... | Get names of all metadata that can be consumed or routed by specified method.
This method returns the names of all metadata, even the ``False``
ones.
Parameters
----------
method : str
The name of the method for which metadata names are requested.
... | _get_param_names | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _route_params(self, *, params, method, parent, caller):
"""Prepare the given parameters to be passed to the method.
This is used when a router is used as a child object of another router.
The parent router then passes all parameters understood by the child
object to it and delegates... | Prepare the given parameters to be passed to the method.
This is used when a router is used as a child object of another router.
The parent router then passes all parameters understood by the child
object to it and delegates their validation to the child.
The output of this method can ... | _route_params | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def route_params(self, *, caller, params):
"""Return the input parameters requested by child objects.
The output of this method is a :class:`~sklearn.utils.Bunch`, which includes the
metadata for all methods of each child object that is used in the router's
`caller` method.
If ... | Return the input parameters requested by child objects.
The output of this method is a :class:`~sklearn.utils.Bunch`, which includes the
metadata for all methods of each child object that is used in the router's
`caller` method.
If the router is also a consumer, it also checks for warn... | route_params | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def validate_metadata(self, *, method, params):
"""Validate given metadata for a method.
This raises a ``TypeError`` if some of the passed metadata are not
understood by child objects.
Parameters
----------
method : str
The name of the method for which the p... | Validate given metadata for a method.
This raises a ``TypeError`` if some of the passed metadata are not
understood by child objects.
Parameters
----------
method : str
The name of the method for which the parameters are requested and
routed. If called i... | validate_metadata | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def get_routing_for_object(obj=None):
"""Get a ``Metadata{Router, Request}`` instance from the given object.
This function returns a
:class:`~sklearn.utils.metadata_routing.MetadataRouter` or a
:class:`~sklearn.utils.metadata_routing.MetadataRequest` from the given input.
This function always retu... | Get a ``Metadata{Router, Request}`` instance from the given object.
This function returns a
:class:`~sklearn.utils.metadata_routing.MetadataRouter` or a
:class:`~sklearn.utils.metadata_routing.MetadataRequest` from the given input.
This function always returns a copy or an instance constructed from th... | get_routing_for_object | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def func(*args, **kw):
"""Updates the request for provided parameters
This docstring is overwritten below.
See REQUESTER_DOC for expected functionality
"""
if not _routing_enabled():
raise RuntimeError(
"This method is only... | Updates the request for provided parameters
This docstring is overwritten below.
See REQUESTER_DOC for expected functionality
| func | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def __init_subclass__(cls, **kwargs):
"""Set the ``set_{method}_request`` methods.
This uses PEP-487 [1]_ to set the ``set_{method}_request`` methods. It
looks for the information available in the set default values which are
set using ``__metadata_request__*`` class attributes, or infe... | Set the ``set_{method}_request`` methods.
This uses PEP-487 [1]_ to set the ``set_{method}_request`` methods. It
looks for the information available in the set default values which are
set using ``__metadata_request__*`` class attributes, or inferred
from method signatures.
The... | __init_subclass__ | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _build_request_for_signature(cls, router, method):
"""Build the `MethodMetadataRequest` for a method using its signature.
This method takes all arguments from the method signature and uses
``None`` as their default request value, except ``X``, ``y``, ``Y``,
``Xt``, ``yt``, ``*args``... | Build the `MethodMetadataRequest` for a method using its signature.
This method takes all arguments from the method signature and uses
``None`` as their default request value, except ``X``, ``y``, ``Y``,
``Xt``, ``yt``, ``*args``, and ``**kwargs``.
Parameters
----------
... | _build_request_for_signature | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _get_default_requests(cls):
"""Collect default request values.
This method combines the information present in ``__metadata_request__*``
class attributes, as well as determining request keys from method
signatures.
"""
requests = MetadataRequest(owner=cls.__name__)
... | Collect default request values.
This method combines the information present in ``__metadata_request__*``
class attributes, as well as determining request keys from method
signatures.
| _get_default_requests | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def _get_metadata_request(self):
"""Get requested data properties.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
Returns
-------
request : MetadataRequest
A :class:`~sklearn.utils.metadata_routing.MetadataRequest` inst... | Get requested data properties.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
Returns
-------
request : MetadataRequest
A :class:`~sklearn.utils.metadata_routing.MetadataRequest` instance.
| _get_metadata_request | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def process_routing(_obj, _method, /, **kwargs):
"""Validate and route input parameters.
This function is used inside a router's method, e.g. :term:`fit`,
to validate the metadata and handle the routing.
Assuming this signature of a router's fit method:
``fit(self, X, y, sample_weight=None, **fit_... | Validate and route input parameters.
This function is used inside a router's method, e.g. :term:`fit`,
to validate the metadata and handle the routing.
Assuming this signature of a router's fit method:
``fit(self, X, y, sample_weight=None, **fit_params)``,
a call to this function would be:
``p... | process_routing | python | scikit-learn/scikit-learn | sklearn/utils/_metadata_requests.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py | BSD-3-Clause |
def is_scalar_nan(x):
"""Test if x is NaN.
This function is meant to overcome the issue that np.isnan does not allow
non-numerical types as input, and that np.nan is not float('nan').
Parameters
----------
x : any type
Any scalar value.
Returns
-------
bool
Returns... | Test if x is NaN.
This function is meant to overcome the issue that np.isnan does not allow
non-numerical types as input, and that np.nan is not float('nan').
Parameters
----------
x : any type
Any scalar value.
Returns
-------
bool
Returns true if x is NaN, and false ... | is_scalar_nan | python | scikit-learn/scikit-learn | sklearn/utils/_missing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_missing.py | BSD-3-Clause |
def is_pandas_na(x):
"""Test if x is pandas.NA.
We intentionally do not use this function to return `True` for `pd.NA` in
`is_scalar_nan`, because estimators that support `pd.NA` are the exception
rather than the rule at the moment. When `pd.NA` is more universally
supported, we may reconsider this... | Test if x is pandas.NA.
We intentionally do not use this function to return `True` for `pd.NA` in
`is_scalar_nan`, because estimators that support `pd.NA` are the exception
rather than the rule at the moment. When `pd.NA` is more universally
supported, we may reconsider this decision.
Parameters
... | is_pandas_na | python | scikit-learn/scikit-learn | sklearn/utils/_missing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_missing.py | BSD-3-Clause |
def _check_X_y(self, X, y=None, should_be_fitted=True):
"""Validate X and y and make extra check.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data set.
`X` is checked only if `check_X` is not `None` (default is None).
y : arr... | Validate X and y and make extra check.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data set.
`X` is checked only if `check_X` is not `None` (default is None).
y : array-like of shape (n_samples), default=None
The correspo... | _check_X_y | python | scikit-learn/scikit-learn | sklearn/utils/_mocking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None, **fit_params):
"""Fit classifier.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples and
`n_features` is the number of features.
y : ar... | Fit classifier.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples and
`n_features` is the number of features.
y : array-like of shape (n_samples, n_outputs) or (n_samples,), ... | fit | python | scikit-learn/scikit-learn | sklearn/utils/_mocking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py | BSD-3-Clause |
def predict(self, X):
"""Predict the first class seen in `classes_`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input data.
Returns
-------
preds : ndarray of shape (n_samples,)
Predictions of the first clas... | Predict the first class seen in `classes_`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input data.
Returns
-------
preds : ndarray of shape (n_samples,)
Predictions of the first class seen in `classes_`.
| predict | python | scikit-learn/scikit-learn | sklearn/utils/_mocking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py | BSD-3-Clause |
def predict_proba(self, X):
"""Predict probabilities for each class.
Here, the dummy classifier will provide a probability of 1 for the
first class of `classes_` and 0 otherwise.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input... | Predict probabilities for each class.
Here, the dummy classifier will provide a probability of 1 for the
first class of `classes_` and 0 otherwise.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input data.
Returns
-------... | predict_proba | python | scikit-learn/scikit-learn | sklearn/utils/_mocking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py | BSD-3-Clause |
def decision_function(self, X):
"""Confidence score.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input data.
Returns
-------
decision : ndarray of shape (n_samples,) if n_classes == 2\
else (n_samples, n_... | Confidence score.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input data.
Returns
-------
decision : ndarray of shape (n_samples,) if n_classes == 2 else (n_samples, n_classes)
Confidence score.
... | decision_function | python | scikit-learn/scikit-learn | sklearn/utils/_mocking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py | BSD-3-Clause |
def score(self, X=None, Y=None):
"""Fake score.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data, where `n_samples` is the number of samples and
`n_features` is the number of features.
Y : array-like of shape (n_samples, n... | Fake score.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data, where `n_samples` is the number of samples and
`n_features` is the number of features.
Y : array-like of shape (n_samples, n_output) or (n_samples,)
Target ... | score | python | scikit-learn/scikit-learn | sklearn/utils/_mocking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py | BSD-3-Clause |
def check_matplotlib_support(caller_name):
"""Raise ImportError with detailed error message if mpl is not installed.
Plot utilities like any of the Display's plotting functions should lazily import
matplotlib and call this helper before any computation.
Parameters
----------
caller_name : str
... | Raise ImportError with detailed error message if mpl is not installed.
Plot utilities like any of the Display's plotting functions should lazily import
matplotlib and call this helper before any computation.
Parameters
----------
caller_name : str
The name of the caller that requires matpl... | check_matplotlib_support | python | scikit-learn/scikit-learn | sklearn/utils/_optional_dependencies.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_optional_dependencies.py | BSD-3-Clause |
def check_pandas_support(caller_name):
"""Raise ImportError with detailed error message if pandas is not installed.
Plot utilities like :func:`fetch_openml` should lazily import
pandas and call this helper before any computation.
Parameters
----------
caller_name : str
The name of the ... | Raise ImportError with detailed error message if pandas is not installed.
Plot utilities like :func:`fetch_openml` should lazily import
pandas and call this helper before any computation.
Parameters
----------
caller_name : str
The name of the caller that requires pandas.
Returns
... | check_pandas_support | python | scikit-learn/scikit-learn | sklearn/utils/_optional_dependencies.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_optional_dependencies.py | BSD-3-Clause |
def validate_parameter_constraints(parameter_constraints, params, caller_name):
"""Validate types and values of given parameters.
Parameters
----------
parameter_constraints : dict or {"no_validation"}
If "no_validation", validation is skipped for this parameter.
If a dict, it must be ... | Validate types and values of given parameters.
Parameters
----------
parameter_constraints : dict or {"no_validation"}
If "no_validation", validation is skipped for this parameter.
If a dict, it must be a dictionary `param_name: list of constraints`.
A parameter is valid if it sati... | validate_parameter_constraints | python | scikit-learn/scikit-learn | sklearn/utils/_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py | BSD-3-Clause |
def make_constraint(constraint):
"""Convert the constraint into the appropriate Constraint object.
Parameters
----------
constraint : object
The constraint to convert.
Returns
-------
constraint : instance of _Constraint
The converted constraint.
"""
if isinstance(c... | Convert the constraint into the appropriate Constraint object.
Parameters
----------
constraint : object
The constraint to convert.
Returns
-------
constraint : instance of _Constraint
The converted constraint.
| make_constraint | python | scikit-learn/scikit-learn | sklearn/utils/_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py | BSD-3-Clause |
def validate_params(parameter_constraints, *, prefer_skip_nested_validation):
"""Decorator to validate types and values of functions and methods.
Parameters
----------
parameter_constraints : dict
A dictionary `param_name: list of constraints`. See the docstring of
`validate_parameter_c... | Decorator to validate types and values of functions and methods.
Parameters
----------
parameter_constraints : dict
A dictionary `param_name: list of constraints`. See the docstring of
`validate_parameter_constraints` for a description of the accepted constraints.
Note that the *ar... | validate_params | python | scikit-learn/scikit-learn | sklearn/utils/_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py | BSD-3-Clause |
def _type_name(t):
"""Convert type into human readable string."""
module = t.__module__
qualname = t.__qualname__
if module == "builtins":
return qualname
elif t == Real:
return "float"
elif t == Integral:
return "int"
return f"{module}.{qualname}" | Convert type into human readable string. | _type_name | python | scikit-learn/scikit-learn | sklearn/utils/_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py | BSD-3-Clause |
def is_satisfied_by(self, val):
"""Whether or not a value satisfies the constraint.
Parameters
----------
val : object
The value to check.
Returns
-------
is_satisfied : bool
Whether or not the constraint is satisfied by this value.
... | Whether or not a value satisfies the constraint.
Parameters
----------
val : object
The value to check.
Returns
-------
is_satisfied : bool
Whether or not the constraint is satisfied by this value.
| is_satisfied_by | python | scikit-learn/scikit-learn | sklearn/utils/_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py | BSD-3-Clause |
def _mark_if_deprecated(self, option):
"""Add a deprecated mark to an option if needed."""
option_str = f"{option!r}"
if option in self.deprecated:
option_str = f"{option_str} (deprecated)"
return option_str | Add a deprecated mark to an option if needed. | _mark_if_deprecated | python | scikit-learn/scikit-learn | sklearn/utils/_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py | BSD-3-Clause |
def generate_invalid_param_val(constraint):
"""Return a value that does not satisfy the constraint.
Raises a NotImplementedError if there exists no invalid value for this constraint.
This is only useful for testing purpose.
Parameters
----------
constraint : _Constraint instance
The c... | Return a value that does not satisfy the constraint.
Raises a NotImplementedError if there exists no invalid value for this constraint.
This is only useful for testing purpose.
Parameters
----------
constraint : _Constraint instance
The constraint to generate a value for.
Returns
... | generate_invalid_param_val | python | scikit-learn/scikit-learn | sklearn/utils/_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py | BSD-3-Clause |
def generate_valid_param(constraint):
"""Return a value that does satisfy a constraint.
This is only useful for testing purpose.
Parameters
----------
constraint : Constraint instance
The constraint to generate a value for.
Returns
-------
val : object
A value that doe... | Return a value that does satisfy a constraint.
This is only useful for testing purpose.
Parameters
----------
constraint : Constraint instance
The constraint to generate a value for.
Returns
-------
val : object
A value that does satisfy the constraint.
| generate_valid_param | python | scikit-learn/scikit-learn | sklearn/utils/_param_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py | BSD-3-Clause |
def _get_legend_label(curve_legend_metric, curve_name, legend_metric_name):
"""Helper to get legend label using `name` and `legend_metric`"""
if curve_legend_metric is not None and curve_name is not None:
label = f"{curve_name} ({legend_metric_name} = {curve_legend_metric:0.2f})"
eli... | Helper to get legend label using `name` and `legend_metric` | _get_legend_label | python | scikit-learn/scikit-learn | sklearn/utils/_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py | BSD-3-Clause |
def _validate_curve_kwargs(
n_curves,
name,
legend_metric,
legend_metric_name,
curve_kwargs,
**kwargs,
):
"""Get validated line kwargs for each curve.
Parameters
----------
n_curves : int
Number of curves.
name : l... | Get validated line kwargs for each curve.
Parameters
----------
n_curves : int
Number of curves.
name : list of str or None
Name for labeling legend entries.
legend_metric : dict
Dictionary with "mean" and "std" keys, or "metric" key of metr... | _validate_curve_kwargs | python | scikit-learn/scikit-learn | sklearn/utils/_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py | BSD-3-Clause |
def _validate_score_name(score_name, scoring, negate_score):
"""Validate the `score_name` parameter.
If `score_name` is provided, we just return it as-is.
If `score_name` is `None`, we use `Score` if `negate_score` is `False` and
`Negative score` otherwise.
If `score_name` is a string or a callable... | Validate the `score_name` parameter.
If `score_name` is provided, we just return it as-is.
If `score_name` is `None`, we use `Score` if `negate_score` is `False` and
`Negative score` otherwise.
If `score_name` is a string or a callable, we infer the name. We replace `_` by
spaces and capitalize the... | _validate_score_name | python | scikit-learn/scikit-learn | sklearn/utils/_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py | BSD-3-Clause |
def _interval_max_min_ratio(data):
"""Compute the ratio between the largest and smallest inter-point distances.
A value larger than 5 typically indicates that the parameter range would
better be displayed with a log scale while a linear scale would be more
suitable otherwise.
"""
diff = np.diff... | Compute the ratio between the largest and smallest inter-point distances.
A value larger than 5 typically indicates that the parameter range would
better be displayed with a log scale while a linear scale would be more
suitable otherwise.
| _interval_max_min_ratio | python | scikit-learn/scikit-learn | sklearn/utils/_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py | BSD-3-Clause |
def _validate_style_kwargs(default_style_kwargs, user_style_kwargs):
"""Create valid style kwargs by avoiding Matplotlib alias errors.
Matplotlib raises an error when, for example, 'color' and 'c', or 'linestyle' and
'ls', are specified together. To avoid this, we automatically keep only the one
specif... | Create valid style kwargs by avoiding Matplotlib alias errors.
Matplotlib raises an error when, for example, 'color' and 'c', or 'linestyle' and
'ls', are specified together. To avoid this, we automatically keep only the one
specified by the user and raise an error if the user specifies both.
Paramete... | _validate_style_kwargs | python | scikit-learn/scikit-learn | sklearn/utils/_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py | BSD-3-Clause |
def _despine(ax):
"""Remove the top and right spines of the plot.
Parameters
----------
ax : matplotlib.axes.Axes
The axes of the plot to despine.
"""
for s in ["top", "right"]:
ax.spines[s].set_visible(False)
for s in ["bottom", "left"]:
ax.spines[s].set_bounds(0, 1... | Remove the top and right spines of the plot.
Parameters
----------
ax : matplotlib.axes.Axes
The axes of the plot to despine.
| _despine | python | scikit-learn/scikit-learn | sklearn/utils/_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py | BSD-3-Clause |
def _convert_to_list_leaving_none(param):
"""Convert parameters to a list, leaving `None` as is."""
if param is None:
return None
if isinstance(param, list):
return param
return [param] | Convert parameters to a list, leaving `None` as is. | _convert_to_list_leaving_none | python | scikit-learn/scikit-learn | sklearn/utils/_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py | BSD-3-Clause |
def _check_param_lengths(required, optional, class_name):
"""Check required and optional parameters are of the same length."""
optional_provided = {}
for name, param in optional.items():
if isinstance(param, list):
optional_provided[name] = param
all_params = {**required, **optional... | Check required and optional parameters are of the same length. | _check_param_lengths | python | scikit-learn/scikit-learn | sklearn/utils/_plotting.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py | BSD-3-Clause |
def _changed_params(estimator):
"""Return dict (param_name: value) of parameters that were given to
estimator with non-default values."""
params = estimator.get_params(deep=False)
init_func = getattr(estimator.__init__, "deprecated_original", estimator.__init__)
init_params = inspect.signature(init... | Return dict (param_name: value) of parameters that were given to
estimator with non-default values. | _changed_params | python | scikit-learn/scikit-learn | sklearn/utils/_pprint.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py | BSD-3-Clause |
def _format_params_or_dict_items(
self, object, stream, indent, allowance, context, level, is_dict
):
"""Format dict items or parameters respecting the compact=True
parameter. For some reason, the builtin rendering of dict items doesn't
respect compact=True and will use one line per ... | Format dict items or parameters respecting the compact=True
parameter. For some reason, the builtin rendering of dict items doesn't
respect compact=True and will use one line per key-value if all cannot
fit in a single line.
Dict items will be rendered as <'key': value> while params will... | _format_params_or_dict_items | python | scikit-learn/scikit-learn | sklearn/utils/_pprint.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py | BSD-3-Clause |
def _format_items(self, items, stream, indent, allowance, context, level):
"""Format the items of an iterable (list, tuple...). Same as the
built-in _format_items, with support for ellipsis if the number of
elements is greater than self.n_max_elements_to_show.
"""
write = stream.... | Format the items of an iterable (list, tuple...). Same as the
built-in _format_items, with support for ellipsis if the number of
elements is greater than self.n_max_elements_to_show.
| _format_items | python | scikit-learn/scikit-learn | sklearn/utils/_pprint.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py | BSD-3-Clause |
def _pprint_key_val_tuple(self, object, stream, indent, allowance, context, level):
"""Pretty printing for key-value tuples from dict or parameters."""
k, v = object
rep = self._repr(k, context, level)
if isinstance(object, KeyValTupleParam):
rep = rep.strip("'")
... | Pretty printing for key-value tuples from dict or parameters. | _pprint_key_val_tuple | python | scikit-learn/scikit-learn | sklearn/utils/_pprint.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py | BSD-3-Clause |
def _safe_repr(object, context, maxlevels, level, changed_only=False):
"""Same as the builtin _safe_repr, with added support for Estimator
objects."""
typ = type(object)
if typ in pprint._builtin_scalars:
return repr(object), True, False
r = getattr(typ, "__repr__", None)
if issubclass... | Same as the builtin _safe_repr, with added support for Estimator
objects. | _safe_repr | python | scikit-learn/scikit-learn | sklearn/utils/_pprint.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py | BSD-3-Clause |
def _process_predict_proba(*, y_pred, target_type, classes, pos_label):
"""Get the response values when the response method is `predict_proba`.
This function process the `y_pred` array in the binary and multi-label cases.
In the binary case, it selects the column corresponding to the positive
class. In... | Get the response values when the response method is `predict_proba`.
This function process the `y_pred` array in the binary and multi-label cases.
In the binary case, it selects the column corresponding to the positive
class. In the multi-label case, it stacks the predictions if they are not
in the "co... | _process_predict_proba | python | scikit-learn/scikit-learn | sklearn/utils/_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_response.py | BSD-3-Clause |
def _process_decision_function(*, y_pred, target_type, classes, pos_label):
"""Get the response values when the response method is `decision_function`.
This function process the `y_pred` array in the binary and multi-label cases.
In the binary case, it inverts the sign of the score if the positive label
... | Get the response values when the response method is `decision_function`.
This function process the `y_pred` array in the binary and multi-label cases.
In the binary case, it inverts the sign of the score if the positive label
is not `classes[1]`. In the multi-label case, it stacks the predictions if
th... | _process_decision_function | python | scikit-learn/scikit-learn | sklearn/utils/_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_response.py | BSD-3-Clause |
def _get_response_values(
estimator,
X,
response_method,
pos_label=None,
return_response_method_used=False,
):
"""Compute the response values of a classifier, an outlier detector, or a regressor.
The response values are predictions such that it follows the following shape:
- for binary... | Compute the response values of a classifier, an outlier detector, or a regressor.
The response values are predictions such that it follows the following shape:
- for binary classification, it is a 1d array of shape `(n_samples,)`;
- for multiclass classification, it is a 2d array of shape `(n_samples, n_c... | _get_response_values | python | scikit-learn/scikit-learn | sklearn/utils/_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_response.py | BSD-3-Clause |
def _get_response_values_binary(
estimator, X, response_method, pos_label=None, return_response_method_used=False
):
"""Compute the response values of a binary classifier.
Parameters
----------
estimator : estimator instance
Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
... | Compute the response values of a binary classifier.
Parameters
----------
estimator : estimator instance
Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
in which the last estimator is a binary classifier.
X : {array-like, sparse matrix} of shape (n_samples, n_features... | _get_response_values_binary | python | scikit-learn/scikit-learn | sklearn/utils/_response.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_response.py | BSD-3-Clause |
def create_container(self, X_output, X_original, columns, inplace=False):
"""Create container from `X_output` with additional metadata.
Parameters
----------
X_output : {ndarray, dataframe}
Data to wrap.
X_original : {ndarray, dataframe}
Original input d... | Create container from `X_output` with additional metadata.
Parameters
----------
X_output : {ndarray, dataframe}
Data to wrap.
X_original : {ndarray, dataframe}
Original input dataframe. This is used to extract the metadata that should
be passed to `... | create_container | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def is_supported_container(self, X):
"""Return True if X is a supported container.
Parameters
----------
Xs: container
Containers to be checked.
Returns
-------
is_supported_container : bool
True if X is a supported container.
""" | Return True if X is a supported container.
Parameters
----------
Xs: container
Containers to be checked.
Returns
-------
is_supported_container : bool
True if X is a supported container.
| is_supported_container | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def rename_columns(self, X, columns):
"""Rename columns in `X`.
Parameters
----------
X : container
Container which columns is updated.
columns : ndarray of str
Columns to update the `X`'s columns with.
Returns
-------
updated_co... | Rename columns in `X`.
Parameters
----------
X : container
Container which columns is updated.
columns : ndarray of str
Columns to update the `X`'s columns with.
Returns
-------
updated_container : container
Container with ne... | rename_columns | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def hstack(self, Xs):
"""Stack containers horizontally (column-wise).
Parameters
----------
Xs : list of containers
List of containers to stack.
Returns
-------
stacked_Xs : container
Stacked containers.
""" | Stack containers horizontally (column-wise).
Parameters
----------
Xs : list of containers
List of containers to stack.
Returns
-------
stacked_Xs : container
Stacked containers.
| hstack | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def _get_adapter_from_container(container):
"""Get the adapter that knows how to handle such container.
See :class:`sklearn.utils._set_output.ContainerAdapterProtocol` for more
details.
"""
module_name = container.__class__.__module__.split(".")[0]
try:
return ADAPTERS_MANAGER.adapters[... | Get the adapter that knows how to handle such container.
See :class:`sklearn.utils._set_output.ContainerAdapterProtocol` for more
details.
| _get_adapter_from_container | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def _get_output_config(method, estimator=None):
"""Get output config based on estimator and global configuration.
Parameters
----------
method : {"transform"}
Estimator's method for which the output container is looked up.
estimator : estimator instance or None
Estimator to get the... | Get output config based on estimator and global configuration.
Parameters
----------
method : {"transform"}
Estimator's method for which the output container is looked up.
estimator : estimator instance or None
Estimator to get the output configuration from. If `None`, check global
... | _get_output_config | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def _wrap_data_with_container(method, data_to_wrap, original_input, estimator):
"""Wrap output with container based on an estimator's or global config.
Parameters
----------
method : {"transform"}
Estimator's method to get container output for.
data_to_wrap : {ndarray, dataframe}
D... | Wrap output with container based on an estimator's or global config.
Parameters
----------
method : {"transform"}
Estimator's method to get container output for.
data_to_wrap : {ndarray, dataframe}
Data to wrap with container.
original_input : {ndarray, dataframe}
Original... | _wrap_data_with_container | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def _wrap_method_output(f, method):
"""Wrapper used by `_SetOutputMixin` to automatically wrap methods."""
@wraps(f)
def wrapped(self, X, *args, **kwargs):
data_to_wrap = f(self, X, *args, **kwargs)
if isinstance(data_to_wrap, tuple):
# only wrap the first output for cross decom... | Wrapper used by `_SetOutputMixin` to automatically wrap methods. | _wrap_method_output | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def _auto_wrap_is_configured(estimator):
"""Return True if estimator is configured for auto-wrapping the transform method.
`_SetOutputMixin` sets `_sklearn_auto_wrap_output_keys` to `set()` if auto wrapping
is manually disabled.
"""
auto_wrap_output_keys = getattr(estimator, "_sklearn_auto_wrap_out... | Return True if estimator is configured for auto-wrapping the transform method.
`_SetOutputMixin` sets `_sklearn_auto_wrap_output_keys` to `set()` if auto wrapping
is manually disabled.
| _auto_wrap_is_configured | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def _safe_set_output(estimator, *, transform=None):
"""Safely call estimator.set_output and error if it not available.
This is used by meta-estimators to set the output for child estimators.
Parameters
----------
estimator : estimator instance
Estimator instance.
transform : {"default... | Safely call estimator.set_output and error if it not available.
This is used by meta-estimators to set the output for child estimators.
Parameters
----------
estimator : estimator instance
Estimator instance.
transform : {"default", "pandas", "polars"}, default=None
Configure outp... | _safe_set_output | python | scikit-learn/scikit-learn | sklearn/utils/_set_output.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py | BSD-3-Clause |
def _get_sys_info():
"""System information
Returns
-------
sys_info : dict
system and Python version information
"""
python = sys.version.replace("\n", " ")
blob = [
("python", python),
("executable", sys.executable),
("machine", platform.platform()),
]... | System information
Returns
-------
sys_info : dict
system and Python version information
| _get_sys_info | python | scikit-learn/scikit-learn | sklearn/utils/_show_versions.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_show_versions.py | BSD-3-Clause |
def _get_deps_info():
"""Overview of the installed version of main dependencies
This function does not import the modules to collect the version numbers
but instead relies on standard Python package metadata.
Returns
-------
deps_info: dict
version information on relevant Python librar... | Overview of the installed version of main dependencies
This function does not import the modules to collect the version numbers
but instead relies on standard Python package metadata.
Returns
-------
deps_info: dict
version information on relevant Python libraries
| _get_deps_info | python | scikit-learn/scikit-learn | sklearn/utils/_show_versions.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_show_versions.py | BSD-3-Clause |
def show_versions():
"""Print useful debugging information"
.. versionadded:: 0.20
Examples
--------
>>> from sklearn import show_versions
>>> show_versions() # doctest: +SKIP
"""
sys_info = _get_sys_info()
deps_info = _get_deps_info()
print("\nSystem:")
for k, stat in s... | Print useful debugging information"
.. versionadded:: 0.20
Examples
--------
>>> from sklearn import show_versions
>>> show_versions() # doctest: +SKIP
| show_versions | python | scikit-learn/scikit-learn | sklearn/utils/_show_versions.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_show_versions.py | BSD-3-Clause |
def default_tags(estimator) -> Tags:
"""Get the default tags for an estimator.
This ignores any ``__sklearn_tags__`` method that the estimator may have.
If the estimator is a classifier or a regressor, ``target_tags.required``
will be set to ``True``, otherwise it will be set to ``False``.
``tran... | Get the default tags for an estimator.
This ignores any ``__sklearn_tags__`` method that the estimator may have.
If the estimator is a classifier or a regressor, ``target_tags.required``
will be set to ``True``, otherwise it will be set to ``False``.
``transformer_tags`` will be set to :class:`~.skle... | default_tags | python | scikit-learn/scikit-learn | sklearn/utils/_tags.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_tags.py | BSD-3-Clause |
def get_tags(estimator) -> Tags:
"""Get estimator tags.
:class:`~sklearn.BaseEstimator` provides the estimator tags machinery.
However, if an estimator does not inherit from this base class, we should
fall-back to the default tags.
For scikit-learn built-in estimators, we should still rely on
... | Get estimator tags.
:class:`~sklearn.BaseEstimator` provides the estimator tags machinery.
However, if an estimator does not inherit from this base class, we should
fall-back to the default tags.
For scikit-learn built-in estimators, we should still rely on
`self.__sklearn_tags__()`. `get_tags(est... | get_tags | python | scikit-learn/scikit-learn | sklearn/utils/_tags.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_tags.py | BSD-3-Clause |
def ignore_warnings(obj=None, category=Warning):
"""Context manager and decorator to ignore warnings.
Note: Using this (in both variants) will clear all warnings
from all python modules loaded. In case you need to test
cross-module-warning-logging, this is not your tool of choice.
Parameters
-... | Context manager and decorator to ignore warnings.
Note: Using this (in both variants) will clear all warnings
from all python modules loaded. In case you need to test
cross-module-warning-logging, this is not your tool of choice.
Parameters
----------
obj : callable, default=None
calla... | ignore_warnings | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def __call__(self, fn):
"""Decorator to catch and hide warnings without visual nesting."""
@wraps(fn)
def wrapper(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore", self.category)
return fn(*args, **kwargs)
retu... | Decorator to catch and hide warnings without visual nesting. | __call__ | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def assert_allclose(
actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True
):
"""dtype-aware variant of numpy.testing.assert_allclose
This variant introspects the least precise floating point dtype
in the input argument and automatically sets the relative tolerance
paramete... | dtype-aware variant of numpy.testing.assert_allclose
This variant introspects the least precise floating point dtype
in the input argument and automatically sets the relative tolerance
parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64
in scikit-learn).
`atol` is always left to 0.... | assert_allclose | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def assert_allclose_dense_sparse(x, y, rtol=1e-07, atol=1e-9, err_msg=""):
"""Assert allclose for sparse and dense data.
Both x and y need to be either sparse or dense, they
can't be mixed.
Parameters
----------
x : {array-like, sparse matrix}
First array to compare.
y : {array-li... | Assert allclose for sparse and dense data.
Both x and y need to be either sparse or dense, they
can't be mixed.
Parameters
----------
x : {array-like, sparse matrix}
First array to compare.
y : {array-like, sparse matrix}
Second array to compare.
rtol : float, default=1e-... | assert_allclose_dense_sparse | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def _delete_folder(folder_path, warn=False):
"""Utility function to cleanup a temporary folder if still existing.
Copy from joblib.pool (for independence).
"""
try:
if os.path.exists(folder_path):
# This can fail under windows,
# but will succeed when called by atexit
... | Utility function to cleanup a temporary folder if still existing.
Copy from joblib.pool (for independence).
| _delete_folder | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def create_memmap_backed_data(data, mmap_mode="r", return_folder=False):
"""
Parameters
----------
data
mmap_mode : str, default='r'
return_folder : bool, default=False
"""
temp_folder = tempfile.mkdtemp(prefix="sklearn_testing_")
atexit.register(functools.partial(_delete_folder, te... |
Parameters
----------
data
mmap_mode : str, default='r'
return_folder : bool, default=False
| create_memmap_backed_data | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def _get_func_name(func):
"""Get function full name.
Parameters
----------
func : callable
The function object.
Returns
-------
name : str
The function name.
"""
parts = []
module = inspect.getmodule(func)
if module:
parts.append(module.__name__)
... | Get function full name.
Parameters
----------
func : callable
The function object.
Returns
-------
name : str
The function name.
| _get_func_name | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def check_docstring_parameters(func, doc=None, ignore=None):
"""Helper to check docstring.
Parameters
----------
func : callable
The function object to test.
doc : str, default=None
Docstring if it is passed manually to the test.
ignore : list, default=None
Parameters to... | Helper to check docstring.
Parameters
----------
func : callable
The function object to test.
doc : str, default=None
Docstring if it is passed manually to the test.
ignore : list, default=None
Parameters to ignore.
Returns
-------
incorrect : list
A lis... | check_docstring_parameters | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def _check_item_included(item_name, args):
"""Helper to check if item should be included in checking."""
if args.include is not True and item_name not in args.include:
return False
if args.exclude is not None and item_name in args.exclude:
return False
return True | Helper to check if item should be included in checking. | _check_item_included | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def _get_diff_msg(docstrings_grouped):
"""Get message showing the difference between type/desc docstrings of all objects.
`docstrings_grouped` keys should be the type/desc docstrings and values are a list
of objects with that docstring. Objects with the same type/desc docstring are
thus grouped togethe... | Get message showing the difference between type/desc docstrings of all objects.
`docstrings_grouped` keys should be the type/desc docstrings and values are a list
of objects with that docstring. Objects with the same type/desc docstring are
thus grouped together.
| _get_diff_msg | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def _check_consistency_items(
items_docs,
type_or_desc,
section,
n_objects,
descr_regex_pattern="",
ignore_types=tuple(),
):
"""Helper to check docstring consistency of all `items_docs`.
If item is not present in all objects, checking is skipped and warning raised.
If `regex` provid... | Helper to check docstring consistency of all `items_docs`.
If item is not present in all objects, checking is skipped and warning raised.
If `regex` provided, match descriptions to all descriptions.
Parameters
----------
items_doc : dict of dict of str
Dictionary where the key is the strin... | _check_consistency_items | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def assert_docstring_consistency(
objects,
include_params=False,
exclude_params=None,
include_attrs=False,
exclude_attrs=None,
include_returns=False,
exclude_returns=None,
descr_regex_pattern=None,
ignore_types=tuple(),
):
r"""Check consistency between docstring parameters/attrib... | Check consistency between docstring parameters/attributes/returns of objects.
Checks if parameters/attributes/returns have the same type specification and
description (ignoring whitespace) across `objects`. Intended to be used for
related classes/functions/data descriptors.
Entries that do not appear ... | assert_docstring_consistency | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def assert_run_python_script_without_output(source_code, pattern=".+", timeout=60):
"""Utility to check assertions in an independent Python subprocess.
The script provided in the source code should return 0 and the stdtout +
stderr should not match the pattern `pattern`.
This is a port from cloudpickl... | Utility to check assertions in an independent Python subprocess.
The script provided in the source code should return 0 and the stdtout +
stderr should not match the pattern `pattern`.
This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle
Parameters
----------
source_code :... | assert_run_python_script_without_output | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def _convert_container(
container,
constructor_name,
columns_name=None,
dtype=None,
minversion=None,
categorical_feature_names=None,
):
"""Convert a given container to a specific array-like with a dtype.
Parameters
----------
container : array-like
The container to conve... | Convert a given container to a specific array-like with a dtype.
Parameters
----------
container : array-like
The container to convert.
constructor_name : {"list", "tuple", "array", "sparse", "dataframe", "series", "index", "slice", "sparse_csr", "sparse_csc", "sparse_cs... | _convert_container | python | scikit-learn/scikit-learn | sklearn/utils/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py | BSD-3-Clause |
def _attach_unique(y):
"""Attach unique values of y to y and return the result.
The result is a view of y, and the metadata (unique) is not attached to y.
"""
if not isinstance(y, np.ndarray):
return y
try:
# avoid recalculating unique in nested calls.
if "unique" in y.dtype... | Attach unique values of y to y and return the result.
The result is a view of y, and the metadata (unique) is not attached to y.
| _attach_unique | python | scikit-learn/scikit-learn | sklearn/utils/_unique.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_unique.py | BSD-3-Clause |
def attach_unique(*ys, return_tuple=False):
"""Attach unique values of ys to ys and return the results.
The result is a view of y, and the metadata (unique) is not attached to y.
IMPORTANT: The output of this function should NEVER be returned in functions.
This is to avoid this pattern:
.. code::... | Attach unique values of ys to ys and return the results.
The result is a view of y, and the metadata (unique) is not attached to y.
IMPORTANT: The output of this function should NEVER be returned in functions.
This is to avoid this pattern:
.. code:: python
y = np.array([1, 2, 3])
y ... | attach_unique | python | scikit-learn/scikit-learn | sklearn/utils/_unique.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_unique.py | BSD-3-Clause |
def _cached_unique(y, xp=None):
"""Return the unique values of y.
Use the cached values from dtype.metadata if present.
This function does NOT cache the values in y, i.e. it doesn't change y.
Call `attach_unique` to attach the unique values to y.
"""
try:
if y.dtype.metadata is not No... | Return the unique values of y.
Use the cached values from dtype.metadata if present.
This function does NOT cache the values in y, i.e. it doesn't change y.
Call `attach_unique` to attach the unique values to y.
| _cached_unique | python | scikit-learn/scikit-learn | sklearn/utils/_unique.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_unique.py | BSD-3-Clause |
def cached_unique(*ys, xp=None):
"""Return the unique values of ys.
Use the cached values from dtype.metadata if present.
This function does NOT cache the values in y, i.e. it doesn't change y.
Call `attach_unique` to attach the unique values to y.
Parameters
----------
*ys : sequence of... | Return the unique values of ys.
Use the cached values from dtype.metadata if present.
This function does NOT cache the values in y, i.e. it doesn't change y.
Call `attach_unique` to attach the unique values to y.
Parameters
----------
*ys : sequence of array-like
Input data arrays.
... | cached_unique | python | scikit-learn/scikit-learn | sklearn/utils/_unique.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_unique.py | BSD-3-Clause |
def _message_with_time(source, message, time):
"""Create one line message for logging purposes.
Parameters
----------
source : str
String indicating the source or the reference of the message.
message : str
Short message.
time : int
Time in seconds.
"""
start_m... | Create one line message for logging purposes.
Parameters
----------
source : str
String indicating the source or the reference of the message.
message : str
Short message.
time : int
Time in seconds.
| _message_with_time | python | scikit-learn/scikit-learn | sklearn/utils/_user_interface.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_user_interface.py | BSD-3-Clause |
def _print_elapsed_time(source, message=None):
"""Log elapsed time to stdout when the context is exited.
Parameters
----------
source : str
String indicating the source or the reference of the message.
message : str, default=None
Short message. If None, nothing will be printed.
... | Log elapsed time to stdout when the context is exited.
Parameters
----------
source : str
String indicating the source or the reference of the message.
message : str, default=None
Short message. If None, nothing will be printed.
Returns
-------
context_manager
Prin... | _print_elapsed_time | python | scikit-learn/scikit-learn | sklearn/utils/_user_interface.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_user_interface.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.