Model Selection

GridSearchCV

class cca_zoo.model_selection.GridSearchCV(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)[source]
Example

>>> from cca_zoo.model_selection import GridSearchCV
>>> from cca_zoo.models import MCCA
>>> X1 = [[0, 0, 1], [1, 0, 0], [2, 2, 2], [3, 5, 4]]
>>> X2 = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]]
>>> X3 = [[0, 1, 0], [1, 9, 0], [4, 3, 3,], [12, 8, 10]]
>>> model = MCCA()
>>> params = {'c': [[0.1, 0.2], [0.3, 0.4], 0.1]}
>>> GridSearchCV(model,param_grid=params, cv=3).fit([X1,X2,X3]).best_estimator_.c
[0.1, 0.3, 0.1]
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.

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

Run fit with all sets of parameters.

Parameters
  • X (array-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.

  • y (array-like of shape (n_samples, n_output) or (n_samples,), default=None) – Target relative to X for classification or regression; None for unsupervised 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).

  • **fit_params (dict of str -> object) – Parameters passed to the fit method of the estimator.

Returns

self – Instance of fitted estimator.

Return type

object

property classes_

Class labels.

Only available when refit=True and the estimator is a classifier.

decision_function(X)

Call decision_function on the estimator with the best found parameters.

Only available if refit=True and the underlying estimator supports decision_function.

Parameters

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

y_score – Result of the decision function for X based on the estimator with the best found parameters.

Return type

ndarray of shape (n_samples,) or (n_samples, n_classes) or (n_samples, n_classes * (n_classes-1) / 2)

get_params(deep=True)

Get parameters for this estimator.

Parameters

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns

params – Parameter names mapped to their values.

Return type

dict

inverse_transform(Xt)

Call inverse_transform on the estimator with the best found params.

Only available if the underlying estimator implements inverse_transform and refit=True.

Parameters

Xt (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

X – Result of the inverse_transform function for Xt based on the estimator with the best found parameters.

Return type

{ndarray, sparse matrix} of shape (n_samples, n_features)

property n_features_in_

Number of features seen during fit.

Only available when refit=True.

predict(X)

Call predict on the estimator with the best found parameters.

Only available if refit=True and the underlying estimator supports predict.

Parameters

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

y_pred – The predicted labels or values for X based on the estimator with the best found parameters.

Return type

ndarray of shape (n_samples,)

predict_log_proba(X)

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

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

y_pred – Predicted class log-probabilities for X based on the estimator with the best found parameters. The order of the classes corresponds to that in the fitted attribute classes_.

Return type

ndarray of shape (n_samples,) or (n_samples, n_classes)

predict_proba(X)

Call predict_proba on the estimator with the best found parameters.

Only available if refit=True and the underlying estimator supports predict_proba.

Parameters

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

y_pred – Predicted class probabilities for X based on the estimator with the best found parameters. The order of the classes corresponds to that in the fitted attribute classes_.

Return type

ndarray of shape (n_samples,) or (n_samples, n_classes)

score(X, y=None)

Return 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
  • X (array-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.

  • y (array-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

score – The score defined by scoring if provided, and the best_estimator_.score method otherwise.

Return type

float

score_samples(X)

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

X (iterable) – Data to predict on. Must fulfill input requirements of the underlying estimator.

Returns

y_score – The best_estimator_.score_samples method.

Return type

ndarray of shape (n_samples,)

set_params(**params)

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

**params (dict) – Estimator parameters.

Returns

self – Estimator instance.

Return type

estimator instance

transform(X)

Call transform on the estimator with the best found parameters.

Only available if the underlying estimator supports transform and refit=True.

Parameters

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

XtX transformed in the new space based on the estimator with the best found parameters.

Return type

{ndarray, sparse matrix} of shape (n_samples, n_features)

RandomizedSearchCV

class cca_zoo.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]
Example

>>> from cca_zoo.model_selection import RandomizedSearchCV
>>> from cca_zoo.models import MCCA
>>> from sklearn.utils.fixes import loguniform
>>> X1 = [[0, 0, 1], [1, 0, 0], [2, 2, 2], [3, 5, 4]]
>>> X2 = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]]
>>> X3 = [[0, 1, 0], [1, 9, 0], [4, 3, 3,], [12, 8, 10]]
>>> model = MCCA()
>>> params = {'c': [loguniform(1e-4, 1e0), loguniform(1e-4, 1e0), [0.1]]}
>>> def scorer(estimator, X):
...    scores = estimator.score(X)
...    return np.mean(scores)
>>> RandomizedSearchCV(model,param_distributions=params, cv=3, scoring=scorer,n_iter=10).fit([X1,X2,X3]).n_iter
10
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.

property classes_

Class labels.

Only available when refit=True and the estimator is a classifier.

decision_function(X)

Call decision_function on the estimator with the best found parameters.

Only available if refit=True and the underlying estimator supports decision_function.

Parameters

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

y_score – Result of the decision function for X based on the estimator with the best found parameters.

Return type

ndarray of shape (n_samples,) or (n_samples, n_classes) or (n_samples, n_classes * (n_classes-1) / 2)

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

Run fit with all sets of parameters.

Parameters
  • X (array-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.

  • y (array-like of shape (n_samples, n_output) or (n_samples,), default=None) – Target relative to X for classification or regression; None for unsupervised 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).

  • **fit_params (dict of str -> object) – Parameters passed to the fit method of the estimator.

Returns

self – Instance of fitted estimator.

Return type

object

get_params(deep=True)

Get parameters for this estimator.

Parameters

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns

params – Parameter names mapped to their values.

Return type

dict

inverse_transform(Xt)

Call inverse_transform on the estimator with the best found params.

Only available if the underlying estimator implements inverse_transform and refit=True.

Parameters

Xt (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

X – Result of the inverse_transform function for Xt based on the estimator with the best found parameters.

Return type

{ndarray, sparse matrix} of shape (n_samples, n_features)

property n_features_in_

Number of features seen during fit.

Only available when refit=True.

predict(X)

Call predict on the estimator with the best found parameters.

Only available if refit=True and the underlying estimator supports predict.

Parameters

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

y_pred – The predicted labels or values for X based on the estimator with the best found parameters.

Return type

ndarray of shape (n_samples,)

predict_log_proba(X)

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

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

y_pred – Predicted class log-probabilities for X based on the estimator with the best found parameters. The order of the classes corresponds to that in the fitted attribute classes_.

Return type

ndarray of shape (n_samples,) or (n_samples, n_classes)

predict_proba(X)

Call predict_proba on the estimator with the best found parameters.

Only available if refit=True and the underlying estimator supports predict_proba.

Parameters

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

y_pred – Predicted class probabilities for X based on the estimator with the best found parameters. The order of the classes corresponds to that in the fitted attribute classes_.

Return type

ndarray of shape (n_samples,) or (n_samples, n_classes)

score(X, y=None)

Return 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
  • X (array-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.

  • y (array-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

score – The score defined by scoring if provided, and the best_estimator_.score method otherwise.

Return type

float

score_samples(X)

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

X (iterable) – Data to predict on. Must fulfill input requirements of the underlying estimator.

Returns

y_score – The best_estimator_.score_samples method.

Return type

ndarray of shape (n_samples,)

set_params(**params)

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

**params (dict) – Estimator parameters.

Returns

self – Estimator instance.

Return type

estimator instance

transform(X)

Call transform on the estimator with the best found parameters.

Only available if the underlying estimator supports transform and refit=True.

Parameters

X (indexable, length n_samples) – Must fulfill the input assumptions of the underlying estimator.

Returns

XtX transformed in the new space based on the estimator with the best found parameters.

Return type

{ndarray, sparse matrix} of shape (n_samples, n_features)

cross_validate

cca_zoo.model_selection.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)[source]

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).

  • 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 y is either binary or multiclass, StratifiedKFold is used. In all other cases, Fold is 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. .. versionchanged:: 0.22

    cv default 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. None means 1 unless in a joblib.parallel_backend context. -1 means 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’

Example

permutation_test_score

cca_zoo.model_selection.permutation_test_score(estimator, X, y=None, groups=None, cv=None, n_permutations=100, n_jobs=None, random_state=0, verbose=0, scoring=None, fit_params=None)[source]

Evaluate the significance of a cross-validated score with permutations Permutes targets to generate ‘randomized data’ and compute the empirical p-value against the null hypothesis that features and targets are independent. The p-value represents the fraction of randomized data sets where the estimator performed as well or better than in the original data. A small p-value suggests that there is a real dependency between features and targets which has been used by the estimator to give good predictions. A large p-value may be due to lack of real dependency between features and targets or the estimator was not able to use the dependency to give good predictions. 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 at least 2D The data to fit.

  • y – array-like of shape (n_samples,) or (n_samples, n_outputs) or None The target variable to try to predict in the case of supervised learning.

  • groups – array-like of shape (n_samples,), default=None Labels to constrain permutation within groups, i.e. y values are permuted among samples with the same group identifier. When not specified, y values are permuted among all samples. When a grouped cross-validator is used, the group labels are also passed on to the split method of the cross-validator. The cross-validator uses them for grouping the samples while splitting the dataset into train/test set.

  • scoring – str or callable, default=None A single str (see scoring_parameter) or a callable (see scoring) to evaluate the predictions on the test set. If None the estimator’s score method is used.

  • 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 y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is 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. .. versionchanged:: 0.22

    cv default value if None changed from 3-fold to 5-fold.

  • n_permutations – int, default=100 Number of times to permute y.

  • n_jobs – int, default=None Number of jobs to run in parallel. Training the estimator and computing the cross-validated score are parallelized over the permutations. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

  • random_state – int, RandomState instance or None, default=0 Pass an int for reproducible output for permutation of y values among samples. See Glossary.

  • verbose – int, default=0 The verbosity level.

  • fit_params – dict, default=None Parameters to pass to the fit method of the estimator. .. versionadded:: 0.24

learning_curve

cca_zoo.model_selection.learning_curve(estimator, X, y=None, groups=None, train_sizes=array([0.1, 0.325, 0.55, 0.775, 1.0]), cv=None, scoring=None, exploit_incremental_learning=False, n_jobs=None, pre_dispatch='all', verbose=0, shuffle=False, random_state=None, error_score=nan, return_times=False, fit_params=None)[source]

Learning curve. Determines cross-validated training and test scores for different training set sizes. A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterwards, the scores will be averaged over all k runs for each training subset size. Read more in the User Guide.

Parameters
  • estimator – object type that implements the “fit” and “predict” methods An object of that type which is cloned for each validation.

  • X – array-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.

  • y – array-like of shape (n_samples,) or (n_samples, n_outputs) Target relative to X for classification or regression; None for unsupervised 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).

  • train_sizes – array-like of shape (n_ticks,), default=np.linspace(0.1, 1.0, 5) Relative or absolute numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of the maximum size of the training set (that is determined by the selected validation method), i.e. it has to be within (0, 1]. Otherwise it is interpreted as absolute sizes of the training sets. Note that for classification the number of samples usually have to be big enough to contain at least one sample from each class.

  • 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 y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is 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. .. versionchanged:: 0.22

    cv default value if None changed from 3-fold to 5-fold.

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

  • exploit_incremental_learning – bool, default=False If the estimator supports incremental learning, this will be used to speed up fitting for different training set sizes.

  • n_jobs – int, default=None Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the different training and test sets. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

  • pre_dispatch – int 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’.

  • verbose – int, default=0 Controls the verbosity: the higher, the more messages.

  • shuffle – bool, default=False Whether to shuffle training data before taking prefixes of it based on``train_sizes``.

  • random_state – int, RandomState instance or None, default=None Used when shuffle is True. 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. .. versionadded:: 0.20

  • return_times – bool, default=False Whether to return the fit and score times.

  • fit_params – dict, default=None Parameters to pass to the fit method of the estimator. .. versionadded:: 0.24