Model Selection

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

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, views):
...    scores = estimator.score(views)
...    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.

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

cca_zoo.model_selection.cross_validate(estimator, views, 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.

  • views – list/tuple of numpy arrays or array likes with the same number of rows (samples)

  • 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 The scoring parameter: defining model evaluation rules); - a callable (see Defining your scoring strategy from metric functions) 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 Specifying multiple metrics for evaluation 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

cca_zoo.model_selection.learning_curve(estimator, views, 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.

  • views – list/tuple of numpy arrays or array likes with the same number of rows (samples)

  • y – array-like of shape (n_samples,) or (n_samples, n_outputs) Target relative to views 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, views, 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

cca_zoo.model_selection.permutation_test_score(estimator, views, 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.

  • views – list/tuple of numpy arrays or array likes with the same number of rows (samples)

  • 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 The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions) 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