rodrigo-arenas/Sklearn-genetic-opt

Hyperparameter tuning and feature selection for scikit-learn. A modern alternative to GridSearchCV and RandomizedSearchCV.

What it is

sklearn-genetic-opt is a Python library that helps you automatically find good hyperparameters (settings) for machine-learning models, and also helps you pick which features (columns of data) matter most. Instead of trying every combination like GridSearchCV or sampling randomly like RandomizedSearchCV, it uses a genetic algorithm — a search method inspired by natural selection. It evaluates full parameter configurations, keeps the promising ones, and recombines them to produce better candidates over successive "generations."

It is designed to feel familiar to anyone who already uses scikit-learn: the main class GASearchCV supports fit, predict, and best_params_, and works with standard scikit-learn estimators and scoring functions.

What it offers

  • GASearchCV — hyperparameter search using a genetic algorithm, as an alternative to GridSearchCV / RandomizedSearchCV.
  • GAFeatureSelectionCV — a wrapper-based feature selector that evaluates different subsets of features using cross-validation, so you don't need a separate feature-selection library.
  • Mixed search spaces — you can combine integer parameters (e.g., number of trees), continuous parameters (uniform or log-uniform), and categorical parameters (e.g., "balanced" vs None) in the same search.
  • Smart initialization — the first generation is seeded with Latin hypercube sampling, estimator defaults, warm-start configurations from previous runs, and duplicate avoidance.
  • Early stopping callbacks — ConsecutiveStopping, DeltaThreshold, and TimerStopping automatically end the search when it converges or runs out of time.
  • Adaptive schedules — crossover and mutation rates gradually anneal (cool down) over generations, shifting the search from broad exploration to focused exploitation.
  • History & plots — per-generation fitness, diversity, and telemetry are stored in a history object; built-in plots visualize the search (fitness curve, parameter scatter plots, search overview dashboard).
  • MLflow integration — optionally log every evaluated candidate as a child run for experiment comparison.
  • Parallel execution — n_jobs=-1 parallelizes candidate or fold evaluation.
  • Starter presets — ready-made search spaces like random_forest_classifier_space(profile="balanced") and xgboost_classifier_space(profile="balanced").
  • Space conversion — from_sklearn_space() converts a RandomizedSearchCV-style parameter grid (using scipy.stats distributions) into the genetic-opt format.

When to use it

Use it when:

  • You can afford several generations of cross-validated evaluations (it's slower than a quick baseline).
  • Your search space mixes parameter types or you suspect parameters interact with each other.
  • You want feature selection and hyperparameter tuning in one reproducible workflow.
  • You want built-in optimization history, convergence plots, callbacks, or MLflow tracking.
  • You have known-good configurations to warm-start from (prior runs, published defaults).
  • You want an adaptive search to compare against a fixed-budget random-search baseline.

When NOT to use it

The README is explicit about these cases:

  • You need a fast baseline — start with a fixed configuration or RandomizedSearchCV(n_iter=20); it's faster and good enough to validate your pipeline.
  • Your grid is tiny (fewer than 50 combinations) — GridSearchCV covers it exhaustively and is simpler to reason about.
  • Your fits are very cheap — the population-management overhead may cost more than it saves.
  • You need conditional or distributed optimization — consider Optuna's define-by-run search and distributed storage.

How it compares to alternatives

Tool Best for Key limitation Where sklearn-genetic-opt helps
GridSearchCV Small, fully discrete grids; guaranteed complete coverage Combinatorial explosion on 4+ params; no continuous params natively Large, mixed, or continuous spaces with interacting parameters
RandomizedSearchCV Larger budgets; simple independent parameter spaces No learning from past evaluations; treats each parameter independently Recombines promising configurations; adaptive schedules; early stopping
Optuna Sequential Bayesian (TPE) search; distributed optimization; neural architecture search Usually needs an objective function or an integration wrapper for sklearn CV Familiar sklearn search API; built-in GAFeatureSelectionCV
RFE Greedy feature elimination for models with coef_ or feature_importances_ Greedy and sequential; can miss non-greedy optimal subsets Searches candidate subsets; works with sklearn-compatible estimators
SelectFromModel Fast embedded selection via a threshold on feature importance Tied to model-specific importances; no cross-estimator comparison Estimator-agnostic wrapper; combinable with hyperparameter tuning in one workflow

Quick start (from the README)

Install:

pip install sklearn-genetic-opt
# With optional plotting and MLflow extras:
# pip install sklearn-genetic-opt[all]

Hyperparameter search example:

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn_genetic import GASearchCV, EvolutionConfig, RuntimeConfig
from sklearn_genetic.space import Categorical, Continuous, Integer

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.2, stratify=y, random_state=42)

search = GASearchCV(
    estimator=RandomForestClassifier(random_state=42),
    param_grid={
        "n_estimators": Integer(50, 300),
        "max_depth":    Integer(3, 20),
        "max_features": Continuous(0.1, 1.0),
        "class_weight": Categorical([None, "balanced"]),
    },
    cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=42),
    scoring="roc_auc",
    evolution_config=EvolutionConfig(population_size=15, generations=12),
    runtime_config=RuntimeConfig(n_jobs=-1, verbose=True),
    random_state=42,
)
search.fit(X_train, y_train)

print(search.best_params_)           # best hyperparameter configuration
print(search.best_score_)            # best cross-validated ROC-AUC
print(search.score(X_test, y_test))  # test-set score

Feature selection example:

from sklearn_genetic import GAFeatureSelectionCV, EvolutionConfig, RuntimeConfig

selector = GAFeatureSelectionCV(
    estimator=RandomForestClassifier(n_estimators=100, random_state=42),
    cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=42),
    scoring="accuracy",
    evolution_config=EvolutionConfig(population_size=20, generations=15),
    runtime_config=RuntimeConfig(n_jobs=-1, verbose=True),
    random_state=42,
)
selector.fit(X_train, y_train)

print(selector.support_)             # boolean mask of selected features
print(selector.score(X_test, y_test)) # accuracy on selected features

Common use cases covered in the docs

  • Hyperparameter tuning for: RandomForest, XGBoost, LightGBM, CatBoost, Gradient Boosting (sklearn), Logistic Regression, SVM, scikit-learn Pipelines (with ColumnTransformer), and imbalanced datasets (using class_weight as a search param).
  • Feature selection — a 3-stage workflow: select features, retune, validate; plus a two-stage recipe combining feature selection + hyperparameter tuning.
  • Experiment tracking & tooling — MLflow logging, callbacks/early stopping, checkpointing and resume, and a full plotting gallery.

Requirements & installation

  • Python ≥ 3.12 and scikit-learn ≥ 1.5.0.
  • Install via pip (sklearn-genetic-opt or sklearn-genetic-opt[all] for plotting + MLflow extras) or conda (conda install -c conda-forge sklearn-genetic-opt).

Benchmarks

The repository includes benchmark scripts comparing GASearchCV against RandomizedSearchCV, GridSearchCV, and Optuna (TPE), using the Bayesmark experimental design — same datasets, same search spaces, equal evaluation budget. Run with:

pip install sklearn-genetic-opt[benchmark]
python benchmarks/benchmark_bayesmark.py --quick

Citation

The README recommends citing the software version used. The suggested citation is:

Arenas, R. (2026). sklearn-genetic-opt: Hyperparameter tuning and feature selection using genetic algorithms, built on top of scikit-learn (Version 0.15.0) [Computer software]. https://github.com/rodrigo-arenas/Sklearn-genetic-opt

Contributing

Contributions of all sizes are welcome — from fixing a typo to adding a tutorial or benchmark. Suggested starting points: add a Recipe, write/improve a tutorial, test with a new estimator, add a benchmark, fix typing/CI/formatting, answer questions in issues, or share community articles. The repo has "good first issue" labels.

Learning paths (from the README)

  • New user: Install → Getting Started with GASearchCV → How Hyperparameter Optimization Works → Pick a Recipe.
  • ML practitioner: When to Use Genetic Algorithm Search → Choosing the Right Search Space → Model-specific Tutorials → Optuna vs sklearn-genetic-opt.
  • Contributor: Contributing guide → Open issues → Benchmarks documentation.

Key links


Note: This explainer is grounded strictly in the README content. No features or facts beyond what the README states have been added.

Related

  • Project
  • Project
  • Project
  • Project
  • Project