Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python hyperparameter optimization libraries search for the training settings, such as learning rate and tree depth, that give a model its best validation score. A searcher proposes each new trial from the results of earlier trials rather than testing every combination. These libraries let machine learning teams tune models in fewer training runs.
Popularity
scikit-learn has the most monthly downloads in this comparison, at 214.9M, a count that covers all its machine learning work.
def __init__(self, prot_attr=None, *, scoring, step=0.05, refit=True, **kwargs):
"""
Args:
prot_attr (single label or list-like, optional): Protected
attribute(s) to use in the post-processing. If more than one
attribute, all combinations of values (intersections) are
considered. Default is ``None`` meaning all protected attributes
from the dataset are used. Note: This algorithm requires there
be exactly 2 groups (privileged and unprivileged).
scoring ('statistical_parity', 'average_odds', 'equal_opportunity',
'disparate_impact', or callable/dict): Fairness scorer to use to
evaluate the predictions. If type is a `str`, constructs the
corresponding scorer for that metric in addition to the default
balanced accuracy. If type is callable (i.e., a scorer object),
that will be used along with balanced accuracy. Finally, if an
explicit dictionary is passed, this will be used as is.
step (float): Step size for grid search. Will search every valid
combination of threshold and margin that are multiples of this
step size. See `param_grid` after fitting for the exact search
space.
refit (bool or callable, optional): Refit the estimator using the
best parameters found. If `True` and not using a custom scoring
function, this chooses the highest balanced accuracy given
fairness score > -0.1 (or > 0.8 for disparate impact only).
Alternatively, a custom refitting function may be passed. See
:class:`~sklearn.model_selection.GridSearchCV` for details.
**kwargs: See :class:`~sklearn.model_selection.GridSearchCV` for
additional kwargs.
"""
self.scoring = scoring
self.refit = refit
self.step = step
self.prot_attr = prot_attr
super().__init__(RejectOptionClassifier(), {}, scoring=scoring,
refit=refit, **kwargs)
Ray Tune
Runs experiments and hyperparameter-tuning trials with configurable searchers and schedulers.
Downloads / mo
15.7M
Stars
44.3K
Last release
2.60.0
License
Apache-2.0
Strengths
Schedules trials across machines.Run a hyperparameter sweep over a multi-node Ray cluster.
Stops underperforming trials early.Choose a trial scheduler that uses the reported training metric.
Limitations
Searchers restrict search-space expressions.Check the selected searcher’s support for lambdas and grid search.
Large search-space values add overhead.Pass large objects through with_parameters instead of the search space.
def _tune(config):
"""Train the YOLO model with the specified hyperparameters and return results."""
model_to_train = ray.get(model_in_store) # get the model from ray store for tuning
model_to_train.trainer = None
model_to_train.reset_callbacks()
config = _sanitize_tune_value(dict(config))
config.update(train_args)
# Set trial-specific name for W&B logging try:
trial_id = tune.get_context().get_trial_id()
trial_suffix = trial_id.split("_")[-1] if "_" in trial_id else trial_id
config["name"] = f"{base_name}_{trial_suffix}"
except Exception:
# Not in Ray Tune context or error getting trial ID, use base name config["name"] = base_name
results = model_to_train.train(**config)
if isinstance(config.get("data"), (list, tuple)):
metric = TASK2METRIC[task]
return {
metric: sum((metrics or {}).get(metric, 0.0) for metrics in results.values()) / len(results),
"epoch": config.get("epochs") or DEFAULT_CFG_DICT["epochs"],
}
return results.results_dict
Optuna
Automates hyperparameter search with Python-defined spaces, samplers, and pruning.
Downloads / mo
14.5M
Stars
15.1K
Last release
5.1.0
License
MIT
Strengths
Defines spaces with Python branches.Suggest parameters inside conditionals and loops.
Prunes unpromising training trials.Report intermediate values and check should_prune during iterative training.
Limitations
Pruning targets single-objective studies.Use another stopping policy when optimizing multiple objectives.
@click.command(
help="Perform hyperparameter search with Hyperopt library. Optimize dl_train target."
)
@click.option("--max-runs", type=click.INT, default=10, help="Maximum number of runs to evaluate.")
@click.option("--epochs", type=click.INT, default=500, help="Number of epochs")
@click.option("--metric", type=click.STRING, default="rmse", help="Metric to optimize on.")
@click.option("--algo", type=click.STRING, default="tpe.suggest", help="Optimizer algorithm.")
@click.option("--seed", type=click.INT, default=97531, help="Seed for the random generator")
@click.argument("training_data")
def train(training_data, max_runs, epochs, metric, algo, seed):
"""
Run hyperparameter optimization.
"""
# create random file to store run ids of the training tasks tracking_client = MlflowClient()
def new_eval(
nepochs, experiment_id, null_train_loss, null_valid_loss, null_test_loss, return_all=False
):
"""
Create a new eval function
Args:
nepochs: Number of epochs to train the model.
experiment_id: Experiment id for the training run.
null_train_loss: Loss of a null model on the training dataset.
null_valid_loss: Loss of a null model on the validation dataset.
null_test_loss Loss of a null model on the test dataset.
return_all: If True, return train, validation, and test loss.
Otherwise, return only the validation loss.
Default is False.
Returns:
An evaluation function that trains the model and logs metrics to MLflow.
"""
def eval(params):
"""
Train Keras model with given parameters by invoking MLflow run.
Notice we store runUuid and resulting metric in a file. We will later use these to pick
the best run and to log the runUuids of the child runs as an artifact. This is a
temporary workaround until MLflow offers better mechanism of linking runs together.
Args:
params: Parameters to the train_keras script we optimize over:
learning_rate, drop_out_1
Returns:
The metric value evaluated on the validation data.
"""
import mlflow.tracking
lr, momentum = params
with mlflow.start_run(nested=True) as child_run:
p = mlflow.projects.run(
uri=".",
entry_point="train",
run_id=child_run.info.run_id,
parameters={
"training_data": training_data,
"epochs": str(nepochs),
"learning_rate": str(lr),
"momentum": str(momentum),
"seed": seed,
},
experiment_id=experiment_id,
synchronous=False, # Allow the run to fail if a model is not properly created
)
succeeded = p.wait()
mlflow.log_params({"lr": lr, "momentum": momentum})
if succeeded:
training_run = tracking_client.get_run(p.run_id)
metrics = training_run.data.metrics
# cap the loss at the loss of the null model train_loss = min(null_train_loss, metrics[f"train_{metric}"])
valid_loss = min(null_valid_loss, metrics[f"val_{metric}"])
test_loss = min(null_test_loss, metrics[f"test_{metric}"])
else:
# run failed => return null loss tracking_client.set_terminated(p.run_id, "FAILED")
train_loss = null_train_loss
valid_loss = null_valid_loss
test_loss = null_test_loss
mlflow.log_metrics({
f"train_{metric}": train_loss,
f"val_{metric}": valid_loss,
f"test_{metric}": test_loss,
})
if return_all:
return train_loss, valid_loss, test_loss
else:
return valid_loss
return eval
space = [
hp.uniform("lr", 1e-5, 1e-1),
hp.uniform("momentum", 0.0, 1.0),
]
with mlflow.start_run() as run:
experiment_id = run.info.experiment_id
# Evaluate null model first. train_null_loss, valid_null_loss, test_null_loss = new_eval(
0, experiment_id, _inf, _inf, _inf, True
)(params=[0, 0])
best = fmin(
fn=new_eval(epochs, experiment_id, train_null_loss, valid_null_loss, test_null_loss),
space=space,
algo=tpe.suggest if algo == "tpe.suggest" else rand.suggest,
max_evals=max_runs,
)
mlflow.set_tag("best params", str(best))
# find the best run, log its metrics as the final metrics of this run. client = MlflowClient()
runs = client.search_runs(
[experiment_id], f"tags.mlflow.parentRunId = '{run.info.run_id}' "
)
best_val_train = _inf
best_val_valid = _inf
best_val_test = _inf
best_run = None
for r in runs:
if r.data.metrics["val_rmse"] < best_val_valid:
best_run = r
best_val_train = r.data.metrics["train_rmse"]
best_val_valid = r.data.metrics["val_rmse"]
best_val_test = r.data.metrics["test_rmse"]
mlflow.set_tag("best_run", best_run.info.run_id)
mlflow.log_metrics({
f"train_{metric}": best_val_train,
f"val_{metric}": best_val_valid,
f"test_{metric}": best_val_test,
})
def suggest(self, trial_id: str) -> Optional[Dict]:
if not self._nevergrad_opt:
raise RuntimeError(
UNDEFINED_SEARCH_SPACE.format(
cls=self.__class__.__name__, space="space"
)
)
if not self._metric or not self._mode:
raise RuntimeError(
UNDEFINED_METRIC_MODE.format(
cls=self.__class__.__name__, metric=self._metric, mode=self._mode
)
)
suggested_config = self._nevergrad_opt.ask()
self._live_trial_mapping[trial_id] = suggested_config
# in v0.2.0+, output of ask() is a Candidate, # with fields args and kwargs if not suggested_config.kwargs:
if self._parameters:
return unflatten_dict(
dict(zip(self._parameters, suggested_config.args[0]))
)
return unflatten_dict(suggested_config.value)
else:
return unflatten_dict(suggested_config.kwargs)
def run(dataset, config):
log.info(f"\n**** FLAML [v{__version__}] ****\n")
X_train, y_train = dataset.train.X, dataset.train.y.squeeze()
is_classification = config.type == "classification"
time_budget = config.max_runtime_seconds
n_jobs = config.framework_params.get("_n_jobs", config.cores)
log.info("Running FLAML with {} number of cores".format(config.cores))
aml = AutoML()
# Mapping of benchmark metrics to flaml metrics metrics_mapping = dict(
acc="accuracy",
auc="roc_auc",
f1="f1",
logloss="log_loss",
mae="mae",
mse="mse",
rmse="rmse",
r2="r2",
)
perf_metric = (
metrics_mapping[config.metric] if config.metric in metrics_mapping else "auto"
)
if perf_metric is None:
log.warning("Performance metric %s not supported.", config.metric)
training_params = {
k: v for k, v in config.framework_params.items() if not k.startswith("_")
}
log_dir = output_subdir("logs", config)
flaml_log_file_name = os.path.join(log_dir, "flaml.log")
with Timer() as training:
aml.fit(
X_train,
y_train,
metric=perf_metric,
task=config.type,
n_jobs=n_jobs,
log_file_name=flaml_log_file_name,
time_budget=time_budget,
**training_params,
)
log.info(f"Finished fit in {training.duration}s.")
def infer(data: Union[str, pd.DataFrame]):
data = pd.read_parquet(data) if isinstance(data, str) else data
predict_fn = aml.predict_proba if is_classification else aml.predict
return predict_fn(data)
inference_times = {}
if config.measure_inference_time:
inference_times["file"] = measure_inference_times(
infer, dataset.inference_subsample_files
)
inference_times["df"] = measure_inference_times(
infer,
[(1, dataset.test.X.sample(1, random_state=i)) for i in range(100)],
)
log.info("Finished inference time measurements.")
with Timer() as predict:
X_test, y_test = dataset.test.X, dataset.test.y.squeeze()
predictions = aml.predict(X_test)
probabilities = aml.predict_proba(X_test) if is_classification else None
labels = None
if is_classification:
labels = (
aml.classes_ if isinstance(aml.classes_, list) else aml.classes_.tolist()
)
log.info(f"Finished predict in {predict.duration}s.")
return result(
output_file=config.output_predictions_file,
probabilities=probabilities,
predictions=predictions,
truth=y_test,
models_count=len(aml.config_history),
training_duration=training.duration,
predict_duration=predict.duration,
probabilities_labels=labels,
inference_times=inference_times,
)
FAQ
Optuna suits most tuning, with search spaces defined in Python, samplers, and pruning. Ray Tune suits distributed trials across a cluster. scikit-learn search classes suit grid and random search around its own estimators.
GridSearchCV is the scikit-learn class that tries every combination of listed parameter values with cross-validation. RandomizedSearchCV samples combinations instead of trying them all.
Optuna automates hyperparameter search with define-by-run objectives, conditional parameters, samplers, and pruning of weak trials.
Optuna defines the search space inside the objective function and prunes weak trials as they run. Hyperopt declares a stochastic search space up front and optimizes a single loss with TPE or random search.
BayesianOptimization maximizes a function with a Gaussian process over declared parameter bounds. scikit-optimize minimizes a function the same way and adds BayesSearchCV for scikit-learn estimators.
For coding agents
Found your hyperparameter optimization library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.