🐝 abcopt
Canonical Artificial Bee Colony (ABC) optimization for Python, with a scikit-learn compatible hyperparameter search.
abcopt implements the Artificial Bee Colony algorithm of Derviş Karaboğa (2005) step for step as in the reference implementation published by the ABC research group at Erciyes University, and wraps it in ABCSearchCV, a drop-in alternative to GridSearchCV and RandomizedSearchCV.
A real CanonicalABCSolver run on the 2-D Rastrigin function (many local minima, one global minimum ★).
Employed bees move one dimension at a time, onlookers revisit the best sources, and a scout restarts an exhausted source at a random spot.
Numbers are failed-trial counters. Generated by docs/make_animation.py.
Highlights
- Verified canonical ABC. A test runs abcopt and the Erciyes University reference code on the same random-number stream and checks that both evaluate identical points and return identical results.
- scikit-learn native.
ABCSearchCVprovidesfit,predict,predict_proba,score,best_params_,best_estimator_and acv_results_table in the same format asGridSearchCV. - Monitor, stop, or drive it yourself. Callbacks with built-in early stopping, and an
ask()/tell()interface for evaluating candidates outside the solver (a cluster job, a simulator, a lab measurement). - Mixed search spaces. Continuous (optionally log-scaled), integer and categorical hyperparameters.
- No wasted runs. Configurations that ABC proposes twice are served from a cache, which roughly halves tuning time on discrete spaces without changing the search.
- Reproducible and predictable. Fixed evaluation budget (
max_evals) andrandom_statefor identical runs. - Lightweight. Depends only on
numpyandscikit-learn.
Contents: Installation · Quick start · How ABC works · Benchmark · API reference · Notes and limitations · Examples · Citation
Installation
pip install abcopt
Requires Python 3.9+, NumPy and scikit-learn.
Quick start
Tune a scikit-learn model
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import HistGradientBoostingClassifier
from abcopt import ABCSearchCV
X, y = load_breast_cancer(return_X_y=True)
param_space = {
"learning_rate": {"type": "float", "range": (0.01, 0.3), "log": True},
"max_iter": {"type": "int", "range": (50, 300)},
"max_leaf_nodes": {"type": "int", "range": (8, 64)},
"l2_regularization": {"type": "float", "range": (1e-6, 1.0), "log": True},
}
search = ABCSearchCV(
HistGradientBoostingClassifier(random_state=0),
param_space,
cv=5,
scoring="accuracy",
max_evals=60, # candidates evaluated by ABC
random_state=0,
)
search.fit(X, y)
print(search.best_score_, search.best_params_)
search.predict(X[:5]) # best_estimator_, refit on all data
Any scikit-learn compatible estimator works, including XGBoost and LightGBM.
Minimize a function
import numpy as np
from abcopt import CanonicalABCSolver
def rastrigin(x):
return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
solver = CanonicalABCSolver(rastrigin, n_params=5, lb=[-5.12] * 5, ub=[5.12] * 5,
max_evals=20_000, random_state=0)
best_x, best_f, history = solver.solve()
Evaluate candidates yourself (ask/tell)
When the objective cannot be a Python call (a job on a cluster, a simulation, an experiment), let the solver propose points and report their costs back:
solver = CanonicalABCSolver(None, n_params=5, lb=[-5.12] * 5, ub=[5.12] * 5,
max_evals=2_000, random_state=0)
while not solver.done:
x = solver.ask() # next candidate (np.ndarray)
solver.tell(x, run_my_job(x)) # its cost, to minimize
print(solver.best_params, solver.best_cost)
For the same seed this visits exactly the same points as solve(). ABC is sequential, so one candidate is pending at a time; if its evaluation fails, call ask() again to get the same point.
Inspect the search
import pandas as pd
import matplotlib.pyplot as plt
results = pd.DataFrame(search.cv_results_) # one row per unique configuration
results.sort_values("rank_test_score").head()
evals, best = zip(*search.history_) # best CV score after each ABC cycle
plt.plot(evals, best); plt.xlabel("candidates evaluated"); plt.ylabel("best CV score")
Monitor and stop early
A callback is called after every ABC cycle with the current state; returning True stops the run. EarlyStopping stops once the best result has not improved for patience cycles.
from abcopt import ABCSearchCV, EarlyStopping
def log(state):
print(f"cycle {state.cycle}: {state.n_evals}/{state.max_evals} evals, best {state.best_score:.4f}")
search = ABCSearchCV(HistGradientBoostingClassifier(random_state=0), param_space,
cv=5, max_evals=500, random_state=0,
callbacks=[log, EarlyStopping(patience=5)])
search.fit(X, y)
search.stopped_early_, search.n_evals_ # (True, 300): no improvement in cycles 3-7
One cycle uses about 2 × pop_size evaluations, so patience=5 with the default pop_size=20 waits roughly 200 evaluations. A longer patience trades time for a chance of a late improvement.
Without a stop request, callbacks do not change the search: they never draw random numbers, so the trajectory is the same as without them.
How ABC works
ABC models the foraging behaviour of a honey bee colony. Each food source is a candidate solution and its nectar amount is the solution's fitness. Three kinds of bees share the work:
| Phase | What happens | Why |
|---|---|---|
| Employed bees | Each source changes one random dimension relative to a random other source, v_ij = x_ij + φ·(x_ij − x_kj), φ ∈ [−1, 1], and keeps the better of old and new. |
Local search around every source |
| Onlooker bees | Sources are visited in turn; source i gets an extra try with probability p_i = 0.9 · fit_i / max(fit) + 0.1, until pop_size tries have been made. |
More effort on promising regions |
| Scout bee | Once per cycle, the source with the most failed tries is replaced by a random one if its counter has reached limit. |
Escapes local minima |
Fitness is derived from cost as 1 / (1 + f) for f ≥ 0 and 1 + |f| otherwise. The best solution found so far is always kept.
Benchmark
abcopt was compared with Random Search and Optuna TPE under identical evaluation budgets (notebook).
Black-box functions (D = 10, mean over 10 seeds, lower is better):
| Function | ABC @ 1k | TPE @ 1k | ABC @ 10k | TPE @ 2k | Random @ 10k |
|---|---|---|---|---|---|
| Sphere | 1.5 | 0.27 | 4e-11 | 0.22 | 12.3 |
| Rosenbrock | 1.3e3 | 88.5 | 0.51 | 114 | 1.1e4 |
| Rastrigin | 29.9 | 59.7 | 0.09 | 47.3 | 71.2 |
| Ackley | 12.8 | 5.58 | 0.0003 | 5.8 | 16.7 |
- With a short budget TPE is usually ahead; ABC beats Random Search everywhere and wins on the highly multimodal Rastrigin.
- With a larger budget ABC converges close to the global optimum on all four functions, while TPE stalls.
- ABC's own overhead is negligible: about 0.02 s versus 24 s for TPE over 2,000 evaluations.
- For hyperparameter tuning with about 50 candidates, the three methods end within noise of each other on test accuracy.
When to use which: TPE for very small budgets of expensive evaluations (for example deep-learning tuning); ABC when evaluations are cheap enough to afford thousands, when the landscape is rugged, or when you want a dependency-light scikit-learn drop-in.
API reference
CanonicalABCSolver
CanonicalABCSolver(objective_func, n_params, lb, ub,
pop_size=20, max_evals=1000, limit=None, random_state=None,
callbacks=None)
objective_func may be None when the solver is driven only through ask() / tell().
| Parameter | Description |
|---|---|
objective_func |
Callable taking a 1-D np.ndarray and returning a scalar cost to minimize. NaN is treated as the worst cost. |
n_params |
Number of dimensions |
lb, ub |
Lower and upper bound of each dimension |
pop_size |
Number of food sources (SN), equal to the number of employed and of onlooker bees. The colony size in the reference code is 2 × pop_size. |
max_evals |
Budget of objective evaluations |
limit |
A source is abandoned once its failed-trial counter reaches limit. Default: pop_size × n_params. |
random_state |
Seed or np.random.Generator |
callbacks |
Callable or list of callables, called after every cycle with a CycleState; returning True stops the run |
solve() returns (best_params, best_cost, history), where history lists (evaluations_used, best_cost_so_far) after initialization and after every cycle. After solve(), n_cycles holds the number of completed cycles and stopped_early tells whether a callback ended the run before the budget was used.
Ask/tell
| Member | Description |
|---|---|
ask() |
Returns the next candidate (a copy). The first call starts a run; until tell() the same candidate is returned again. Raises RuntimeError once the run is done. |
tell(x, cost) |
Reports the cost of the pending candidate x. NaN counts as the worst cost. Raises ValueError if x is not the pending candidate. |
done |
True once the run has used its budget or a callback has stopped it. |
n_evals |
Evaluations reported so far. |
reset() |
Discards the current run; the next ask() starts a new one. solve() always starts a new run. |
best_params, best_cost, history, n_cycles and callbacks behave exactly as with solve().
Callbacks
CycleState fields: cycle (starting at 1), n_evals, max_evals, best_cost, best_params (a copy of the array for CanonicalABCSolver, the decoded dict for ABCSearchCV) and best_score (ABCSearchCV only, equal to -best_cost).
EarlyStopping(patience=10, min_delta=0.0) stops when the best cost has not decreased by more than min_delta for patience cycles. It works for both classes and can be reused across runs.
ABCSearchCV
ABCSearchCV(estimator, param_space, cv=3, scoring="accuracy", pop_size=20, max_evals=200,
limit=None, random_state=None, n_jobs=None, error_score=np.nan,
refit=True, cache=True, callbacks=None, verbose=False)
Search space (param_space), one entry per hyperparameter:
| Kind | Specification |
|---|---|
| Continuous | {"type": "float", "range": (0.01, 0.3)} |
| Continuous, log scale | {"type": "float", "range": (1e-4, 1e-1), "log": True} |
| Integer (both ends inclusive) | {"type": "int", "range": (2, 12)} |
| Categorical | {"type": "categorical", "choices": ["gini", "entropy"]} |
Parameters
| Parameter | Description |
|---|---|
cv, scoring, n_jobs, refit |
As in GridSearchCV. Higher scores are better; use neg_* scorers for errors. |
pop_size, max_evals, limit, random_state |
Passed to CanonicalABCSolver. max_evals counts every candidate ABC proposes. |
error_score |
Score for candidates that fail to fit (a RuntimeWarning is issued); "raise" stops the search. |
cache |
Reuse the score of a configuration ABC has already evaluated instead of cross-validating it again. Saves time; the search is unchanged. |
callbacks |
As in CanonicalABCSolver, with the state given as decoded params and best_score. After a stop, the best configuration so far is refit as usual. |
fit(X, y=None, groups=None, **fit_params): groups is passed to group-aware splitters and fit_params (for example sample_weight) to the estimator.
Attributes after fit
| Attribute | Content |
|---|---|
best_params_, best_score_, best_index_ |
Best configuration, its mean CV score and its row in cv_results_ |
best_estimator_, refit_time_ |
Best configuration refit on all data (refit=True) |
cv_results_ |
One row per unique configuration, in GridSearchCV format |
results_ |
Every candidate in proposal order with params, score and cached |
history_ |
(evaluations_used, best_score_so_far) after each cycle |
n_evals_, n_unique_evals_, n_splits_ |
Candidates evaluated, distinct configurations (cross-validation runs), CV folds |
n_cycles_, stopped_early_ |
Completed ABC cycles; whether a callback stopped the search before max_evals |
Methods: predict, predict_proba, predict_log_proba, decision_function, transform, score and classes_, whenever the underlying estimator supports them.
Notes and limitations
- Budget semantics. As in the reference implementation, the budget is a number of objective evaluations, not of cycles. With
ABCSearchCV, cached repeats still count towardsmax_evals. - Integer and categorical parameters are searched as continuous values and rounded. Categorical choices become equal-width intervals of one dimension, so neighbouring choices are treated as "close"; this works well for a handful of choices.
- Sequential by design. Bees are evaluated one after another, exactly as in the reference algorithm; parallelism comes from
n_jobsinside each cross-validation. The same holds forask()/tell(): one candidate is pending at a time. - Minimization.
CanonicalABCSolverminimizes; to maximize, return the negative value.
Examples
| Example | Content |
|---|---|
| Benchmark | ABC vs Random Search vs Optuna TPE on test functions and two tuning tasks |
| Federated learning on MedMNIST | ABC tunes FedAvg's learning rate and momentum on non-IID PathMNIST (5 clients, Dirichlet α = 0.5); test accuracy rises from 78.05% to 85.28%. Run with abcopt 0.1. |
| Animation | Records every phase of a solver run and renders the GIF above |
Development
git clone https://github.com/yusufkorkmazyigit/abc-optimizer-lib.git
cd abc-optimizer-lib
pip install -e ".[test]"
pytest
The test suite includes the reference-equivalence test (tests/test_reference_equivalence.py) and runs on Python 3.9 to 3.13 for every push. Release notes are in CHANGELOG.md. Issues and pull requests are welcome.
Citation
If abcopt helps your work, please cite the original algorithm and this software:
@techreport{karaboga2005abc,
author = {Karaboğa, Derviş},
title = {An Idea Based on Honey Bee Swarm for Numerical Optimization},
institution = {Erciyes University, Engineering Faculty, Computer Engineering Department},
number = {TR06},
year = {2005}
}
@software{korkmazyigit_abcopt,
author = {Korkmazyiğit, Yusuf},
title = {abcopt: Canonical Artificial Bee Colony optimization for Python},
url = {https://github.com/yusufkorkmazyigit/abc-optimizer-lib},
version = {0.3.0},
year = {2026}
}
License
MIT. See LICENSE. The reference port used in the tests is MIT licensed by its authors.
Developed by Yusuf Korkmazyiğit, Computer Engineering, Erciyes University.
Metadata
Release files for abcopt 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| abcopt-0.3.0.tar.gz | 32.5 kB | With provenance | Details for abcopt-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| abcopt-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for abcopt-0.3.0-py3-none-any.whl |
Total release size: 53.4 kB
Release files / abcopt-0.3.0.tar.gz
| Download URL | abcopt-0.3.0.tar.gz |
|---|---|
| Size | 32.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3b44296d253f825b9a50d4410d74c8aaee43bafa12ac0c131e680374dc02643c
|
|
BLAKE2b-256 checksum How to use checksums |
c39209d4b6b48159c51dd967e8b9cc5e06bce4ce606c9a09b79230ca43e2cf55
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.
Transparency logRelease files / abcopt-0.3.0-py3-none-any.whl
| Download URL | abcopt-0.3.0-py3-none-any.whl |
|---|---|
| Size | 20.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9d899cdd4835f73c6f0c07299f0bcc22c4025556d7fbde7cf4277a82c1c74eef
|
|
BLAKE2b-256 checksum How to use checksums |
a69d0d760a496ceab45acaad84f830e771d6576677b4d03d7792da17e9c15cab
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.
Transparency logSecurity for abcopt 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for abcopt-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.