bipartite_learn.model_selection package#
Module contents#
- class bipartite_learn.model_selection.MultipartiteCrossValidator(cross_validators, diagonal=False, n_parts=2)#
Bases:
BaseCrossValidator- get_n_splits(X=None, y=None, groups=None)#
Returns the number of splitting iterations in the cross-validator
- split(X, y=None, groups=None)#
Generate indices to split data into training and test set.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Training data, where n_samples is the number of samples and n_features is the number of features.
y (array-like of shape (n_samples,)) – The target variable for supervised learning problems.
groups (array-like of shape (n_samples,), default=None) – Group labels for the samples used while splitting the dataset into train/test set.
- Yields:
train (ndarray) – The training set indices for that split.
test (ndarray) – The testing set indices for that split.
- class bipartite_learn.model_selection.MultipartiteGridSearchCV(estimator, param_grid, *, scoring=None, n_jobs=None, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score=nan, return_train_score=False, diagonal=False, train_test_combinations=None, pairwise=False)#
Bases:
BaseMultipartiteSearchCV,GridSearchCVExhaustive search over specified parameter values for an estimator.
Important members are fit, predict.
GridSearchCV 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 grid-search over a parameter grid.
Read more in the User Guide.
- Parameters:
estimator (estimator object) – This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a
scorefunction, orscoringmust be passed.param_grid (dict or list of dictionaries) – Dictionary with parameters names (str) as keys and lists of parameter settings to try as values, or a list of such dictionaries, in which case the grids spanned by each dictionary in the list are explored. This enables searching over any sequence of parameter settings.
scoring (str, 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 scoring_parameter);
a callable (see scoring) that returns a single value.
If scoring represents 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 multimetric_grid_search for an example.
n_jobs (int, default=None) –
Number of jobs to run in parallel.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means using all processors. See Glossary for more details.Changed in version v0.20: n_jobs default changed from 1 to None
refit (bool, 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,
refitcan be set to a function which returns the selectedbest_index_givencv_results_. In that case, thebest_estimator_andbest_params_will be set according to the returnedbest_index_while thebest_score_attribute will not be available.The refitted estimator is made available at the
best_estimator_attribute and permits usingpredictdirectly on thisGridSearchCVinstance.Also for multiple metric evaluation, the attributes
best_index_,best_score_andbest_params_will only be available ifrefitis set and all of them will be determined w.r.t this specific scorer.See
scoringparameter to know more about multiple metric evaluation.Changed in version 0.20: Support for callable added.
cv (int, 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
yis either binary or multiclass,StratifiedKFoldis used. In all other cases,KFoldis used. These splitters are instantiated with shuffle=False so the splits will be the same across calls.Refer User Guide for the various cross-validation strategies that can be used here.
Changed in version 0.22:
cvdefault value if None changed from 3-fold to 5-fold.verbose (int) –
Controls the verbosity: the higher, the more messages.
>1 : the computation time for each fold and parameter candidate is displayed;
>2 : the score is also displayed;
>3 : the fold and candidate parameter indexes are also displayed together with the starting time of the computation.
pre_dispatch (int, or str, default='2*n_jobs') –
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’
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_score (bool, default=False) –
If
False, thecv_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
TruetoFalse
- cv_results_#
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
param_degree
split0_test_score
…
rank_t…
‘poly’
–
2
0.80
…
2
‘poly’
–
3
0.70
…
4
‘rbf’
0.1
–
0.80
…
3
‘rbf’
0.2
–
0.93
…
1
will be represented by a
cv_results_dict of:{ 'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'], mask = [False False False False]...) 'param_gamma': masked_array(data = [-- -- 0.1 0.2], mask = [ True True False False]...), 'param_degree': masked_array(data = [2.0 3.0 -- --], mask = [False False True True]...), 'split0_test_score' : [0.80, 0.70, 0.80, 0.93], 'split1_test_score' : [0.82, 0.50, 0.70, 0.78], 'mean_test_score' : [0.81, 0.60, 0.75, 0.85], 'std_test_score' : [0.01, 0.10, 0.05, 0.08], 'rank_test_score' : [2, 4, 3, 1], 'split0_train_score' : [0.80, 0.92, 0.70, 0.93], 'split1_train_score' : [0.82, 0.55, 0.70, 0.87], 'mean_train_score' : [0.81, 0.74, 0.70, 0.90], 'std_train_score' : [0.01, 0.19, 0.00, 0.03], 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], 'mean_score_time' : [0.01, 0.06, 0.04, 0.04], 'std_score_time' : [0.00, 0.00, 0.00, 0.01], 'params' : [{'kernel': 'poly', 'degree': 2}, ...], }
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_timeandstd_score_timeare 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.)- Type:
dict of numpy (masked) ndarrays
- best_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.See
refitparameter for more information on allowed values.- Type:
estimator
- best_score_#
Mean cross-validated score of the best_estimator
For multi-metric evaluation, this is present only if
refitis specified.This attribute is not available if
refitis a function.- Type:
float
- best_params_#
Parameter setting that gave the best results on the hold out data.
For multi-metric evaluation, this is present only if
refitis specified.- Type:
dict
- best_index_#
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 present only if
refitis specified.- Type:
int
- scorer_#
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
scoringdict which maps the scorer key to the scorer callable.- Type:
function or a dict
- n_splits_#
The number of cross-validation splits (folds/iterations).
- Type:
int
- refit_time_#
Seconds used for refitting the best model on the whole dataset.
This is present only if
refitis not False.New in version 0.20.
- Type:
float
- multimetric_#
Whether or not the scorers compute several metrics.
- Type:
bool
- classes_#
The classes labels. This is present only if
refitis specified and the underlying estimator is a classifier.- Type:
ndarray of shape (n_classes,)
- n_features_in_#
Number of features seen during fit. Only defined if best_estimator_ is defined (see the documentation for the refit parameter for more details) and that best_estimator_ exposes n_features_in_ when fit.
New in version 0.24.
- Type:
int
- feature_names_in_#
Names of features seen during fit. Only defined if best_estimator_ is defined (see the documentation for the refit parameter for more details) and that best_estimator_ exposes feature_names_in_ when fit.
New in version 1.0.
- Type:
ndarray of shape (n_features_in_,)
See also
ParameterGridGenerates all the combinations of a hyperparameter grid.
train_test_splitUtility function to split the data into a development set usable for fitting a GridSearchCV instance and an evaluation set for its final evaluation.
sklearn.metrics.make_scorerMake a scorer from a performance metric or loss function.
Notes
The parameters selected are those that maximize the score of the left out data, unless an explicit score is passed in which case it is used instead.
If n_jobs was set to a value higher than one, the data is copied for each point in the grid (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 import svm, datasets >>> from sklearn.model_selection import GridSearchCV >>> iris = datasets.load_iris() >>> parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]} >>> svc = svm.SVC() >>> clf = GridSearchCV(svc, parameters) >>> clf.fit(iris.data, iris.target) GridSearchCV(estimator=SVC(), param_grid={'C': [1, 10], 'kernel': ('linear', 'rbf')}) >>> sorted(clf.cv_results_.keys()) ['mean_fit_time', 'mean_score_time', 'mean_test_score',... 'param_C', 'param_kernel', 'params',... 'rank_test_score', 'split0_test_score',... 'split2_test_score', ... 'std_fit_time', 'std_score_time', 'std_test_score']
- class bipartite_learn.model_selection.MultipartiteRandomizedSearchCV(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, diagonal=False, train_test_combinations=None, pairwise=True)#
Bases:
BaseMultipartiteSearchCV,RandomizedSearchCVRandomized 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:
estimator (estimator 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
scorefunction, orscoringmust be passed.param_distributions (dict or list of dicts) – Dictionary with parameters names (str) as keys and distributions or lists of parameters to try. Distributions must provide a
rvsmethod 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_iter (int, default=10) – Number of parameter settings that are sampled. n_iter trades off runtime vs quality of the solution.
scoring (str, 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 scoring_parameter);
a callable (see scoring) that returns a single value.
If scoring represents 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 multimetric_grid_search for an example.
If None, the estimator’s score method is used.
n_jobs (int, default=None) –
Number of jobs to run in parallel.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means using all processors. See Glossary for more details.Changed in version v0.20: n_jobs default changed from 1 to None
refit (bool, 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,
refitcan be set to a function which returns the selectedbest_index_given thecv_results. In that case, thebest_estimator_andbest_params_will be set according to the returnedbest_index_while thebest_score_attribute will not be available.The refitted estimator is made available at the
best_estimator_attribute and permits usingpredictdirectly on thisRandomizedSearchCVinstance.Also for multiple metric evaluation, the attributes
best_index_,best_score_andbest_params_will only be available ifrefitis set and all of them will be determined w.r.t this specific scorer.See
scoringparameter to know more about multiple metric evaluation.Changed in version 0.20: Support for callable added.
cv (int, 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
yis either binary or multiclass,StratifiedKFoldis used. In all other cases,KFoldis used. These splitters are instantiated with shuffle=False so the splits will be the same across calls.Refer User Guide for the various cross-validation strategies that can be used here.
Changed in version 0.22:
cvdefault value if None changed from 3-fold to 5-fold.verbose (int) – Controls the verbosity: the higher, the more messages.
pre_dispatch (int, or str, default='2*n_jobs') –
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’
random_state (int, 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_score (bool, default=False) –
If
False, thecv_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
TruetoFalse
- cv_results_#
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_timeandstd_score_timeare 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.)- Type:
dict of numpy (masked) ndarrays
- best_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
refitis specified.See
refitparameter for more information on allowed values.- Type:
estimator
- best_score_#
Mean cross-validated score of the best_estimator.
For multi-metric evaluation, this is not available if
refitisFalse. Seerefitparameter for more information.This attribute is not available if
refitis a function.- Type:
float
- best_params_#
Parameter setting that gave the best results on the hold out data.
For multi-metric evaluation, this is not available if
refitisFalse. Seerefitparameter for more information.- Type:
dict
- best_index_#
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
refitisFalse. Seerefitparameter for more information.- Type:
int
- scorer_#
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
scoringdict which maps the scorer key to the scorer callable.- Type:
function or a dict
- n_splits_#
The number of cross-validation splits (folds/iterations).
- Type:
int
- refit_time_#
Seconds used for refitting the best model on the whole dataset.
This is present only if
refitis not False.New in version 0.20.
- Type:
float
- multimetric_#
Whether or not the scorers compute several metrics.
- Type:
bool
- classes_#
The classes labels. This is present only if
refitis specified and the underlying estimator is a classifier.- Type:
ndarray of shape (n_classes,)
- n_features_in_#
Number of features seen during fit. Only defined if best_estimator_ is defined (see the documentation for the refit parameter for more details) and that best_estimator_ exposes n_features_in_ when fit.
New in version 0.24.
- Type:
int
- feature_names_in_#
Names of features seen during fit. Only defined if best_estimator_ is defined (see the documentation for the refit parameter for more details) and that best_estimator_ exposes feature_names_in_ when fit.
New in version 1.0.
- Type:
ndarray of shape (n_features_in_,)
See also
GridSearchCVDoes exhaustive search over a grid of parameters.
ParameterSamplerA 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'}
- bipartite_learn.model_selection.make_multipartite_train_test_splitter(n_parts, test_size=None, train_size=None, shuffle=False, stratified=False, random_state=None)#
Build a len(n_samples)-dimensional train-test splitter.
Wraps len(n_samples) CrossValidator data splitters with a MultipartiteCrossValidator, that provides train-test indices for splitting InputDataND objects. The returned wrapper object is compatible with parameter search objects in bipartite_learn.model_selection, such as MultipartiteGridSearchCV and MultipartiteRandomizedSearchCV.
The parameters ‘test_size’, ‘train_size’, ‘shuffle’ and ‘stratify’ can be optionally passed as a tuple or list of values intended for each respective axis of the ND data. Otherwise, the single value is equally considered for all axes.
- Parameters:
test_size (float or int or list-like of (float 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_sizeis also None, it will be set to 0.25. One can optionally pass values for each axis in a list or tuple. If a single value is provided, it will be considered for all axes.train_size (float or int or list-like of (float 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. One can optionally pass values for each axis in a list or tuple. If a single value is provided, it will be considered for all axes.
random_state (int, 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.
shuffle (bool or list-like of bool, default=True) – Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None. One can optionally pass values for each axis in a list or tuple. If a single value is provided, it will be considered for all axes.
stratified (bool or list-like of array-like, default=None) – whether or not to generate a stratified splitter. Read more in the User Guide. One can optionally pass arrays for each axis in a list or tuple. If a single array is provided, it will be considered for all axes.
- Returns:
cross-validation splitter
- Return type:
- bipartite_learn.model_selection.multipartite_cross_validate(estimator, X, y=None, *, groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2*n_jobs', return_train_score=False, return_estimator=False, error_score=nan, diagonal=False, train_test_combinations=None, pairwise=False, shuffle=False, random_state=None)#
Evaluate metric(s) by cross-validation and also record fit/score times.
Read more in the User Guide.
- Parameters:
estimator (estimator object implementing 'fit') – The object to use to fit the data.
X (array-like of shape (n_samples, n_features)) – The data to fit. Can be for example a list, or an array.
y (array-like of shape (n_samples,) or (n_samples, n_outputs), default=None) – The target variable to try to predict in the case of supervised learning.
groups (array-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).diagonal (bool, default=False) – Wether to combine each axis splits in a product-manner or zip-manner.
scoring (str, 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 scoring_parameter);
a callable (see scoring) that returns a single value.
If scoring represents 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 multimetric_grid_search for an example.
cv (int, 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
yis either binary or multiclass,StratifiedKFoldis used. In all other cases,Foldis used. These splitters are instantiated with shuffle=False so the splits will be the same across calls.Refer User Guide for the various cross-validation strategies that can be used here.
Changed in version 0.22:
cvdefault value if None changed from 3-fold to 5-fold.n_jobs (int, default=None) – Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the cross-validation splits.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means using all processors. See Glossary for more details.verbose (int, default=0) – The verbosity level.
fit_params (dict, default=None) – Parameters to pass to the fit method of the estimator.
pre_dispatch (int or str, default='2*n_jobs') –
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’
return_train_score (bool, default=False) –
Whether to include train 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
TruetoFalsereturn_estimator (bool, default=False) –
Whether to return the estimators fitted on each split.
New in version 0.20.
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:
scores – Array of scores of the estimator for each run of the cross validation.
A dict of arrays containing the score/time arrays for each scorer is returned. The possible keys for this
dictare:test_scoreThe score array for test scores on each cv split. Suffix
_scoreintest_scorechanges to a specific metric liketest_r2ortest_aucif there are multiple scoring metrics in the scoring parameter.train_scoreThe score array for train scores on each cv split. Suffix
_scoreintrain_scorechanges to a specific metric liketrain_r2ortrain_aucif there are multiple scoring metrics in the scoring parameter. This is available only ifreturn_train_scoreparameter isTrue.fit_timeThe time for fitting the estimator on the train set for each cv split.
score_timeThe time for scoring the estimator on the test set for each cv split. (Note time for scoring on the train set is not included even if
return_train_scoreis set toTrueestimatorThe estimator objects for each cv split. This is available only if
return_estimatorparameter is set toTrue.
- Return type:
dict of float arrays of shape (n_splits,)
Examples
>>> from sklearn import datasets, linear_model >>> from sklearn.model_selection import cross_validate >>> from sklearn.metrics import make_scorer >>> from sklearn.metrics import confusion_matrix >>> from sklearn.svm import LinearSVC >>> diabetes = datasets.load_diabetes() >>> X = diabetes.data[:150] >>> y = diabetes.target[:150] >>> lasso = linear_model.Lasso()
Single metric evaluation using
cross_validate>>> cv_results = cross_validate(lasso, X, y, cv=3) >>> sorted(cv_results.keys()) ['fit_time', 'score_time', 'test_score'] >>> cv_results['test_score'] array([0.3315057 , 0.08022103, 0.03531816])
Multiple metric evaluation using
cross_validate(please refer thescoringparameter doc for more information)>>> scores = cross_validate(lasso, X, y, cv=3, ... scoring=('r2', 'neg_mean_squared_error'), ... return_train_score=True) >>> print(scores['test_neg_mean_squared_error']) [-3635.5... -3573.3... -6114.7...] >>> print(scores['train_r2']) [0.28009951 0.3908844 0.22784907]
See also
cross_val_scoreRun cross-validation for single metric evaluation.
cross_val_predictGet predictions from each split of cross-validation for diagnostic purposes.
sklearn.metrics.make_scorerMake a scorer from a performance metric or loss function.