ScikitLearn API (tune.sklearn)¶
TuneGridSearchCV¶

class
ray.tune.sklearn.
TuneGridSearchCV
(estimator, param_grid, early_stopping=None, scoring=None, n_jobs=None, cv=5, refit=True, verbose=0, error_score='raise', return_train_score=False, local_dir='~/ray_results', name=None, max_iters=1, use_gpu=False, loggers=None, pipeline_auto_early_stop=True, stopper=None, time_budget_s=None, sk_n_jobs=None, mode=None)[source]¶ Exhaustive search over specified parameter values for an estimator.
Important members are fit, predict.
GridSearchCV implements a “fit” and a “score” method. It also implements “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 crossvalidated gridsearch over a parameter grid.
 Parameters
estimator (estimator) – Object that implements the scikitlearn estimator interface. Either estimator needs to provide a
score
function, orscoring
must be passed.param_grid (dict or list of dict) – Dictionary with parameters names (string) as keys and lists or tune.grid_search outputs 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.
early_stopping (bool, str or
TrialScheduler
, optional) –Option to stop fitting to a hyperparameter configuration if it performs poorly. Possible inputs are:
If True, defaults to ASHAScheduler.
A string corresponding to the name of a Tune Trial Scheduler (i.e., “ASHAScheduler”). To specify parameters of the scheduler, pass in a scheduler object instead of a string.
Scheduler for executing fit with early stopping. Only a subset of schedulers are currently supported. The scheduler will only be used if the estimator supports partial fitting
If None or False, early stopping will not be used.
scoring (str, list/tuple, dict, or None) – A single string or a callable to evaluate the predictions on the test set. See https://scikitlearn.org/stable/modules/model_evaluation.html #scoringparameter for all options. For evaluating multiple metrics, either give a list/tuple of (unique) strings or a dict with names as keys and callables as values. If None, the estimator’s score method is used. Defaults to None.
n_jobs (int) – Number of jobs to run in parallel. None or 1 means using all processors. Defaults to None. If set to 1, jobs will be run using Ray’s ‘local mode’. This can lead to significant speedups if the model takes < 10 seconds to fit due to removing interprocess communication overheads.
cv (int, crossvalidation generator or iterable) –
Determines the crossvalidation splitting strategy. Possible inputs for cv are:
None, to use the default 5fold cross validation,
integer, to specify the number of folds in a (Stratified)KFold,
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. Defaults to None.refit (bool or str) – Refit an estimator using the best found parameters on the whole dataset. For multiple metric evaluation, this needs to be a string denoting the scorer that would be used to find the best parameters for refitting the estimator at the end. The refitted estimator is made available at the
best_estimator_
attribute and permits usingpredict
directly on thisGridSearchCV
instance. Also for multiple metric evaluation, the attributesbest_index_
,best_score_
andbest_params_
will only be available ifrefit
is set and all of them will be determined w.r.t this specific scorer. If refit not needed, set to False. Seescoring
parameter to know more about multiple metric evaluation. Defaults to True.verbose (int) – Controls the verbosity: 0 = silent, 1 = only status updates, 2 = status and trial results. Defaults to 0.
error_score ('raise' or int or float) – 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. Defaults to np.nan.
return_train_score (bool) – If
False
, thecv_results_
attribute will not include training scores. Defaults to False. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting tradeoff. 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.local_dir (str) – A string that defines where checkpoints will be stored. Defaults to “~/ray_results”.
name (str) – Name of experiment (for Ray Tune) –
max_iters (int) – Indicates the maximum number of epochs to run for each hyperparameter configuration sampled. This parameter is used for early stopping. Defaults to 1. Depending on the classifier type provided, a resource parameter (resource_param = max_iter or n_estimators) will be detected. The value of resource_param will be treated as a “max resource value”, and all classifiers will be initialized with max resource value // max_iters, where max_iters is this defined parameter. On each epoch, resource_param (max_iter or n_estimators) is incremented by max resource value // max_iters.
use_gpu (bool) – Indicates whether to use gpu for fitting. Defaults to False. If True, training will start processes with the proper CUDA VISIBLE DEVICE settings set. If a Ray cluster has been initialized, all available GPUs will be used.
loggers (list) – A list of the names of the Tune loggers as strings to be used to log results. Possible values are “tensorboard”, “csv”, “mlflow”, and “json”
pipeline_auto_early_stop (bool) – Only relevant if estimator is Pipeline object and early_stopping is enabled/True. If True, early stopping will be performed on the last stage of the pipeline (which must support early stopping). If False, early stopping will be determined by ‘Pipeline.warm_start’ or ‘Pipeline.partial_fit’ capabilities, which are by default not supported by standard SKlearn. Defaults to True.
stopper (ray.tune.stopper.Stopper) – Stopper objects passed to
tune.run()
.time_budget_s (intfloatdatetime.timedelta) – Global time budget in seconds after which all trials are stopped. Can also be a
datetime.timedelta
object.mode (str) – One of {min, max}. Determines whether objective is minimizing or maximizing the metric attribute. Defaults to “max”.

property
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
refit
parameter for more information on allowed values. Type
estimator

property
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 multimetric evaluation, this is present only if
refit
is specified. Type
int

property
best_params_
¶ Parameter setting that gave the best results on the hold out data.
For multimetric evaluation, this is present only if
refit
is specified. Type
dict

property
best_score_
¶ Mean crossvalidated score of the best_estimator
For multimetric evaluation, this is present only if
refit
is specified. Type
float

property
classes_
¶ Get the list of unique classes found in the target y.
 Type
list

property
decision_function
¶ Get decision_function on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportsdecision_function
. Type
function

fit
(X, y=None, groups=None, tune_params=None, **fit_params)¶ Run fit with all sets of parameters.
tune.run
is used to perform the fit procedure. Parameters
X (
arraylike
(shape = [n_samples, n_features])) – Training vector, where n_samples is the number of samples and n_features is the number of features.y (
arraylike
) – Shape of array expected to be [n_samples] or [n_samples, n_output]). Target relative to X for classification or regression; None for unsupervised learning.groups (
arraylike
(shape (n_samples,)), optional) – 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).tune_params (
dict
, optional) – Parameters passed totune.run
used for parameter search.**fit_params (
dict
of str) – Parameters passed to thefit
method of the estimator.
 Returns
TuneBaseSearchCV
child instance, after fitting.

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

property
inverse_transform
¶ Get inverse_transform on the estimator with the best found parameters.
Only available if the underlying estimator implements
inverse_transform
andrefit=True
. Type
function

property
multimetric_
¶ Whether evaluation performed was multimetric.
 Type
bool

property
n_splits_
¶ The number of crossvalidation splits (folds/iterations).
 Type
int

property
predict
¶ Get predict on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict
. Type
function

property
predict_log_proba
¶ Get predict_log_proba on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict_log_proba
. Type
function

property
predict_proba
¶ Get predict_proba on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict_proba
. Type
function

property
refit_time_
¶ Seconds used for refitting the best model on the whole dataset.
This is present only if
refit
is not False. Type
float

score
(X, y=None)¶ Compute the score(s) of an estimator on a given test set.
 Parameters
X (
arraylike
(shape = [n_samples, n_features])) – Input data, where n_samples is the number of samples and n_features is the number of features.y (
arraylike
) – Shape of array is expected to be [n_samples] or [n_samples, n_output]). Target relative to X for classification or regression. You can also pass in None for unsupervised learning.
 Returns
computed score
 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 supportsscore_samples
.New in version 0.24.
 Parameters
X (iterable) – Data to predict on. Must fulfill input requirements of the underlying estimator.
 Returns
y_score
 Return type
ndarray of shape (n_samples,)

property
scorer_
¶ Scorer function used on the held out data to choose the best parameters for the model.
For multimetric evaluation, this attribute holds the validated
scoring
dict which maps the scorer key to the scorer callable. Type
function or a dict

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

property
transform
¶ Get transform on the estimator with the best found parameters.
Only available if the underlying estimator supports
transform
andrefit=True
. Type
function
TuneSearchCV¶

class
ray.tune.sklearn.
TuneSearchCV
(estimator, param_distributions, early_stopping=None, n_trials=10, scoring=None, n_jobs=None, refit=True, cv=None, verbose=0, random_state=None, error_score=nan, return_train_score=False, local_dir='~/ray_results', name=None, max_iters=1, search_optimization='random', use_gpu=False, loggers=None, pipeline_auto_early_stop=True, stopper=None, time_budget_s=None, sk_n_jobs=None, mode=None, **search_kwargs)[source]¶ Generic, nongrid search on hyper parameters.
Randomized search is invoked with
search_optimization
set to"random"
and behaves like scikitlearn’sRandomizedSearchCV
.Bayesian search can be invoked with several values of
search_optimization
."bayesian"
, using https://scikitoptimize.github.io/stable/"bohb"
, using HpBandSter  https://github.com/automl/HpBandSter
TreeParzen Estimators search is invoked with
search_optimization
set to"hyperopt"
, using HyperOpt  http://hyperopt.github.io/hyperoptAll types of search aside from Randomized search require parent libraries to be installed.
TuneSearchCV implements a “fit” and a “score” method. It also implements “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 crossvalidated 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_trials.
 Parameters
estimator (estimator) – This is assumed to implement the scikitlearn estimator interface. Either estimator needs to provide a
score
function, orscoring
must be passed.param_distributions (dict or list or ConfigurationSpace) –
Serves as the
param_distributions
parameter in scikitlearn’sRandomizedSearchCV
or as thesearch_space
parameter inBayesSearchCV
. For randomized search: dictionary with parameters names (string) as keys and distributions or lists of parameter settings to try for randomized search. Distributions must provide a rvs method for sampling (such as those from scipy.stats.distributions). Ray Tune search spaces are also supported. 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. For other types of search: dictionary with parameter names (string) as keys. Values can bea (lower_bound, upper_bound) tuple (for Real or Integer params)
a (lower_bound, upper_bound, “prior”) tuple (for Real params)
as a list of categories (for Categorical dimensions)
Ray Tune search space (eg.
tune.uniform
)
"bayesian"
(scikitoptimize) also acceptsskopt.space.Dimension instance (Real, Integer or Categorical).
"hyperopt"
(HyperOpt) also acceptsan instance of a hyperopt.pyll.base.Apply object.
"bohb"
(HpBandSter) also acceptsConfigSpace.hyperparameters.Hyperparameter instance.
"optuna"
(Optuna) also acceptsan instance of a optuna.distributions.BaseDistribution object.
For
"bohb"
(HpBandSter) it is also possible to pass a ConfigSpace.ConfigurationSpace object instead of dict or a list.https://scikitoptimize.github.io/stable/modules/ classes.html#moduleskopt.space.space
early_stopping (bool, str or
TrialScheduler
, optional) –Option to stop fitting to a hyperparameter configuration if it performs poorly. Possible inputs are:
If True, defaults to ASHAScheduler.
A string corresponding to the name of a Tune Trial Scheduler (i.e., “ASHAScheduler”). To specify parameters of the scheduler, pass in a scheduler object instead of a string.
Scheduler for executing fit with early stopping. Only a subset of schedulers are currently supported. The scheduler will only be used if the estimator supports partial fitting
If None or False, early stopping will not be used.
Unless a
HyperBandForBOHB
object is passed, this parameter is ignored for"bohb"
, as it requiresHyperBandForBOHB
.n_trials (int) – Number of parameter settings that are sampled. n_trials trades off runtime vs quality of the solution. Defaults to 10.
scoring (str, callable, list/tuple, dict, or None) – A single string or a callable to evaluate the predictions on the test set. See https://scikitlearn.org/stable/modules/model_evaluation.html #scoringparameter for all options. For evaluating multiple metrics, either give a list/tuple of (unique) strings or a dict with names as keys and callables as values. If None, the estimator’s score method is used. Defaults to None.
n_jobs (int) – Number of jobs to run in parallel. None or 1 means using all processors. Defaults to None. If set to 1, jobs will be run using Ray’s ‘local mode’. This can lead to significant speedups if the model takes < 10 seconds to fit due to removing interprocess communication overheads.
refit (bool, str, or callable) – Refit an estimator using the best found parameters on the whole dataset. For multiple metric evaluation, this needs to be a string denoting the scorer that would be used to find the best parameters for refitting the estimator at the end. The refitted estimator is made available at the
best_estimator_
attribute and permits usingpredict
directly on thisGridSearchCV
instance. Also for multiple metric evaluation, the attributesbest_index_
,best_score_
andbest_params_
will only be available ifrefit
is set and all of them will be determined w.r.t this specific scorer. If refit not needed, set to False. Seescoring
parameter to know more about multiple metric evaluation. Defaults to True.cv (int, crossvalidation generator or iterable) –
Determines the crossvalidation splitting strategy. Possible inputs for cv are:
None, to use the default 5fold cross validation,
integer, to specify the number of folds in a (Stratified)KFold,
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. Defaults to None.verbose (int) – Controls the verbosity: 0 = silent, 1 = only status updates, 2 = status and trial results. Defaults to 0.
random_state (int or RandomState) – Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions. If int, random_state is the seed used by the random number generator; If RandomState instance, a seed is sampled from random_state; If None, the random number generator is the RandomState instance used by np.random and no seed is provided. Defaults to None. Ignored when using BOHB.
error_score ('raise' or int or float) – 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. Defaults to np.nan.
return_train_score (bool) – If
False
, thecv_results_
attribute will not include training scores. Defaults to False. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting tradeoff. 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.local_dir (str) – A string that defines where checkpoints and logs will be stored. Defaults to “~/ray_results”
name (str) – Name of experiment (for Ray Tune) –
max_iters (int) – Indicates the maximum number of epochs to run for each hyperparameter configuration sampled (specified by
n_trials
). This parameter is used for early stopping. Defaults to 1. Depending on the classifier type provided, a resource parameter (resource_param = max_iter or n_estimators) will be detected. The value of resource_param will be treated as a “max resource value”, and all classifiers will be initialized with max resource value // max_iters, where max_iters is this defined parameter. On each epoch, resource_param (max_iter or n_estimators) is incremented by max resource value // max_iters.("random" or "bayesian" or "bohb" or "hyperopt" (search_optimization) –
or “optuna” or ray.tune.suggest.Searcher instance): Randomized search is invoked with
search_optimization
set to"random"
and behaves like scikitlearn’sRandomizedSearchCV
.Bayesian search can be invoked with several values of
search_optimization
."bayesian"
via https://scikitoptimize.github.io/stable/"bohb"
via http://github.com/automl/HpBandSter
TreeParzen Estimators search is invoked with
search_optimization
set to"hyperopt"
via HyperOpt: http://hyperopt.github.io/hyperoptAll types of search aside from Randomized search require parent libraries to be installed.
Alternatively, instead of a string, a Ray Tune Searcher instance can be used, which will be passed to
tune.run()
.use_gpu (bool) – Indicates whether to use gpu for fitting. Defaults to False. If True, training will start processes with the proper CUDA VISIBLE DEVICE settings set. If a Ray cluster has been initialized, all available GPUs will be used.
loggers (list) – A list of the names of the Tune loggers as strings to be used to log results. Possible values are “tensorboard”, “csv”, “mlflow”, and “json”
pipeline_auto_early_stop (bool) – Only relevant if estimator is Pipeline object and early_stopping is enabled/True. If True, early stopping will be performed on the last stage of the pipeline (which must support early stopping). If False, early stopping will be determined by ‘Pipeline.warm_start’ or ‘Pipeline.partial_fit’ capabilities, which are by default not supported by standard SKlearn. Defaults to True.
stopper (ray.tune.stopper.Stopper) – Stopper objects passed to
tune.run()
.time_budget_s (intfloatdatetime.timedelta) – Global time budget in seconds after which all trials are stopped. Can also be a
datetime.timedelta
object. The stopping condition is checked after receiving a result, i.e. after each training iteration.mode (str) – One of {min, max}. Determines whether objective is minimizing or maximizing the metric attribute. Defaults to “max”.
**search_kwargs (Any) – Additional arguments to pass to the SearchAlgorithms (tune.suggest) objects.

property
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
refit
parameter for more information on allowed values. Type
estimator

property
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 multimetric evaluation, this is present only if
refit
is specified. Type
int

property
best_params_
¶ Parameter setting that gave the best results on the hold out data.
For multimetric evaluation, this is present only if
refit
is specified. Type
dict

property
best_score_
¶ Mean crossvalidated score of the best_estimator
For multimetric evaluation, this is present only if
refit
is specified. Type
float

property
classes_
¶ Get the list of unique classes found in the target y.
 Type
list

property
decision_function
¶ Get decision_function on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportsdecision_function
. Type
function

fit
(X, y=None, groups=None, tune_params=None, **fit_params)¶ Run fit with all sets of parameters.
tune.run
is used to perform the fit procedure. Parameters
X (
arraylike
(shape = [n_samples, n_features])) – Training vector, where n_samples is the number of samples and n_features is the number of features.y (
arraylike
) – Shape of array expected to be [n_samples] or [n_samples, n_output]). Target relative to X for classification or regression; None for unsupervised learning.groups (
arraylike
(shape (n_samples,)), optional) – 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).tune_params (
dict
, optional) – Parameters passed totune.run
used for parameter search.**fit_params (
dict
of str) – Parameters passed to thefit
method of the estimator.
 Returns
TuneBaseSearchCV
child instance, after fitting.

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

property
inverse_transform
¶ Get inverse_transform on the estimator with the best found parameters.
Only available if the underlying estimator implements
inverse_transform
andrefit=True
. Type
function

property
multimetric_
¶ Whether evaluation performed was multimetric.
 Type
bool

property
n_splits_
¶ The number of crossvalidation splits (folds/iterations).
 Type
int

property
predict
¶ Get predict on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict
. Type
function

property
predict_log_proba
¶ Get predict_log_proba on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict_log_proba
. Type
function

property
predict_proba
¶ Get predict_proba on the estimator with the best found parameters.
Only available if
refit=True
and the underlying estimator supportspredict_proba
. Type
function

property
refit_time_
¶ Seconds used for refitting the best model on the whole dataset.
This is present only if
refit
is not False. Type
float

score
(X, y=None)¶ Compute the score(s) of an estimator on a given test set.
 Parameters
X (
arraylike
(shape = [n_samples, n_features])) – Input data, where n_samples is the number of samples and n_features is the number of features.y (
arraylike
) – Shape of array is expected to be [n_samples] or [n_samples, n_output]). Target relative to X for classification or regression. You can also pass in None for unsupervised learning.
 Returns
computed score
 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 supportsscore_samples
.New in version 0.24.
 Parameters
X (iterable) – Data to predict on. Must fulfill input requirements of the underlying estimator.
 Returns
y_score
 Return type
ndarray of shape (n_samples,)

property
scorer_
¶ Scorer function used on the held out data to choose the best parameters for the model.
For multimetric evaluation, this attribute holds the validated
scoring
dict which maps the scorer key to the scorer callable. Type
function or a dict

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

property
transform
¶ Get transform on the estimator with the best found parameters.
Only available if the underlying estimator supports
transform
andrefit=True
. Type
function