sklearn.model_selection.RandomizedSearchCV
class sklearn.model_selection.RandomizedSearchCV(estimator, param_distributions, *, n_iter=10, scoring=None, n_jobs=None, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score=nan, return_train_score=False) [source]

Randomized search on hyper parameters. RandomizedSearchCV implements a “fit” and a “score” method. It also implements “score_samples”, “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used. The parameters of the estimator used to apply these methods are optimized by cross-validated search over parameter settings. In contrast to GridSearchCV, not all parameter values are tried out, but rather a fixed number of parameter settings is sampled from the specified distributions. The number of parameter settings that are tried is given by n_iter. If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribution, sampling with replacement is used. It is highly recommended to use continuous distributions for continuous parameters. Read more in the User Guide.  New in version 0.14.   Parameters

estimatorestimator object.

A object of that type is instantiated for each grid point. This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a score function, or scoring must be passed.
param_distributionsdict or list of dicts

Dictionary with parameters names (str) as keys and distributions or lists of parameters to try. Distributions must provide a rvs method for sampling (such as those from scipy.stats.distributions). If a list is given, it is sampled uniformly. If a list of dicts is given, first a dict is sampled uniformly, and then a parameter is sampled using that dict as above.
n_iterint, default=10

Number of parameter settings that are sampled. n_iter trades off runtime vs quality of the solution.
scoringstr, callable, list, tuple or dict, default=None

Strategy to evaluate the performance of the cross-validated model on the test set. If scoring represents a single score, one can use:  a single string (see The scoring parameter: defining model evaluation rules); a callable (see Defining your scoring strategy from metric functions) that returns a single value.  If scoring reprents multiple scores, one can use:  a list or tuple of unique strings; a callable returning a dictionary where the keys are the metric names and the values are the metric scores; a dictionary with metric names as keys and callables a values.  See Specifying multiple metrics for evaluation for an example. If None, the estimator’s score method is used.
n_jobsint, default=None

Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.  Changed in version v0.20: n_jobs default changed from 1 to None
pre_dispatchint, or str, default=None

Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:  None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs An int, giving the exact number of total jobs that are spawned A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’
cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:  None, to use the default 5-fold cross validation, integer, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices.  For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
refitbool, str, or callable, default=True

Refit an estimator using the best found parameters on the whole dataset. For multiple metric evaluation, this needs to be a str denoting the scorer that would be used to find the best parameters for refitting the estimator at the end. Where there are considerations other than maximum score in choosing a best estimator, refit can be set to a function which returns the selected best_index_ given the cv_results. In that case, the best_estimator_ and best_params_ will be set according to the returned best_index_ while the best_score_ attribute will not be available. The refitted estimator is made available at the best_estimator_ attribute and permits using predict directly on this RandomizedSearchCV instance. Also for multiple metric evaluation, the attributes best_index_, best_score_ and best_params_ will only be available if refit is set and all of them will be determined w.r.t this specific scorer. See scoring parameter to know more about multiple metric evaluation.  Changed in version 0.20: Support for callable added.
verboseint

Controls the verbosity: the higher, the more messages.
random_stateint, RandomState instance or None, default=None

Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions. Pass an int for reproducible output across multiple function calls. See Glossary.
error_score‘raise’ or numeric, default=np.nan

Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.
return_train_scorebool, default=False

If False, the cv_results_ attribute will not include training scores. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting trade-off. However computing the scores on the training set can be computationally expensive and is not strictly required to select the parameters that yield the best generalization performance.  New in version 0.19.   Changed in version 0.21: Default value was changed from True to False     Attributes

cv_results_dict of numpy (masked) ndarrays

A dict with keys as column headers and values as columns, that can be imported into a pandas DataFrame. For instance the below given table
param_kernel param_gamma split0_test_score … rank_test_score
‘rbf’ 0.1 0.80 … 1
‘rbf’ 0.2 0.84 … 3
‘rbf’ 0.3 0.70 … 2   will be represented by a cv_results_ dict of: {
'param_kernel' : masked_array(data = ['rbf', 'rbf', 'rbf'],
                              mask = False),
'param_gamma'  : masked_array(data = [0.1 0.2 0.3], mask = False),
'split0_test_score'  : [0.80, 0.84, 0.70],
'split1_test_score'  : [0.82, 0.50, 0.70],
'mean_test_score'    : [0.81, 0.67, 0.70],
'std_test_score'     : [0.01, 0.24, 0.00],
'rank_test_score'    : [1, 3, 2],
'split0_train_score' : [0.80, 0.92, 0.70],
'split1_train_score' : [0.82, 0.55, 0.70],
'mean_train_score'   : [0.81, 0.74, 0.70],
'std_train_score'    : [0.01, 0.19, 0.00],
'mean_fit_time'      : [0.73, 0.63, 0.43],
'std_fit_time'       : [0.01, 0.02, 0.01],
'mean_score_time'    : [0.01, 0.06, 0.04],
'std_score_time'     : [0.00, 0.00, 0.00],
'params'             : [{'kernel' : 'rbf', 'gamma' : 0.1}, ...],
}
 NOTE The key 'params' is used to store a list of parameter settings dicts for all the parameter candidates. The mean_fit_time, std_fit_time, mean_score_time and std_score_time are all in seconds. For multi-metric evaluation, the scores for all the scorers are available in the cv_results_ dict at the keys ending with that scorer’s name ('_<scorer_name>') instead of '_score' shown above. (‘split0_test_precision’, ‘mean_train_precision’ etc.)
best_estimator_estimator

Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False. For multi-metric evaluation, this attribute is present only if refit is specified. See refit parameter for more information on allowed values.
best_score_float

Mean cross-validated score of the best_estimator. For multi-metric evaluation, this is not available if refit is False. See refit parameter for more information. This attribute is not available if refit is a function.
best_params_dict

Parameter setting that gave the best results on the hold out data. For multi-metric evaluation, this is not available if refit is False. See refit parameter for more information.
best_index_int

The index (of the cv_results_ arrays) which corresponds to the best candidate parameter setting. The dict at search.cv_results_['params'][search.best_index_] gives the parameter setting for the best model, that gives the highest mean score (search.best_score_). For multi-metric evaluation, this is not available if refit is False. See refit parameter for more information.
scorer_function or a dict

Scorer function used on the held out data to choose the best parameters for the model. For multi-metric evaluation, this attribute holds the validated scoring dict which maps the scorer key to the scorer callable.
n_splits_int

The number of cross-validation splits (folds/iterations).
refit_time_float

Seconds used for refitting the best model on the whole dataset. This is present only if refit is not False.  New in version 0.20.
multimetric_bool

Whether or not the scorers compute several metrics.      See also
GridSearchCV

Does exhaustive search over a grid of parameters.
ParameterSampler

A generator over parameter settings, constructed from param_distributions.    Notes The parameters selected are those that maximize the score of the held-out data, according to the scoring parameter. If n_jobs was set to a value higher than one, the data is copied for each parameter setting(and not n_jobs times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set pre_dispatch. Then, the memory is copied only pre_dispatch many times. A reasonable value for pre_dispatch is 2 *
n_jobs. Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.model_selection import RandomizedSearchCV
>>> from scipy.stats import uniform
>>> iris = load_iris()
>>> logistic = LogisticRegression(solver='saga', tol=1e-2, max_iter=200,
...                               random_state=0)
>>> distributions = dict(C=uniform(loc=0, scale=4),
...                      penalty=['l2', 'l1'])
>>> clf = RandomizedSearchCV(logistic, distributions, random_state=0)
>>> search = clf.fit(iris.data, iris.target)
>>> search.best_params_
{'C': 2..., 'penalty': 'l1'}
 Methods
decision_function(X) Call decision_function on the estimator with the best found parameters.
fit(X[, y, groups]) Run fit with all sets of parameters.
get_params([deep]) Get parameters for this estimator.
inverse_transform(Xt) Call inverse_transform on the estimator with the best found params.
predict(X) Call predict on the estimator with the best found parameters.
predict_log_proba(X) Call predict_log_proba on the estimator with the best found parameters.
predict_proba(X) Call predict_proba on the estimator with the best found parameters.
score(X[, y]) Returns the score on the given data, if the estimator has been refit.
score_samples(X) Call score_samples on the estimator with the best found parameters.
set_params(**params) Set the parameters of this estimator.
transform(X) Call transform on the estimator with the best found parameters.
decision_function(X) [source]

Call decision_function on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports decision_function.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

fit(X, y=None, *, groups=None, **fit_params) [source]

Run fit with all sets of parameters.  Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples, n_output) or (n_samples,), default=None

Target relative to X for classification or regression; None for unsupervised learning.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold).
**fit_paramsdict of str -> object

Parameters passed to the fit method of the estimator

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(Xt) [source]

Call inverse_transform on the estimator with the best found params. Only available if the underlying estimator implements inverse_transform and refit=True.  Parameters

Xtindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

predict(X) [source]

Call predict on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

predict_log_proba(X) [source]

Call predict_log_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_log_proba.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

predict_proba(X) [source]

Call predict_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_proba.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

score(X, y=None) [source]

Returns the score on the given data, if the estimator has been refit. This uses the score defined by scoring where provided, and the best_estimator_.score method otherwise.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples, n_output) or (n_samples,), default=None

Target relative to X for classification or regression; None for unsupervised learning.    Returns

scorefloat

score_samples(X) [source]

Call score_samples on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports score_samples.  New in version 0.24.   Parameters

Xiterable

Data to predict on. Must fulfill input requirements of the underlying estimator.    Returns

y_scorendarray of shape (n_samples,)

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Call transform on the estimator with the best found parameters. Only available if the underlying estimator supports transform and refit=True.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.

 Examples using sklearn.model_selection.RandomizedSearchCV

  Release Highlights for scikit-learn 0.24

  Comparing randomized search and grid search for hyperparameter estimation


decision_function(X) [source]

Call decision_function on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports decision_function.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.


fit(X, y=None, *, groups=None, **fit_params) [source]

Run fit with all sets of parameters.  Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples, n_output) or (n_samples,), default=None

Target relative to X for classification or regression; None for unsupervised learning.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold).
**fit_paramsdict of str -> object

Parameters passed to the fit method of the estimator


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


inverse_transform(Xt) [source]

Call inverse_transform on the estimator with the best found params. Only available if the underlying estimator implements inverse_transform and refit=True.  Parameters

Xtindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.


predict(X) [source]

Call predict on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.


predict_log_proba(X) [source]

Call predict_log_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_log_proba.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.


predict_proba(X) [source]

Call predict_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_proba.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.


score(X, y=None) [source]

Returns the score on the given data, if the estimator has been refit. This uses the score defined by scoring where provided, and the best_estimator_.score method otherwise.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples, n_output) or (n_samples,), default=None

Target relative to X for classification or regression; None for unsupervised learning.    Returns

scorefloat


score_samples(X) [source]

Call score_samples on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports score_samples.  New in version 0.24.   Parameters

Xiterable

Data to predict on. Must fulfill input requirements of the underlying estimator.    Returns

y_scorendarray of shape (n_samples,)


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


transform(X) [source]

Call transform on the estimator with the best found parameters. Only available if the underlying estimator supports transform and refit=True.  Parameters

Xindexable, length n_samples

Must fulfill the input assumptions of the underlying estimator.


class sklearn.model_selection.RepeatedKFold(*, n_splits=5, n_repeats=10, random_state=None) [source]

Repeated K-Fold cross validator. Repeats K-Fold n times with different randomization in each repetition. Read more in the User Guide.  Parameters

n_splitsint, default=5

Number of folds. Must be at least 2.
n_repeatsint, default=10

Number of times cross-validator needs to be repeated.
random_stateint, RandomState instance or None, default=None

Controls the randomness of each repeated cross-validation instance. Pass an int for reproducible output across multiple function calls. See Glossary.      See also
RepeatedStratifiedKFold

Repeats Stratified K-Fold n times.    Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer. Examples >>> import numpy as np
>>> from sklearn.model_selection import RepeatedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> rkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=2652124)
>>> for train_index, test_index in rkf.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
...
TRAIN: [0 1] TEST: [2 3]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [1 2] TEST: [0 3]
TRAIN: [0 3] TEST: [1 2]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generates indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
yobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y=None, groups=None) [source]

Generates indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.


sklearn.model_selection.RepeatedKFold
class sklearn.model_selection.RepeatedKFold(*, n_splits=5, n_repeats=10, random_state=None) [source]

Repeated K-Fold cross validator. Repeats K-Fold n times with different randomization in each repetition. Read more in the User Guide.  Parameters

n_splitsint, default=5

Number of folds. Must be at least 2.
n_repeatsint, default=10

Number of times cross-validator needs to be repeated.
random_stateint, RandomState instance or None, default=None

Controls the randomness of each repeated cross-validation instance. Pass an int for reproducible output across multiple function calls. See Glossary.      See also
RepeatedStratifiedKFold

Repeats Stratified K-Fold n times.    Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer. Examples >>> import numpy as np
>>> from sklearn.model_selection import RepeatedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> rkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=2652124)
>>> for train_index, test_index in rkf.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
...
TRAIN: [0 1] TEST: [2 3]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [1 2] TEST: [0 3]
TRAIN: [0 3] TEST: [1 2]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generates indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
yobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y=None, groups=None) [source]

Generates indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.

 Examples using sklearn.model_selection.RepeatedKFold

  Common pitfalls in interpretation of coefficients of linear models


get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
yobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.


split(X, y=None, groups=None) [source]

Generates indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.


class sklearn.model_selection.RepeatedStratifiedKFold(*, n_splits=5, n_repeats=10, random_state=None) [source]

Repeated Stratified K-Fold cross validator. Repeats Stratified K-Fold n times with different randomization in each repetition. Read more in the User Guide.  Parameters

n_splitsint, default=5

Number of folds. Must be at least 2.
n_repeatsint, default=10

Number of times cross-validator needs to be repeated.
random_stateint, RandomState instance or None, default=None

Controls the generation of the random states for each repetition. Pass an int for reproducible output across multiple function calls. See Glossary.      See also
RepeatedKFold

Repeats K-Fold n times.    Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer. Examples >>> import numpy as np
>>> from sklearn.model_selection import RepeatedStratifiedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> rskf = RepeatedStratifiedKFold(n_splits=2, n_repeats=2,
...     random_state=36851234)
>>> for train_index, test_index in rskf.split(X, y):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
...
TRAIN: [1 2] TEST: [0 3]
TRAIN: [0 3] TEST: [1 2]
TRAIN: [1 3] TEST: [0 2]
TRAIN: [0 2] TEST: [1 3]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generates indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
yobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y=None, groups=None) [source]

Generates indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.


sklearn.model_selection.RepeatedStratifiedKFold
class sklearn.model_selection.RepeatedStratifiedKFold(*, n_splits=5, n_repeats=10, random_state=None) [source]

Repeated Stratified K-Fold cross validator. Repeats Stratified K-Fold n times with different randomization in each repetition. Read more in the User Guide.  Parameters

n_splitsint, default=5

Number of folds. Must be at least 2.
n_repeatsint, default=10

Number of times cross-validator needs to be repeated.
random_stateint, RandomState instance or None, default=None

Controls the generation of the random states for each repetition. Pass an int for reproducible output across multiple function calls. See Glossary.      See also
RepeatedKFold

Repeats K-Fold n times.    Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer. Examples >>> import numpy as np
>>> from sklearn.model_selection import RepeatedStratifiedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> rskf = RepeatedStratifiedKFold(n_splits=2, n_repeats=2,
...     random_state=36851234)
>>> for train_index, test_index in rskf.split(X, y):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
...
TRAIN: [1 2] TEST: [0 3]
TRAIN: [0 3] TEST: [1 2]
TRAIN: [1 3] TEST: [0 2]
TRAIN: [0 2] TEST: [1 3]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generates indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
yobject

Always ignored, exists for compatibility. np.zeros(n_samples) may be used as a placeholder.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y=None, groups=None) [source]

Generates indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.

 Examples using sklearn.model_selection.RepeatedStratifiedKFold

  Statistical comparison of models using grid search


class sklearn.model_selection.ShuffleSplit(n_splits=10, *, test_size=None, train_size=None, random_state=None) [source]

Random permutation cross-validator Yields indices to split data into training and test sets. Note: contrary to other cross-validation strategies, random splits do not guarantee that all folds will be different, although this is still very likely for sizeable datasets. Read more in the User Guide.  Parameters

n_splitsint, default=10

Number of re-shuffling & splitting iterations.
test_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If train_size is also None, it will be set to 0.1.
train_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size.
random_stateint, RandomState instance or None, default=None

Controls the randomness of the training and testing indices produced. Pass an int for reproducible output across multiple function calls. See Glossary.     Examples >>> import numpy as np
>>> from sklearn.model_selection import ShuffleSplit
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [3, 4], [5, 6]])
>>> y = np.array([1, 2, 1, 2, 1, 2])
>>> rs = ShuffleSplit(n_splits=5, test_size=.25, random_state=0)
>>> rs.get_n_splits(X)
5
>>> print(rs)
ShuffleSplit(n_splits=5, random_state=0, test_size=0.25, train_size=None)
>>> for train_index, test_index in rs.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
TRAIN: [1 3 0 4] TEST: [5 2]
TRAIN: [4 0 2 5] TEST: [1 3]
TRAIN: [1 2 4 0] TEST: [3 5]
TRAIN: [3 4 1 0] TEST: [5 2]
TRAIN: [3 5 1 0] TEST: [2 4]
>>> rs = ShuffleSplit(n_splits=5, train_size=0.5, test_size=.25,
...                   random_state=0)
>>> for train_index, test_index in rs.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
TRAIN: [1 3 0] TEST: [5 2]
TRAIN: [4 0 2] TEST: [1 3]
TRAIN: [1 2 4] TEST: [3 5]
TRAIN: [3 4 1] TEST: [5 2]
TRAIN: [3 5 1] TEST: [2 4]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y=None, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.


sklearn.model_selection.ShuffleSplit
class sklearn.model_selection.ShuffleSplit(n_splits=10, *, test_size=None, train_size=None, random_state=None) [source]

Random permutation cross-validator Yields indices to split data into training and test sets. Note: contrary to other cross-validation strategies, random splits do not guarantee that all folds will be different, although this is still very likely for sizeable datasets. Read more in the User Guide.  Parameters

n_splitsint, default=10

Number of re-shuffling & splitting iterations.
test_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If train_size is also None, it will be set to 0.1.
train_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size.
random_stateint, RandomState instance or None, default=None

Controls the randomness of the training and testing indices produced. Pass an int for reproducible output across multiple function calls. See Glossary.     Examples >>> import numpy as np
>>> from sklearn.model_selection import ShuffleSplit
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [3, 4], [5, 6]])
>>> y = np.array([1, 2, 1, 2, 1, 2])
>>> rs = ShuffleSplit(n_splits=5, test_size=.25, random_state=0)
>>> rs.get_n_splits(X)
5
>>> print(rs)
ShuffleSplit(n_splits=5, random_state=0, test_size=0.25, train_size=None)
>>> for train_index, test_index in rs.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
TRAIN: [1 3 0 4] TEST: [5 2]
TRAIN: [4 0 2 5] TEST: [1 3]
TRAIN: [1 2 4 0] TEST: [3 5]
TRAIN: [3 4 1 0] TEST: [5 2]
TRAIN: [3 5 1 0] TEST: [2 4]
>>> rs = ShuffleSplit(n_splits=5, train_size=0.5, test_size=.25,
...                   random_state=0)
>>> for train_index, test_index in rs.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
TRAIN: [1 3 0] TEST: [5 2]
TRAIN: [4 0 2] TEST: [1 3]
TRAIN: [1 2 4] TEST: [3 5]
TRAIN: [3 4 1] TEST: [5 2]
TRAIN: [3 5 1] TEST: [2 4]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y=None, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.

 Examples using sklearn.model_selection.ShuffleSplit

  Visualizing cross-validation behavior in scikit-learn

  Plotting Learning Curves

  Scaling the regularization parameter for SVCs


get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.


split(X, y=None, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.


class sklearn.model_selection.StratifiedKFold(n_splits=5, *, shuffle=False, random_state=None) [source]

Stratified K-Folds cross-validator. Provides train/test indices to split data in train/test sets. This cross-validation object is a variation of KFold that returns stratified folds. The folds are made by preserving the percentage of samples for each class. Read more in the User Guide.  Parameters

n_splitsint, default=5

Number of folds. Must be at least 2.  Changed in version 0.22: n_splits default value changed from 3 to 5.
shufflebool, default=False

Whether to shuffle each class’s samples before splitting into batches. Note that the samples within each split will not be shuffled.
random_stateint, RandomState instance or None, default=None

When shuffle is True, random_state affects the ordering of the indices, which controls the randomness of each fold for each class. Otherwise, leave random_state as None. Pass an int for reproducible output across multiple function calls. See Glossary.      See also
RepeatedStratifiedKFold

Repeats Stratified K-Fold n times.    Notes The implementation is designed to:  Generate test sets such that all contain the same distribution of classes, or as close as possible. Be invariant to class label: relabelling y = ["Happy", "Sad"] to y = [1, 0] should not change the indices generated. Preserve order dependencies in the dataset ordering, when shuffle=False: all samples from class k in some test set were contiguous in y, or separated in y by samples from classes other than k. Generate test sets where the smallest and largest differ by at most one sample.   Changed in version 0.22: The previous implementation did not follow the last constraint.  Examples >>> import numpy as np
>>> from sklearn.model_selection import StratifiedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> skf = StratifiedKFold(n_splits=2)
>>> skf.get_n_splits(X, y)
2
>>> print(skf)
StratifiedKFold(n_splits=2, random_state=None, shuffle=False)
>>> for train_index, test_index in skf.split(X, y):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
TRAIN: [1 3] TEST: [0 2]
TRAIN: [0 2] TEST: [1 3]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X, y[, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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 is sufficient to generate the splits and hence np.zeros(n_samples) may be used as a placeholder for X instead of actual training data.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems. Stratification is done based on the y labels.
groupsobject

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.


sklearn.model_selection.StratifiedKFold
class sklearn.model_selection.StratifiedKFold(n_splits=5, *, shuffle=False, random_state=None) [source]

Stratified K-Folds cross-validator. Provides train/test indices to split data in train/test sets. This cross-validation object is a variation of KFold that returns stratified folds. The folds are made by preserving the percentage of samples for each class. Read more in the User Guide.  Parameters

n_splitsint, default=5

Number of folds. Must be at least 2.  Changed in version 0.22: n_splits default value changed from 3 to 5.
shufflebool, default=False

Whether to shuffle each class’s samples before splitting into batches. Note that the samples within each split will not be shuffled.
random_stateint, RandomState instance or None, default=None

When shuffle is True, random_state affects the ordering of the indices, which controls the randomness of each fold for each class. Otherwise, leave random_state as None. Pass an int for reproducible output across multiple function calls. See Glossary.      See also
RepeatedStratifiedKFold

Repeats Stratified K-Fold n times.    Notes The implementation is designed to:  Generate test sets such that all contain the same distribution of classes, or as close as possible. Be invariant to class label: relabelling y = ["Happy", "Sad"] to y = [1, 0] should not change the indices generated. Preserve order dependencies in the dataset ordering, when shuffle=False: all samples from class k in some test set were contiguous in y, or separated in y by samples from classes other than k. Generate test sets where the smallest and largest differ by at most one sample.   Changed in version 0.22: The previous implementation did not follow the last constraint.  Examples >>> import numpy as np
>>> from sklearn.model_selection import StratifiedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> skf = StratifiedKFold(n_splits=2)
>>> skf.get_n_splits(X, y)
2
>>> print(skf)
StratifiedKFold(n_splits=2, random_state=None, shuffle=False)
>>> for train_index, test_index in skf.split(X, y):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
TRAIN: [1 3] TEST: [0 2]
TRAIN: [0 2] TEST: [1 3]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X, y[, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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 is sufficient to generate the splits and hence np.zeros(n_samples) may be used as a placeholder for X instead of actual training data.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems. Stratification is done based on the y labels.
groupsobject

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.

 Examples using sklearn.model_selection.StratifiedKFold

  Recursive feature elimination with cross-validation

  Test with permutations the significance of a classification score

  GMM covariances

  Receiver Operating Characteristic (ROC) with cross validation

  Visualizing cross-validation behavior in scikit-learn

  Effect of varying threshold for self-training


split(X, y, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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 is sufficient to generate the splits and hence np.zeros(n_samples) may be used as a placeholder for X instead of actual training data.
yarray-like of shape (n_samples,)

The target variable for supervised learning problems. Stratification is done based on the y labels.
groupsobject

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.


class sklearn.model_selection.StratifiedShuffleSplit(n_splits=10, *, test_size=None, train_size=None, random_state=None) [source]

Stratified ShuffleSplit cross-validator Provides train/test indices to split data in train/test sets. This cross-validation object is a merge of StratifiedKFold and ShuffleSplit, which returns stratified randomized folds. The folds are made by preserving the percentage of samples for each class. Note: like the ShuffleSplit strategy, stratified random splits do not guarantee that all folds will be different, although this is still very likely for sizeable datasets. Read more in the User Guide.  Parameters

n_splitsint, default=10

Number of re-shuffling & splitting iterations.
test_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If train_size is also None, it will be set to 0.1.
train_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size.
random_stateint, RandomState instance or None, default=None

Controls the randomness of the training and testing indices produced. Pass an int for reproducible output across multiple function calls. See Glossary.     Examples >>> import numpy as np
>>> from sklearn.model_selection import StratifiedShuffleSplit
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 0, 1, 1, 1])
>>> sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0)
>>> sss.get_n_splits(X, y)
5
>>> print(sss)
StratifiedShuffleSplit(n_splits=5, random_state=0, ...)
>>> for train_index, test_index in sss.split(X, y):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
TRAIN: [5 2 3] TEST: [4 1 0]
TRAIN: [5 1 4] TEST: [0 2 3]
TRAIN: [5 0 2] TEST: [4 3 1]
TRAIN: [4 1 0] TEST: [2 3 5]
TRAIN: [0 5 1] TEST: [3 4 2]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X, y[, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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 is sufficient to generate the splits and hence np.zeros(n_samples) may be used as a placeholder for X instead of actual training data.
yarray-like of shape (n_samples,) or (n_samples, n_labels)

The target variable for supervised learning problems. Stratification is done based on the y labels.
groupsobject

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.


sklearn.model_selection.StratifiedShuffleSplit
class sklearn.model_selection.StratifiedShuffleSplit(n_splits=10, *, test_size=None, train_size=None, random_state=None) [source]

Stratified ShuffleSplit cross-validator Provides train/test indices to split data in train/test sets. This cross-validation object is a merge of StratifiedKFold and ShuffleSplit, which returns stratified randomized folds. The folds are made by preserving the percentage of samples for each class. Note: like the ShuffleSplit strategy, stratified random splits do not guarantee that all folds will be different, although this is still very likely for sizeable datasets. Read more in the User Guide.  Parameters

n_splitsint, default=10

Number of re-shuffling & splitting iterations.
test_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If train_size is also None, it will be set to 0.1.
train_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size.
random_stateint, RandomState instance or None, default=None

Controls the randomness of the training and testing indices produced. Pass an int for reproducible output across multiple function calls. See Glossary.     Examples >>> import numpy as np
>>> from sklearn.model_selection import StratifiedShuffleSplit
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 0, 1, 1, 1])
>>> sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0)
>>> sss.get_n_splits(X, y)
5
>>> print(sss)
StratifiedShuffleSplit(n_splits=5, random_state=0, ...)
>>> for train_index, test_index in sss.split(X, y):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
TRAIN: [5 2 3] TEST: [4 1 0]
TRAIN: [5 1 4] TEST: [0 2 3]
TRAIN: [5 0 2] TEST: [4 3 1]
TRAIN: [4 1 0] TEST: [2 3 5]
TRAIN: [0 5 1] TEST: [3 4 2]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X, y[, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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 is sufficient to generate the splits and hence np.zeros(n_samples) may be used as a placeholder for X instead of actual training data.
yarray-like of shape (n_samples,) or (n_samples, n_labels)

The target variable for supervised learning problems. Stratification is done based on the y labels.
groupsobject

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.

 Examples using sklearn.model_selection.StratifiedShuffleSplit

  Visualizing cross-validation behavior in scikit-learn

  RBF SVM parameters


split(X, y, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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 is sufficient to generate the splits and hence np.zeros(n_samples) may be used as a placeholder for X instead of actual training data.
yarray-like of shape (n_samples,) or (n_samples, n_labels)

The target variable for supervised learning problems. Stratification is done based on the y labels.
groupsobject

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.     Notes Randomized CV splitters may return different results for each call of split. You can make the results identical by setting random_state to an integer.


class sklearn.model_selection.TimeSeriesSplit(n_splits=5, *, max_train_size=None, test_size=None, gap=0) [source]

Time Series cross-validator Provides train/test indices to split time series data samples that are observed at fixed time intervals, in train/test sets. In each split, test indices must be higher than before, and thus shuffling in cross validator is inappropriate. This cross-validation object is a variation of KFold. In the kth split, it returns first k folds as train set and the (k+1)th fold as test set. Note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them. Read more in the User Guide.  New in version 0.18.   Parameters

n_splitsint, default=5

Number of splits. Must be at least 2.  Changed in version 0.22: n_splits default value changed from 3 to 5.
max_train_sizeint, default=None

Maximum size for a single training set.
test_sizeint, default=None

Used to limit the size of the test set. Defaults to n_samples // (n_splits + 1), which is the maximum allowed value with gap=0.  New in version 0.24.
gapint, default=0

Number of samples to exclude from the end of each train set before the test set.  New in version 0.24.      Notes The training set has size i * n_samples // (n_splits + 1)
+ n_samples % (n_splits + 1) in the i th split, with a test set of size n_samples//(n_splits + 1) by default, where n_samples is the number of samples. Examples >>> import numpy as np
>>> from sklearn.model_selection import TimeSeriesSplit
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4, 5, 6])
>>> tscv = TimeSeriesSplit()
>>> print(tscv)
TimeSeriesSplit(gap=0, max_train_size=None, n_splits=5, test_size=None)
>>> for train_index, test_index in tscv.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
TRAIN: [0] TEST: [1]
TRAIN: [0 1] TEST: [2]
TRAIN: [0 1 2] TEST: [3]
TRAIN: [0 1 2 3] TEST: [4]
TRAIN: [0 1 2 3 4] TEST: [5]
>>> # Fix test_size to 2 with 12 samples
>>> X = np.random.randn(12, 2)
>>> y = np.random.randint(0, 2, 12)
>>> tscv = TimeSeriesSplit(n_splits=3, test_size=2)
>>> for train_index, test_index in tscv.split(X):
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [0 1 2 3 4 5] TEST: [6 7]
TRAIN: [0 1 2 3 4 5 6 7] TEST: [8 9]
TRAIN: [0 1 2 3 4 5 6 7 8 9] TEST: [10 11]
>>> # Add in a 2 period gap
>>> tscv = TimeSeriesSplit(n_splits=3, test_size=2, gap=2)
>>> for train_index, test_index in tscv.split(X):
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [0 1 2 3] TEST: [6 7]
TRAIN: [0 1 2 3 4 5] TEST: [8 9]
TRAIN: [0 1 2 3 4 5 6 7] TEST: [10 11]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y=None, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

Always ignored, exists for compatibility.
groupsarray-like of shape (n_samples,)

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.


sklearn.model_selection.TimeSeriesSplit
class sklearn.model_selection.TimeSeriesSplit(n_splits=5, *, max_train_size=None, test_size=None, gap=0) [source]

Time Series cross-validator Provides train/test indices to split time series data samples that are observed at fixed time intervals, in train/test sets. In each split, test indices must be higher than before, and thus shuffling in cross validator is inappropriate. This cross-validation object is a variation of KFold. In the kth split, it returns first k folds as train set and the (k+1)th fold as test set. Note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them. Read more in the User Guide.  New in version 0.18.   Parameters

n_splitsint, default=5

Number of splits. Must be at least 2.  Changed in version 0.22: n_splits default value changed from 3 to 5.
max_train_sizeint, default=None

Maximum size for a single training set.
test_sizeint, default=None

Used to limit the size of the test set. Defaults to n_samples // (n_splits + 1), which is the maximum allowed value with gap=0.  New in version 0.24.
gapint, default=0

Number of samples to exclude from the end of each train set before the test set.  New in version 0.24.      Notes The training set has size i * n_samples // (n_splits + 1)
+ n_samples % (n_splits + 1) in the i th split, with a test set of size n_samples//(n_splits + 1) by default, where n_samples is the number of samples. Examples >>> import numpy as np
>>> from sklearn.model_selection import TimeSeriesSplit
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4, 5, 6])
>>> tscv = TimeSeriesSplit()
>>> print(tscv)
TimeSeriesSplit(gap=0, max_train_size=None, n_splits=5, test_size=None)
>>> for train_index, test_index in tscv.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
TRAIN: [0] TEST: [1]
TRAIN: [0 1] TEST: [2]
TRAIN: [0 1 2] TEST: [3]
TRAIN: [0 1 2 3] TEST: [4]
TRAIN: [0 1 2 3 4] TEST: [5]
>>> # Fix test_size to 2 with 12 samples
>>> X = np.random.randn(12, 2)
>>> y = np.random.randint(0, 2, 12)
>>> tscv = TimeSeriesSplit(n_splits=3, test_size=2)
>>> for train_index, test_index in tscv.split(X):
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [0 1 2 3 4 5] TEST: [6 7]
TRAIN: [0 1 2 3 4 5 6 7] TEST: [8 9]
TRAIN: [0 1 2 3 4 5 6 7 8 9] TEST: [10 11]
>>> # Add in a 2 period gap
>>> tscv = TimeSeriesSplit(n_splits=3, test_size=2, gap=2)
>>> for train_index, test_index in tscv.split(X):
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [0 1 2 3] TEST: [6 7]
TRAIN: [0 1 2 3 4 5] TEST: [8 9]
TRAIN: [0 1 2 3 4 5 6 7] TEST: [10 11]
 Methods
get_n_splits([X, y, groups]) Returns the number of splitting iterations in the cross-validator
split(X[, y, groups]) Generate indices to split data into training and test set.
get_n_splits(X=None, y=None, groups=None) [source]

Returns the number of splitting iterations in the cross-validator  Parameters

Xobject

Always ignored, exists for compatibility.
yobject

Always ignored, exists for compatibility.
groupsobject

Always ignored, exists for compatibility.    Returns

n_splitsint

Returns the number of splitting iterations in the cross-validator.

split(X, y=None, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

Always ignored, exists for compatibility.
groupsarray-like of shape (n_samples,)

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.

 Examples using sklearn.model_selection.TimeSeriesSplit

  Visualizing cross-validation behavior in scikit-learn


split(X, y=None, groups=None) [source]

Generate indices to split data into training and test set.  Parameters

Xarray-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.
yarray-like of shape (n_samples,)

Always ignored, exists for compatibility.
groupsarray-like of shape (n_samples,)

Always ignored, exists for compatibility.    Yields

trainndarray

The training set indices for that split.
testndarray

The testing set indices for that split.


sklearn.model_selection.train_test_split(*arrays, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None) [source]

Split arrays or matrices into random train and test subsets Quick utility that wraps input validation and next(ShuffleSplit().split(X, y)) and application to input data into a single call for splitting (and optionally subsampling) data in a oneliner. Read more in the User Guide.  Parameters

*arrayssequence of indexables with same length / shape[0]

Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
test_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If train_size is also None, it will be set to 0.25.
train_sizefloat or int, default=None

If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size.
random_stateint, RandomState instance or None, default=None

Controls the shuffling applied to the data before applying the split. Pass an int for reproducible output across multiple function calls. See Glossary.
shufflebool, default=True

Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.
stratifyarray-like, default=None

If not None, data is split in a stratified fashion, using this as the class labels. Read more in the User Guide.    Returns

splittinglist, length=2 * len(arrays)

List containing train-test split of inputs.  New in version 0.16: If the input is sparse, the output will be a scipy.sparse.csr_matrix. Else, output type is the same as the input type.      Examples >>> import numpy as np
>>> from sklearn.model_selection import train_test_split
>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
>>> list(y)
[0, 1, 2, 3, 4]
 >>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.33, random_state=42)
...
>>> X_train
array([[4, 5],
       [0, 1],
       [6, 7]])
>>> y_train
[2, 0, 3]
>>> X_test
array([[2, 3],
       [8, 9]])
>>> y_test
[1, 4]
 >>> train_test_split(y, shuffle=False)
[[0, 1, 2], [3, 4]]


sklearn.model_selection.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=nan, fit_params=None) [source]

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 results. Read more in the User Guide.  Parameters

estimatorobject type that implements the “fit” and “predict” methods

An object of that type which is cloned for each validation.
Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,) or (n_samples, n_outputs) or None

Target relative to X for classification or regression; None for unsupervised learning.
param_namestr

Name of the parameter that will be varied.
param_rangearray-like of shape (n_values,)

The values of the parameter that will be evaluated.
groupsarray-like of shape (n_samples,), default=None

Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a “Group” cv instance (e.g., GroupKFold).
cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:  None, to use the default 5-fold cross validation, int, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices.  For int/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
scoringstr or callable, default=None

A str (see model evaluation documentation) or a scorer callable object / function with signature scorer(estimator, X, y).
n_jobsint, default=None

Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the combinations of each parameter value and each cross-validation split. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
pre_dispatchint or str, default=’all’

Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The str can be an expression like ‘2*n_jobs’.
verboseint, default=0

Controls the verbosity: the higher, the more messages.
fit_paramsdict, default=None

Parameters to pass to the fit method of the estimator.  New in version 0.24.
error_score‘raise’ or numeric, default=np.nan

Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised.  New in version 0.20.     Returns

train_scoresarray of shape (n_ticks, n_cv_folds)

Scores on training sets.
test_scoresarray of shape (n_ticks, n_cv_folds)

Scores on test set.     Notes See Plotting Validation Curves


class sklearn.multiclass.OneVsOneClassifier(estimator, *, n_jobs=None) [source]

One-vs-one multiclass strategy This strategy consists in fitting one classifier per class pair. At prediction time, the class which received the most votes is selected. Since it requires to fit n_classes * (n_classes - 1) / 2 classifiers, this method is usually slower than one-vs-the-rest, due to its O(n_classes^2) complexity. However, this method may be advantageous for algorithms such as kernel algorithms which don’t scale well with n_samples. This is because each individual learning problem only involves a small subset of the data whereas, with one-vs-the-rest, the complete dataset is used n_classes times. Read more in the User Guide.  Parameters

estimatorestimator object

An estimator object implementing fit and one of decision_function or predict_proba.
n_jobsint, default=None

The number of jobs to use for the computation: the n_classes * (
n_classes - 1) / 2 OVO problems are computed in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.    Attributes

estimators_list of n_classes * (n_classes - 1) / 2 estimators

Estimators used for predictions.
classes_numpy array of shape [n_classes]

Array containing labels.
n_classes_int

Number of classes
pairwise_indices_list, length = len(estimators_), or None

Indices of samples used when training the estimators. None when estimator’s pairwise tag is False.  Deprecated since version 0.24: The _pairwise attribute is deprecated in 0.24. From 1.1 (renaming of 0.25) and onward, pairwise_indices_ will use the pairwise estimator tag instead.      Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.multiclass import OneVsOneClassifier
>>> from sklearn.svm import LinearSVC
>>> X, y = load_iris(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.33, shuffle=True, random_state=0)
>>> clf = OneVsOneClassifier(
...     LinearSVC(random_state=0)).fit(X_train, y_train)
>>> clf.predict(X_test[:10])
array([2, 1, 0, 2, 0, 2, 0, 1, 1, 1])
 Methods
decision_function(X) Decision function for the OneVsOneClassifier.
fit(X, y) Fit underlying estimators.
get_params([deep]) Get parameters for this estimator.
partial_fit(X, y[, classes]) Partially fit underlying estimators
predict(X) Estimate the best class label for each sample in X.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
decision_function(X) [source]

Decision function for the OneVsOneClassifier. The decision values for the samples are computed by adding the normalized sum of pair-wise classification confidence levels to the votes in order to disambiguate between the decision values when the votes for all the classes are equal leading to a tie.  Parameters

Xarray-like of shape (n_samples, n_features)
  Returns

Yarray-like of shape (n_samples, n_classes) or (n_samples,) for binary classification.

 Changed in version 0.19: output shape changed to (n_samples,) to conform to scikit-learn conventions for binary classification.

fit(X, y) [source]

Fit underlying estimators.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.
yarray-like of shape (n_samples,)

Multi-class targets.    Returns
 self

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

partial_fit(X, y, classes=None) [source]

Partially fit underlying estimators Should be used when memory is inefficient to train all data. Chunks of data can be passed in several iteration, where the first call should have an array of all target variables.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.
yarray-like of shape (n_samples,)

Multi-class targets.
classesarray, shape (n_classes, )

Classes across all calls to partial_fit. Can be obtained via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is only required in the first call of partial_fit and can be omitted in the subsequent calls.    Returns
 self

predict(X) [source]

Estimate the best class label for each sample in X. This is implemented as argmax(decision_function(X), axis=1) which will return the label of the class with most votes by estimators predicting the outcome of a decision for each possible class pair.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.    Returns

ynumpy array of shape [n_samples]

Predicted multi-class targets.

score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.multiclass.OneVsOneClassifier
class sklearn.multiclass.OneVsOneClassifier(estimator, *, n_jobs=None) [source]

One-vs-one multiclass strategy This strategy consists in fitting one classifier per class pair. At prediction time, the class which received the most votes is selected. Since it requires to fit n_classes * (n_classes - 1) / 2 classifiers, this method is usually slower than one-vs-the-rest, due to its O(n_classes^2) complexity. However, this method may be advantageous for algorithms such as kernel algorithms which don’t scale well with n_samples. This is because each individual learning problem only involves a small subset of the data whereas, with one-vs-the-rest, the complete dataset is used n_classes times. Read more in the User Guide.  Parameters

estimatorestimator object

An estimator object implementing fit and one of decision_function or predict_proba.
n_jobsint, default=None

The number of jobs to use for the computation: the n_classes * (
n_classes - 1) / 2 OVO problems are computed in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.    Attributes

estimators_list of n_classes * (n_classes - 1) / 2 estimators

Estimators used for predictions.
classes_numpy array of shape [n_classes]

Array containing labels.
n_classes_int

Number of classes
pairwise_indices_list, length = len(estimators_), or None

Indices of samples used when training the estimators. None when estimator’s pairwise tag is False.  Deprecated since version 0.24: The _pairwise attribute is deprecated in 0.24. From 1.1 (renaming of 0.25) and onward, pairwise_indices_ will use the pairwise estimator tag instead.      Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.multiclass import OneVsOneClassifier
>>> from sklearn.svm import LinearSVC
>>> X, y = load_iris(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.33, shuffle=True, random_state=0)
>>> clf = OneVsOneClassifier(
...     LinearSVC(random_state=0)).fit(X_train, y_train)
>>> clf.predict(X_test[:10])
array([2, 1, 0, 2, 0, 2, 0, 1, 1, 1])
 Methods
decision_function(X) Decision function for the OneVsOneClassifier.
fit(X, y) Fit underlying estimators.
get_params([deep]) Get parameters for this estimator.
partial_fit(X, y[, classes]) Partially fit underlying estimators
predict(X) Estimate the best class label for each sample in X.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
decision_function(X) [source]

Decision function for the OneVsOneClassifier. The decision values for the samples are computed by adding the normalized sum of pair-wise classification confidence levels to the votes in order to disambiguate between the decision values when the votes for all the classes are equal leading to a tie.  Parameters

Xarray-like of shape (n_samples, n_features)
  Returns

Yarray-like of shape (n_samples, n_classes) or (n_samples,) for binary classification.

 Changed in version 0.19: output shape changed to (n_samples,) to conform to scikit-learn conventions for binary classification.

fit(X, y) [source]

Fit underlying estimators.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.
yarray-like of shape (n_samples,)

Multi-class targets.    Returns
 self

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

partial_fit(X, y, classes=None) [source]

Partially fit underlying estimators Should be used when memory is inefficient to train all data. Chunks of data can be passed in several iteration, where the first call should have an array of all target variables.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.
yarray-like of shape (n_samples,)

Multi-class targets.
classesarray, shape (n_classes, )

Classes across all calls to partial_fit. Can be obtained via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is only required in the first call of partial_fit and can be omitted in the subsequent calls.    Returns
 self

predict(X) [source]

Estimate the best class label for each sample in X. This is implemented as argmax(decision_function(X), axis=1) which will return the label of the class with most votes by estimators predicting the outcome of a decision for each possible class pair.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.    Returns

ynumpy array of shape [n_samples]

Predicted multi-class targets.

score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


decision_function(X) [source]

Decision function for the OneVsOneClassifier. The decision values for the samples are computed by adding the normalized sum of pair-wise classification confidence levels to the votes in order to disambiguate between the decision values when the votes for all the classes are equal leading to a tie.  Parameters

Xarray-like of shape (n_samples, n_features)
  Returns

Yarray-like of shape (n_samples, n_classes) or (n_samples,) for binary classification.

 Changed in version 0.19: output shape changed to (n_samples,) to conform to scikit-learn conventions for binary classification.


fit(X, y) [source]

Fit underlying estimators.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.
yarray-like of shape (n_samples,)

Multi-class targets.    Returns
 self


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


partial_fit(X, y, classes=None) [source]

Partially fit underlying estimators Should be used when memory is inefficient to train all data. Chunks of data can be passed in several iteration, where the first call should have an array of all target variables.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.
yarray-like of shape (n_samples,)

Multi-class targets.
classesarray, shape (n_classes, )

Classes across all calls to partial_fit. Can be obtained via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is only required in the first call of partial_fit and can be omitted in the subsequent calls.    Returns
 self


predict(X) [source]

Estimate the best class label for each sample in X. This is implemented as argmax(decision_function(X), axis=1) which will return the label of the class with most votes by estimators predicting the outcome of a decision for each possible class pair.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.    Returns

ynumpy array of shape [n_samples]

Predicted multi-class targets.


score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


class sklearn.multiclass.OneVsRestClassifier(estimator, *, n_jobs=None) [source]

One-vs-the-rest (OvR) multiclass strategy. Also known as one-vs-all, this strategy consists in fitting one classifier per class. For each classifier, the class is fitted against all the other classes. In addition to its computational efficiency (only n_classes classifiers are needed), one advantage of this approach is its interpretability. Since each class is represented by one and one classifier only, it is possible to gain knowledge about the class by inspecting its corresponding classifier. This is the most commonly used strategy for multiclass classification and is a fair default choice. OneVsRestClassifier can also be used for multilabel classification. To use this feature, provide an indicator matrix for the target y when calling .fit. In other words, the target labels should be formatted as a 2D binary (0/1) matrix, where [i, j] == 1 indicates the presence of label j in sample i. This estimator uses the binary relevance method to perform multilabel classification, which involves training one binary classifier independently for each label. Read more in the User Guide.  Parameters

estimatorestimator object

An estimator object implementing fit and one of decision_function or predict_proba.
n_jobsint, default=None

The number of jobs to use for the computation: the n_classes one-vs-rest problems are computed in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.  Changed in version v0.20: n_jobs default changed from 1 to None     Attributes

estimators_list of n_classes estimators

Estimators used for predictions.
coef_ndarray of shape (1, n_features) or (n_classes, n_features)

Coefficient of the features in the decision function. This attribute exists only if the estimators_ defines coef_.  Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). If you use this attribute in RFE or SelectFromModel, you may pass a callable to the importance_getter parameter that extracts feature the importances from estimators_.
intercept_ndarray of shape (1, 1) or (n_classes, 1)

If y is binary, the shape is (1, 1) else (n_classes, 1) This attribute exists only if the estimators_ defines intercept_.  Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). If you use this attribute in RFE or SelectFromModel, you may pass a callable to the importance_getter parameter that extracts feature the importances from estimators_.
classes_array, shape = [n_classes]

Class labels.
n_classes_int

Number of classes.
label_binarizer_LabelBinarizer object

Object used to transform multiclass labels to binary labels and vice-versa.
multilabel_boolean

Whether this is a multilabel classifier      See also
sklearn.multioutput.MultiOutputClassifier

Alternate way of extending an estimator for multilabel classification.
sklearn.preprocessing.MultiLabelBinarizer

Transform iterable of iterables to binary indicator matrix.    Examples >>> import numpy as np
>>> from sklearn.multiclass import OneVsRestClassifier
>>> from sklearn.svm import SVC
>>> X = np.array([
...     [10, 10],
...     [8, 10],
...     [-5, 5.5],
...     [-5.4, 5.5],
...     [-20, -20],
...     [-15, -20]
... ])
>>> y = np.array([0, 0, 1, 1, 2, 2])
>>> clf = OneVsRestClassifier(SVC()).fit(X, y)
>>> clf.predict([[-19, -20], [9, 9], [-5, 5]])
array([2, 0, 1])
 Methods
decision_function(X) Returns the distance of each sample from the decision boundary for each class.
fit(X, y) Fit underlying estimators.
get_params([deep]) Get parameters for this estimator.
partial_fit(X, y[, classes]) Partially fit underlying estimators
predict(X) Predict multi-class targets using underlying estimators.
predict_proba(X) Probability estimates.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
decision_function(X) [source]

Returns the distance of each sample from the decision boundary for each class. This can only be used with estimators which implement the decision_function method.  Parameters

Xarray-like of shape (n_samples, n_features)
  Returns

Tarray-like of shape (n_samples, n_classes) or (n_samples,) for binary classification.

 Changed in version 0.19: output shape changed to (n_samples,) to conform to scikit-learn conventions for binary classification.

fit(X, y) [source]

Fit underlying estimators.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.
y(sparse) array-like of shape (n_samples,) or (n_samples, n_classes)

Multi-class targets. An indicator matrix turns on multilabel classification.    Returns
 self

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

property multilabel_
Whether this is a multilabel classifier

partial_fit(X, y, classes=None) [source]

Partially fit underlying estimators Should be used when memory is inefficient to train all data. Chunks of data can be passed in several iteration.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.
y(sparse) array-like of shape (n_samples,) or (n_samples, n_classes)

Multi-class targets. An indicator matrix turns on multilabel classification.
classesarray, shape (n_classes, )

Classes across all calls to partial_fit. Can be obtained via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is only required in the first call of partial_fit and can be omitted in the subsequent calls.    Returns
 self

predict(X) [source]

Predict multi-class targets using underlying estimators.  Parameters

X(sparse) array-like of shape (n_samples, n_features)

Data.    Returns

y(sparse) array-like of shape (n_samples,) or (n_samples, n_classes)

Predicted multi-class targets.

predict_proba(X) [source]

Probability estimates. The returned estimates for all classes are ordered by label of classes. Note that in the multilabel case, each sample can have any number of labels. This returns the marginal probability that the given sample has the label in question. For example, it is entirely consistent that two labels both have a 90% probability of applying to a given sample. In the single label multiclass case, the rows of the returned matrix sum to 1.  Parameters

Xarray-like of shape (n_samples, n_features)
  Returns

T(sparse) array-like of shape (n_samples, n_classes)

Returns the probability of the sample for each class in the model, where classes are ordered as they are in self.classes_.

score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.