Skip to content

Development version

This is the latest (dev) documentation. For stable docs, see stable.

Optuna vs sklearn-genetic-opt: When to Use Each ​

Optuna and sklearn-genetic-opt both support hyperparameter search for scikit-learn estimators. Optuna runs trials defined by an objective function. GASearchCV accepts a scikit-learn estimator, search space, scorer and CV splitter. This page compares Optuna's TPE sampler with the default DEAP backend in GASearchCV.

How Each Method Works ​

Optuna with TPE ​

Optuna's default sampler for a single objective is the Tree-structured Parzen Estimator (TPE). After its startup trials, TPE models parameter values associated with better objective scores and compares their density with that of the remaining values. It uses the density ratio to select new suggestions. Optuna also provides other samplers and conditional search spaces. See the TPE sampler reference.

sklearn-genetic-opt with DEAP ​

The default DEAP backend maintains a population of configurations and uses selection, crossover and mutation to propose new ones. GASearchCV scores each candidate with the requested CV splitter and exposes the scores in cv_results_. The library also provides four other optimization backends.

Quick Decision Guide ​

You needStart with
Parameters that depend on earlier choices, such as an SVM kernelOptuna's conditional trial suggestions
A search object with scikit-learn's fit, best_params_ and cv_results_GASearchCV
Scoring feature subsets with CV for a chosen estimatorGAFeatureSelectionCV
Trial pruning based on intermediate training metricsAn Optuna objective that reports intermediate values
The best quality for a fixed resource budgetCompare methods on the same splits and count the work each performs

Performance Benchmark ​

This historical Bayesmark comparison used a budget of 48 candidate evaluations, three seeds and three CV folds. The table reports mean best inner CV scores. Accuracy is higher-is-better. MSE is lower-is-better.

DatasetModelMetricGASearchCVOptunaRandomizedSearchCVBest displayed mean
wineknnaccuracy ↑0.98320.98320.9813tie
winesvmaccuracy ↑0.98690.98510.9850gasearch
winedtaccuracy ↑0.85200.86510.8463optuna
winerfaccuracy ↑0.96450.97190.9532optuna
breastknnaccuracy ↑0.96840.96950.9678optuna
breastsvmaccuracy ↑0.97890.97830.9783gasearch
breastdtaccuracy ↑0.91330.91510.9133optuna
breastrfaccuracy ↑0.92560.92850.9215optuna
diabetesknnMSE ↓3223.403229.593223.47gasearch
diabetessvmMSE ↓3035.663034.173053.55optuna
diabetesdtMSE ↓3994.283837.883852.95optuna
diabetesrfMSE ↓3553.563320.703498.15optuna

At the displayed precision, Optuna has the best mean in eight rows and GASearchCV in three, with one tie. At the larger budget of 96 evaluations, the ordering reversed on Wine with a decision tree and the MSE gap narrowed on Diabetes with a random forest. Optuna retained the higher mean accuracy on both random-forest classification tasks.

The optimizer catalog compares five engines with random search and Optuna TPE using observed CV calls and separate holdout scores.

CASH: Algorithm Selection and Tuning ​

In the combined algorithm selection and hyperparameter tuning experiment, each optimizer completed 184 candidate evaluations per run, using three seeds and three CV folds. The comparison used a conditional Optuna objective and a flat encoding for GASearchCV.

OptimizerMean accuracy ± SDMean evaluationsMean wall time
Optuna0.8636 ± 0.005018459 s
RandomizedSearchCV0.8591 ± 0.005518427 s
GASearchCV0.8582 ± 0.0087184205 s

Code Comparison — Same Problem, Both Tools ​

Install the example dependencies with pip install optuna sklearn-genetic-opt. Run the following blocks in order. Both searches tune a RandomForestClassifier over the same space with one worker, three fixed folds and a budget of 24 candidate CV calls. The train/test split is made before either search. Evaluate the selected models on the test set after both searches finish.

Set up the benchmark ​

python
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split

from sklearn_genetic import GASearchCV
from sklearn_genetic.callbacks import CVBudgetStopping
from sklearn_genetic.space import Categorical, Integer

seed = 42
budget = 24
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=seed
)
splitter = StratifiedKFold(n_splits=3, shuffle=True, random_state=seed)
folds = list(splitter.split(X_train, y_train))
forest = RandomForestClassifier(random_state=seed, n_jobs=1)

Optuna ​

python
from sklearn.base import clone

def objective(trial):
    params = {
        "n_estimators": trial.suggest_int("n_estimators", 20, 80),
        "max_depth": trial.suggest_int("max_depth", 2, 12),
        "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 6),
        "max_features": trial.suggest_categorical("max_features", ["sqrt", "log2"]),
    }
    candidate = clone(forest).set_params(**params)
    return cross_val_score(
        candidate, X_train, y_train, cv=folds, scoring="roc_auc", n_jobs=1,
        error_score="raise",
    ).mean()

optuna.logging.set_verbosity(optuna.logging.WARNING)
study = optuna.create_study(
    direction="maximize", sampler=optuna.samplers.TPESampler(seed=seed)
)
study.optimize(objective, n_trials=budget, n_jobs=1)
optuna_winner = clone(forest).set_params(**study.best_params).fit(X_train, y_train)

print("Optuna search CV calls", len(study.trials))
print("Optuna best CV ROC AUC", study.best_value)
print("Optuna holdout ROC AUC", roc_auc_score(y_test, optuna_winner.predict_proba(X_test)[:, 1]))

sklearn-genetic-opt ​

python
search = GASearchCV(
    forest,
    param_grid={
        "n_estimators": Integer(20, 80),
        "max_depth": Integer(2, 12),
        "min_samples_leaf": Integer(1, 6),
        "max_features": Categorical(["sqrt", "log2"]),
    },
    cv=folds,
    scoring="roc_auc",
    population_size=6,
    generations=8,
    n_jobs=1,
    use_cache=False,
    error_score="raise",
    random_state=seed,
    verbose=False,
)
search.fit(X_train, y_train, callbacks=CVBudgetStopping(budget))

print("GASearchCV search CV calls", search.fit_counts_["search_cv_calls"])
print("GASearchCV best CV ROC AUC", search.best_score_)
print("GASearchCV holdout ROC AUC", roc_auc_score(y_test, search.predict_proba(X_test)[:, 1]))

One CV call fits three folds here. Both methods also fit the selected model on the full training set. Compare the printed search CV counts before comparing scores, especially if you change the budget or enable caching. The holdout scores describe one test partition.

When Optuna Is the Better Choice ​

  • Use conditional trials when parameters depend on model choices.
  • Use a pruner with a training loop that can report intermediate metrics.
  • Use parallel trials with shared storage when multiple processes or machines contribute to a study.

When sklearn-genetic-opt Is the Better Choice ​

Using Both Together ​

To try a two-stage search, pass parameter dictionaries from completed Optuna trials into PopulationConfig(warm_start_configs=...). Reuse the example above and keep the starting values within the same search space.

python
from sklearn_genetic import PopulationConfig

trials = sorted(
    study.get_trials(states=(optuna.trial.TrialState.COMPLETE,)),
    key=lambda trial: trial.value,
    reverse=True,
)
warm_search = clone(search).set_params(
    population_config=PopulationConfig(warm_start_configs=[trial.params for trial in trials[:3]])
)
warm_search.fit(X_train, y_train, callbacks=CVBudgetStopping(budget))
print("Additional search CV calls", warm_search.fit_counts_["search_cv_calls"])

Include both stages' CV calls in the total if you compare this workflow with a single search. See warm-start the search for examples and how the initializer handles duplicates.

See Also ​

Released under the MIT License.