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_clusterer_compute_labels_predict(name, clusterer_orig): """Check that predict is invariant of compute_labels.""" X, y = make_blobs(n_samples=20, random_state=0) clusterer = clone(clusterer_orig) set_random_state(clusterer) if hasattr(clusterer, "compute_labels"): # MiniBatchKMeans...
Check that predict is invariant of compute_labels.
check_clusterer_compute_labels_predict
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_classifiers_one_label_sample_weights(name, classifier_orig): """Check that classifiers accepting sample_weight fit or throws a ValueError with an explicit message if the problem is reduced to one class. """ error_fit = ( f"{name} failed when fitted on one label after sample_weight trim...
Check that classifiers accepting sample_weight fit or throws a ValueError with an explicit message if the problem is reduced to one class.
check_classifiers_one_label_sample_weights
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_classifiers_multilabel_output_format_predict(name, classifier_orig): """Check the output of the `predict` method for classifiers supporting multilabel-indicator targets.""" classifier = clone(classifier_orig) set_random_state(classifier) n_samples, test_size, n_outputs = 100, 25, 5 X,...
Check the output of the `predict` method for classifiers supporting multilabel-indicator targets.
check_classifiers_multilabel_output_format_predict
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_classifiers_multilabel_output_format_predict_proba(name, classifier_orig): """Check the output of the `predict_proba` method for classifiers supporting multilabel-indicator targets.""" classifier = clone(classifier_orig) set_random_state(classifier) n_samples, test_size, n_outputs = 100, ...
Check the output of the `predict_proba` method for classifiers supporting multilabel-indicator targets.
check_classifiers_multilabel_output_format_predict_proba
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_classifiers_multilabel_output_format_decision_function(name, classifier_orig): """Check the output of the `decision_function` method for classifiers supporting multilabel-indicator targets.""" classifier = clone(classifier_orig) set_random_state(classifier) n_samples, test_size, n_outputs...
Check the output of the `decision_function` method for classifiers supporting multilabel-indicator targets.
check_classifiers_multilabel_output_format_decision_function
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_get_feature_names_out_error(name, estimator_orig): """Check the error raised by get_feature_names_out when called before fit. Unfitted estimators with get_feature_names_out should raise a NotFittedError. """ estimator = clone(estimator_orig) err_msg = ( f"Estimator {name} should ...
Check the error raised by get_feature_names_out when called before fit. Unfitted estimators with get_feature_names_out should raise a NotFittedError.
check_get_feature_names_out_error
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_estimators_fit_returns_self(name, estimator_orig): """Check if self is returned when calling fit.""" X, y = make_blobs(random_state=0, n_samples=21) X = _enforce_estimator_tags_X(estimator_orig, X) estimator = clone(estimator_orig) y = _enforce_estimator_tags_y(estimator, y) set_rand...
Check if self is returned when calling fit.
check_estimators_fit_returns_self
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_readonly_memmap_input(name, estimator_orig): """Check that the estimator can handle readonly memmap backed data. This is particularly needed to support joblib parallelisation. """ X, y = make_blobs(random_state=0, n_samples=21) X = _enforce_estimator_tags_X(estimator_orig, X) estimat...
Check that the estimator can handle readonly memmap backed data. This is particularly needed to support joblib parallelisation.
check_readonly_memmap_input
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_estimators_unfitted(name, estimator_orig): """Check that predict raises an exception in an unfitted estimator. Unfitted estimators should raise a NotFittedError. """ err_msg = ( "Estimator should raise a NotFittedError when calling `{method}` before fit. " "Either call `check_...
Check that predict raises an exception in an unfitted estimator. Unfitted estimators should raise a NotFittedError.
check_estimators_unfitted
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_class_weight_balanced_linear_classifier(name, estimator_orig): """Test class weights with non-contiguous class labels.""" # this is run on classes, not instances, though this should be changed X = np.array([[-1.0, -1.0], [-1.0, 0], [-0.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) y = np.array([1, 1, 1, ...
Test class weights with non-contiguous class labels.
check_class_weight_balanced_linear_classifier
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_estimator_cloneable(name, estimator_orig): """Checks whether the estimator can be cloned.""" try: clone(estimator_orig) except Exception as e: raise AssertionError(f"Cloning of {name} failed with error: {e}.") from e
Checks whether the estimator can be cloned.
check_estimator_cloneable
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_estimator_repr(name, estimator_orig): """Check that the estimator has a functioning repr.""" estimator = clone(estimator_orig) try: repr(estimator) except Exception as e: raise AssertionError(f"Repr of {name} failed with error: {e}.") from e
Check that the estimator has a functioning repr.
check_estimator_repr
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def param_default_value(p): """Identify hyper parameters of an estimator.""" return ( p.name != "self" and p.kind != p.VAR_KEYWORD and p.kind != p.VAR_POSITIONAL # and it should have a default value for this ...
Identify hyper parameters of an estimator.
param_default_value
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def param_required(p): """Identify hyper parameters of an estimator.""" return ( p.name != "self" and p.kind != p.VAR_KEYWORD # technically VAR_POSITIONAL is also required, but we don't have a # nice way to c...
Identify hyper parameters of an estimator.
param_required
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_positive_only_tag_during_fit(name, estimator_orig): """Test that the estimator correctly sets the tags.input_tags.positive_only If the tag is False, the estimator should accept negative input regardless of the tags.input_tags.pairwise flag. """ estimator = clone(estimator_orig) tags =...
Test that the estimator correctly sets the tags.input_tags.positive_only If the tag is False, the estimator should accept negative input regardless of the tags.input_tags.pairwise flag.
check_positive_only_tag_during_fit
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_valid_tag_types(name, estimator): """Check that estimator tags are valid.""" assert hasattr(estimator, "__sklearn_tags__"), ( f"Estimator {name} does not have `__sklearn_tags__` method. This method is" " implemented in BaseEstimator and returns a sklearn.utils.Tags instance." ) ...
Check that estimator tags are valid.
check_valid_tag_types
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def _output_from_fit_transform(transformer, name, X, df, y): """Generate output to test `set_output` for different configuration: - calling either `fit.transform` or `fit_transform`; - passing either a dataframe or a numpy array to fit; - passing either a dataframe or a numpy array to transform. ""...
Generate output to test `set_output` for different configuration: - calling either `fit.transform` or `fit_transform`; - passing either a dataframe or a numpy array to fit; - passing either a dataframe or a numpy array to transform.
_output_from_fit_transform
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def _check_generated_dataframe( name, case, index, outputs_default, outputs_dataframe_lib, is_supported_dataframe, create_dataframe, assert_frame_equal, ): """Check if the generated DataFrame by the transformer is valid. The DataFrame implementation is specified through the para...
Check if the generated DataFrame by the transformer is valid. The DataFrame implementation is specified through the parameters of this function. Parameters ---------- name : str The name of the transformer. case : str A single case from the cases generated by `_output_from_fit_tran...
_check_generated_dataframe
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def _check_set_output_transform_dataframe( name, transformer_orig, *, dataframe_lib, is_supported_dataframe, create_dataframe, assert_frame_equal, context, ): """Check that a transformer can output a DataFrame when requested. The DataFrame implementation is specified through the...
Check that a transformer can output a DataFrame when requested. The DataFrame implementation is specified through the parameters of this function. Parameters ---------- name : str The name of the transformer. transformer_orig : estimator The original transformer instance. dataf...
_check_set_output_transform_dataframe
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_inplace_ensure_writeable(name, estimator_orig): """Check that estimators able to do inplace operations can work on read-only input data even if a copy is not explicitly requested by the user. Make sure that a copy is made and consequently that the input array and its writeability are not modi...
Check that estimators able to do inplace operations can work on read-only input data even if a copy is not explicitly requested by the user. Make sure that a copy is made and consequently that the input array and its writeability are not modified by the estimator.
check_inplace_ensure_writeable
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_do_not_raise_errors_in_init_or_set_params(name, estimator_orig): """Check that init or set_param does not raise errors.""" Estimator = type(estimator_orig) params = signature(Estimator).parameters smoke_test_values = [-1, 3.0, "helloworld", np.array([1.0, 4.0]), [1], {}, []] for value in ...
Check that init or set_param does not raise errors.
check_do_not_raise_errors_in_init_or_set_params
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def check_classifier_not_supporting_multiclass(name, estimator_orig): """Check that if the classifier has tags.classifier_tags.multi_class=False, then it should raise a ValueError when calling fit with a multiclass dataset. This test is not yielded if the tag is not False. """ estimator = clone(est...
Check that if the classifier has tags.classifier_tags.multi_class=False, then it should raise a ValueError when calling fit with a multiclass dataset. This test is not yielded if the tag is not False.
check_classifier_not_supporting_multiclass
python
scikit-learn/scikit-learn
sklearn/utils/estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/estimator_checks.py
BSD-3-Clause
def squared_norm(x): """Squared Euclidean or Frobenius norm of x. Faster than norm(x) ** 2. Parameters ---------- x : array-like The input array which could be either be a vector or a 2 dimensional array. Returns ------- float The Euclidean norm when x is a vector, the...
Squared Euclidean or Frobenius norm of x. Faster than norm(x) ** 2. Parameters ---------- x : array-like The input array which could be either be a vector or a 2 dimensional array. Returns ------- float The Euclidean norm when x is a vector, the Frobenius norm when x ...
squared_norm
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def row_norms(X, squared=False): """Row-wise (squared) Euclidean norm of X. Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse matrices and does not create an X.shape-sized temporary. Performs no input validation. Parameters ---------- X : array-like The input ar...
Row-wise (squared) Euclidean norm of X. Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse matrices and does not create an X.shape-sized temporary. Performs no input validation. Parameters ---------- X : array-like The input array. squared : bool, default=False ...
row_norms
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def fast_logdet(A): """Compute logarithm of determinant of a square matrix. The (natural) logarithm of the determinant of a square matrix is returned if det(A) is non-negative and well defined. If the determinant is zero or negative returns -Inf. Equivalent to : np.log(np.det(A)) but more robust. ...
Compute logarithm of determinant of a square matrix. The (natural) logarithm of the determinant of a square matrix is returned if det(A) is non-negative and well defined. If the determinant is zero or negative returns -Inf. Equivalent to : np.log(np.det(A)) but more robust. Parameters -------...
fast_logdet
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def density(w): """Compute density of a sparse vector. Parameters ---------- w : {ndarray, sparse matrix} The input data can be numpy ndarray or a sparse matrix. Returns ------- float The density of w, between 0 and 1. Examples -------- >>> from scipy import sp...
Compute density of a sparse vector. Parameters ---------- w : {ndarray, sparse matrix} The input data can be numpy ndarray or a sparse matrix. Returns ------- float The density of w, between 0 and 1. Examples -------- >>> from scipy import sparse >>> from sklea...
density
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def safe_sparse_dot(a, b, *, dense_output=False): """Dot product that handle the sparse matrix case correctly. Parameters ---------- a : {ndarray, sparse matrix} b : {ndarray, sparse matrix} dense_output : bool, default=False When False, ``a`` and ``b`` both being sparse will yield spar...
Dot product that handle the sparse matrix case correctly. Parameters ---------- a : {ndarray, sparse matrix} b : {ndarray, sparse matrix} dense_output : bool, default=False When False, ``a`` and ``b`` both being sparse will yield sparse output. When True, output will always be a den...
safe_sparse_dot
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def randomized_range_finder( A, *, size, n_iter, power_iteration_normalizer="auto", random_state=None ): """Compute an orthonormal matrix whose range approximates the range of A. Parameters ---------- A : {array-like, sparse matrix} of shape (n_samples, n_features) The input data matrix. ...
Compute an orthonormal matrix whose range approximates the range of A. Parameters ---------- A : {array-like, sparse matrix} of shape (n_samples, n_features) The input data matrix. size : int Size of the return array. n_iter : int Number of power iterations used to stabili...
randomized_range_finder
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def randomized_svd( M, n_components, *, n_oversamples=10, n_iter="auto", power_iteration_normalizer="auto", transpose="auto", flip_sign=True, random_state=None, svd_lapack_driver="gesdd", ): """Compute a truncated randomized SVD. This method solves the fixed-rank approxi...
Compute a truncated randomized SVD. This method solves the fixed-rank approximation problem described in [1]_ (problem (1.5), p5). Refer to :ref:`sphx_glr_auto_examples_applications_wikipedia_principal_eigenvector.py` for a typical example where the power iteration algorithm is used to rank web pa...
randomized_svd
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def weighted_mode(a, w, *, axis=0): """Return an array of the weighted modal (most common) value in the passed array. If there is more than one such value, only the first is returned. The bin-count for the modal bins is also returned. This is an extension of the algorithm in scipy.stats.mode. Par...
Return an array of the weighted modal (most common) value in the passed array. If there is more than one such value, only the first is returned. The bin-count for the modal bins is also returned. This is an extension of the algorithm in scipy.stats.mode. Parameters ---------- a : array-like o...
weighted_mode
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def cartesian(arrays, out=None): """Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. out : ndarray of shape (M, len(arrays)), default=None Array to place the cartesian product in. Return...
Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. out : ndarray of shape (M, len(arrays)), default=None Array to place the cartesian product in. Returns ------- out : ndarray of shape...
cartesian
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def svd_flip(u, v, u_based_decision=True): """Sign correction to ensure deterministic output from SVD. Adjusts the columns of u and the rows of v such that the loadings in the columns in u that are largest in absolute value are always positive. If u_based_decision is False, then the same sign correcti...
Sign correction to ensure deterministic output from SVD. Adjusts the columns of u and the rows of v such that the loadings in the columns in u that are largest in absolute value are always positive. If u_based_decision is False, then the same sign correction is applied to so that the rows in v that ar...
svd_flip
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def softmax(X, copy=True): """ Calculate the softmax function. The softmax function is calculated by np.exp(X) / np.sum(np.exp(X), axis=1) This will cause overflow when large values are exponentiated. Hence the largest value in each row is subtracted from each data point to prevent this. ...
Calculate the softmax function. The softmax function is calculated by np.exp(X) / np.sum(np.exp(X), axis=1) This will cause overflow when large values are exponentiated. Hence the largest value in each row is subtracted from each data point to prevent this. Parameters ---------- ...
softmax
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def make_nonnegative(X, min_value=0): """Ensure `X.min()` >= `min_value`. Parameters ---------- X : array-like The matrix to make non-negative. min_value : float, default=0 The threshold value. Returns ------- array-like The thresholded array. Raises --...
Ensure `X.min()` >= `min_value`. Parameters ---------- X : array-like The matrix to make non-negative. min_value : float, default=0 The threshold value. Returns ------- array-like The thresholded array. Raises ------ ValueError When X is sparse....
make_nonnegative
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def _safe_accumulator_op(op, x, *args, **kwargs): """ This function provides numpy accumulator functions with a float64 dtype when used on a floating point input. This prevents accumulator overflow on smaller floating point dtypes. Parameters ---------- op : function A numpy accumul...
This function provides numpy accumulator functions with a float64 dtype when used on a floating point input. This prevents accumulator overflow on smaller floating point dtypes. Parameters ---------- op : function A numpy accumulator function such as np.mean or np.sum. x : ndarray ...
_safe_accumulator_op
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def _incremental_mean_and_var( X, last_mean, last_variance, last_sample_count, sample_weight=None ): """Calculate mean update and a Youngs and Cramer variance update. If sample_weight is given, the weighted mean and variance is computed. Update a given mean and (possibly) variance according to new dat...
Calculate mean update and a Youngs and Cramer variance update. If sample_weight is given, the weighted mean and variance is computed. Update a given mean and (possibly) variance according to new data given in X. last_mean is always required to compute the new mean. If last_variance is None, no varianc...
_incremental_mean_and_var
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def _deterministic_vector_sign_flip(u): """Modify the sign of vectors for reproducibility. Flips the sign of elements of all the vectors (rows of u) such that the absolute maximum element of each vector is positive. Parameters ---------- u : ndarray Array with vectors as its rows. ...
Modify the sign of vectors for reproducibility. Flips the sign of elements of all the vectors (rows of u) such that the absolute maximum element of each vector is positive. Parameters ---------- u : ndarray Array with vectors as its rows. Returns ------- u_flipped : ndarray wi...
_deterministic_vector_sign_flip
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08): """Use high precision for cumsum and check that final value matches sum. Warns if the final cumulative sum does not match the sum (up to the chosen tolerance). Parameters ---------- arr : array-like To be cumulatively summed as...
Use high precision for cumsum and check that final value matches sum. Warns if the final cumulative sum does not match the sum (up to the chosen tolerance). Parameters ---------- arr : array-like To be cumulatively summed as flat. axis : int, default=None Axis along which the c...
stable_cumsum
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def _nanaverage(a, weights=None): """Compute the weighted average, ignoring NaNs. Parameters ---------- a : ndarray Array containing data to be averaged. weights : array-like, default=None An array of weights associated with the values in a. Each value in a contributes to th...
Compute the weighted average, ignoring NaNs. Parameters ---------- a : ndarray Array containing data to be averaged. weights : array-like, default=None An array of weights associated with the values in a. Each value in a contributes to the average according to its associated wei...
_nanaverage
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def safe_sqr(X, *, copy=True): """Element wise squaring of array-likes and sparse matrices. Parameters ---------- X : {array-like, ndarray, sparse matrix} copy : bool, default=True Whether to create a copy of X and operate on it or to perform inplace computation (default behaviour)...
Element wise squaring of array-likes and sparse matrices. Parameters ---------- X : {array-like, ndarray, sparse matrix} copy : bool, default=True Whether to create a copy of X and operate on it or to perform inplace computation (default behaviour). Returns ------- X ** 2 ...
safe_sqr
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def _approximate_mode(class_counts, n_draws, rng): """Computes approximate mode of multivariate hypergeometric. This is an approximation to the mode of the multivariate hypergeometric given by class_counts and n_draws. It shouldn't be off by more than one. It is the mostly likely outcome of drawin...
Computes approximate mode of multivariate hypergeometric. This is an approximation to the mode of the multivariate hypergeometric given by class_counts and n_draws. It shouldn't be off by more than one. It is the mostly likely outcome of drawing n_draws many samples from the population given by cl...
_approximate_mode
python
scikit-learn/scikit-learn
sklearn/utils/extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py
BSD-3-Clause
def _yeojohnson_lambda(_neg_log_likelihood, x): """Estimate the optimal Yeo-Johnson transformation parameter (lambda). This function provides a compatibility workaround for versions of SciPy older than 1.9.0, where `scipy.stats.yeojohnson` did not return the estimated lambda directly. Parameters ...
Estimate the optimal Yeo-Johnson transformation parameter (lambda). This function provides a compatibility workaround for versions of SciPy older than 1.9.0, where `scipy.stats.yeojohnson` did not return the estimated lambda directly. Parameters ---------- _neg_log_likelihood : callable ...
_yeojohnson_lambda
python
scikit-learn/scikit-learn
sklearn/utils/fixes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py
BSD-3-Clause
def _preserve_dia_indices_dtype( sparse_container, original_container_format, requested_sparse_format ): """Preserve indices dtype for SciPy < 1.12 when converting from DIA to CSR/CSC. For SciPy < 1.12, DIA arrays indices are upcasted to `np.int64` that is inconsistent with DIA matrices. We downcast th...
Preserve indices dtype for SciPy < 1.12 when converting from DIA to CSR/CSC. For SciPy < 1.12, DIA arrays indices are upcasted to `np.int64` that is inconsistent with DIA matrices. We downcast the indices dtype to `np.int32` to be consistent with DIA matrices. The converted indices arrays are affected...
_preserve_dia_indices_dtype
python
scikit-learn/scikit-learn
sklearn/utils/fixes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py
BSD-3-Clause
def _smallest_admissible_index_dtype(arrays=(), maxval=None, check_contents=False): """Based on input (integer) arrays `a`, determine a suitable index data type that can hold the data in the arrays. This function returns `np.int64` if it either required by `maxval` or based on the largest precision of ...
Based on input (integer) arrays `a`, determine a suitable index data type that can hold the data in the arrays. This function returns `np.int64` if it either required by `maxval` or based on the largest precision of the dtype of the arrays passed as argument, or by their contents (when `check_contents ...
_smallest_admissible_index_dtype
python
scikit-learn/scikit-learn
sklearn/utils/fixes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py
BSD-3-Clause
def _in_unstable_openblas_configuration(): """Return True if in an unstable configuration for OpenBLAS""" # Import libraries which might load OpenBLAS. import numpy # noqa: F401 import scipy # noqa: F401 modules_info = _get_threadpool_controller().info() open_blas_used = any(info["internal_...
Return True if in an unstable configuration for OpenBLAS
_in_unstable_openblas_configuration
python
scikit-learn/scikit-learn
sklearn/utils/fixes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py
BSD-3-Clause
def single_source_shortest_path_length(graph, source, *, cutoff=None): """Return the length of the shortest path from source to all reachable nodes. Parameters ---------- graph : {array-like, sparse matrix} of shape (n_nodes, n_nodes) Adjacency matrix of the graph. Sparse matrix of format LIL i...
Return the length of the shortest path from source to all reachable nodes. Parameters ---------- graph : {array-like, sparse matrix} of shape (n_nodes, n_nodes) Adjacency matrix of the graph. Sparse matrix of format LIL is preferred. source : int Start node for path. cutoff...
single_source_shortest_path_length
python
scikit-learn/scikit-learn
sklearn/utils/graph.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/graph.py
BSD-3-Clause
def _fix_connected_components( X, graph, n_connected_components, component_labels, mode="distance", metric="euclidean", **kwargs, ): """Add connections to sparse graph to connect unconnected components. For each pair of unconnected components, compute all pairwise distances from...
Add connections to sparse graph to connect unconnected components. For each pair of unconnected components, compute all pairwise distances from one component to the other, and add a connection on the closest pair of samples. This is a hacky way to get a graph with a single connected component, which is...
_fix_connected_components
python
scikit-learn/scikit-learn
sklearn/utils/graph.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/graph.py
BSD-3-Clause
def _safe_split(estimator, X, y, indices, train_indices=None): """Create subset of dataset and properly handle kernels. Slice X, y according to indices for cross-validation, but take care of precomputed kernel-matrices or pairwise affinities / distances. If ``estimator._pairwise is True``, X needs to ...
Create subset of dataset and properly handle kernels. Slice X, y according to indices for cross-validation, but take care of precomputed kernel-matrices or pairwise affinities / distances. If ``estimator._pairwise is True``, X needs to be square and we slice rows and columns. If ``train_indices`` is n...
_safe_split
python
scikit-learn/scikit-learn
sklearn/utils/metaestimators.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/metaestimators.py
BSD-3-Clause
def unique_labels(*ys): """Extract an ordered array of unique labels. We don't allow: - mix of multilabel and multiclass (single label) targets - mix of label indicator matrix and anything else, because there are no explicit labels) - mix of label indicator matrices of differe...
Extract an ordered array of unique labels. We don't allow: - mix of multilabel and multiclass (single label) targets - mix of label indicator matrix and anything else, because there are no explicit labels) - mix of label indicator matrices of different sizes - mix of strin...
unique_labels
python
scikit-learn/scikit-learn
sklearn/utils/multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py
BSD-3-Clause
def is_multilabel(y): """Check if ``y`` is in a multilabel format. Parameters ---------- y : ndarray of shape (n_samples,) Target values. Returns ------- out : bool Return ``True``, if ``y`` is in a multilabel format, else ``False``. Examples -------- >>> impor...
Check if ``y`` is in a multilabel format. Parameters ---------- y : ndarray of shape (n_samples,) Target values. Returns ------- out : bool Return ``True``, if ``y`` is in a multilabel format, else ``False``. Examples -------- >>> import numpy as np >>> from sk...
is_multilabel
python
scikit-learn/scikit-learn
sklearn/utils/multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py
BSD-3-Clause
def check_classification_targets(y): """Ensure that target y is of a non-regression type. Only the following target types (as defined in type_of_target) are allowed: 'binary', 'multiclass', 'multiclass-multioutput', 'multilabel-indicator', 'multilabel-sequences' Parameters ---------- ...
Ensure that target y is of a non-regression type. Only the following target types (as defined in type_of_target) are allowed: 'binary', 'multiclass', 'multiclass-multioutput', 'multilabel-indicator', 'multilabel-sequences' Parameters ---------- y : array-like Target values. ...
check_classification_targets
python
scikit-learn/scikit-learn
sklearn/utils/multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py
BSD-3-Clause
def type_of_target(y, input_name="", raise_unknown=False): """Determine the type of data indicated by the target. Note that this type is the most specific type that can be inferred. For example: * ``binary`` is more specific but compatible with ``multiclass``. * ``multiclass`` of integers is more ...
Determine the type of data indicated by the target. Note that this type is the most specific type that can be inferred. For example: * ``binary`` is more specific but compatible with ``multiclass``. * ``multiclass`` of integers is more specific but compatible with ``continuous``. * ``multilabel-in...
type_of_target
python
scikit-learn/scikit-learn
sklearn/utils/multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py
BSD-3-Clause
def _raise_or_return(): """Depending on the value of raise_unknown, either raise an error or return 'unknown'. """ if raise_unknown: input = input_name if input_name else "data" raise ValueError(f"Unknown label type for {input}: {y!r}") else: r...
Depending on the value of raise_unknown, either raise an error or return 'unknown'.
_raise_or_return
python
scikit-learn/scikit-learn
sklearn/utils/multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py
BSD-3-Clause
def _check_partial_fit_first_call(clf, classes=None): """Private helper function for factorizing common classes param logic. Estimators that implement the ``partial_fit`` API need to be provided with the list of possible classes at the first call to partial_fit. Subsequent calls to partial_fit should ...
Private helper function for factorizing common classes param logic. Estimators that implement the ``partial_fit`` API need to be provided with the list of possible classes at the first call to partial_fit. Subsequent calls to partial_fit should check that ``classes`` is still consistent with a previou...
_check_partial_fit_first_call
python
scikit-learn/scikit-learn
sklearn/utils/multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py
BSD-3-Clause
def class_distribution(y, sample_weight=None): """Compute class priors from multioutput-multiclass target data. Parameters ---------- y : {array-like, sparse matrix} of size (n_samples, n_outputs) The labels for each example. sample_weight : array-like of shape (n_samples,), default=None ...
Compute class priors from multioutput-multiclass target data. Parameters ---------- y : {array-like, sparse matrix} of size (n_samples, n_outputs) The labels for each example. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- cl...
class_distribution
python
scikit-learn/scikit-learn
sklearn/utils/multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py
BSD-3-Clause
def _ovr_decision_function(predictions, confidences, n_classes): """Compute a continuous, tie-breaking OvR decision function from OvO. It is important to include a continuous value, not only votes, to make computing AUC or calibration meaningful. Parameters ---------- predictions : array-like ...
Compute a continuous, tie-breaking OvR decision function from OvO. It is important to include a continuous value, not only votes, to make computing AUC or calibration meaningful. Parameters ---------- predictions : array-like of shape (n_samples, n_classifiers) Predicted classes for each b...
_ovr_decision_function
python
scikit-learn/scikit-learn
sklearn/utils/multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py
BSD-3-Clause
def _line_search_wolfe12( f, fprime, xk, pk, gfk, old_fval, old_old_fval, verbose=0, **kwargs ): """ Same as line_search_wolfe1, but fall back to line_search_wolfe2 if suitable step length is not found, and raise an exception if a suitable step length is not found. Raises ------ _LineSe...
Same as line_search_wolfe1, but fall back to line_search_wolfe2 if suitable step length is not found, and raise an exception if a suitable step length is not found. Raises ------ _LineSearchError If no suitable step size is found.
_line_search_wolfe12
python
scikit-learn/scikit-learn
sklearn/utils/optimize.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/optimize.py
BSD-3-Clause
def _cg(fhess_p, fgrad, maxiter, tol, verbose=0): """ Solve iteratively the linear system 'fhess_p . xsupi = fgrad' with a conjugate gradient descent. Parameters ---------- fhess_p : callable Function that takes the gradient as a parameter and returns the matrix product of the H...
Solve iteratively the linear system 'fhess_p . xsupi = fgrad' with a conjugate gradient descent. Parameters ---------- fhess_p : callable Function that takes the gradient as a parameter and returns the matrix product of the Hessian and gradient. fgrad : ndarray of shape (n_fea...
_cg
python
scikit-learn/scikit-learn
sklearn/utils/optimize.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/optimize.py
BSD-3-Clause
def _newton_cg( grad_hess, func, grad, x0, args=(), tol=1e-4, maxiter=100, maxinner=200, line_search=True, warn=True, verbose=0, ): """ Minimization of scalar function of one or more variables using the Newton-CG algorithm. Parameters ---------- grad_...
Minimization of scalar function of one or more variables using the Newton-CG algorithm. Parameters ---------- grad_hess : callable Should return the gradient and a callable returning the matvec product of the Hessian. func : callable Should return the value of the func...
_newton_cg
python
scikit-learn/scikit-learn
sklearn/utils/optimize.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/optimize.py
BSD-3-Clause
def _check_optimize_result(solver, result, max_iter=None, extra_warning_msg=None): """Check the OptimizeResult for successful convergence Parameters ---------- solver : str Solver name. Currently only `lbfgs` is supported. result : OptimizeResult Result of the scipy.optimize.minimize...
Check the OptimizeResult for successful convergence Parameters ---------- solver : str Solver name. Currently only `lbfgs` is supported. result : OptimizeResult Result of the scipy.optimize.minimize function. max_iter : int, default=None Expected maximum number of iterations....
_check_optimize_result
python
scikit-learn/scikit-learn
sklearn/utils/optimize.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/optimize.py
BSD-3-Clause
def _with_config_and_warning_filters(delayed_func, config, warning_filters): """Helper function that intends to attach a config to a delayed function.""" if hasattr(delayed_func, "with_config_and_warning_filters"): return delayed_func.with_config_and_warning_filters(config, warning_filters) else: ...
Helper function that intends to attach a config to a delayed function.
_with_config_and_warning_filters
python
scikit-learn/scikit-learn
sklearn/utils/parallel.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/parallel.py
BSD-3-Clause
def __call__(self, iterable): """Dispatch the tasks and return the results. Parameters ---------- iterable : iterable Iterable containing tuples of (delayed_function, args, kwargs) that should be consumed. Returns ------- results : list ...
Dispatch the tasks and return the results. Parameters ---------- iterable : iterable Iterable containing tuples of (delayed_function, args, kwargs) that should be consumed. Returns ------- results : list List of results of the tasks. ...
__call__
python
scikit-learn/scikit-learn
sklearn/utils/parallel.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/parallel.py
BSD-3-Clause
def delayed(function): """Decorator used to capture the arguments of a function. This alternative to `joblib.delayed` is meant to be used in conjunction with `sklearn.utils.parallel.Parallel`. The latter captures the scikit- learn configuration by calling `sklearn.get_config()` in the current threa...
Decorator used to capture the arguments of a function. This alternative to `joblib.delayed` is meant to be used in conjunction with `sklearn.utils.parallel.Parallel`. The latter captures the scikit- learn configuration by calling `sklearn.get_config()` in the current thread, prior to dispatching the fi...
delayed
python
scikit-learn/scikit-learn
sklearn/utils/parallel.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/parallel.py
BSD-3-Clause
def _get_threadpool_controller(): """Return the global threadpool controller instance.""" global _threadpool_controller if _threadpool_controller is None: _threadpool_controller = ThreadpoolController() return _threadpool_controller
Return the global threadpool controller instance.
_get_threadpool_controller
python
scikit-learn/scikit-learn
sklearn/utils/parallel.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/parallel.py
BSD-3-Clause
def _random_choice_csc(n_samples, classes, class_probability=None, random_state=None): """Generate a sparse random matrix given column class distributions Parameters ---------- n_samples : int, Number of samples to draw in each column. classes : list of size n_outputs of arrays of size (n_...
Generate a sparse random matrix given column class distributions Parameters ---------- n_samples : int, Number of samples to draw in each column. classes : list of size n_outputs of arrays of size (n_classes,) List of classes for each column. class_probability : list of size n_out...
_random_choice_csc
python
scikit-learn/scikit-learn
sklearn/utils/random.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/random.py
BSD-3-Clause
def _raise_typeerror(X): """Raises a TypeError if X is not a CSR or CSC matrix""" input_type = X.format if sp.issparse(X) else type(X) err = "Expected a CSR or CSC sparse matrix, got %s." % input_type raise TypeError(err)
Raises a TypeError if X is not a CSR or CSC matrix
_raise_typeerror
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 inplace_csr_column_scale(X, scale): """Inplace column scaling of a CSR matrix. Scale each feature of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) ...
Inplace column scaling of a CSR matrix. Scale each feature of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix to normalize using the variance ...
inplace_csr_column_scale
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 inplace_csr_row_scale(X, scale): """Inplace row scaling of a CSR matrix. Scale each sample of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) ...
Inplace row scaling of a CSR matrix. Scale each sample of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix to be scaled. It should be of CSR fo...
inplace_csr_row_scale
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 mean_variance_axis(X, axis, weights=None, return_sum_weights=False): """Compute mean and variance along an axis on a CSR or CSC matrix. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Input data. It can be of CSR or CSC format. axis : {0, 1} Axis along ...
Compute mean and variance along an axis on a CSR or CSC matrix. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Input data. It can be of CSR or CSC format. axis : {0, 1} Axis along which the axis should be computed. weights : ndarray of shape (n_samples,) ...
mean_variance_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 incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None): """Compute incremental mean and variance along an axis on a CSR or CSC matrix. last_mean, last_var are the statistics computed at the last step by this function. Both must be initialized to 0-arrays of the proper size, i.e....
Compute incremental mean and variance along an axis on a CSR or CSC matrix. last_mean, last_var are the statistics computed at the last step by this function. Both must be initialized to 0-arrays of the proper size, i.e. the number of features in X. last_n is the number of samples encountered until now...
incr_mean_variance_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 inplace_column_scale(X, scale): """Inplace column scaling of a CSC/CSR matrix. Scale each feature of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) ...
Inplace column scaling of a CSC/CSR matrix. Scale each feature of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix to normalize using the varia...
inplace_column_scale
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 inplace_row_scale(X, scale): """Inplace row scaling of a CSR or CSC matrix. Scale each row of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) ...
Inplace row scaling of a CSR or CSC matrix. Scale each row of the data matrix by multiplying with specific scale provided by the caller assuming a (n_samples, n_features) shape. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix to be scaled. It should be of CS...
inplace_row_scale
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 inplace_swap_row_csc(X, m, n): """Swap two rows of a CSC matrix in-place. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix whose two rows are to be swapped. It should be of CSC format. m : int Index of the row of X to be swapped. n : ...
Swap two rows of a CSC matrix in-place. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix whose two rows are to be swapped. It should be of CSC format. m : int Index of the row of X to be swapped. n : int Index of the row of X to be sw...
inplace_swap_row_csc
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 inplace_swap_row_csr(X, m, n): """Swap two rows of a CSR matrix in-place. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix whose two rows are to be swapped. It should be of CSR format. m : int Index of the row of X to be swapped. n : ...
Swap two rows of a CSR matrix in-place. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix whose two rows are to be swapped. It should be of CSR format. m : int Index of the row of X to be swapped. n : int Index of the row of X to be sw...
inplace_swap_row_csr
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 inplace_swap_row(X, m, n): """ Swap two rows of a CSC/CSR matrix in-place. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix whose two rows are to be swapped. It should be of CSR or CSC format. m : int Index of the row of X to be swappe...
Swap two rows of a CSC/CSR matrix in-place. Parameters ---------- X : sparse matrix of shape (n_samples, n_features) Matrix whose two rows are to be swapped. It should be of CSR or CSC format. m : int Index of the row of X to be swapped. n : int Index of the r...
inplace_swap_row
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 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