optican 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- optican-0.1.0/.github/ISSUE_TEMPLATE/bug_report.md +18 -0
- optican-0.1.0/.github/workflows/publish.yml +24 -0
- optican-0.1.0/.github/workflows/tests.yml +24 -0
- optican-0.1.0/CHANGELOG.md +5 -0
- optican-0.1.0/CITATION.cff +9 -0
- optican-0.1.0/CONTRIBUTING.md +13 -0
- optican-0.1.0/LICENSE +21 -0
- optican-0.1.0/MANIFEST.in +10 -0
- optican-0.1.0/PKG-INFO +356 -0
- optican-0.1.0/README.md +320 -0
- optican-0.1.0/SECURITY.md +5 -0
- optican-0.1.0/examples/pytorch_objective.py +99 -0
- optican-0.1.0/examples/scalar_objective.py +27 -0
- optican-0.1.0/pyproject.toml +60 -0
- optican-0.1.0/setup.cfg +4 -0
- optican-0.1.0/src/optican/__init__.py +15 -0
- optican-0.1.0/src/optican/optimizer.py +803 -0
- optican-0.1.0/src/optican/space.py +163 -0
- optican-0.1.0/src/optican.egg-info/PKG-INFO +356 -0
- optican-0.1.0/src/optican.egg-info/SOURCES.txt +22 -0
- optican-0.1.0/src/optican.egg-info/dependency_links.txt +1 -0
- optican-0.1.0/src/optican.egg-info/requires.txt +19 -0
- optican-0.1.0/src/optican.egg-info/top_level.txt +1 -0
- optican-0.1.0/tests/test_optimizer.py +344 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Bug report
|
|
3
|
+
about: Report a reproducible problem
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
## Environment
|
|
7
|
+
- Python version:
|
|
8
|
+
- OptiCan version:
|
|
9
|
+
- Operating system:
|
|
10
|
+
|
|
11
|
+
## Reproduction
|
|
12
|
+
Provide a small objective and search-space example that reproduces the issue.
|
|
13
|
+
|
|
14
|
+
## Expected behavior
|
|
15
|
+
|
|
16
|
+
## Actual behavior
|
|
17
|
+
|
|
18
|
+
## Traceback
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
name: publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
permissions:
|
|
8
|
+
contents: read
|
|
9
|
+
id-token: write
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
publish:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
environment:
|
|
15
|
+
name: pypi
|
|
16
|
+
url: https://pypi.org/p/optican
|
|
17
|
+
steps:
|
|
18
|
+
- uses: actions/checkout@v4
|
|
19
|
+
- uses: actions/setup-python@v5
|
|
20
|
+
with:
|
|
21
|
+
python-version: "3.12"
|
|
22
|
+
- run: python -m pip install --upgrade build
|
|
23
|
+
- run: python -m build
|
|
24
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
name: tests
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
pull_request:
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
test:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
strategy:
|
|
11
|
+
fail-fast: false
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
- run: python -m pip install --upgrade pip
|
|
20
|
+
- run: python -m pip install -e ".[dev]"
|
|
21
|
+
- run: pytest
|
|
22
|
+
- run: ruff check src tests examples
|
|
23
|
+
- run: python -m build
|
|
24
|
+
- run: python -m twine check dist/*
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
cff-version: 1.2.0
|
|
2
|
+
message: "If you use OptiCan in research, software, or publications, please cite this software."
|
|
3
|
+
title: "OptiCan"
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
type: software
|
|
6
|
+
abstract: "A framework-agnostic, candidate-based hyperparameter tuner using multiple algorithms validated for speed and accuracy."
|
|
7
|
+
license: MIT
|
|
8
|
+
authors:
|
|
9
|
+
- name: "Seal-CL"
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Contributions, bug reports, and reproducible benchmark results are welcome.
|
|
4
|
+
|
|
5
|
+
## Before opening a pull request
|
|
6
|
+
|
|
7
|
+
- Create a virtual environment.
|
|
8
|
+
- Install development dependencies with `python -m pip install -e ".[dev]"`.
|
|
9
|
+
- Add or update tests for behavior changes.
|
|
10
|
+
- Run `pytest` and `ruff check src tests examples`.
|
|
11
|
+
- Include the search space, objective, Python version, and random seed when reporting performance changes.
|
|
12
|
+
|
|
13
|
+
Do not claim that the search is globally optimal. Use the same evaluation budget, seeds, validation splits, and stopping rules when comparing with other search methods. Do not use a held-out test set for tuning.
|
optican-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 OptiCan contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
optican-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: optican
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Framework-agnostic adaptive hyperparameter optimization with elite-guided search.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Keywords: hyperparameter-optimization,machine-learning,adaptive-search,optimization,pytorch,scikit-learn,tensorflow
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Provides-Extra: torch
|
|
22
|
+
Requires-Dist: torch>=2.0; extra == "torch"
|
|
23
|
+
Requires-Dist: numpy>=1.23; extra == "torch"
|
|
24
|
+
Provides-Extra: numpy
|
|
25
|
+
Requires-Dist: numpy>=1.23; extra == "numpy"
|
|
26
|
+
Provides-Extra: sklearn
|
|
27
|
+
Requires-Dist: scikit-learn>=1.2; extra == "sklearn"
|
|
28
|
+
Provides-Extra: tensorflow
|
|
29
|
+
Requires-Dist: tensorflow>=2.12; extra == "tensorflow"
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
32
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
33
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
34
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# OptiCan
|
|
38
|
+
|
|
39
|
+
OptiCan is a lightweight, framework-agnostic hyperparameter optimization library. It searches continuous, integer, categorical, Boolean, and fixed parameter spaces with adaptive elite-guided refinement.
|
|
40
|
+
|
|
41
|
+
OptiCan does not require PyTorch, TensorFlow, scikit-learn, NumPy, or another machine-learning framework. You provide an objective function that trains and validates your model. OptiCan searches the configuration values passed to that function.
|
|
42
|
+
|
|
43
|
+
The current release is `0.1.0`. The API may change before the first stable release. The search is a heuristic and does not guarantee a global optimum.
|
|
44
|
+
|
|
45
|
+
## Features
|
|
46
|
+
|
|
47
|
+
- Continuous, log-scaled, integer, categorical, Boolean, and fixed parameters.
|
|
48
|
+
- Adaptive range contraction guided by elite candidate density.
|
|
49
|
+
- Elite-parent mutation that preserves successful parameter combinations.
|
|
50
|
+
- Probability-based categorical refinement.
|
|
51
|
+
- Shared random seeds across candidate evaluations.
|
|
52
|
+
- Optional multi-seed stability scoring.
|
|
53
|
+
- Duplicate configuration avoidance and full trial history.
|
|
54
|
+
- Minimization and maximization objectives.
|
|
55
|
+
- Early stopping and trial limits.
|
|
56
|
+
- No required third-party dependencies.
|
|
57
|
+
|
|
58
|
+
## Install
|
|
59
|
+
|
|
60
|
+
install it with:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install optican
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
For local development:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
python -m pip install -e ".[dev]"
|
|
70
|
+
pytest
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Quick start
|
|
74
|
+
|
|
75
|
+
An objective receives a configuration dictionary and optionally a seed. It returns one numeric validation metric. The default direction is `"min"`, which is useful for loss and error metrics.
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from optican import OptiCan, Float, Int, Choice, Bool
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def objective(config, seed):
|
|
82
|
+
validation_loss = train_and_validate(
|
|
83
|
+
learning_rate=config["learning_rate"],
|
|
84
|
+
batch_size=config["batch_size"],
|
|
85
|
+
weight_decay=config["weight_decay"],
|
|
86
|
+
optimizer=config["optimizer"],
|
|
87
|
+
use_scheduler=config["use_scheduler"],
|
|
88
|
+
seed=seed,
|
|
89
|
+
)
|
|
90
|
+
return validation_loss
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
search = OptiCan(
|
|
94
|
+
objective=objective,
|
|
95
|
+
config={
|
|
96
|
+
"learning_rate": Float(1e-5, 1e-2, log=True),
|
|
97
|
+
"batch_size": Choice([32, 64, 128, 256]),
|
|
98
|
+
"weight_decay": Float(1e-7, 1e-2, log=True, allow_zero=True),
|
|
99
|
+
"optimizer": Choice(["AdamW", "Adam", "SGD"]),
|
|
100
|
+
"use_scheduler": Bool(),
|
|
101
|
+
},
|
|
102
|
+
rounds=3,
|
|
103
|
+
ubest=False,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
last_round_config = search.optimize()
|
|
107
|
+
print(last_round_config)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Return behavior
|
|
111
|
+
|
|
112
|
+
`ubest=False` returns the best configuration from the latest completed round that produced a successful trial. This is useful when you want to inspect what the newest refinement round found.
|
|
113
|
+
|
|
114
|
+
`ubest=True` returns a `TuningResult`. Its `best_config`, `best_trial`, and `best_score` refer to the best result across all rounds.
|
|
115
|
+
|
|
116
|
+
The full result is available as `search.result` in both modes. It keeps the global best and the latest successful round best:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
print(search.result.best_config)
|
|
120
|
+
print(search.result.best_score)
|
|
121
|
+
print(search.result.last_round_best_config)
|
|
122
|
+
print(search.result.last_round_best_score)
|
|
123
|
+
print(search.result.summary())
|
|
124
|
+
|
|
125
|
+
for trial in search.result.trials:
|
|
126
|
+
print(trial.config, trial.mean_score, trial.std_score, trial.error)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
If the latest round has no successful trials, OptiCan uses the best result from the latest earlier round that had a successful trial. A fixed-only search or an empty configuration is evaluated once.
|
|
130
|
+
|
|
131
|
+
## Search-space parameters
|
|
132
|
+
|
|
133
|
+
Use helper classes for explicit search spaces:
|
|
134
|
+
|
|
135
|
+
| Type | Example | Behavior |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| Float | `Float(1e-5, 1e-2)` | Samples a continuous range |
|
|
138
|
+
| Log float | `Float(1e-5, 1e-2, log=True)` | Samples uniformly in log10 space |
|
|
139
|
+
| Zero-capable float | `Float(1e-7, 1e-2, log=True, allow_zero=True)` | Adds exact zero as a separate option |
|
|
140
|
+
| Integer | `Int(16, 256, step=16)` | Samples integer values on a stepped range |
|
|
141
|
+
| Categorical | `Choice(["Adam", "AdamW"])` | Learns category probabilities |
|
|
142
|
+
| Boolean | `Bool()` | Learns probabilities for `True` and `False` |
|
|
143
|
+
| Fixed | `Fixed("gelu")` | Keeps a value unchanged |
|
|
144
|
+
|
|
145
|
+
A list or tuple is treated as a categorical choice. Any other scalar is treated as a fixed value. An empty `config={}` is valid and evaluates the objective once with an empty configuration.
|
|
146
|
+
|
|
147
|
+
Compact dictionary definitions are also supported:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
config = {
|
|
151
|
+
"learning_rate": {
|
|
152
|
+
"type": "float",
|
|
153
|
+
"low": 1e-5,
|
|
154
|
+
"high": 1e-2,
|
|
155
|
+
"log": True,
|
|
156
|
+
},
|
|
157
|
+
"depth": {"type": "int", "low": 2, "high": 12},
|
|
158
|
+
"optimizer": {"type": "choice", "values": ["Adam", "AdamW"]},
|
|
159
|
+
"use_dropout": {"type": "bool"},
|
|
160
|
+
"activation": ["relu", "gelu", "silu"],
|
|
161
|
+
"device": "cuda",
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Options
|
|
166
|
+
|
|
167
|
+
| Option | Default | Meaning |
|
|
168
|
+
|---|---:|---|
|
|
169
|
+
| `rounds` | `3` | Total search rounds, including the initial round |
|
|
170
|
+
| `initial_candidates` | `24` | Configurations sampled in the first round |
|
|
171
|
+
| `candidates_per_round` | `12` | New configurations in each later round |
|
|
172
|
+
| `elite_size` | `20` | Top configurations used to guide refinement |
|
|
173
|
+
| `seeds` | `1` | Number of shared seeds used per configuration |
|
|
174
|
+
| `seed` | `42` | Base seed, later seeds increase by one |
|
|
175
|
+
| `direction` | `"min"` | Use `"max"` for metrics such as accuracy or F1 |
|
|
176
|
+
| `stability_penalty` | `0.25` | Penalty for score variation across seeds |
|
|
177
|
+
| `mutation_rate` | `0.70` | Chance of mutating each parameter in a child |
|
|
178
|
+
| `exploration_mix` | `0.20` | Fraction sampled independently of elite parents |
|
|
179
|
+
| `categorical_exploration` | `0.15` | Keeps category sampling from collapsing too early |
|
|
180
|
+
| `shrink_fraction` | `0.20` | Fraction of the active numeric range contracted per round |
|
|
181
|
+
| `min_range_fraction` | `0.05` | Minimum range width relative to its initial width |
|
|
182
|
+
| `max_trials` | `None` | Optional cap on evaluated configurations |
|
|
183
|
+
| `patience_rounds` | `0` | Stop after this many stagnant rounds, zero disables it |
|
|
184
|
+
| `min_delta` | `0.0` | Minimum improvement needed to reset patience |
|
|
185
|
+
| `ubest` | `False` | Selects the latest-round config or returns the full global result |
|
|
186
|
+
| `verbose` | `True` | Prints progress while evaluating candidates |
|
|
187
|
+
| `catch_exceptions` | `True` | Records failed evaluations and continues |
|
|
188
|
+
|
|
189
|
+
Use `seeds=1` for faster tests. Increase it to `3` or `5` for more stable comparisons. The same seed set is used for every configuration.
|
|
190
|
+
|
|
191
|
+
OptiCan evaluates candidates sequentially by default. This avoids global random-seed interference and unexpected GPU memory use across different frameworks. Reduce candidate counts, use `max_trials`, or add early stopping inside the objective to reduce evaluation time.
|
|
192
|
+
|
|
193
|
+
## Metric formulas
|
|
194
|
+
|
|
195
|
+
A separate `metric="t/a"` option is not needed. The objective function already provides a flexible way to calculate any metric. Compute the values your formula needs and return the result.
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
def objective(config, seed):
|
|
199
|
+
predictions = train_and_predict(config, seed)
|
|
200
|
+
t = count_true_predictions(predictions)
|
|
201
|
+
a = count_all_predictions(predictions)
|
|
202
|
+
return t / max(a, 1)
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
The objective can calculate a single metric, combine several metrics, or call an existing scoring function. OptiCan only needs the final numeric result. Set `direction="max"` when higher values are better.
|
|
206
|
+
|
|
207
|
+
## PyTorch example
|
|
208
|
+
|
|
209
|
+
OptiCan does not create or manage models itself. Put model creation, training, early stopping, and validation inside the objective. Replace `Model` and the data variables with your own objects.
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
import random
|
|
213
|
+
import numpy as np
|
|
214
|
+
import torch
|
|
215
|
+
import torch.nn as nn
|
|
216
|
+
from torch.utils.data import DataLoader, TensorDataset
|
|
217
|
+
|
|
218
|
+
from optican import OptiCan, Float, Choice, Bool
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def objective(config, seed):
|
|
222
|
+
random.seed(seed)
|
|
223
|
+
np.random.seed(seed)
|
|
224
|
+
torch.manual_seed(seed)
|
|
225
|
+
if torch.cuda.is_available():
|
|
226
|
+
torch.cuda.manual_seed_all(seed)
|
|
227
|
+
|
|
228
|
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
229
|
+
model = Model().to(device)
|
|
230
|
+
optimizer_class = getattr(torch.optim, config["optimizer"])
|
|
231
|
+
optimizer = optimizer_class(
|
|
232
|
+
model.parameters(),
|
|
233
|
+
lr=config["learning_rate"],
|
|
234
|
+
weight_decay=config["weight_decay"],
|
|
235
|
+
)
|
|
236
|
+
loss_fn = nn.CrossEntropyLoss()
|
|
237
|
+
scheduler = None
|
|
238
|
+
if config["use_scheduler"]:
|
|
239
|
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=20)
|
|
240
|
+
loader = DataLoader(
|
|
241
|
+
TensorDataset(X_train, y_train),
|
|
242
|
+
batch_size=config["batch_size"],
|
|
243
|
+
shuffle=True,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
best_val_loss = float("inf")
|
|
247
|
+
for _ in range(20):
|
|
248
|
+
model.train()
|
|
249
|
+
for x, y in loader:
|
|
250
|
+
x, y = x.to(device), y.to(device)
|
|
251
|
+
optimizer.zero_grad(set_to_none=True)
|
|
252
|
+
loss = loss_fn(model(x), y)
|
|
253
|
+
loss.backward()
|
|
254
|
+
optimizer.step()
|
|
255
|
+
|
|
256
|
+
model.eval()
|
|
257
|
+
with torch.no_grad():
|
|
258
|
+
val_loss = loss_fn(
|
|
259
|
+
model(X_valid.to(device)),
|
|
260
|
+
y_valid.to(device),
|
|
261
|
+
).item()
|
|
262
|
+
best_val_loss = min(best_val_loss, val_loss)
|
|
263
|
+
if scheduler is not None:
|
|
264
|
+
scheduler.step()
|
|
265
|
+
|
|
266
|
+
return best_val_loss
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
search = OptiCan(
|
|
270
|
+
objective,
|
|
271
|
+
config={
|
|
272
|
+
"learning_rate": Float(1e-5, 3e-3, log=True),
|
|
273
|
+
"weight_decay": Float(1e-7, 1e-2, log=True, allow_zero=True),
|
|
274
|
+
"batch_size": Choice([32, 64, 128, 256]),
|
|
275
|
+
"optimizer": Choice(["AdamW", "Adam"]),
|
|
276
|
+
"use_scheduler": Bool(),
|
|
277
|
+
},
|
|
278
|
+
rounds=3,
|
|
279
|
+
seeds=3,
|
|
280
|
+
ubest=True,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
result = search.optimize()
|
|
284
|
+
print(result.best_config)
|
|
285
|
+
print(result.best_score)
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
## Scikit-learn example
|
|
289
|
+
|
|
290
|
+
```python
|
|
291
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
292
|
+
from sklearn.model_selection import cross_val_score
|
|
293
|
+
from optican import OptiCan, Int, Choice
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def objective(config, seed):
|
|
297
|
+
estimator = RandomForestClassifier(
|
|
298
|
+
n_estimators=config["n_estimators"],
|
|
299
|
+
max_depth=config["max_depth"],
|
|
300
|
+
criterion=config["criterion"],
|
|
301
|
+
random_state=seed,
|
|
302
|
+
n_jobs=-1,
|
|
303
|
+
)
|
|
304
|
+
return cross_val_score(
|
|
305
|
+
estimator, X, y, cv=5, scoring="accuracy", n_jobs=-1
|
|
306
|
+
).mean()
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
search = OptiCan(
|
|
310
|
+
objective,
|
|
311
|
+
config={
|
|
312
|
+
"n_estimators": Int(100, 600, step=50),
|
|
313
|
+
"max_depth": Choice([None, 5, 10, 20, 30]),
|
|
314
|
+
"criterion": Choice(["gini", "entropy", "log_loss"]),
|
|
315
|
+
},
|
|
316
|
+
direction="max",
|
|
317
|
+
rounds=3,
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
best_config = search.optimize()
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
## How the algorithm works
|
|
324
|
+
|
|
325
|
+
1. Initial configurations are sampled from the parameter distributions.
|
|
326
|
+
2. Every configuration is evaluated with the same seed set.
|
|
327
|
+
3. Successful trials are ranked by their mean metric and optional stability penalty.
|
|
328
|
+
4. Numeric ranges contract toward elite regions, with more contraction on the side with fewer elite samples.
|
|
329
|
+
5. Categorical probabilities increase for values that appear more often among elite trials.
|
|
330
|
+
6. New configurations mutate successful parent configurations, preserving useful parameter combinations.
|
|
331
|
+
7. Every trial is kept, so the global best can be selected across all rounds.
|
|
332
|
+
|
|
333
|
+
This is an adaptive heuristic. It can miss a global optimum, especially with narrow ranges, noisy objectives, strong parameter interactions, or too few evaluations. Use a suitable evaluation budget and validation split.
|
|
334
|
+
|
|
335
|
+
## Reproducibility and objective requirements
|
|
336
|
+
|
|
337
|
+
- Return one finite numeric validation metric.
|
|
338
|
+
- Do not use the test set to choose hyperparameters. Reserve it for final evaluation.
|
|
339
|
+
- Use the supplied seed for model initialization, data shuffling, and randomized preprocessing.
|
|
340
|
+
- OptiCan seeds Python and seeds NumPy, PyTorch, and TensorFlow only when they are already imported.
|
|
341
|
+
- Some GPU operations may remain nondeterministic unless the framework is configured for deterministic execution.
|
|
342
|
+
- Add early stopping inside the objective when the training loop supports it.
|
|
343
|
+
|
|
344
|
+
## Development
|
|
345
|
+
|
|
346
|
+
```bash
|
|
347
|
+
python -m pip install -e ".[dev]"
|
|
348
|
+
pytest
|
|
349
|
+
ruff check src tests examples
|
|
350
|
+
python -m build
|
|
351
|
+
python -m twine check dist/*
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
## License
|
|
355
|
+
|
|
356
|
+
MIT. See [LICENSE](LICENSE).
|