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 inplace_swap_column(X, m, n):
"""
Swap two columns of a CSC/CSR matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two columns are to be swapped. It should be of
CSR or CSC format.
m : int
Index of the column of X ... |
Swap two columns of a CSC/CSR matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two columns are to be swapped. It should be of
CSR or CSC format.
m : int
Index of the column of X to be swapped.
n : int
Index... | inplace_swap_column | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def min_max_axis(X, axis, ignore_nan=False):
"""Compute minimum and maximum along an axis on a CSR or CSC matrix.
Optionally ignore NaN values.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Input data. It should be of CSR or CSC format.
axis : {0, 1}
... | Compute minimum and maximum along an axis on a CSR or CSC matrix.
Optionally ignore NaN values.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Input data. It should be of CSR or CSC format.
axis : {0, 1}
Axis along which the axis should be computed.
... | min_max_axis | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def count_nonzero(X, axis=None, sample_weight=None):
"""A variant of X.getnnz() with extension to weighting on axis 0.
Useful in efficiently calculating multilabel metrics.
Parameters
----------
X : sparse matrix of shape (n_samples, n_labels)
Input data. It should be of CSR format.
a... | A variant of X.getnnz() with extension to weighting on axis 0.
Useful in efficiently calculating multilabel metrics.
Parameters
----------
X : sparse matrix of shape (n_samples, n_labels)
Input data. It should be of CSR format.
axis : {0, 1}, default=None
The axis on which the dat... | count_nonzero | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def _get_median(data, n_zeros):
"""Compute the median of data with n_zeros additional zeros.
This function is used to support sparse matrices; it modifies data
in-place.
"""
n_elems = len(data) + n_zeros
if not n_elems:
return np.nan
n_negative = np.count_nonzero(data < 0)
middl... | Compute the median of data with n_zeros additional zeros.
This function is used to support sparse matrices; it modifies data
in-place.
| _get_median | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def _get_elem_at_rank(rank, data, n_negative, n_zeros):
"""Find the value in data augmented with n_zeros for the given rank"""
if rank < n_negative:
return data[rank]
if rank - n_negative < n_zeros:
return 0
return data[rank - n_zeros] | Find the value in data augmented with n_zeros for the given rank | _get_elem_at_rank | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def csc_median_axis_0(X):
"""Find the median across axis 0 of a CSC matrix.
It is equivalent to doing np.median(X, axis=0).
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Input data. It should be of CSC format.
Returns
-------
median : ndarray of shap... | Find the median across axis 0 of a CSC matrix.
It is equivalent to doing np.median(X, axis=0).
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Input data. It should be of CSC format.
Returns
-------
median : ndarray of shape (n_features,)
Median.
... | csc_median_axis_0 | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def _implicit_column_offset(X, offset):
"""Create an implicitly offset linear operator.
This is used by PCA on sparse data to avoid densifying the whole data
matrix.
Params
------
X : sparse matrix of shape (n_samples, n_features)
offset : ndarray of shape (n_features,)
Return... | Create an implicitly offset linear operator.
This is used by PCA on sparse data to avoid densifying the whole data
matrix.
Params
------
X : sparse matrix of shape (n_samples, n_features)
offset : ndarray of shape (n_features,)
Returns
-------
centered : LinearOperator
... | _implicit_column_offset | python | scikit-learn/scikit-learn | sklearn/utils/sparsefuncs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/sparsefuncs.py | BSD-3-Clause |
def _weighted_percentile(array, sample_weight, percentile_rank=50, xp=None):
"""Compute the weighted percentile with method 'inverted_cdf'.
When the percentile lies between two data points of `array`, the function returns
the lower value.
If `array` is a 2D array, the `values` are selected along axis ... | Compute the weighted percentile with method 'inverted_cdf'.
When the percentile lies between two data points of `array`, the function returns
the lower value.
If `array` is a 2D array, the `values` are selected along axis 0.
`NaN` values are ignored by setting their weights to 0. If `array` is 2D, th... | _weighted_percentile | python | scikit-learn/scikit-learn | sklearn/utils/stats.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/stats.py | BSD-3-Clause |
def _deprecate_positional_args(func=None, *, version="1.3"):
"""Decorator for methods that issues warnings for positional arguments.
Using the keyword-only argument syntax in pep 3102, arguments after the
* will issue a warning when passed as a positional argument.
Parameters
----------
func :... | Decorator for methods that issues warnings for positional arguments.
Using the keyword-only argument syntax in pep 3102, arguments after the
* will issue a warning when passed as a positional argument.
Parameters
----------
func : callable, default=None
Function to check arguments on.
... | _deprecate_positional_args | 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 assert_all_finite(
X,
*,
allow_nan=False,
estimator_name=None,
input_name="",
):
"""Throw a ValueError if X contains NaN or infinity.
Parameters
----------
X : {ndarray, sparse matrix}
The input data.
allow_nan : bool, default=False
If True, do not throw err... | Throw a ValueError if X contains NaN or infinity.
Parameters
----------
X : {ndarray, sparse matrix}
The input data.
allow_nan : bool, default=False
If True, do not throw error when `X` contains NaN.
estimator_name : str, default=None
The estimator name, used to construct ... | assert_all_finite | 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 as_float_array(
X, *, copy=True, force_all_finite="deprecated", ensure_all_finite=None
):
"""Convert an array-like to an array of floats.
The new dtype will be np.float32 or np.float64, depending on the original
type. The function can create a copy or modify the argument depending
on the argume... | Convert an array-like to an array of floats.
The new dtype will be np.float32 or np.float64, depending on the original
type. The function can create a copy or modify the argument depending
on the argument copy.
Parameters
----------
X : {array-like, sparse matrix}
The input data.
... | as_float_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 _is_arraylike(x):
"""Returns whether the input is array-like."""
if sp.issparse(x):
return False
return hasattr(x, "__len__") or hasattr(x, "shape") or hasattr(x, "__array__") | Returns whether the input is array-like. | _is_arraylike | 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 _num_features(X):
"""Return the number of features in an array-like X.
This helper function tries hard to avoid to materialize an array version
of X unless necessary. For instance, if X is a list of lists,
this function will return the length of the first element, assuming
that subsequent eleme... | Return the number of features in an array-like X.
This helper function tries hard to avoid to materialize an array version
of X unless necessary. For instance, if X is a list of lists,
this function will return the length of the first element, assuming
that subsequent elements are all lists of the same... | _num_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 _num_samples(x):
"""Return number of samples in array-like x."""
message = "Expected sequence or array-like, got %s" % type(x)
if hasattr(x, "fit") and callable(x.fit):
# Don't get num_samples from an ensembles length!
raise TypeError(message)
if _use_interchange_protocol(x):
... | Return number of samples in array-like x. | _num_samples | 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_memory(memory):
"""Check that ``memory`` is joblib.Memory-like.
joblib.Memory-like means that ``memory`` can be converted into a
joblib.Memory instance (typically a str denoting the ``location``)
or has the same interface (has a ``cache`` method).
Parameters
----------
memory : N... | Check that ``memory`` is joblib.Memory-like.
joblib.Memory-like means that ``memory`` can be converted into a
joblib.Memory instance (typically a str denoting the ``location``)
or has the same interface (has a ``cache`` method).
Parameters
----------
memory : None, str or object with the jobli... | check_memory | 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_consistent_length(*arrays):
"""Check that all arrays have consistent first dimensions.
Checks whether all objects in arrays have the same shape or length.
Parameters
----------
*arrays : list or tuple of input objects.
Objects that will be checked for consistent length.
Exam... | Check that all arrays have consistent first dimensions.
Checks whether all objects in arrays have the same shape or length.
Parameters
----------
*arrays : list or tuple of input objects.
Objects that will be checked for consistent length.
Examples
--------
>>> from sklearn.utils.... | check_consistent_length | 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 _make_indexable(iterable):
"""Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, d... | Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, dataframe, ndarray, sparse matrix} or N... | _make_indexable | 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 indexable(*iterables):
"""Make arrays indexable for cross-validation.
Checks consistent length, passes through None, and ensures that everything
can be indexed by converting sparse matrices to csr and converting
non-iterable objects to arrays.
Parameters
----------
*iterables : {lists,... | Make arrays indexable for cross-validation.
Checks consistent length, passes through None, and ensures that everything
can be indexed by converting sparse matrices to csr and converting
non-iterable objects to arrays.
Parameters
----------
*iterables : {lists, dataframes, ndarrays, sparse matr... | indexable | 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 _ensure_sparse_format(
sparse_container,
accept_sparse,
dtype,
copy,
ensure_all_finite,
accept_large_sparse,
estimator_name=None,
input_name="",
):
"""Convert a sparse container to a given format.
Checks the sparse format of `sparse_container` and converts if necessary.
... | Convert a sparse container to a given format.
Checks the sparse format of `sparse_container` and converts if necessary.
Parameters
----------
sparse_container : sparse matrix or array
Input to validate and convert.
accept_sparse : str, bool or list/tuple of str
String[s] represent... | _ensure_sparse_format | 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 _pandas_dtype_needs_early_conversion(pd_dtype):
"""Return True if pandas extension pd_dtype need to be converted early."""
# Check these early for pandas versions without extension dtypes
from pandas import SparseDtype
from pandas.api.types import (
is_bool_dtype,
is_float_dtype,
... | Return True if pandas extension pd_dtype need to be converted early. | _pandas_dtype_needs_early_conversion | 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_array(
array,
accept_sparse=False,
*,
accept_large_sparse=True,
dtype="numeric",
order=None,
copy=False,
force_writeable=False,
force_all_finite="deprecated",
ensure_all_finite=None,
ensure_non_negative=False,
ensure_2d=True,
allow_nd=False,
ensure_min_s... | Input validation on an array, list, sparse matrix or similar.
By default, the input is checked to be a non-empty 2D array containing
only finite values. If the dtype of the array is object, attempt
converting to float, raising on failure.
Parameters
----------
array : object
Input obje... | check_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_large_sparse(X, accept_large_sparse=False):
"""Raise a ValueError if X has 64bit indices and accept_large_sparse=False"""
if not accept_large_sparse:
supported_indices = ["int32"]
if X.format == "coo":
index_keys = ["col", "row"]
elif X.format in ["csr", "csc", "bs... | Raise a ValueError if X has 64bit indices and accept_large_sparse=False | _check_large_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_X_y(
X,
y,
accept_sparse=False,
*,
accept_large_sparse=True,
dtype="numeric",
order=None,
copy=False,
force_writeable=False,
force_all_finite="deprecated",
ensure_all_finite=None,
ensure_2d=True,
allow_nd=False,
multi_output=False,
ensure_min_samples... | Input validation for standard estimators.
Checks X and y for consistent length, enforces X to be 2D and y 1D. By
default, X is checked to be non-empty and containing only finite values.
Standard input checks are also applied to y, such as checking that y
does not have np.nan or np.inf targets. For mult... | check_X_y | 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_y(y, multi_output=False, y_numeric=False, estimator=None):
"""Isolated part of check_X_y dedicated to y validation"""
if multi_output:
y = check_array(
y,
accept_sparse="csr",
ensure_all_finite=True,
ensure_2d=False,
dtype=None,
... | Isolated part of check_X_y dedicated to y validation | _check_y | 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 column_or_1d(y, *, dtype=None, warn=False, device=None):
"""Ravel column or 1d numpy array, else raises an error.
Parameters
----------
y : array-like
Input data.
dtype : data-type, default=None
Data type for `y`.
.. versionadded:: 1.2
warn : bool, default=False
... | Ravel column or 1d numpy array, else raises an error.
Parameters
----------
y : array-like
Input data.
dtype : data-type, default=None
Data type for `y`.
.. versionadded:: 1.2
warn : bool, default=False
To control display of warnings.
device : device, default=N... | column_or_1d | 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_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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.