Skip to main content

CI Documentation Status Licence

Logo

SKSurrogate

Lightweight, maintained, scikit-learn-native surrogate tuner — a drop-in replacement for ``BayesSearchCV``.

SKSurrogate searches expensive objectives (hyperparameters, AutoML pipelines) with a surrogate response surface built on scikit-learn. The tuner is a BaseSearchCV subclass, so it plugs into existing scikit-learn code with the same fit/predict contract as GridSearchCV, RandomizedSearchCV, or BayesSearchCV — no new estimator API, no framework lock-in.

Why not Optuna / vanilla BO?

  • Inequality constraints (ineq): constrain the search region directly, rather than through penalty tricks or rejection sampling.

  • Trust-region contraction dynamics (contraction=0.9): TuRBO/DYCORS-style radius contraction that keeps the search focused as it converges, scaling to medium- and high-dimensional spaces.

  • scikit-learn-native: the tuner is a BaseSearchCV — it composes with pipelines, cross-validation, and the rest of the scikit-learn ecosystem.

  • Drift-aware (see below): it records the identity of the data it optimized, so you can detect drift before inference.

The hybrid loop

Two cooperating search layers are the centerpiece of the package:

  • Evolutionary pipeline selector (EOA): explores the space of transformers and estimators to assemble candidate pipelines.

  • Local surrogate tuner (SurrogateRandomCV): fits a response surface to the best candidates and focuses evaluations where the surrogate predicts improvement.

This hybrid — global structure search plus local surrogate refinement — is what makes SKSurrogate a pipeline designer rather than just a hyperparameter tuner.

Since v0.2 the default response surface is a stock, un-tuned RBF Gaussian process (chosen over the previous cubic Hilbert polynomial on the evidence of the equal-budget benchmark suite); a custom regressor based on Hilbert Space techniques is still available (HilbertRegressor), and all scikit-learn regressors are accepted for optimization.

Understand what you tuned

Once a run has finished, SKSurrogate explains what the fitted model depends on — not just where the search stopped:

  • Model explanations: permutation importance, partial dependence, and accumulated local effects for a stored model bundle show which features drive its predictions globally, while an exact row-level explanation reconstructs one prediction from its baseline as ordered feature contributions. Every response carries the explained quantity, the model’s provenance, a checked reconstruction status, an out-of-distribution flag for rows, and grouped/stability-checked importance for correlated features. Available through the control plane (explain, ale and explain/row endpoints) and in the web UI; see the control-plane guide and the scientific workflow guide.

  • Paired model comparison: refits stored bundles on one shared fold list and reports oriented deltas with percentile bootstrap intervals, Holm-adjusted Wilcoxon p-values, Cliff’s ordinal effect size, a score/complexity/cost Pareto front and calibration — with the exploratory-selection caveat stated in the payload. See the model-comparison guide.

  • Sensitivity analysis: Sobol, Morris, and moment-independent δ indices quantify which inputs dominate output variance — useful for pruning expensive models or diagnosing a tuned pipeline. See the sensitivity analysis guide.

  • Data diagnostics before a run: the Data page profiles a registered partition — distributions, target composition, target/feature associations, collinearity, identifier and leakage flags, Little’s MCAR, Anderson–Darling normality, bootstrap effect sizes, half-sample stability, partition-to-partition drift — and exports the same tables as a Markdown report. The Experiments page repeats the actionable findings as advisory pre-flight checks, so a score is never read without its data caveats. See the monitoring guide.

All of these are descriptive analyses: the model-attribution views show how the learned response depends on its inputs, and the data diagnostics describe the partition — none of them is a causal claim.

Observe what a run did

Search progress goes through the standard library logging module (SKSurrogate loggers, with WARNING/ERROR for degraded surrogate fits, stagnation and failures), and the core exposes per-trial telemetry: a per-refit fit_score, init/explore/surrogate_exploit sampling tags, a callbacks hook that delivers one event per evaluated candidate, and a JSON-safe to_audit_dict() export. The control plane captures those records per background job into a Logs page with severity, dataset/task and research-project filters — see the telemetry contract, the log endpoints and the UI manual.

Serve what you built

A finished run leaves a portable ModelBundle behind: a schema-checked input contract, a prediction/model_version/request_id output frame, and atomic CSV writes — scoreable in batch through SKSurrogate.predict_batch or the sksurrogate-batch-predict CLI, or online through the dependency-free SKSurrogate.serve WSGI adapter. In the control plane you declare which model a task serves: a serving pin naming either an exact model version (frozen, later promotions leave it alone) or a registry alias (follows promote/rollback), after which clients score through POST /api/serving/{task}/predict without naming a model at all (409 while nothing is served). The web UI states the same declaration: a Serving <version> · <task> pill in the top bar while a model is served, and a Serving card on the Inference page that sets, replaces and stops it. See the inference guide and the control-plane guide.

Trained bundles can also be combined into one model with scikit-learn’s own meta-estimators — voting, averaging, stacking, bagging and boosting over a selection of models — from the library (SKSurrogate.ensembling), the /api/ensembles routes or the web UI’s Ensembles page. The result is an ordinary bundle, so the same evaluation, registry and serving paths apply to it; its reported scores carry the caveat that member selection was made on the same data.

A combination can then be refined: every member’s probabilities can be calibrated (Platt/isotonic, with the Brier score and log loss recorded before and after on identical folds), the member weights can be fitted on out-of-fold member output (a convex simplex least-squares, a random search over the task’s metric, or Caruana greedy selection), and the whole procedure can be re-priced by an honest nested estimate that refits the members, the calibration and the weight search inside every outer fold. See the combining-models guide.

Quick start

SurrogateRandomCV is a drop-in for RandomizedSearchCV; ranges can be written as plain tuples (integers or floats) and lists (categorical values):

from sklearn.svm import SVC
from SKSurrogate import SurrogateRandomCV

search = SurrogateRandomCV(
    SVC(),
    param_distributions={"C": (1e-3, 10.0), "kernel": ["poly", "rbf"], "degree": (1, 4)},
    n_iter=30,
).fit(X, y)
search.best_params_, search.best_score_

For automatic pipeline design, AML(preset="classification").fit(X, y) (or preset="regression") needs no search configuration. For pandas DataFrames, the preset automatically fits numeric, categorical, datetime, and text preprocessing inside each cross-validation fold when cat_cols is omitted. Array-like inputs should already be numeric; cat_cols retains the explicit categorical-encoding path. fit(X, y, strategy="eoa") selects evolutionary search.

More workflows are covered in the surrogate-search guide, preprocessing guide, scientific workflow guide, experiment design guide, research projects guide, and monitoring guide. For the API and UI, see the control-plane guide UI manual and worked example with screenshots.

Run the web UI and API with Docker

A prebuilt image of the current release is published on Docker Hub as mghasemi/sksurrogate (overview):

docker run --rm -p 8013:8013 -v sksurrogate-data:/data mghasemi/sksurrogate:latest   # UI and API on http://localhost:8013

Datasets, experiments, logs and model bundles live in the named volume mounted at /data; the image ships no user data. On first use docker run pulls the image automatically; to upgrade an existing deployment to a new release, re-pull first — run will not refresh a cached copy (or pin a version tag such as 0.8.0):

docker pull mghasemi/sksurrogate:latest

From a source checkout (Docker with Compose required):

docker compose --profile prod up --build -d   # UI and API on http://localhost:8013
docker compose --profile dev up --build       # hot reload; UI on http://localhost:5174

Set SKSURROGATE_PORT to change the port and SKSURROGATE_API_KEY to require an API key; for any published port also set SKSURROGATE_REQUIRE_AUTH=1 so the container refuses to start without a key. With SKSURROGATE_REQUIRE_AUTH enabled the UI asks for a username and password instead, and every dataset, bundle and project belongs to an account that can share it with others; bootstrap the first administrator with SKSURROGATE_ADMIN_USERNAME/SKSURROGATE_ADMIN_PASSWORD or python -m api.auth_cli create-admin, then create per-user API keys in Settings → API keys. Data persists in the sksurrogate-data volume. See the control-plane guide and the authentication and sharing chapter for details.

Benchmarks

The surrogate-guided search is validated against strong HPO/AutoML baselines at equal evaluation budgets (candidate-model evaluations, not wall-clock). Mean final cross-validated accuracy over 7 seeds at a budget of 30 evaluations (full protocol, figures, and the raw-results archive DOI 10.5281/zenodo.23629024 are in docs/benchmarks.md):

dataset

SKSurrogate (RBF-GP, v0.2)

no surrogate

random

Optuna-TPE

arrhythmia

0.7020

0.6910

0.6941

0.7036

credit-g

0.7423

0.7391

0.7405

0.7436

galaxy3

0.6473

0.6448

0.6484

0.6507

ionosphere

0.9352

0.9347

0.9347

0.9337

optdigits

0.9403

0.9392

0.9380

0.9405

spambase

0.9280

0.9269

0.9272

0.9286

The RBF-GP response surface matches the top baseline within ~0.002 on every dataset and edges it out on the hardest case (ionosphere); the with-vs-without surrogate ablation (srs-no-surrogate) shows the surrogate raises or matches final accuracy on every dataset. At the extended budget of 60 evaluations, SKSurrogate (RBF-GP) leads all six datasets. Median-evaluations-to-target and seed-averaged best-so-far curves are in the benchmark report.

Optimize with confidence: detect drift before inference

SKSurrogate records a deterministic dataset fingerprint and a JSON-serializable schema for each tracked dataset. Each call to mltrack.register_data(...) stores dataset metadata, including the target column, row count, column names, dtypes, nullability, and categorical values. This lets a run be identified and later compared against a different dataset or a refreshed training sample — a differentiator that Optuna, TPOT, and SMAC all lack, because they ignore data identity entirely.

The tracker also exposes validate_data(...) and validate_prediction_data(...) to compare incoming data against the stored schema before training or inference. By default the checks are strict: missing columns, reordered columns, dtype mismatches, and unknown categorical values fail with actionable errors. For compatibility workflows, these checks can be relaxed explicitly with missing_columns='ignore' or unknown_categories='ignore'.

The intended workflow is:

  1. Register the training dataset with mltrack.register_data(frame, target).

  2. Validate training data before fitting with tracker.validate_data(frame, target=...).

  3. Validate prediction inputs with tracker.validate_prediction_data(frame) before calling predict on a model or pipeline.

  4. Use the stored dataset_fingerprint and dataset_schema metadata for reproducibility, drift checks, and auditability.

Installation

From PyPI:

pip install sksurrogate

or from source (development):

pip install git+https://github.com/mghasemi/sksurrogate.git

The base install is intentionally small: it pulls seven packages (numpy, scipy, pandas, scikit-learn, joblib, peewee, tqdm) and nothing compiled beyond scikit-learn. Measured on Python 3.12, a cold resolveless install takes ~7 s / 250 MB of site-packages, and import SKSurrogate takes ~0.55 s.

Optional extras

Every other backend is imported lazily and installed through an extra. Naming a component whose backend is absent raises an error that names the extra:

SKSurrogate needs the optional package 'xgboost' for the XGBoost estimator, but it is not installed.
Install it with: pip install "sksurrogate[xgboost]"

Extra

Adds

Needed for

[lightgbm] / [xgboost] / [rgf]

one boosting backend each

the corresponding catalog rows

[gbm]

lightgbm + xgboost

both tree-boosting families

[estimators]

gbm + rgf + category-encoders

the full estimator library

[sensitivity]

SALib

SensAprx (Sobol / Morris / delta)

[explain]

eli5, skrebate

permutation-importance and ReliefF/SURF feature weights

[imbalance]

imbalanced-learn

sampler steps in a pipeline

[categorical]

category-encoders

cat_cols encoding

[plots]

matplotlib

diagnostic plots

[api] / [ui]

FastAPI, uvicorn, python-multipart

the control plane’s dependencies, for a source checkout (pip install ".[ui]"). The api and webui packages ship in the repository and the Docker image, not in the wheel — see the guide

[dask]

dask[distributed]

the distributed execution backend

[all]

every extra above

CI, Docker, “just make everything work” (~938 MB)

[mcp]

httpx, the MCP Python SDK

the agent-facing MCP server (console script sksurrogate-mcp). Kept out of [all] so container images stay SDK-free; see the MCP chapter

[automl] (AutoGluon + PyTorch) is kept separate on purpose: it is multi-GB and only used by the benchmark studies.

Dependencies

SKSurrogate depends on NumPy, scipy, and scikit-learn, for its main functionalities, plus pandas, joblib, peewee (the run tracker’s SQLite ORM) and tqdm. Everything else — matplotlib, SALib, LightGBM, XGBoost, RGF, eli5, skrebate, imbalanced-learn, category-encoders — is an optional extra, imported only by the code path that uses it.

Documentation

The documentation is produced by Sphinx and is intended to cover code usage as well as a bit of theory to explain each method briefly. For more details refer to the documentation at sksurrogate.rtfd.io.

License

This code is distributed under MIT license:

MIT License

Copyright (c) 2019–2026 Mehdi Ghasemi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Metadata

Release files for SKSurrogate 0.8.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for SKSurrogate 0.8.1
File Size Uploaded Provenance Actions
sksurrogate-0.8.1.tar.gz 14.4 MB Without provenance Details for sksurrogate-0.8.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for SKSurrogate 0.8.1
File Interpreter ABI Platform Actions
sksurrogate-0.8.1-py3-none-any.whl Python 3 none any Details for sksurrogate-0.8.1-py3-none-any.whl

Total release size: 14.6 MB

Release files / sksurrogate-0.8.1.tar.gz

Download URL sksurrogate-0.8.1.tar.gz
Size 14.4 MB
Tags Source
SHA-256 checksum
How to use checksums
1dd63a486d7c27972e46f58e85959f77ea770b7ba178f3379d80dc8cd872c19f
BLAKE2b-256 checksum
How to use checksums
e4ba60f34357755bc972da28add749764abbd2a876e0aaa5e05efc5fba5168cb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Release files / sksurrogate-0.8.1-py3-none-any.whl

Download URL sksurrogate-0.8.1-py3-none-any.whl
Size 269.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
97198b70537aee7257b2ffa1c73c6976437b146facd12ef5d46933306452057d
BLAKE2b-256 checksum
How to use checksums
9734f438d04d1dbbc4199f08646f462e3f5f95611f2841d9c835edf65f79c3d4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Security for SKSurrogate 0.8.1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page