Skip to content
项目

关于

用于 scikit-learn 的超参数调优和特征选择。GridSearchCV 和 RandomizedSearchCV 的现代替代方案。

人工智能与机器学习

这些数字如何统计

实测星标增长

24小时
0
7天
0
15天
+1
1个月
+7

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

sklearn-genetic-opt

sklearn-genetic-opt

Latest release on PyPI Continuous integration on master MIT license

Hyperparameter tuning and feature selection for scikit-learn. Give GASearchCV or GAFeatureSelectionCV a model, a scorer and a budget. The search evaluates candidates with cross-validation, refits the winner and lets you call predict on new data. Use it when the combinations of parameters or columns would make an exhaustive search too expensive.

Stable documentation · Backend tutorial · Benchmarks · Plot gallery

Run your first search

Install the published package on Python 3.12 or newer:

python -m pip install sklearn-genetic-opt

How deep should a decision tree grow? Search integer depths and two split criteria on the training set. Compare the winning cross-validation score with balanced accuracy on data the search never saw.

from sklearn.datasets import load_breast_cancer
from sklearn.metrics import balanced_accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn_genetic import GASearchCV
from sklearn_genetic.space import Categorical, Integer

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, stratify=y, test_size=0.25, random_state=7
)
tree = DecisionTreeClassifier(random_state=7)
settings = dict(cv=3, scoring="balanced_accuracy", population_size=8,
                generations=3, random_state=7, n_jobs=1, verbose=False)

search = GASearchCV(
    tree,
    param_grid={"max_depth": Integer(2, 12), "criterion": Categorical(["gini", "entropy"])},
    **settings,
).fit(X_train, y_train)

print(search.best_params_, search.best_score_)
print(balanced_accuracy_score(y_test, search.predict(X_test)))

Which columns does the tree need?

Reuse the model, folds and budget with GAFeatureSelectionCV. Set an upper limit of eight columns. The fitted selector applies its mask during prediction.

from sklearn_genetic import GAFeatureSelectionCV

selector = GAFeatureSelectionCV(tree, max_features=8, **settings).fit(X_train, y_train)
print(selector.get_support(indices=True))
print(balanced_accuracy_score(y_test, selector.predict(X_test)))

Choose an optimizer

DEAP is included by default. Four additional engines are available as extras. Install the extra for the engine you want. For example, to use pymoo:

python -m pip install "sklearn-genetic-opt[pymoo]>=0.16.0"

Change one parameter on either estimator to run the same experiment with a different engine. Cloning keeps the earlier result available for comparison.

from sklearn.base import clone

alternative = clone(selector).set_params(optimizer_backend="pymoo")
alternative.fit(X_train, y_train)
print(alternative.get_support(indices=True), alternative.fit_stats_["cross_validate_calls"])
Backend What it brings to the search
deap Included by default. Choose genetic operators, adaptive schedules and local search.
scipy Differential evolution for bounded spaces. It can stop early when the population converges.
nevergrad OnePlusOne adjusts its mutations as candidates succeed or fail. TwoPointsDE is also available.
cmaes CatCMA with Margin learns how numeric variables vary together and adapts category probabilities.
pymoo Uses type-specific operators for mixed parameters and a binary genetic algorithm for feature masks.

Each optional engine has a pip extra with the same name. All five support live plotting, early stopping and resuming from a completed generation. The engine reference lists supported domains, controls and checkpoint requirements. To integrate another optimizer, see the plugin protocol.

How do they compare? The benchmarks compare the bundled optimizers at matched counts of fresh CV calls, using separate held-out scores. No single engine wins on every workload; choose the search space, metric and budget before comparing engines on your own data.

Inspect a fitted search

Use cv_results_ for individual candidates and history for progress by generation. This example from the digits walkthrough shows how a neural network search progressed and which candidates finished near the top.

Digits search dashboard with fitness by generation, population diversity, optimizer events and top candidate scores

What changed in 0.18.0

  • Tune transformers and clusterers inside scikit-learn pipelines. A searched target encoder keeps its native cross-fitting on training rows.
  • Use preserve_dataframe="align_named_columns" to select features with named column preprocessors, including inside nested searches.
  • Explore positive integer parameters with distribution="log-uniform". DEAP can use optional retries to explore more distinct candidates at a fixed evaluation budget. See the release notes for the measured results.

Go further

Cite sklearn-genetic-opt

If you use the library in research, cite the version used in your experiment. For version 0.18.0, cite Rodrigo Arenas (2026), sklearn-genetic-opt (version 0.18.0) [Computer software]. The software citation contains the machine-readable metadata. For BibTeX, use:

@software{arenas2026sklearn_genetic_opt,
  author  = {Arenas, Rodrigo},
  title   = {{sklearn-genetic-opt}},
  year    = {2026},
  version = {0.18.0},
  url     = {https://pypi.org/project/sklearn-genetic-opt/0.18.0/}
}

探索相关项目

加载中…