# Python hyperparameter optimization libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [scikit-learn](#scikit-learn) | 214.9M | 68.2K | Sep 2026 | BSD-3-Clause |
| [Ray Tune](#ray-tune) | 15.7M | 44.3K | Nov 2026 | Apache-2.0 |
| [Optuna](#optuna) | 14.5M | 15.1K | Nov 2026 | MIT |
| [Hyperopt](#hyperopt) | 1.7M | 7.6K | Jul 2026 | BSD-3-Clause |
| [BayesianOptimization](#bayesian-optimization) | 843.0K | 8.7K | Oct 2026 | MIT |
| [scikit-optimize](#scikit-optimize) | 609.1K | 25 | Jun 2024 | BSD-3-Clause |
| [Nevergrad](#nevergrad) | 518.5K | 4.2K | Apr 2025 | MIT |
| [FLAML](#flaml) | 361.1K | 4.4K | Nov 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[scikit-learn](#scikit-learn) has the most monthly downloads in this comparison, at 214.9M, a count that covers all its machine learning work.

## Capabilities

| Library | Multiple optimization objectives | Resource-adaptive trial scheduling |
| --- | --- | --- |
| [scikit-learn](#scikit-learn) | No | Yes |
| [Ray Tune](#ray-tune) | Via plugin | Yes |
| [Optuna](#optuna) | Yes | Yes |
| [Hyperopt](#hyperopt) | No | Undocumented |
| [BayesianOptimization](#bayesian-optimization) | No | No |
| [scikit-optimize](#scikit-optimize) | No | No |
| [Nevergrad](#nevergrad) | Yes | Undocumented |
| [FLAML](#flaml) | Yes | Yes |

## Libraries

### scikit-learn

[GitHub](https://github.com/scikit-learn/scikit-learn) · [PyPI](https://pypi.org/project/scikit-learn) · [Docs](https://scikit-learn.org/stable/modules/grid_search.html)

Provides Python modules for machine learning and data mining.

- Downloads / mo: 214.9M
- Stars: 68.2K
- Last release: 1.9.1
- License: BSD-3-Clause
- Capabilities: [From the scikit-learn docs](https://scikit-learn.org/stable/modules/grid_search.html)

```sh
pip install scikit-learn
```

**Trusted-AI/AIF360** (2.9K stars)

[Trusted-AI/AIF360](https://github.com/Trusted-AI/AIF360) 

```python
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)

```

[aif360/sklearn/postprocessing/reject_option_classification.py](https://github.com/Trusted-AI/AIF360/blob/34877916b789e569edf5c0aac033403ca90f34b3/aif360/sklearn/postprocessing/reject_option_classification.py#L251-L285) · [More projects using scikit-learn →](https://dashboard.exa.ai/playground/search?q=scikit-learn%20GitHub%20projects)

**Quickstart**

```python
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC

X, y = load_iris(return_X_y=True)
search = GridSearchCV(SVC(), {"C": [0.1, 1.0, 10.0]}, cv=3).fit(X, y)
print(search.best_params_)

```

From [sklearn.model_selection.GridSearchCV.html](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html)

### Ray Tune

[GitHub](https://github.com/ray-project/ray) · [PyPI](https://pypi.org/project/ray) · [Docs](https://docs.ray.io/en/latest/tune/index.html)

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
- Capabilities: [From the Ray Tune docs](https://docs.ray.io/en/latest/tune/index.html)

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

**Watch out for**

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

```sh
pip install "ray[tune]"
```

**ultralytics/ultralytics** (63.5K stars)

[ultralytics/ultralytics](https://github.com/ultralytics/ultralytics) 

```python
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

```

[ultralytics/utils/tuner.py](https://github.com/ultralytics/ultralytics/blob/95d2e2a72ff002e81228ea1074d59fb69baa175d/ultralytics/utils/tuner.py#L432-L456) · [More projects using Ray Tune →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20ray%20for%20hyperparameter%20searches%20and%20trial%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from ray import tune

def objective(config):
    return {"loss": (config["x"] - 2) ** 2}

tuner = tune.Tuner(objective, param_space={"x": tune.grid_search([0, 1, 2])})
results = tuner.fit()
print(results.get_best_result(metric="loss", mode="min").config)

```

From [index.html](https://docs.ray.io/en/latest/tune/index.html)

### Optuna

[GitHub](https://github.com/optuna/optuna) · [PyPI](https://pypi.org/project/optuna) · [Docs](https://optuna.readthedocs.io/en/stable/)

Automates hyperparameter search with Python-defined spaces, samplers, and pruning.

- Downloads / mo: 14.5M
- Stars: 15.1K
- Last release: 5.1.0
- License: MIT
- Capabilities: [From the Optuna docs](https://optuna.readthedocs.io/en/stable/)

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

**Watch out for**

- **Pruning targets single-objective studies.** Use another stopping policy when optimizing multiple objectives.

```sh
pip install optuna
```

**optuna/optuna-examples** (870 stars)

[optuna/optuna-examples](https://github.com/optuna/optuna-examples) 

```python
def objective(trial):
    iris = sklearn.datasets.load_iris()
    x, y = iris.data, iris.target

    classifier_name = trial.suggest_categorical("classifier", ["SVC", "RandomForest"])
    if classifier_name == "SVC":
        svc_c = trial.suggest_float("svc_c", 1e-10, 1e10, log=True)
        classifier_obj = sklearn.svm.SVC(C=svc_c, gamma="auto")
    else:
        rf_max_depth = trial.suggest_int("rf_max_depth", 2, 32, log=True)
        classifier_obj = sklearn.ensemble.RandomForestClassifier(
            max_depth=rf_max_depth, n_estimators=10
        )

    score = sklearn.model_selection.cross_val_score(classifier_obj, x, y, n_jobs=-1, cv=3)
    accuracy = score.mean()
    return accuracy
```

[sklearn/sklearn_simple.py](https://github.com/optuna/optuna-examples/blob/9450de9b8b042e396bb816fdbe7fb4b5227b3323/sklearn/sklearn_simple.py) · [More projects using Optuna →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20optuna%20for%20hyperparameter%20searches%20and%20trial%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import optuna

def objective(trial):
    return (trial.suggest_float("x", -10, 10) - 2) ** 2

study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=10)
print(study.best_params)

```

From [stable.md](https://optuna.readthedocs.io/en/stable/)

### Hyperopt

[GitHub](https://github.com/hyperopt/hyperopt) · [PyPI](https://pypi.org/project/hyperopt) · [Docs](https://hyperopt.github.io/hyperopt/)

Optimizes objective functions over stochastic search spaces, including conditional parameters.

- Downloads / mo: 1.7M
- Stars: 7.6K
- Last release: 0.3.0
- License: BSD-3-Clause
- Capabilities: [From the Hyperopt docs](https://hyperopt.github.io/hyperopt/)

**Strengths**

- **Encodes conditional parameter choices.** Use nested choices to expose parameters only in the relevant branch.
- **Retains trial diagnostics.** Return a dictionary with loss, status, and additional trial information.

**Watch out for**

- **Spark trials fit single-machine models.** Use another execution approach for models that need distributed training.

```sh
pip install hyperopt
```

**mlflow/mlflow** (28.8K stars)

[mlflow/mlflow](https://github.com/mlflow/mlflow) 

```python
@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,
        })

```

[examples/hyperparam/search_hyperopt.py](https://github.com/mlflow/mlflow/blob/db0a3f686c4823d96b373e9fb0846dadd2ab46ff/examples/hyperparam/search_hyperopt.py#L24-L161) · [More projects using Hyperopt →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20hyperopt%20for%20hyperparameter%20searches%20and%20trial%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from hyperopt import fmin, hp, tpe

best = fmin(lambda x: x ** 2, hp.uniform("x", -1, 1), algo=tpe.suggest, max_evals=10)
print(best)

```

From [minimizing_functions.md](https://hyperopt.github.io/hyperopt/getting-started/minimizing_functions/)

### BayesianOptimization

[GitHub](https://github.com/bayesian-optimization/BayesianOptimization) · [PyPI](https://pypi.org/project/bayesian-optimization) · [Docs](https://bayesian-optimization.github.io/BayesianOptimization/master/basic-tour.html)

Runs Bayesian optimization.

- Downloads / mo: 843.0K
- Stars: 8.7K
- Last release: 3.4.0
- License: MIT
- Capabilities: [From the BayesianOptimization docs](https://bayesian-optimization.github.io/BayesianOptimization/master/basic-tour.html)

```sh
pip install bayesian-optimization
```

**optimagic-dev/optimagic** (324 stars)

[optimagic-dev/optimagic](https://github.com/optimagic-dev/optimagic) 

```python
def _solve_internal_problem(
    self, problem: InternalOptimizationProblem, x0: NDArray[np.float64]
) -> InternalOptimizeResult:
    if not IS_BAYESOPT_INSTALLED_AND_VERSION_NEWER_THAN_2:
        raise NotInstalledError(
            "To use the 'bayes_opt' optimizer you need to install bayes_opt. "
            "Use 'pip install bayesian-optimization'. "
            "Check the documentation for more details: "
            "https://bayesian-optimization.github.io/BayesianOptimization/index.html"
        )

    from bayes_opt import BayesianOptimization

    pbounds = _process_bounds(problem.bounds)

    acq = _process_acquisition_function(
        acquisition_function=self.acquisition_function,
        kappa=self.kappa,
        xi=self.xi,
        exploration_decay=self.exploration_decay,
        exploration_decay_delay=self.exploration_decay_delay,
        random_seed=self.seed,
    )

    constraint = None
    constraint = self._process_constraints(problem.nonlinear_constraints)

    def objective(**kwargs: dict[str, float]) -> float:
        x = _extract_params_from_kwargs(kwargs)
        return -float(
            problem.fun(x)
        )  # Negate to convert minimization to maximization

    bounds_transformer = None
    if self.enable_sdr:
        from bayes_opt import SequentialDomainReductionTransformer

        bounds_transformer = SequentialDomainReductionTransformer(
            gamma_osc=self.sdr_gamma_osc,
            gamma_pan=self.sdr_gamma_pan,
            eta=self.sdr_eta,
            minimum_window=self.sdr_minimum_window,
        )

    optimizer = BayesianOptimization(
        f=objective,
        pbounds=pbounds,
        acquisition_function=acq,
        constraint=constraint,
        random_state=self.seed,
        verbose=self.verbose,
        bounds_transformer=bounds_transformer,
        allow_duplicate_points=self.allow_duplicate_points,
    )

    # Set Gaussian Process parameters
    optimizer.set_gp_params(alpha=self.alpha, n_restarts_optimizer=self.n_restarts)

    # Use initial point as first probe
    probe_params = {f"param{i}": float(val) for i, val in enumerate(x0)}
    optimizer.probe(
        params=probe_params,
        lazy=True,
    )
    optimizer.maximize(
        init_points=self.init_points,
        n_iter=self.stopping_maxiter,
    )

    res = _process_bayes_opt_result(optimizer=optimizer, x0=x0, problem=problem)
    return res
```

[src/optimagic/optimizers/bayesian_optimizer.py](https://github.com/optimagic-dev/optimagic/blob/103029363cfce45bc54129e8aca70e5e3147c66a/src/optimagic/optimizers/bayesian_optimizer.py#L211-L281) · [More projects using BayesianOptimization →](https://dashboard.exa.ai/playground/search?q=bayesian-optimization%20GitHub%20projects)

**Quickstart**

```python
from bayes_opt import BayesianOptimization

optimizer = BayesianOptimization(f=lambda x: -(x - 2) ** 2, pbounds={"x": (-5, 5)}, random_state=1)
optimizer.maximize(init_points=2, n_iter=3)
print(optimizer.max)

```

From [basic-tour.html](https://bayesian-optimization.github.io/BayesianOptimization/master/basic-tour.html)

### scikit-optimize

[GitHub](https://github.com/holgern/scikit-optimize) · [PyPI](https://pypi.org/project/scikit-optimize) · [Docs](https://scikit-optimize.readthedocs.io/en/latest/)

Provides sequential model-based optimization for expensive or noisy black-box functions.

- Downloads / mo: 609.1K
- Stars: 25
- Last release: 0.10.2
- License: BSD-3-Clause
- Capabilities: [From the scikit-optimize docs](https://scikit-optimize.readthedocs.io/en/latest/)

**Strengths**

- **Fits scikit-learn search workflows.** Use BayesSearchCV with an estimator’s existing fit and score methods.
- **Exposes a manual optimization loop.** Use Optimizer ask and tell to control objective evaluation.

**Watch out for**

- **Gradient methods need another optimizer.** Use SciPy when gradients should drive the optimization.
- **Parallel search copies training data.** Limit pre_dispatch when parallel parameter settings exceed available memory.

```sh
pip install scikit-optimize
```

**SpikeInterface/spikeinterface** (873 stars)

[SpikeInterface/spikeinterface](https://github.com/SpikeInterface/spikeinterface) 

```python
def _train_and_evaluate(
    self, imputation_strategy, scaler, classifier, X_train, X_test, y_train, y_test, model_id, search_kwargs
):
    from sklearn.metrics import balanced_accuracy_score, precision_score, recall_score

    search_kwargs = set_default_search_kwargs(search_kwargs)

    X_train_scaled, X_test_scaled, y_train, y_test, imputer, scaler = self.apply_scaling_imputation(
        imputation_strategy, scaler, X_train, X_test, y_train, y_test
    )
    if self.verbose is True:
        print(f"Running {classifier.__class__.__name__} with imputation {imputation_strategy} and scaling {scaler}")
    model, param_space = self.get_classifier_search_space(classifier.__class__.__name__)

    try:
        from skopt import BayesSearchCV

        model = BayesSearchCV(
            model,
            param_space,
            random_state=self.seed,
            **search_kwargs,
        )
    except Exception:
        if self.verbose is True:
            print("BayesSearchCV from scikit-optimize not available, using RandomizedSearchCV")
        from sklearn.model_selection import RandomizedSearchCV

        model = RandomizedSearchCV(model, param_space, **search_kwargs)

    model.fit(X_train_scaled, y_train)
    y_pred = model.predict(X_test_scaled)
    balanced_acc = balanced_accuracy_score(y_test, y_pred)
    precision = precision_score(y_test, y_pred, average="macro")
    recall = recall_score(y_test, y_pred, average="macro")
    return {
        "classifier name": classifier.__class__.__name__,
        "imputation_strategy": imputation_strategy,
        "scaling_strategy": scaler,
        "balanced_accuracy": balanced_acc,
        "precision": precision,
        "recall": recall,
        "model_id": model_id,
        "best_params": model.best_params_,
    }, (model, imputer, scaler)

```

[src/spikeinterface/curation/train_manual_curation.py](https://github.com/SpikeInterface/spikeinterface/blob/1d7bacaa2a934ed4547f906e637887f3f609f9b1/src/spikeinterface/curation/train_manual_curation.py#L606-L650) · [More projects using scikit-optimize →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20scikit-optimize%20for%20hyperparameter%20searches%20and%20trial%20evaluation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from skopt import gp_minimize

result = gp_minimize(lambda x: x[0] ** 2, [(-1.0, 1.0)], n_calls=10, random_state=0)
print(result.x, result.fun)

```

From [README.rst](https://scikit-optimize.readthedocs.io/en/latest/modules/generated/skopt.gp_minimize.html)

### Nevergrad

[GitHub](https://github.com/facebookresearch/nevergrad) · [PyPI](https://pypi.org/project/nevergrad) · [Docs](https://facebookresearch.github.io/nevergrad/optimization.html)

Performs gradient-free optimization.

- Downloads / mo: 518.5K
- Stars: 4.2K
- Last release: 1.0.12
- License: MIT
- Capabilities: [From the Nevergrad docs](https://facebookresearch.github.io/nevergrad/optimization.html)

```sh
pip install nevergrad
```

**ray-project/ray** (44.3K stars)

[ray-project/ray](https://github.com/ray-project/ray) 

```python
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)

```

[python/ray/tune/search/nevergrad/nevergrad_search.py](https://github.com/ray-project/ray/blob/3cba3775f01657bee9f95e46f1925b88d5806621/python/ray/tune/search/nevergrad/nevergrad_search.py#L264-L290) · [More projects using Nevergrad →](https://dashboard.exa.ai/playground/search?q=nevergrad%20GitHub%20projects)

**Quickstart**

```python
import nevergrad as ng

optimizer = ng.optimizers.NGOpt(parametrization=ng.p.Scalar(lower=-5, upper=5), budget=10)
recommendation = optimizer.minimize(lambda x: (x - 2) ** 2)
print(recommendation.value)

```

From [optimization.html](https://facebookresearch.github.io/nevergrad/optimization.html)

### FLAML

[GitHub](https://github.com/microsoft/FLAML) · [PyPI](https://pypi.org/project/flaml) · [Docs](https://microsoft.github.io/FLAML/docs/Use-Cases/Tune-User-Defined-Function/)

Automates machine learning and tuning.

- Downloads / mo: 361.1K
- Stars: 4.4K
- Last release: 2.8.0
- License: MIT
- Capabilities: [From the FLAML docs](https://microsoft.github.io/FLAML/docs/Use-Cases/Tune-User-Defined-Function/)

```sh
pip install flaml
```

**openml/automlbenchmark** (472 stars)

[openml/automlbenchmark](https://github.com/openml/automlbenchmark) 

```python
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,
    )

```

[frameworks/flaml/exec.py](https://github.com/openml/automlbenchmark/blob/dfe8d21871e2dec2b7cab6c9fbfe3575ce4dadc6/frameworks/flaml/exec.py#L19-L103) · [More projects using FLAML →](https://dashboard.exa.ai/playground/search?q=flaml%20GitHub%20projects)

**Quickstart**

```python
from flaml import tune

analysis = tune.run(
    lambda config: {"loss": config["x"] ** 2},
    config={"x": tune.uniform(-1, 1)}, metric="loss", mode="min",
    num_samples=10, use_ray=False,
)
print(analysis.best_config)

```

From [README.md](https://microsoft.github.io/FLAML/docs/Use-Cases/Tune-User-Defined-Function/)

## FAQ

### Which Python hyperparameter optimization library should I use?

[Optuna](#optuna) suits most tuning, with search spaces defined in Python, samplers, and pruning. [Ray Tune](#ray-tune) suits distributed trials across a cluster. [scikit-learn](#scikit-learn) search classes suit grid and random search around its own estimators.

### What is GridSearchCV?

GridSearchCV is the [scikit-learn](#scikit-learn) class that tries every combination of listed parameter values with cross-validation. RandomizedSearchCV samples combinations instead of trying them all.

### What is Optuna?

[Optuna](#optuna) automates hyperparameter search with define-by-run objectives, conditional parameters, samplers, and pruning of weak trials.

### Optuna vs Hyperopt: which should I use?

[Optuna](#optuna) defines the search space inside the objective function and prunes weak trials as they run. [Hyperopt](#hyperopt) declares a stochastic search space up front and optimizes a single loss with TPE or random search.

### How do I do Bayesian optimization in Python?

[BayesianOptimization](#bayesian-optimization) maximizes a function with a Gaussian process over declared parameter bounds. [scikit-optimize](#scikit-optimize) minimizes a function the same way and adds BayesSearchCV for scikit-learn estimators.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python hyperparameter optimization libraries Optuna Hyperopt Ray Tune Scikit-Optimize code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
