threshold_opt
Threshold optimization for binary and multiclass classification.
Given a trained classifier and a cost matrix (or metric objective), threshold_opt finds the decision rule that minimizes expected cost. It supports binary and multiclass problems, with strategies ranging from closed-form analytical solutions to empirical search and calibration-based approaches.
This library is part of a master's dissertation on multiclass threshold optimization. The full experiment pipeline lives in experiments/.
Install
pip install threshold-opt
The package is published as threshold-opt and imported as threshold_opt.
For development (includes experiment dependencies):
git clone https://github.com/vitaliset/threshold-opt.git
cd threshold-opt
uv sync
Quick example
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from threshold_opt import binary_strategies
# Train any sklearn-compatible classifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.3, random_state=42
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
# Define a cost matrix: missing cancer (FN) costs 10x more than a false alarm (FP)
cost_matrix = np.array([
[0.0, 1.0], # TN=0, FP=1
[10.0, 0.0], # FN=10, TP=0
])
# Find the optimal threshold analytically (no validation data needed)
strategy = binary_strategies.AnalyticalThreshold(model)
strategy.fit(np.array([]), np.array([]), cost_matrix)
y_pred = strategy.predict(X_val)
# Or search empirically on a validation set
strategy = binary_strategies.EmpiricalThreshold(model)
strategy.fit(X_val, y_val, cost_matrix)
y_pred = strategy.predict(X_val)
What's inside
| Module | Description |
|---|---|
binary_strategies |
11 strategies for binary classification: default, analytical, empirical search, and calibration variants (isotonic, Platt, temperature, Dirichlet) |
multiclass_strategies |
12 strategies for multiclass: argmax, risk minimization, threshold ratios, Voronoi tuning, sequential selection, risk partitioning, and calibration variants |
calibration |
DirichletCalibrator for post-hoc probability calibration in log-space |
metrics |
Cost matrix utilities, metric objectives (MetricObjective), vectorized scoring, analytical threshold derivation |
optimization |
Grid search and random search optimizers for strategy parameter tuning |
base |
DecisionStrategy abstract base class |
All strategies follow a unified interface: fit(X, y, objective) then predict(X). Objectives can be cost matrices (numpy arrays), MetricObjective instances, or callable factories.
Public API
threshold_opt ships its public API as importable submodules; there is no flat top-level namespace re-export. Stable surface:
- Strategy contract (
base.DecisionStrategy). All strategies subclassDecisionStrategyand expose:fit(X, y, optimization_objective)— fit the decision layer on validation data and returnself.predict(X)— emit class predictions.needs_validation_set: bool—Trueif the strategy consumes a held-out validation split (calibrators, single-split tuners),Falseotherwise (default, analytical, CV-tuners).
- Optimization objectives (
metrics.OptimizationObjective). Either a numpy(K, K)cost matrix (cell[i, j]= cost of predictingjwhen the truth isi), or ametrics.MetricObjective(metric_fn, higher_is_better, ...)wrapping any(y_true, y_pred) -> floatcallable.MetricObjective.vectorized_keyis the optional fast path used by binary strategies; binary metric objectives that omit it still work via a per-threshold loop. - Calibrator (
calibration.DirichletCalibrator). Standalonefit(probs, y)/predict_proba(probs)calibrator with optional ODIR penalties (reg_lambda,reg_mu). Used byDirichletCalibrationArgmax/DirichletCalibrationAnalyticaland freely composable. - Optimizers (
optimization.RandomSearchOptimizer,GridSearchOptimizer). Pluggable parameter optimizers for tuning strategies; subclassoptimization.ParameterOptimizerto add new ones. - Shared CV seed (
base.CV_RANDOM_STATE). Every K-fold loop in the library uses this constant, so external precompute caches that key on it stay in sync with strategies' lazy refits.
Internal symbols (prefixed with _, e.g. base._CVFoldPredictions, binary_strategies._positive_class_probs) are not part of the public API and may change without notice.
Dissertation and experiments
This repo also contains the experiment pipeline and LaTeX source for the dissertation. See experiments/README.md for how to run experiments, generate tables, and build the PDF.
Development
make test # run pytest
make lint # ruff + ruff-format + chktex
make help # all available targets
Releasing
The package is uploaded to PyPI by .github/workflows/publish.yml, through trusted publishing. To release a new version:
- Set
versioninpyproject.toml. - Publish a GitHub release whose tag is
vfollowed by that version (v0.1.0for version0.1.0).
The workflow checks that the tag matches the version, builds the package and uploads it. Releases with any other tag publish nothing.
Project structure
src/threshold_opt/ Library: strategies, calibration, metrics, optimization
experiments/ Experiment pipeline, analysis, cloud scripts
tex/ LaTeX dissertation source
Metadata
Release files for threshold-opt 0.1.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 |
|---|---|---|---|---|
| threshold_opt-0.1.0.tar.gz | 49.8 kB | With provenance | Details for threshold_opt-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| threshold_opt-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for threshold_opt-0.1.0-py3-none-any.whl |
Total release size: 77.8 kB
Release files / threshold_opt-0.1.0.tar.gz
| Download URL | threshold_opt-0.1.0.tar.gz |
|---|---|
| Size | 49.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c86ad44a4d7a201cdef179845b7443dbbdfd144571da80a6d918ad41be1b11dd
|
|
BLAKE2b-256 checksum How to use checksums |
c5887e28b40e4f46942f5ed2c43ef2c99b859b5659b3bc00c65fd5e1038dbf7f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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 11, 2026.
Transparency logRelease files / threshold_opt-0.1.0-py3-none-any.whl
| Download URL | threshold_opt-0.1.0-py3-none-any.whl |
|---|---|
| Size | 28.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c7d862c94426af27ff51e0644376d0eb87a1d9cdb7a24611dabe628a25dc7a1a
|
|
BLAKE2b-256 checksum How to use checksums |
8c4554fcc5f847fa0b5639a39a0c3ad02f3cc42e4b79c00daaa236435c6d4c08
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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 11, 2026.
Transparency logSecurity for threshold-opt 0.1.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 threshold_opt-0.1.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 11, 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.