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 get_n_splits(self, X, y=None, groups=None): """Returns the number of splitting iterations in the cross-validator. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` ...
Returns the number of splitting iterations in the cross-validator. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : object ...
get_n_splits
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def get_n_splits(self, X, y=None, groups=None): """Returns the number of splitting iterations in the cross-validator. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` ...
Returns the number of splitting iterations in the cross-validator. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : object ...
get_n_splits
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def split(self, X, y=None, groups=None): """Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number o...
Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samp...
split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def split(self, X, y, groups=None): """Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of fea...
Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. Note that providing ``y`` i...
split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def split(self, X, y=None, groups=None): """Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number o...
Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samp...
split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def _split(self, X): """Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. ...
Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. Yields ------ t...
_split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def split(self, X, y=None, groups=None): """Generates indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number ...
Generates indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_sam...
split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def get_n_splits(self, X=None, y=None, groups=None): """Returns the number of splitting iterations in the cross-validator. Parameters ---------- X : object Always ignored, exists for compatibility. ``np.zeros(n_samples)`` may be used as a placeholder. y ...
Returns the number of splitting iterations in the cross-validator. Parameters ---------- X : object Always ignored, exists for compatibility. ``np.zeros(n_samples)`` may be used as a placeholder. y : object Always ignored, exists for compatibility. ...
get_n_splits
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def split(self, X, y=None, groups=None): """Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number o...
Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samp...
split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def split(self, X, y, groups=None): """Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of fea...
Generate indices to split data into training and test set. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. Note that providing ``y`` i...
split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def _validate_shuffle_split(n_samples, test_size, train_size, default_test_size=None): """ Validation helper to check if the train/test sizes are meaningful w.r.t. the size of the data (n_samples). """ if test_size is None and train_size is None: test_size = default_test_size test_size_...
Validation helper to check if the train/test sizes are meaningful w.r.t. the size of the data (n_samples).
_validate_shuffle_split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def split(self, X=None, y=None, groups=None): """Generate indices to split data into training and test set. Parameters ---------- X : object Always ignored, exists for compatibility. y : object Always ignored, exists for compatibility. groups : ...
Generate indices to split data into training and test set. Parameters ---------- X : object Always ignored, exists for compatibility. y : object Always ignored, exists for compatibility. groups : object Always ignored, exists for compatibili...
split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def _split(self): """Generate indices to split data into training and test set. Yields ------ train : ndarray The training set indices for that split. test : ndarray The testing set indices for that split. """ ind = np.arange(len(self.tes...
Generate indices to split data into training and test set. Yields ------ train : ndarray The training set indices for that split. test : ndarray The testing set indices for that split.
_split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def _iter_test_masks(self): """Generates boolean masks corresponding to test sets.""" for f in self.unique_folds: test_index = np.where(self.test_fold == f)[0] test_mask = np.zeros(len(self.test_fold), dtype=bool) test_mask[test_index] = True yield test_ma...
Generates boolean masks corresponding to test sets.
_iter_test_masks
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def check_cv(cv=5, y=None, *, classifier=False): """Input checker utility for building a cross-validator. Parameters ---------- cv : int, cross-validation generator, iterable or None, default=5 Determines the cross-validation splitting strategy. Possible inputs for cv are: - Non...
Input checker utility for building a cross-validator. Parameters ---------- cv : int, cross-validation generator, iterable or None, default=5 Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold cross validation, -...
check_cv
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def train_test_split( *arrays, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None, ): """Split arrays or matrices into random train and test subsets. Quick utility that wraps input validation, ``next(ShuffleSplit().split(X, y))``, and application to inpu...
Split arrays or matrices into random train and test subsets. Quick utility that wraps input validation, ``next(ShuffleSplit().split(X, y))``, and application to input data into a single call for splitting (and optionally subsampling) data into a one-liner. Read more in the :ref:`User Guide <cross_...
train_test_split
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def _pprint(params, offset=0, printer=repr): """Pretty print the dictionary 'params' Parameters ---------- params : dict The dictionary to pretty print offset : int, default=0 The offset in characters to add at the begin of each line. printer : callable, default=repr T...
Pretty print the dictionary 'params' Parameters ---------- params : dict The dictionary to pretty print offset : int, default=0 The offset in characters to add at the begin of each line. printer : callable, default=repr The function to convert entries to strings, typically...
_pprint
python
scikit-learn/scikit-learn
sklearn/model_selection/_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py
BSD-3-Clause
def _check_params_groups_deprecation(fit_params, params, groups, version): """A helper function to check deprecations on `groups` and `fit_params`. # TODO(SLEP6): To be removed when set_config(enable_metadata_routing=False) is not # possible. """ if params is not None and fit_params is not None: ...
A helper function to check deprecations on `groups` and `fit_params`. # TODO(SLEP6): To be removed when set_config(enable_metadata_routing=False) is not # possible.
_check_params_groups_deprecation
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def cross_validate( estimator, X, y=None, *, groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, params=None, pre_dispatch="2*n_jobs", return_train_score=False, return_estimator=False, return_indices=False, error_score=np.nan, ): """Evaluate metric...
Evaluate metric(s) by cross-validation and also record fit/score times. Read more in the :ref:`User Guide <multimetric_cross_validation>`. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : {array-like, sparse matrix} of shape (n_s...
cross_validate
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _insert_error_scores(results, error_score): """Insert error in `results` by replacing them inplace with `error_score`. This only applies to multimetric scores because `_fit_and_score` will handle the single metric case. """ successful_score = None failed_indices = [] for i, result in en...
Insert error in `results` by replacing them inplace with `error_score`. This only applies to multimetric scores because `_fit_and_score` will handle the single metric case.
_insert_error_scores
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _normalize_score_results(scores, scaler_score_key="score"): """Creates a scoring dictionary based on the type of `scores`""" if isinstance(scores[0], dict): # multimetric scoring return _aggregate_score_dicts(scores) # scaler return {scaler_score_key: scores}
Creates a scoring dictionary based on the type of `scores`
_normalize_score_results
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _fit_and_score( estimator, X, y, *, scorer, train, test, verbose, parameters, fit_params, score_params, return_train_score=False, return_parameters=False, return_n_test_samples=False, return_times=False, return_estimator=False, split_progress=None,...
Fit estimator and compute scores for a given dataset split. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like of shape (n_samples, n_features) The data to fit. y : array-like of shape (n_samples,) or (n_samples,...
_fit_and_score
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _score(estimator, X_test, y_test, scorer, score_params, error_score="raise"): """Compute the score(s) of an estimator on a given test set. Will return a dict of floats if `scorer` is a _MultiMetricScorer, otherwise a single float is returned. """ score_params = {} if score_params is None else s...
Compute the score(s) of an estimator on a given test set. Will return a dict of floats if `scorer` is a _MultiMetricScorer, otherwise a single float is returned.
_score
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def cross_val_predict( estimator, X, y=None, *, groups=None, cv=None, n_jobs=None, verbose=0, params=None, pre_dispatch="2*n_jobs", method="predict", ): """Generate cross-validated estimates for each input data point. The data is split according to the cv parameter. ...
Generate cross-validated estimates for each input data point. The data is split according to the cv parameter. Each sample belongs to exactly one test set, and its prediction is computed with an estimator fitted on the corresponding training set. Passing these predictions into an evaluation metric may...
cross_val_predict
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _fit_and_predict(estimator, X, y, train, test, fit_params, method): """Fit estimator and predict values for a given dataset split. Read more in the :ref:`User Guide <cross_validation>`. Parameters ---------- estimator : estimator object implementing 'fit' and 'predict' The object to us...
Fit estimator and predict values for a given dataset split. Read more in the :ref:`User Guide <cross_validation>`. Parameters ---------- estimator : estimator object implementing 'fit' and 'predict' The object to use to fit the data. X : array-like of shape (n_samples, n_features) ...
_fit_and_predict
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _enforce_prediction_order(classes, predictions, n_classes, method): """Ensure that prediction arrays have correct column order When doing cross-validation, if one or more classes are not present in the subset of data used for training, then the output prediction array might not have the same co...
Ensure that prediction arrays have correct column order When doing cross-validation, if one or more classes are not present in the subset of data used for training, then the output prediction array might not have the same columns as other folds. Use the list of class names (assumed to be ints) to e...
_enforce_prediction_order
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _check_is_permutation(indices, n_samples): """Check whether indices is a reordering of the array np.arange(n_samples) Parameters ---------- indices : ndarray int array to test n_samples : int number of expected elements Returns ------- is_partition : bool Tr...
Check whether indices is a reordering of the array np.arange(n_samples) Parameters ---------- indices : ndarray int array to test n_samples : int number of expected elements Returns ------- is_partition : bool True iff sorted(indices) is np.arange(n)
_check_is_permutation
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def permutation_test_score( estimator, X, y, *, groups=None, cv=None, n_permutations=100, n_jobs=None, random_state=0, verbose=0, scoring=None, fit_params=None, params=None, ): """Evaluate the significance of a cross-validated score with permutations. Permute...
Evaluate the significance of a cross-validated score with permutations. Permutes targets to generate 'randomized data' and compute the empirical p-value against the null hypothesis that features and targets are independent. The p-value represents the fraction of randomized data sets where the esti...
permutation_test_score
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _shuffle(y, groups, random_state): """Return a shuffled copy of y eventually shuffle among same groups.""" if groups is None: indices = random_state.permutation(len(y)) else: indices = np.arange(len(groups)) for group in np.unique(groups): this_mask = groups == group ...
Return a shuffled copy of y eventually shuffle among same groups.
_shuffle
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def learning_curve( estimator, X, y, *, groups=None, train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None, exploit_incremental_learning=False, n_jobs=None, pre_dispatch="all", verbose=0, shuffle=False, random_state=None, error_score=np.nan, return_t...
Learning curve. Determines cross-validated training and test scores for different training set sizes. A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each tra...
learning_curve
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _translate_train_sizes(train_sizes, n_max_training_samples): """Determine absolute sizes of training subsets and validate 'train_sizes'. Examples: _translate_train_sizes([0.5, 1.0], 10) -> [5, 10] _translate_train_sizes([5, 10], 10) -> [5, 10] Parameters ---------- train_sizes ...
Determine absolute sizes of training subsets and validate 'train_sizes'. Examples: _translate_train_sizes([0.5, 1.0], 10) -> [5, 10] _translate_train_sizes([5, 10], 10) -> [5, 10] Parameters ---------- train_sizes : array-like of shape (n_ticks,) Numbers of training examples th...
_translate_train_sizes
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _incremental_fit_estimator( estimator, X, y, classes, train, test, train_sizes, scorer, return_times, error_score, fit_params, score_params, ): """Train estimator on training subsets incrementally and compute scores.""" train_scores, test_scores, fit_times, sc...
Train estimator on training subsets incrementally and compute scores.
_incremental_fit_estimator
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def validation_curve( estimator, X, y, *, param_name, param_range, groups=None, cv=None, scoring=None, n_jobs=None, pre_dispatch="all", verbose=0, error_score=np.nan, fit_params=None, params=None, ): """Validation curve. Determine training and test sc...
Validation curve. Determine training and test scores for varying parameter values. Compute scores for an estimator with different values of a specified parameter. This is similar to grid search with one parameter. However, this will also compute training scores and is merely a utility for plotting the...
validation_curve
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def _aggregate_score_dicts(scores): """Aggregate the list of dict to dict of np ndarray The aggregated output of _aggregate_score_dicts will be a list of dict of form [{'prec': 0.1, 'acc':1.0}, {'prec': 0.1, 'acc':1.0}, ...] Convert it to a dict of array {'prec': np.array([0.1 ...]), ...} Paramete...
Aggregate the list of dict to dict of np ndarray The aggregated output of _aggregate_score_dicts will be a list of dict of form [{'prec': 0.1, 'acc':1.0}, {'prec': 0.1, 'acc':1.0}, ...] Convert it to a dict of array {'prec': np.array([0.1 ...]), ...} Parameters ---------- scores : list of dic...
_aggregate_score_dicts
python
scikit-learn/scikit-learn
sklearn/model_selection/_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py
BSD-3-Clause
def test_fit_and_score_over_thresholds_curve_scorers(): """Check that `_fit_and_score_over_thresholds` returns thresholds in ascending order for the different accepted curve scorers.""" X, y = make_classification(n_samples=100, random_state=0) train_idx, val_idx = np.arange(50), np.arange(50, 100) c...
Check that `_fit_and_score_over_thresholds` returns thresholds in ascending order for the different accepted curve scorers.
test_fit_and_score_over_thresholds_curve_scorers
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_fit_and_score_over_thresholds_prefit(): """Check the behaviour with a prefit classifier.""" X, y = make_classification(n_samples=100, random_state=0) # `train_idx is None` to indicate that the classifier is prefit train_idx, val_idx = None, np.arange(50, 100) classifier = DecisionTreeClass...
Check the behaviour with a prefit classifier.
test_fit_and_score_over_thresholds_prefit
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_fit_and_score_over_thresholds_sample_weight(): """Check that we dispatch the sample-weight to fit and score the classifier.""" X, y = load_iris(return_X_y=True) X, y = X[:100], y[:100] # only 2 classes # create a dataset and repeat twice the sample of class #0 X_repeated, y_repeated = np....
Check that we dispatch the sample-weight to fit and score the classifier.
test_fit_and_score_over_thresholds_sample_weight
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_fit_and_score_over_thresholds_fit_params(fit_params_type): """Check that we pass `fit_params` to the classifier when calling `fit`.""" X, y = make_classification(n_samples=100, random_state=0) fit_params = { "a": _convert_container(y, fit_params_type), "b": _convert_container(y, fit...
Check that we pass `fit_params` to the classifier when calling `fit`.
test_fit_and_score_over_thresholds_fit_params
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_no_binary(data): """Check that we raise an informative error message for non-binary problem.""" err_msg = "Only binary classification is supported." with pytest.raises(ValueError, match=err_msg): TunedThresholdClassifierCV(LogisticRegression()).fit(*data)
Check that we raise an informative error message for non-binary problem.
test_tuned_threshold_classifier_no_binary
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_conflict_cv_refit(params, err_type, err_msg): """Check that we raise an informative error message when `cv` and `refit` cannot be used together. """ X, y = make_classification(n_samples=100, random_state=0) with pytest.raises(err_type, match=err_msg): Tune...
Check that we raise an informative error message when `cv` and `refit` cannot be used together.
test_tuned_threshold_classifier_conflict_cv_refit
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_threshold_classifier_estimator_response_methods( ThresholdClassifier, estimator, response_method ): """Check that `TunedThresholdClassifierCV` exposes the same response methods as the underlying estimator. """ X, y = make_classification(n_samples=100, random_state=0) model = ThresholdC...
Check that `TunedThresholdClassifierCV` exposes the same response methods as the underlying estimator.
test_threshold_classifier_estimator_response_methods
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_without_constraint_value(response_method): """Check that `TunedThresholdClassifierCV` is optimizing a given objective metric.""" X, y = load_breast_cancer(return_X_y=True) # remove feature to degrade performances X = X[:, :5] # make the problem completely imb...
Check that `TunedThresholdClassifierCV` is optimizing a given objective metric.
test_tuned_threshold_classifier_without_constraint_value
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_metric_with_parameter(): """Check that we can pass a metric with a parameter in addition check that `f_beta` with `beta=1` is equivalent to `f1` and different from `f_beta` with `beta=2`. """ X, y = load_breast_cancer(return_X_y=True) lr = make_pipeline(Standa...
Check that we can pass a metric with a parameter in addition check that `f_beta` with `beta=1` is equivalent to `f1` and different from `f_beta` with `beta=2`.
test_tuned_threshold_classifier_metric_with_parameter
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_with_string_targets(response_method, metric): """Check that targets represented by str are properly managed. Also, check with several metrics to be sure that `pos_label` is properly dispatched. """ X, y = load_breast_cancer(return_X_y=True) # Encode numeric ta...
Check that targets represented by str are properly managed. Also, check with several metrics to be sure that `pos_label` is properly dispatched.
test_tuned_threshold_classifier_with_string_targets
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_refit(with_sample_weight, global_random_seed): """Check the behaviour of the `refit` parameter.""" rng = np.random.RandomState(global_random_seed) X, y = make_classification(n_samples=100, random_state=0) if with_sample_weight: sample_weight = rng.randn(X.shap...
Check the behaviour of the `refit` parameter.
test_tuned_threshold_classifier_refit
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_cv_zeros_sample_weights_equivalence(): """Check that passing removing some sample from the dataset `X` is equivalent to passing a `sample_weight` with a factor 0.""" X, y = load_iris(return_X_y=True) # Scale the data to avoid any convergence issue X = StandardScal...
Check that passing removing some sample from the dataset `X` is equivalent to passing a `sample_weight` with a factor 0.
test_tuned_threshold_classifier_cv_zeros_sample_weights_equivalence
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_thresholds_array(): """Check that we can pass an array to `thresholds` and it is used as candidate threshold internally.""" X, y = make_classification(random_state=0) estimator = LogisticRegression() thresholds = np.linspace(0, 1, 11) tuned_model = TunedThresh...
Check that we can pass an array to `thresholds` and it is used as candidate threshold internally.
test_tuned_threshold_classifier_thresholds_array
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_store_cv_results(store_cv_results): """Check that if `cv_results_` exists depending on `store_cv_results`.""" X, y = make_classification(random_state=0) estimator = LogisticRegression() tuned_model = TunedThresholdClassifierCV( estimator, store_cv_results=stor...
Check that if `cv_results_` exists depending on `store_cv_results`.
test_tuned_threshold_classifier_store_cv_results
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_cv_float(): """Check the behaviour when `cv` is set to a float.""" X, y = make_classification(random_state=0) # case where `refit=False` and cv is a float: the underlying estimator will be fit # on the training set given by a ShuffleSplit. We check that we get the sa...
Check the behaviour when `cv` is set to a float.
test_tuned_threshold_classifier_cv_float
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_tuned_threshold_classifier_error_constant_predictor(): """Check that we raise a ValueError if the underlying classifier returns constant probabilities such that we cannot find any threshold. """ X, y = make_classification(random_state=0) estimator = DummyClassifier(strategy="constant", cons...
Check that we raise a ValueError if the underlying classifier returns constant probabilities such that we cannot find any threshold.
test_tuned_threshold_classifier_error_constant_predictor
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_fixed_threshold_classifier_equivalence_default(response_method): """Check that `FixedThresholdClassifier` has the same behaviour as the vanilla classifier. """ X, y = make_classification(random_state=0) classifier = LogisticRegression().fit(X, y) classifier_default_threshold = FixedThre...
Check that `FixedThresholdClassifier` has the same behaviour as the vanilla classifier.
test_fixed_threshold_classifier_equivalence_default
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_fixed_threshold_classifier(response_method, threshold, pos_label): """Check that applying `predict` lead to the same prediction as applying the threshold to the output of the response method. """ X, y = make_classification(n_samples=50, random_state=0) logistic_regression = LogisticRegressi...
Check that applying `predict` lead to the same prediction as applying the threshold to the output of the response method.
test_fixed_threshold_classifier
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_fixed_threshold_classifier_metadata_routing(): """Check that everything works with metadata routing.""" X, y = make_classification(random_state=0) sample_weight = np.ones_like(y) sample_weight[::2] = 2 classifier = LogisticRegression().set_fit_request(sample_weight=True) classifier.fit(...
Check that everything works with metadata routing.
test_fixed_threshold_classifier_metadata_routing
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_fixed_threshold_classifier_fitted_estimator(method): """Check that if the underlying estimator is already fitted, no fit is required.""" X, y = make_classification(random_state=0) classifier = LogisticRegression().fit(X, y) fixed_threshold_classifier = FixedThresholdClassifier(estimator=classif...
Check that if the underlying estimator is already fitted, no fit is required.
test_fixed_threshold_classifier_fitted_estimator
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_fixed_threshold_classifier_classes_(): """Check that the classes_ attribute is properly set.""" X, y = make_classification(random_state=0) with pytest.raises( AttributeError, match="The underlying estimator is not fitted yet." ): FixedThresholdClassifier(estimator=LogisticRegres...
Check that the classes_ attribute is properly set.
test_fixed_threshold_classifier_classes_
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_classification_threshold.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py
BSD-3-Clause
def test_curve_display_parameters_validation( pyplot, data, params, err_type, err_msg, CurveDisplay, specific_params ): """Check that we raise a proper error when passing invalid parameters.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) with pytest.raises(err_type, match=err_msg...
Check that we raise a proper error when passing invalid parameters.
test_curve_display_parameters_validation
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_learning_curve_display_default_usage(pyplot, data): """Check the default usage of the LearningCurveDisplay class.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) train_sizes = [0.3, 0.6, 0.9] display = LearningCurveDisplay.from_estimator( estimator, X, y, train_si...
Check the default usage of the LearningCurveDisplay class.
test_learning_curve_display_default_usage
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_validation_curve_display_default_usage(pyplot, data): """Check the default usage of the ValidationCurveDisplay class.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) param_name, param_range = "max_depth", [1, 3, 5] display = ValidationCurveDisplay.from_estimator( ...
Check the default usage of the ValidationCurveDisplay class.
test_validation_curve_display_default_usage
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_curve_display_negate_score(pyplot, data, CurveDisplay, specific_params): """Check the behaviour of the `negate_score` parameter calling `from_estimator` and `plot`. """ X, y = data estimator = DecisionTreeClassifier(max_depth=1, random_state=0) negate_score = False display = CurveD...
Check the behaviour of the `negate_score` parameter calling `from_estimator` and `plot`.
test_curve_display_negate_score
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_curve_display_score_name( pyplot, data, score_name, ylabel, CurveDisplay, specific_params ): """Check that we can overwrite the default score name shown on the y-axis.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) display = CurveDisplay.from_estimator( estimator...
Check that we can overwrite the default score name shown on the y-axis.
test_curve_display_score_name
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_learning_curve_display_score_type(pyplot, data, std_display_style): """Check the behaviour of setting the `score_type` parameter.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) train_sizes = [0.3, 0.6, 0.9] train_sizes_abs, train_scores, test_scores = learning_curve( ...
Check the behaviour of setting the `score_type` parameter.
test_learning_curve_display_score_type
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_curve_display_xscale_auto( pyplot, data, CurveDisplay, specific_params, expected_xscale ): """Check the behaviour of the x-axis scaling depending on the data provided.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) display = CurveDisplay.from_estimator(estimator, X, y, *...
Check the behaviour of the x-axis scaling depending on the data provided.
test_curve_display_xscale_auto
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_curve_display_std_display_style(pyplot, data, CurveDisplay, specific_params): """Check the behaviour of the parameter `std_display_style`.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) import matplotlib as mpl std_display_style = None display = CurveDisplay.from_es...
Check the behaviour of the parameter `std_display_style`.
test_curve_display_std_display_style
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_curve_display_plot_kwargs(pyplot, data, CurveDisplay, specific_params): """Check the behaviour of the different plotting keyword arguments: `line_kw`, `fill_between_kw`, and `errorbar_kw`.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) std_display_style = "fill_between" ...
Check the behaviour of the different plotting keyword arguments: `line_kw`, `fill_between_kw`, and `errorbar_kw`.
test_curve_display_plot_kwargs
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_validation_curve_xscale_from_param_range_provided_as_a_list( pyplot, data, param_range, xscale ): """Check the induced xscale from the provided param_range values.""" X, y = data estimator = DecisionTreeClassifier(random_state=0) param_name = "max_depth" display = ValidationCurveDispla...
Check the induced xscale from the provided param_range values.
test_validation_curve_xscale_from_param_range_provided_as_a_list
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_plot.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_plot.py
BSD-3-Clause
def test_refit_callable(): """ Test refit=callable, which adds flexibility in identifying the "best" estimator. """ def refit_callable(cv_results): """ A dummy function tests `refit=callable` interface. Return the index of a model that has the least `mean_test_score`...
Test refit=callable, which adds flexibility in identifying the "best" estimator.
test_refit_callable
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def refit_callable(cv_results): """ A dummy function tests `refit=callable` interface. Return the index of a model that has the least `mean_test_score`. """ # Fit a dummy clf with `refit=True` to get a list of keys in # clf.cv_results_. X, y = make_classif...
A dummy function tests `refit=callable` interface. Return the index of a model that has the least `mean_test_score`.
refit_callable
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_refit_callable_invalid_type(): """ Test implementation catches the errors when 'best_index_' returns an invalid result. """ def refit_callable_invalid_type(cv_results): """ A dummy function tests when returned 'best_index_' is not integer. """ return None ...
Test implementation catches the errors when 'best_index_' returns an invalid result.
test_refit_callable_invalid_type
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_refit_callable_out_bound(out_bound_value, search_cv): """ Test implementation catches the errors when 'best_index_' returns an out of bound result. """ def refit_callable_out_bound(cv_results): """ A dummy function tests when returned 'best_index_' is out of bounds. ...
Test implementation catches the errors when 'best_index_' returns an out of bound result.
test_refit_callable_out_bound
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_refit_callable_multi_metric(): """ Test refit=callable in multiple metric evaluation setting """ def refit_callable(cv_results): """ A dummy function tests `refit=callable` interface. Return the index of a model that has the least `mean_test_prec`. """ ...
Test refit=callable in multiple metric evaluation setting
test_refit_callable_multi_metric
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def compare_cv_results_multimetric_with_single(search_multi, search_acc, search_rec): """Compare multi-metric cv_results with the ensemble of multiple single metric cv_results from single metric grid/random search""" assert search_multi.multimetric_ assert_array_equal(sorted(search_multi.scorer_), ("ac...
Compare multi-metric cv_results with the ensemble of multiple single metric cv_results from single metric grid/random search
compare_cv_results_multimetric_with_single
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def compare_refit_methods_when_refit_with_acc(search_multi, search_acc, refit): """Compare refit multi-metric search methods with single metric methods""" assert search_acc.refit == refit if refit: assert search_multi.refit == "accuracy" else: assert not search_multi.refit return...
Compare refit multi-metric search methods with single metric methods
compare_refit_methods_when_refit_with_acc
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_unsupported_sample_weight_scorer(): """Checks that fitting with sample_weight raises a warning if the scorer does not support sample_weight""" def fake_score_func(y_true, y_pred): "Fake scoring function that does not support sample_weight" return 0.5 fake_scorer = make_scorer(...
Checks that fitting with sample_weight raises a warning if the scorer does not support sample_weight
test_unsupported_sample_weight_scorer
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_search_cv_pairwise_property_delegated_to_base_estimator(pairwise): """ Test implementation of BaseSearchCV has the pairwise tag which matches the pairwise tag of its estimator. This test make sure pairwise tag is delegated to the base estimator. Non-regression test for issue #13920. ""...
Test implementation of BaseSearchCV has the pairwise tag which matches the pairwise tag of its estimator. This test make sure pairwise tag is delegated to the base estimator. Non-regression test for issue #13920.
test_search_cv_pairwise_property_delegated_to_base_estimator
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_search_cv__pairwise_property_delegated_to_base_estimator(): """ Test implementation of BaseSearchCV has the pairwise property which matches the pairwise tag of its estimator. This test make sure pairwise tag is delegated to the base estimator. Non-regression test for issue #13920. """ ...
Test implementation of BaseSearchCV has the pairwise property which matches the pairwise tag of its estimator. This test make sure pairwise tag is delegated to the base estimator. Non-regression test for issue #13920.
test_search_cv__pairwise_property_delegated_to_base_estimator
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_search_cv_pairwise_property_equivalence_of_precomputed(): """ Test implementation of BaseSearchCV has the pairwise tag which matches the pairwise tag of its estimator. This test ensures the equivalence of 'precomputed'. Non-regression test for issue #13920. """ n_samples = 50 n...
Test implementation of BaseSearchCV has the pairwise tag which matches the pairwise tag of its estimator. This test ensures the equivalence of 'precomputed'. Non-regression test for issue #13920.
test_search_cv_pairwise_property_equivalence_of_precomputed
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_search_cv_verbose_3(capsys, return_train_score): """Check that search cv with verbose>2 shows the score for single metrics. non-regression test for #19658.""" X, y = make_classification(n_samples=100, n_classes=2, flip_y=0.2, random_state=0) clf = LinearSVC(random_state=0) grid = {"C": [0.1...
Check that search cv with verbose>2 shows the score for single metrics. non-regression test for #19658.
test_search_cv_verbose_3
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_search_html_repr(): """Test different HTML representations for GridSearchCV.""" X, y = make_classification(random_state=42) pipeline = Pipeline([("scale", StandardScaler()), ("clf", DummyClassifier())]) param_grid = {"clf": [DummyClassifier(), LogisticRegression()]} # Unfitted shows the o...
Test different HTML representations for GridSearchCV.
test_search_html_repr
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_multi_metric_search_forwards_metadata(SearchCV, param_search): """Test that *SearchCV forwards metadata correctly when passed multiple metrics.""" X, y = make_classification(random_state=42) n_samples = _num_samples(X) rng = np.random.RandomState(0) score_weights = rng.rand(n_samples) s...
Test that *SearchCV forwards metadata correctly when passed multiple metrics.
test_multi_metric_search_forwards_metadata
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_score_rejects_params_with_no_routing_enabled(SearchCV, param_search): """*SearchCV should reject **params when metadata routing is not enabled since this is added only when routing is enabled.""" X, y = make_classification(random_state=42) est = LinearSVC() param_grid_search = {param_search...
*SearchCV should reject **params when metadata routing is not enabled since this is added only when routing is enabled.
test_score_rejects_params_with_no_routing_enabled
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_cv_results_dtype_issue_29074(): """Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29074""" class MetaEstimator(BaseEstimator, ClassifierMixin): def __init__( self, base_clf, parameter1=None, parameter2=None, ...
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29074
test_cv_results_dtype_issue_29074
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_search_with_estimators_issue_29157(): """Check cv_results_ for estimators with a `dtype` parameter, e.g. OneHotEncoder.""" pd = pytest.importorskip("pandas") df = pd.DataFrame( { "numeric_1": [1, 2, 3, 4, 5], "object_1": ["a", "a", "a", "a", "a"], "target...
Check cv_results_ for estimators with a `dtype` parameter, e.g. OneHotEncoder.
test_search_with_estimators_issue_29157
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_cv_results_multi_size_array(): """Check that GridSearchCV works with params that are arrays of different sizes. Non-regression test for #29277. """ n_features = 10 X, y = make_classification(n_features=10) spline_reg_pipe = make_pipeline( SplineTransformer(extrapolation="perio...
Check that GridSearchCV works with params that are arrays of different sizes. Non-regression test for #29277.
test_cv_results_multi_size_array
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_search.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_search.py
BSD-3-Clause
def test_train_test_split_32bit_overflow(): """Check for integer overflow on 32-bit platforms. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/20774 """ # A number 'n' big enough for expression 'n * n * train_size' to cause # an overflow for signed 32-bit integer ...
Check for integer overflow on 32-bit platforms. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/20774
test_train_test_split_32bit_overflow
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_split.py
BSD-3-Clause
def test_splitter_set_split_request(cv): """Check set_split_request is defined for group splitters and not for others.""" if cv in GROUP_SPLITTERS: assert hasattr(cv, "set_split_request") elif cv in NO_GROUP_SPLITTERS: assert not hasattr(cv, "set_split_request")
Check set_split_request is defined for group splitters and not for others.
test_splitter_set_split_request
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_split.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_split.py
BSD-3-Clause
def test_nan_handling(HalvingSearch, fail_at): """Check the selection of the best scores in presence of failure represented by NaN values.""" n_samples = 1_000 X, y = make_classification(n_samples=n_samples, random_state=0) search = HalvingSearch( SometimesFailClassifier(), {f"fail_...
Check the selection of the best scores in presence of failure represented by NaN values.
test_nan_handling
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_successive_halving.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_successive_halving.py
BSD-3-Clause
def test_min_resources_null(SearchCV): """Check that we raise an error if the minimum resources is set to 0.""" base_estimator = FastClassifier() param_grid = {"a": [1]} X = np.empty(0).reshape(0, 3) search = SearchCV(base_estimator, param_grid, min_resources="smallest") err_msg = "min_resourc...
Check that we raise an error if the minimum resources is set to 0.
test_min_resources_null
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_successive_halving.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_successive_halving.py
BSD-3-Clause
def test_select_best_index(SearchCV): """Check the selection strategy of the halving search.""" results = { # this isn't a 'real world' result dict "iter": np.array([0, 0, 0, 0, 1, 1, 2, 2, 2]), "mean_test_score": np.array([4, 3, 5, 1, 11, 10, 5, 6, 9]), "params": np.array(["a", "b", "c...
Check the selection strategy of the halving search.
test_select_best_index
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_successive_halving.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_successive_halving.py
BSD-3-Clause
def test_halving_random_search_list_of_dicts(): """Check the behaviour of the `HalvingRandomSearchCV` with `param_distribution` being a list of dictionary. """ X, y = make_classification(n_samples=150, n_features=4, random_state=42) params = [ {"kernel": ["rbf"], "C": expon(scale=10), "gamm...
Check the behaviour of the `HalvingRandomSearchCV` with `param_distribution` being a list of dictionary.
test_halving_random_search_list_of_dicts
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_successive_halving.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_successive_halving.py
BSD-3-Clause
def fit( self, X, Y=None, sample_weight=None, class_prior=None, sparse_sample_weight=None, sparse_param=None, dummy_int=None, dummy_str=None, dummy_obj=None, callback=None, ): """The dummy arguments are to test that this...
The dummy arguments are to test that this fit function can accept non-array arguments through cross-validation, such as: - int - str (this is actually array-like) - object - function
fit
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def check_cross_val_predict_binary(est, X, y, method): """Helper for tests of cross_val_predict with binary classification""" cv = KFold(n_splits=3, shuffle=False) # Generate expected outputs if y.ndim == 1: exp_shape = (len(X),) if method == "decision_function" else (len(X), 2) else: ...
Helper for tests of cross_val_predict with binary classification
check_cross_val_predict_binary
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def check_cross_val_predict_multiclass(est, X, y, method): """Helper for tests of cross_val_predict with multiclass classification""" cv = KFold(n_splits=3, shuffle=False) # Generate expected outputs float_min = np.finfo(np.float64).min default_values = { "decision_function": float_min, ...
Helper for tests of cross_val_predict with multiclass classification
check_cross_val_predict_multiclass
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def check_cross_val_predict_multilabel(est, X, y, method): """Check the output of cross_val_predict for 2D targets using Estimators which provide a predictions as a list with one element per class. """ cv = KFold(n_splits=3, shuffle=False) # Create empty arrays of the correct size to hold outpu...
Check the output of cross_val_predict for 2D targets using Estimators which provide a predictions as a list with one element per class.
check_cross_val_predict_multilabel
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def test_learning_curve_partial_fit_regressors(): """Check that regressors with partial_fit is supported. Non-regression test for #22981. """ X, y = make_regression(random_state=42) # Does not error learning_curve(MLPRegressor(), X, y, exploit_incremental_learning=True, cv=2)
Check that regressors with partial_fit is supported. Non-regression test for #22981.
test_learning_curve_partial_fit_regressors
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def test_learning_curve_some_failing_fits_warning(global_random_seed): """Checks for fit failures in `learning_curve` and raises the required warning""" X, y = make_classification( n_samples=30, n_classes=3, n_informative=6, shuffle=False, random_state=global_random_seed...
Checks for fit failures in `learning_curve` and raises the required warning
test_learning_curve_some_failing_fits_warning
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def test_fit_param_deprecation(func, extra_args): """Check that we warn about deprecating `fit_params`.""" with pytest.warns(FutureWarning, match="`fit_params` is deprecated"): func( estimator=ConsumingClassifier(), X=X, y=y, cv=2, fit_params={}, **extra_args ) with pytest.raise...
Check that we warn about deprecating `fit_params`.
test_fit_param_deprecation
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def test_groups_with_routing_validation(func, extra_args): """Check that we raise an error if `groups` are passed to the cv method instead of `params` when metadata routing is enabled. """ with pytest.raises(ValueError, match="`groups` can only be passed if"): func( estimator=Consumi...
Check that we raise an error if `groups` are passed to the cv method instead of `params` when metadata routing is enabled.
test_groups_with_routing_validation
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def test_cross_validate_params_none(func, extra_args): """Test that no errors are raised when passing `params=None`, which is the default value. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/30447 """ X, y = make_classification(n_samples=100, n_classes=2, random_state=...
Test that no errors are raised when passing `params=None`, which is the default value. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/30447
test_cross_validate_params_none
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def test_passed_unrequested_metadata(func, extra_args): """Check that we raise an error when passing metadata that is not requested.""" err_msg = re.escape( "[metadata] are passed but are not explicitly set as requested or not " "requested for ConsumingClassifier.fit, which is used within" ...
Check that we raise an error when passing metadata that is not requested.
test_passed_unrequested_metadata
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause
def test_validation_functions_routing(func, extra_args): """Check that the respective cv method is properly dispatching the metadata to the consumer.""" scorer_registry = _Registry() scorer = ConsumingScorer(registry=scorer_registry).set_score_request( sample_weight="score_weights", metadata="sc...
Check that the respective cv method is properly dispatching the metadata to the consumer.
test_validation_functions_routing
python
scikit-learn/scikit-learn
sklearn/model_selection/tests/test_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py
BSD-3-Clause