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 check_random_state(seed):
"""Turn seed into a np.random.RandomState instance.
Parameters
----------
seed : None, int or instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.... | Turn seed into a np.random.RandomState instance.
Parameters
----------
seed : None, int or instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomS... | check_random_state | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def has_fit_parameter(estimator, parameter):
"""Check whether the estimator's fit method supports the given parameter.
Parameters
----------
estimator : object
An estimator to inspect.
parameter : str
The searched parameter.
Returns
-------
is_parameter : bool
... | Check whether the estimator's fit method supports the given parameter.
Parameters
----------
estimator : object
An estimator to inspect.
parameter : str
The searched parameter.
Returns
-------
is_parameter : bool
Whether the parameter was found to be a named parame... | has_fit_parameter | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def check_symmetric(array, *, tol=1e-10, raise_warning=True, raise_exception=False):
"""Make sure that array is 2D, square and symmetric.
If the array is not symmetric, then a symmetrized version is returned.
Optionally, a warning or exception is raised if the matrix is not
symmetric.
Parameters
... | Make sure that array is 2D, square and symmetric.
If the array is not symmetric, then a symmetrized version is returned.
Optionally, a warning or exception is raised if the matrix is not
symmetric.
Parameters
----------
array : {ndarray, sparse matrix}
Input object to check / convert. ... | check_symmetric | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _is_fitted(estimator, attributes=None, all_or_any=all):
"""Determine if an estimator is fitted
Parameters
----------
estimator : estimator instance
Estimator instance for which the check is performed.
attributes : str, list or tuple of str, default=None
Attribute name(s) given ... | Determine if an estimator is fitted
Parameters
----------
estimator : estimator instance
Estimator instance for which the check is performed.
attributes : str, list or tuple of str, default=None
Attribute name(s) given as string or a list/tuple of strings
Eg.: ``["coef_", "esti... | _is_fitted | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=all):
"""Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence of
fitted attributes (ending with a trailing underscore) and otherwise
raises a :class:`~sklearn.exceptions.NotFittedE... | Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence of
fitted attributes (ending with a trailing underscore) and otherwise
raises a :class:`~sklearn.exceptions.NotFittedError` with the given message.
If an estimator does not set any attributes with a... | check_is_fitted | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _estimator_has(attr, *, delegates=("estimator_", "estimator")):
"""Check if we can delegate a method to the underlying estimator.
We check the `delegates` in the order they are passed. By default, we first check
the fitted estimator if available, otherwise we check the unfitted estimator.
Paramete... | Check if we can delegate a method to the underlying estimator.
We check the `delegates` in the order they are passed. By default, we first check
the fitted estimator if available, otherwise we check the unfitted estimator.
Parameters
----------
attr : str
Name of the attribute the delegate... | _estimator_has | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def check_non_negative(X, whom):
"""
Check if there is any negative value in an array.
Parameters
----------
X : {array-like, sparse matrix}
Input data.
whom : str
Who passed X to this function.
"""
xp, _ = get_namespace(X)
# avoid X.min() on sparse matrix since it ... |
Check if there is any negative value in an array.
Parameters
----------
X : {array-like, sparse matrix}
Input data.
whom : str
Who passed X to this function.
| check_non_negative | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def check_scalar(
x,
name,
target_type,
*,
min_val=None,
max_val=None,
include_boundaries="both",
):
"""Validate scalar parameters type and value.
Parameters
----------
x : object
The scalar parameter to validate.
name : str
The name of the parameter to ... | Validate scalar parameters type and value.
Parameters
----------
x : object
The scalar parameter to validate.
name : str
The name of the parameter to be printed in error messages.
target_type : type or tuple
Acceptable data types for the parameter.
min_val : float or ... | check_scalar | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def type_name(t):
"""Convert type into humman readable string."""
module = t.__module__
qualname = t.__qualname__
if module == "builtins":
return qualname
elif t == numbers.Real:
return "float"
elif t == numbers.Integral:
return "int"
... | Convert type into humman readable string. | type_name | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_psd_eigenvalues(lambdas, enable_warnings=False):
"""Check the eigenvalues of a positive semidefinite (PSD) matrix.
Checks the provided array of PSD matrix eigenvalues for numerical or
conditioning issues and returns a fixed validated version. This method
should typically be used if the PSD m... | Check the eigenvalues of a positive semidefinite (PSD) matrix.
Checks the provided array of PSD matrix eigenvalues for numerical or
conditioning issues and returns a fixed validated version. This method
should typically be used if the PSD matrix is user-provided (e.g. a
Gram matrix) or computed using a... | _check_psd_eigenvalues | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_sample_weight(
sample_weight, X, *, dtype=None, ensure_non_negative=False, copy=False
):
"""Validate sample weights.
Note that passing sample_weight=None will output an array of ones.
Therefore, in some cases, you may want to protect the call with:
if sample_weight is not None:
s... | Validate sample weights.
Note that passing sample_weight=None will output an array of ones.
Therefore, in some cases, you may want to protect the call with:
if sample_weight is not None:
sample_weight = _check_sample_weight(...)
Parameters
----------
sample_weight : {ndarray, Number or... | _check_sample_weight | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _allclose_dense_sparse(x, y, rtol=1e-7, atol=1e-9):
"""Check 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}
... | Check 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-7... | _allclose_dense_sparse | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_response_method(estimator, response_method):
"""Check if `response_method` is available in estimator and return it.
.. versionadded:: 1.3
Parameters
----------
estimator : estimator instance
Classifier or regressor to check.
response_method : {"predict_proba", "predict_log_... | Check if `response_method` is available in estimator and return it.
.. versionadded:: 1.3
Parameters
----------
estimator : estimator instance
Classifier or regressor to check.
response_method : {"predict_proba", "predict_log_proba", "decision_function",
"predict"} or list of ... | _check_response_method | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_method_params(X, params, indices=None):
"""Check and validate the parameters passed to a specific
method like `fit`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data array.
params : dict
Dictionary containing the parameters passed to the met... | Check and validate the parameters passed to a specific
method like `fit`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data array.
params : dict
Dictionary containing the parameters passed to the method.
indices : array-like of shape (n_samples,), defa... | _check_method_params | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _is_pandas_df_or_series(X):
"""Return True if the X is a pandas dataframe or series."""
try:
pd = sys.modules["pandas"]
except KeyError:
return False
return isinstance(X, (pd.DataFrame, pd.Series)) | Return True if the X is a pandas dataframe or series. | _is_pandas_df_or_series | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _is_pandas_df(X):
"""Return True if the X is a pandas dataframe."""
try:
pd = sys.modules["pandas"]
except KeyError:
return False
return isinstance(X, pd.DataFrame) | Return True if the X is a pandas dataframe. | _is_pandas_df | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _is_pyarrow_data(X):
"""Return True if the X is a pyarrow Table, RecordBatch, Array or ChunkedArray."""
try:
pa = sys.modules["pyarrow"]
except KeyError:
return False
return isinstance(X, (pa.Table, pa.RecordBatch, pa.Array, pa.ChunkedArray)) | Return True if the X is a pyarrow Table, RecordBatch, Array or ChunkedArray. | _is_pyarrow_data | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _is_polars_df_or_series(X):
"""Return True if the X is a polars dataframe or series."""
try:
pl = sys.modules["polars"]
except KeyError:
return False
return isinstance(X, (pl.DataFrame, pl.Series)) | Return True if the X is a polars dataframe or series. | _is_polars_df_or_series | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _is_polars_df(X):
"""Return True if the X is a polars dataframe."""
try:
pl = sys.modules["polars"]
except KeyError:
return False
return isinstance(X, pl.DataFrame) | Return True if the X is a polars dataframe. | _is_polars_df | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _get_feature_names(X):
"""Get feature names from X.
Support for other array containers should place its implementation here.
Parameters
----------
X : {ndarray, dataframe} of shape (n_samples, n_features)
Array container to extract feature names.
- pandas dataframe : The colum... | Get feature names from X.
Support for other array containers should place its implementation here.
Parameters
----------
X : {ndarray, dataframe} of shape (n_samples, n_features)
Array container to extract feature names.
- pandas dataframe : The columns will be considered to be featur... | _get_feature_names | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_feature_names_in(estimator, input_features=None, *, generate_names=True):
"""Check `input_features` and generate names if needed.
Commonly used in :term:`get_feature_names_out`.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
... | Check `input_features` and generate names if needed.
Commonly used in :term:`get_feature_names_out`.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
- If `input_features` is `None`, then `feature_names_in_` is
used as feature na... | _check_feature_names_in | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _generate_get_feature_names_out(estimator, n_features_out, input_features=None):
"""Generate feature names out for estimator using the estimator name as the prefix.
The input_feature names are validated but not used. This function is useful
for estimators that generate their own names based on `n_featu... | Generate feature names out for estimator using the estimator name as the prefix.
The input_feature names are validated but not used. This function is useful
for estimators that generate their own names based on `n_features_out`, i.e. PCA.
Parameters
----------
estimator : estimator instance
... | _generate_get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_monotonic_cst(estimator, monotonic_cst=None):
"""Check the monotonic constraints and return the corresponding array.
This helper function should be used in the `fit` method of an estimator
that supports monotonic constraints and called after the estimator has
introspected input data to set t... | Check the monotonic constraints and return the corresponding array.
This helper function should be used in the `fit` method of an estimator
that supports monotonic constraints and called after the estimator has
introspected input data to set the `n_features_in_` and optionally the
`feature_names_in_` a... | _check_monotonic_cst | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_pos_label_consistency(pos_label, y_true):
"""Check if `pos_label` need to be specified or not.
In binary classification, we fix `pos_label=1` if the labels are in the set
{-1, 1} or {0, 1}. Otherwise, we raise an error asking to specify the
`pos_label` parameters.
Parameters
-------... | Check if `pos_label` need to be specified or not.
In binary classification, we fix `pos_label=1` if the labels are in the set
{-1, 1} or {0, 1}. Otherwise, we raise an error asking to specify the
`pos_label` parameters.
Parameters
----------
pos_label : int, float, bool, str or None
Th... | _check_pos_label_consistency | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _to_object_array(sequence):
"""Convert sequence to a 1-D NumPy array of object dtype.
numpy.array constructor has a similar use but it's output
is ambiguous. It can be 1-D NumPy array of object dtype if
the input is a ragged array, but if the input is a list of
equal length arrays, then the out... | Convert sequence to a 1-D NumPy array of object dtype.
numpy.array constructor has a similar use but it's output
is ambiguous. It can be 1-D NumPy array of object dtype if
the input is a ragged array, but if the input is a list of
equal length arrays, then the output is a 2D numpy.array.
_to_object... | _to_object_array | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_feature_names(estimator, X, *, reset):
"""Set or check the `feature_names_in_` attribute of an estimator.
.. versionadded:: 1.0
.. versionchanged:: 1.6
Moved from :class:`~sklearn.base.BaseEstimator` to
:mod:`sklearn.utils.validation`.
Parameters
----------
estimato... | Set or check the `feature_names_in_` attribute of an estimator.
.. versionadded:: 1.0
.. versionchanged:: 1.6
Moved from :class:`~sklearn.base.BaseEstimator` to
:mod:`sklearn.utils.validation`.
Parameters
----------
estimator : estimator instance
The estimator to validate ... | _check_feature_names | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _check_n_features(estimator, X, reset):
"""Set the `n_features_in_` attribute, or check against it on an estimator.
.. versionchanged:: 1.6
Moved from :class:`~sklearn.base.BaseEstimator` to
:mod:`~sklearn.utils.validation`.
Parameters
----------
estimator : estimator instance
... | Set the `n_features_in_` attribute, or check against it on an estimator.
.. versionchanged:: 1.6
Moved from :class:`~sklearn.base.BaseEstimator` to
:mod:`~sklearn.utils.validation`.
Parameters
----------
estimator : estimator instance
The estimator to validate the input for.
... | _check_n_features | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def validate_data(
_estimator,
/,
X="no_validation",
y="no_validation",
reset=True,
validate_separately=False,
skip_check_array=False,
**check_params,
):
"""Validate input data and set or check feature names and counts of the input.
This helper function should be used in an esti... | Validate input data and set or check feature names and counts of the input.
This helper function should be used in an estimator that requires input
validation. This mutates the estimator and sets the `n_features_in_` and
`feature_names_in_` attributes if `reset=True`.
.. versionadded:: 1.6
Parame... | validate_data | python | scikit-learn/scikit-learn | sklearn/utils/validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py | BSD-3-Clause |
def _init_arpack_v0(size, random_state):
"""Initialize the starting vector for iteration in ARPACK functions.
Initialize a ndarray with values sampled from the uniform distribution on
[-1, 1]. This initialization model has been chosen to be consistent with
the ARPACK one as another initialization can l... | Initialize the starting vector for iteration in ARPACK functions.
Initialize a ndarray with values sampled from the uniform distribution on
[-1, 1]. This initialization model has been chosen to be consistent with
the ARPACK one as another initialization can lead to convergence issues.
Parameters
-... | _init_arpack_v0 | python | scikit-learn/scikit-learn | sklearn/utils/_arpack.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_arpack.py | BSD-3-Clause |
def yield_namespaces(include_numpy_namespaces=True):
"""Yield supported namespace.
This is meant to be used for testing purposes only.
Parameters
----------
include_numpy_namespaces : bool, default=True
If True, also yield numpy namespaces.
Returns
-------
array_namespace : st... | Yield supported namespace.
This is meant to be used for testing purposes only.
Parameters
----------
include_numpy_namespaces : bool, default=True
If True, also yield numpy namespaces.
Returns
-------
array_namespace : str
The name of the Array API namespace.
| yield_namespaces | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def yield_namespace_device_dtype_combinations(include_numpy_namespaces=True):
"""Yield supported namespace, device, dtype tuples for testing.
Use this to test that an estimator works with all combinations.
Use in conjunction with `ids=_get_namespace_device_dtype_ids` to give
clearer pytest parametrizat... | Yield supported namespace, device, dtype tuples for testing.
Use this to test that an estimator works with all combinations.
Use in conjunction with `ids=_get_namespace_device_dtype_ids` to give
clearer pytest parametrization ID names.
Parameters
----------
include_numpy_namespaces : bool, def... | yield_namespace_device_dtype_combinations | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _check_array_api_dispatch(array_api_dispatch):
"""Check that array_api_compat is installed and NumPy version is compatible.
array_api_compat follows NEP29, which has a higher minimum NumPy version than
scikit-learn.
"""
if not array_api_dispatch:
return
scipy_version = parse_versio... | Check that array_api_compat is installed and NumPy version is compatible.
array_api_compat follows NEP29, which has a higher minimum NumPy version than
scikit-learn.
| _check_array_api_dispatch | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _single_array_device(array):
"""Hardware device where the array data resides on."""
if (
isinstance(array, (numpy.ndarray, numpy.generic))
or not hasattr(array, "device")
# When array API dispatch is disabled, we expect the scikit-learn code
# to use np.asarray so that the re... | Hardware device where the array data resides on. | _single_array_device | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def device(*array_list, remove_none=True, remove_types=(str,)):
"""Hardware device where the array data resides on.
If the hardware device is not the same for all arrays, an error is raised.
Parameters
----------
*array_list : arrays
List of array instances from NumPy or an array API compa... | Hardware device where the array data resides on.
If the hardware device is not the same for all arrays, an error is raised.
Parameters
----------
*array_list : arrays
List of array instances from NumPy or an array API compatible library.
remove_none : bool, default=True
Whether to... | device | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def isdtype(dtype, kind, *, xp):
"""Returns a boolean indicating whether a provided dtype is of type "kind".
Included in the v2022.12 of the Array API spec.
https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
"""
if isinstance(kind, tuple):
return any(_... | Returns a boolean indicating whether a provided dtype is of type "kind".
Included in the v2022.12 of the Array API spec.
https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
| isdtype | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def supported_float_dtypes(xp):
"""Supported floating point types for the namespace.
Note: float16 is not officially part of the Array API spec at the
time of writing but scikit-learn estimators and functions can choose
to accept it when xp.float16 is defined.
https://data-apis.org/array-api/lates... | Supported floating point types for the namespace.
Note: float16 is not officially part of the Array API spec at the
time of writing but scikit-learn estimators and functions can choose
to accept it when xp.float16 is defined.
https://data-apis.org/array-api/latest/API_specification/data_types.html
... | supported_float_dtypes | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def ensure_common_namespace_device(reference, *arrays):
"""Ensure that all arrays use the same namespace and device as reference.
If necessary the arrays are moved to the same namespace and device as
the reference array.
Parameters
----------
reference : array
Reference array.
*ar... | Ensure that all arrays use the same namespace and device as reference.
If necessary the arrays are moved to the same namespace and device as
the reference array.
Parameters
----------
reference : array
Reference array.
*arrays : array
Arrays to check.
Returns
-------
... | ensure_common_namespace_device | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _remove_non_arrays(*arrays, remove_none=True, remove_types=(str,)):
"""Filter arrays to exclude None and/or specific types.
Sparse arrays are always filtered out.
Parameters
----------
*arrays : array objects
Array objects.
remove_none : bool, default=True
Whether to ignor... | Filter arrays to exclude None and/or specific types.
Sparse arrays are always filtered out.
Parameters
----------
*arrays : array objects
Array objects.
remove_none : bool, default=True
Whether to ignore None objects passed in arrays.
remove_types : tuple or list, default=(st... | _remove_non_arrays | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def get_namespace(*arrays, remove_none=True, remove_types=(str,), xp=None):
"""Get namespace of arrays.
Introspect `arrays` arguments and return their common Array API compatible
namespace object, if any.
Note that sparse arrays are filtered by default.
See: https://numpy.org/neps/nep-0047-array-... | Get namespace of arrays.
Introspect `arrays` arguments and return their common Array API compatible
namespace object, if any.
Note that sparse arrays are filtered by default.
See: https://numpy.org/neps/nep-0047-array-api-standard.html
If `arrays` are regular numpy arrays, `array_api_compat.nump... | get_namespace | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def get_namespace_and_device(
*array_list, remove_none=True, remove_types=(str,), xp=None
):
"""Combination into one single function of `get_namespace` and `device`.
Parameters
----------
*array_list : array objects
Array objects.
remove_none : bool, default=True
Whether to igno... | Combination into one single function of `get_namespace` and `device`.
Parameters
----------
*array_list : array objects
Array objects.
remove_none : bool, default=True
Whether to ignore None objects passed in arrays.
remove_types : tuple or list, default=(str,)
Types to igno... | get_namespace_and_device | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _fill_or_add_to_diagonal(array, value, xp, add_value=True, wrap=False):
"""Implementation to facilitate adding or assigning specified values to the
diagonal of a 2-d array.
If ``add_value`` is `True` then the values will be added to the diagonal
elements otherwise the values will be assigned to the... | Implementation to facilitate adding or assigning specified values to the
diagonal of a 2-d array.
If ``add_value`` is `True` then the values will be added to the diagonal
elements otherwise the values will be assigned to the diagonal elements.
By default, ``add_value`` is set to `True. This is currentl... | _fill_or_add_to_diagonal | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _max_precision_float_dtype(xp, device):
"""Return the float dtype with the highest precision supported by the device."""
# TODO: Update to use `__array_namespace__info__()` from array-api v2023.12
# when/if that becomes more widespread.
if _is_xp_namespace(xp, "torch") and str(device).startswith(
... | Return the float dtype with the highest precision supported by the device. | _max_precision_float_dtype | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _find_matching_floating_dtype(*arrays, xp):
"""Find a suitable floating point dtype when computing with arrays.
If any of the arrays are floating point, return the dtype with the highest
precision by following official type promotion rules:
https://data-apis.org/array-api/latest/API_specification/... | Find a suitable floating point dtype when computing with arrays.
If any of the arrays are floating point, return the dtype with the highest
precision by following official type promotion rules:
https://data-apis.org/array-api/latest/API_specification/type_promotion.html
If there are no floating point... | _find_matching_floating_dtype | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _average(a, axis=None, weights=None, normalize=True, xp=None):
"""Partial port of np.average to support the Array API.
It does a best effort at mimicking the return dtype rule described at
https://numpy.org/doc/stable/reference/generated/numpy.average.html but
only for the common cases needed in sc... | Partial port of np.average to support the Array API.
It does a best effort at mimicking the return dtype rule described at
https://numpy.org/doc/stable/reference/generated/numpy.average.html but
only for the common cases needed in scikit-learn.
| _average | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _asarray_with_order(
array, dtype=None, order=None, copy=None, *, xp=None, device=None
):
"""Helper to support the order kwarg only for NumPy-backed arrays
Memory layout parameter `order` is not exposed in the Array API standard,
however some input validation code in scikit-learn needs to work both... | Helper to support the order kwarg only for NumPy-backed arrays
Memory layout parameter `order` is not exposed in the Array API standard,
however some input validation code in scikit-learn needs to work both
for classes and functions that will leverage Array API only operations
and for code that inheren... | _asarray_with_order | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _ravel(array, xp=None):
"""Array API compliant version of np.ravel.
For non numpy namespaces, it just returns a flattened array, that might
be or not be a copy.
"""
xp, _ = get_namespace(array, xp=xp)
if _is_numpy_namespace(xp):
array = numpy.asarray(array)
return xp.asarray... | Array API compliant version of np.ravel.
For non numpy namespaces, it just returns a flattened array, that might
be or not be a copy.
| _ravel | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _convert_to_numpy(array, xp):
"""Convert X into a NumPy ndarray on the CPU."""
if _is_xp_namespace(xp, "torch"):
return array.cpu().numpy()
elif _is_xp_namespace(xp, "cupy"): # pragma: nocover
return array.get()
elif _is_xp_namespace(xp, "array_api_strict"):
return numpy.asa... | Convert X into a NumPy ndarray on the CPU. | _convert_to_numpy | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _estimator_with_converted_arrays(estimator, converter):
"""Create new estimator which converting all attributes that are arrays.
The converter is called on all NumPy arrays and arrays that support the
`DLPack interface <https://dmlc.github.io/dlpack/latest/>`__.
Parameters
----------
estim... | Create new estimator which converting all attributes that are arrays.
The converter is called on all NumPy arrays and arrays that support the
`DLPack interface <https://dmlc.github.io/dlpack/latest/>`__.
Parameters
----------
estimator : Estimator
Estimator to convert
converter : call... | _estimator_with_converted_arrays | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _atol_for_type(dtype_or_dtype_name):
"""Return the absolute tolerance for a given numpy dtype."""
if dtype_or_dtype_name is None:
# If no dtype is specified when running tests for a given namespace, we
# expect the same floating precision level as NumPy's default floating
# point dty... | Return the absolute tolerance for a given numpy dtype. | _atol_for_type | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def indexing_dtype(xp):
"""Return a platform-specific integer dtype suitable for indexing.
On 32-bit platforms, this will typically return int32 and int64 otherwise.
Note: using dtype is recommended for indexing transient array
datastructures. For long-lived arrays, such as the fitted attributes of
... | Return a platform-specific integer dtype suitable for indexing.
On 32-bit platforms, this will typically return int32 and int64 otherwise.
Note: using dtype is recommended for indexing transient array
datastructures. For long-lived arrays, such as the fitted attributes of
estimators, it is instead rec... | indexing_dtype | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _isin(element, test_elements, xp, assume_unique=False, invert=False):
"""Calculates ``element in test_elements``, broadcasting over `element`
only.
Returns a boolean array of the same shape as `element` that is True
where an element of `element` is in `test_elements` and False otherwise.
"""
... | Calculates ``element in test_elements``, broadcasting over `element`
only.
Returns a boolean array of the same shape as `element` that is True
where an element of `element` is in `test_elements` and False otherwise.
| _isin | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _in1d(ar1, ar2, xp, assume_unique=False, invert=False):
"""Checks whether each element of an array is also present in a
second array.
Returns a boolean array the same length as `ar1` that is True
where an element of `ar1` is in `ar2` and False otherwise.
This function has been adapted using th... | Checks whether each element of an array is also present in a
second array.
Returns a boolean array the same length as `ar1` that is True
where an element of `ar1` is in `ar2` and False otherwise.
This function has been adapted using the original implementation
present in numpy:
https://github.... | _in1d | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _count_nonzero(X, axis=None, sample_weight=None, xp=None, device=None):
"""A variant of `sklearn.utils.sparsefuncs.count_nonzero` for the Array API.
If the array `X` is sparse, and we are using the numpy namespace then we
simply call the original function. This function only supports 2D arrays.
"""... | A variant of `sklearn.utils.sparsefuncs.count_nonzero` for the Array API.
If the array `X` is sparse, and we are using the numpy namespace then we
simply call the original function. This function only supports 2D arrays.
| _count_nonzero | python | scikit-learn/scikit-learn | sklearn/utils/_array_api.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_array_api.py | BSD-3-Clause |
def _set_deprecated(self, value, *, new_key, deprecated_key, warning_message):
"""Set key in dictionary to be deprecated with its warning message."""
self.__dict__["_deprecated_key_to_warnings"][deprecated_key] = warning_message
self[new_key] = self[deprecated_key] = value | Set key in dictionary to be deprecated with its warning message. | _set_deprecated | python | scikit-learn/scikit-learn | sklearn/utils/_bunch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_bunch.py | BSD-3-Clause |
def chunk_generator(gen, chunksize):
"""Chunk generator, ``gen`` into lists of length ``chunksize``. The last
chunk may have a length less than ``chunksize``."""
while True:
chunk = list(islice(gen, chunksize))
if chunk:
yield chunk
else:
return | Chunk generator, ``gen`` into lists of length ``chunksize``. The last
chunk may have a length less than ``chunksize``. | chunk_generator | python | scikit-learn/scikit-learn | sklearn/utils/_chunking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_chunking.py | BSD-3-Clause |
def gen_batches(n, batch_size, *, min_batch_size=0):
"""Generator to create slices containing `batch_size` elements from 0 to `n`.
The last slice may contain less than `batch_size` elements, when
`batch_size` does not divide `n`.
Parameters
----------
n : int
Size of the sequence.
... | Generator to create slices containing `batch_size` elements from 0 to `n`.
The last slice may contain less than `batch_size` elements, when
`batch_size` does not divide `n`.
Parameters
----------
n : int
Size of the sequence.
batch_size : int
Number of elements in each batch.
... | gen_batches | python | scikit-learn/scikit-learn | sklearn/utils/_chunking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_chunking.py | BSD-3-Clause |
def gen_even_slices(n, n_packs, *, n_samples=None):
"""Generator to create `n_packs` evenly spaced slices going up to `n`.
If `n_packs` does not divide `n`, except for the first `n % n_packs`
slices, remaining slices may contain fewer elements.
Parameters
----------
n : int
Size of the... | Generator to create `n_packs` evenly spaced slices going up to `n`.
If `n_packs` does not divide `n`, except for the first `n % n_packs`
slices, remaining slices may contain fewer elements.
Parameters
----------
n : int
Size of the sequence.
n_packs : int
Number of slices to ge... | gen_even_slices | python | scikit-learn/scikit-learn | sklearn/utils/_chunking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_chunking.py | BSD-3-Clause |
def get_chunk_n_rows(row_bytes, *, max_n_rows=None, working_memory=None):
"""Calculate how many rows can be processed within `working_memory`.
Parameters
----------
row_bytes : int
The expected number of bytes of memory that will be consumed
during the processing of each row.
max_n_... | Calculate how many rows can be processed within `working_memory`.
Parameters
----------
row_bytes : int
The expected number of bytes of memory that will be consumed
during the processing of each row.
max_n_rows : int, default=None
The maximum return value.
working_memory : i... | get_chunk_n_rows | python | scikit-learn/scikit-learn | sklearn/utils/_chunking.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_chunking.py | BSD-3-Clause |
def _unique(values, *, return_inverse=False, return_counts=False):
"""Helper function to find unique values with support for python objects.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : ndarray
Values to check for unkno... | Helper function to find unique values with support for python objects.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : ndarray
Values to check for unknowns.
return_inverse : bool, default=False
If True, also retur... | _unique | python | scikit-learn/scikit-learn | sklearn/utils/_encode.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_encode.py | BSD-3-Clause |
def _unique_np(values, return_inverse=False, return_counts=False):
"""Helper function to find unique values for numpy arrays that correctly
accounts for nans. See `_unique` documentation for details."""
xp, _ = get_namespace(values)
inverse, counts = None, None
if return_inverse and return_counts:... | Helper function to find unique values for numpy arrays that correctly
accounts for nans. See `_unique` documentation for details. | _unique_np | python | scikit-learn/scikit-learn | sklearn/utils/_encode.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_encode.py | BSD-3-Clause |
def to_list(self):
"""Convert tuple to a list where None is always first."""
output = []
if self.none:
output.append(None)
if self.nan:
output.append(np.nan)
return output | Convert tuple to a list where None is always first. | to_list | python | scikit-learn/scikit-learn | sklearn/utils/_encode.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_encode.py | BSD-3-Clause |
def _extract_missing(values):
"""Extract missing values from `values`.
Parameters
----------
values: set
Set of values to extract missing from.
Returns
-------
output: set
Set with missing values extracted.
missing_values: MissingValues
Object with missing valu... | Extract missing values from `values`.
Parameters
----------
values: set
Set of values to extract missing from.
Returns
-------
output: set
Set with missing values extracted.
missing_values: MissingValues
Object with missing value information.
| _extract_missing | python | scikit-learn/scikit-learn | sklearn/utils/_encode.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_encode.py | BSD-3-Clause |
def _map_to_integer(values, uniques):
"""Map values based on its position in uniques."""
xp, _ = get_namespace(values, uniques)
table = _nandict({val: i for i, val in enumerate(uniques)})
return xp.asarray([table[v] for v in values], device=device(values)) | Map values based on its position in uniques. | _map_to_integer | python | scikit-learn/scikit-learn | sklearn/utils/_encode.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_encode.py | BSD-3-Clause |
def _check_unknown(values, known_values, return_mask=False):
"""
Helper function to check for unknowns in values to be encoded.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : array
Values to check for unknowns.
kn... |
Helper function to check for unknowns in values to be encoded.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : array
Values to check for unknowns.
known_values : array
Known values. Must be unique.
return_... | _check_unknown | python | scikit-learn/scikit-learn | sklearn/utils/_encode.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_encode.py | BSD-3-Clause |
def _generate_items(self, items):
"""Generate items without nans. Stores the nan counts separately."""
for item in items:
if not is_scalar_nan(item):
yield item
continue
if not hasattr(self, "nan_count"):
self.nan_count = 0
... | Generate items without nans. Stores the nan counts separately. | _generate_items | python | scikit-learn/scikit-learn | sklearn/utils/_encode.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_encode.py | BSD-3-Clause |
def _get_counts(values, uniques):
"""Get the count of each of the `uniques` in `values`.
The counts will use the order passed in by `uniques`. For non-object dtypes,
`uniques` is assumed to be sorted and `np.nan` is at the end.
"""
if values.dtype.kind in "OU":
counter = _NaNCounter(values)... | Get the count of each of the `uniques` in `values`.
The counts will use the order passed in by `uniques`. For non-object dtypes,
`uniques` is assumed to be sorted and `np.nan` is at the end.
| _get_counts | python | scikit-learn/scikit-learn | sklearn/utils/_encode.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_encode.py | BSD-3-Clause |
def _array_indexing(array, key, key_dtype, axis):
"""Index an array or scipy.sparse consistently across NumPy version."""
xp, is_array_api = get_namespace(array)
if is_array_api:
return xp.take(array, key, axis=axis)
if issparse(array) and key_dtype == "bool":
key = np.asarray(key)
i... | Index an array or scipy.sparse consistently across NumPy version. | _array_indexing | python | scikit-learn/scikit-learn | sklearn/utils/_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_indexing.py | BSD-3-Clause |
def _determine_key_type(key, accept_slice=True):
"""Determine the data type of key.
Parameters
----------
key : scalar, slice or array-like
The key from which we want to infer the data type.
accept_slice : bool, default=True
Whether or not to raise an error if the key is a slice.
... | Determine the data type of key.
Parameters
----------
key : scalar, slice or array-like
The key from which we want to infer the data type.
accept_slice : bool, default=True
Whether or not to raise an error if the key is a slice.
Returns
-------
dtype : {'int', 'str', 'bool... | _determine_key_type | python | scikit-learn/scikit-learn | sklearn/utils/_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_indexing.py | BSD-3-Clause |
def _safe_indexing(X, indices, *, axis=0):
"""Return rows, items or columns of X using indices.
.. warning::
This utility is documented, but **private**. This means that
backward compatibility might be broken without any deprecation
cycle.
Parameters
----------
X : array-l... | Return rows, items or columns of X using indices.
.. warning::
This utility is documented, but **private**. This means that
backward compatibility might be broken without any deprecation
cycle.
Parameters
----------
X : array-like, sparse-matrix, list, pandas.DataFrame, pandas... | _safe_indexing | python | scikit-learn/scikit-learn | sklearn/utils/_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_indexing.py | BSD-3-Clause |
def _safe_assign(X, values, *, row_indexer=None, column_indexer=None):
"""Safe assignment to a numpy array, sparse matrix, or pandas dataframe.
Parameters
----------
X : {ndarray, sparse-matrix, dataframe}
Array to be modified. It is expected to be 2-dimensional.
values : ndarray
T... | Safe assignment to a numpy array, sparse matrix, or pandas dataframe.
Parameters
----------
X : {ndarray, sparse-matrix, dataframe}
Array to be modified. It is expected to be 2-dimensional.
values : ndarray
The values to be assigned to `X`.
row_indexer : array-like, dtype={int, bo... | _safe_assign | python | scikit-learn/scikit-learn | sklearn/utils/_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_indexing.py | BSD-3-Clause |
def _get_column_indices(X, key):
"""Get feature column indices for input data X and key.
For accepted values of `key`, see the docstring of
:func:`_safe_indexing`.
"""
key_dtype = _determine_key_type(key)
if _use_interchange_protocol(X):
return _get_column_indices_interchange(X.__datafr... | Get feature column indices for input data X and key.
For accepted values of `key`, see the docstring of
:func:`_safe_indexing`.
| _get_column_indices | python | scikit-learn/scikit-learn | sklearn/utils/_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_indexing.py | BSD-3-Clause |
def _get_column_indices_interchange(X_interchange, key, key_dtype):
"""Same as _get_column_indices but for X with __dataframe__ protocol."""
n_columns = X_interchange.num_columns()
if isinstance(key, (list, tuple)) and not key:
# we get an empty list
return []
elif key_dtype in ("bool"... | Same as _get_column_indices but for X with __dataframe__ protocol. | _get_column_indices_interchange | python | scikit-learn/scikit-learn | sklearn/utils/_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_indexing.py | BSD-3-Clause |
def resample(
*arrays,
replace=True,
n_samples=None,
random_state=None,
stratify=None,
sample_weight=None,
):
"""Resample arrays or sparse matrices in a consistent way.
The default strategy implements one step of the bootstrapping
procedure.
Parameters
----------
*array... | Resample arrays or sparse matrices in a consistent way.
The default strategy implements one step of the bootstrapping
procedure.
Parameters
----------
*arrays : sequence of array-like of shape (n_samples,) or (n_samples, n_outputs)
Indexable data-structures can be arrays, lists... | resample | python | scikit-learn/scikit-learn | sklearn/utils/_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_indexing.py | BSD-3-Clause |
def shuffle(*arrays, random_state=None, n_samples=None):
"""Shuffle arrays or sparse matrices in a consistent way.
This is a convenience alias to ``resample(*arrays, replace=False)`` to do
random permutations of the collections.
Parameters
----------
*arrays : sequence of indexable data-struct... | Shuffle arrays or sparse matrices in a consistent way.
This is a convenience alias to ``resample(*arrays, replace=False)`` to do
random permutations of the collections.
Parameters
----------
*arrays : sequence of indexable data-structures
Indexable data-structures can be arrays, lists, dat... | shuffle | python | scikit-learn/scikit-learn | sklearn/utils/_indexing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_indexing.py | BSD-3-Clause |
def _get_mask(X, value_to_mask):
"""Compute the boolean mask X == value_to_mask.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Input data, where ``n_samples`` is the number of samples and
``n_features`` is the number of features.
value_to_mask ... | Compute the boolean mask X == value_to_mask.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Input data, where ``n_samples`` is the number of samples and
``n_features`` is the number of features.
value_to_mask : {int, float}
The value which i... | _get_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 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 _serialize(self):
"""Serialize the object.
Returns
-------
obj : dict
A serialized version of the instance in the form of a dictionary.
"""
res = dict()
if self._self_request:
res["$self_request"] = self._self_request._serialize()
... | 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 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 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.