hyperparameter-optimizer 0.1.1__tar.gz → 0.2.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.
- hyperparameter_optimizer-0.2.0/LICENSE +21 -0
- hyperparameter_optimizer-0.2.0/PKG-INFO +379 -0
- hyperparameter_optimizer-0.2.0/README.md +357 -0
- hyperparameter_optimizer-0.2.0/hyperparameter_optimizer/__init__.py +5 -0
- hyperparameter_optimizer-0.2.0/hyperparameter_optimizer/core.py +1294 -0
- hyperparameter_optimizer-0.2.0/hyperparameter_optimizer.egg-info/PKG-INFO +379 -0
- {hyperparameter_optimizer-0.1.1 → hyperparameter_optimizer-0.2.0}/hyperparameter_optimizer.egg-info/SOURCES.txt +1 -1
- hyperparameter_optimizer-0.2.0/hyperparameter_optimizer.egg-info/requires.txt +8 -0
- hyperparameter_optimizer-0.2.0/pyproject.toml +31 -0
- hyperparameter_optimizer-0.1.1/PKG-INFO +0 -170
- hyperparameter_optimizer-0.1.1/README.md +0 -143
- hyperparameter_optimizer-0.1.1/hyperparameter_optimizer/__init__.py +0 -1
- hyperparameter_optimizer-0.1.1/hyperparameter_optimizer/core.py +0 -260
- hyperparameter_optimizer-0.1.1/hyperparameter_optimizer.egg-info/PKG-INFO +0 -170
- hyperparameter_optimizer-0.1.1/hyperparameter_optimizer.egg-info/requires.txt +0 -2
- hyperparameter_optimizer-0.1.1/pyproject.toml +0 -3
- hyperparameter_optimizer-0.1.1/setup.py +0 -25
- {hyperparameter_optimizer-0.1.1 → hyperparameter_optimizer-0.2.0}/hyperparameter_optimizer.egg-info/dependency_links.txt +0 -0
- {hyperparameter_optimizer-0.1.1 → hyperparameter_optimizer-0.2.0}/hyperparameter_optimizer.egg-info/top_level.txt +0 -0
- {hyperparameter_optimizer-0.1.1 → hyperparameter_optimizer-0.2.0}/setup.cfg +0 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Dr. Ahmed Moussa
|
|
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.
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hyperparameter-optimizer
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A lightweight Python library for hyperparameter tuning using Metaheuristic algorithms.
|
|
5
|
+
Author: Dr. Ahmed Moussa
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/real-ahmed-moussa/hyperparameter_optimizer
|
|
8
|
+
Keywords: hyperparameter optimization,metaheuristics,particle swarm,pattern search,genetic algorithm,nsga-ii,multi-objective,scikit-learn,tensorflow,pytorch
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: numpy
|
|
16
|
+
Requires-Dist: scikit-learn
|
|
17
|
+
Provides-Extra: tensorflow
|
|
18
|
+
Requires-Dist: tensorflow; extra == "tensorflow"
|
|
19
|
+
Provides-Extra: torch
|
|
20
|
+
Requires-Dist: torch; extra == "torch"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# Hyperparameter Optimizer
|
|
24
|
+
|
|
25
|
+
<p align="center">
|
|
26
|
+
<img src="https://raw.githubusercontent.com/real-ahmed-moussa/hyperparameter_optimizer/main/imgs/Hyperparameter%20Optimizer%20(Python%20Package).png" alt="hpo" width="300">
|
|
27
|
+
</p>
|
|
28
|
+
|
|
29
|
+
A lightweight and flexible Python library for hyperparameter tuning using metaheuristic techniques. Currently, the library includes **Particle Swarm Optimization (PSO)**, **Pattern Search (PS)**, a **Genetic Algorithm (GA)**, and **NSGA-II** for multi-objective optimization.
|
|
30
|
+
|
|
31
|
+
Designed for Scikit-learn-compatible models, this package offers an easy-to-use interface for optimizing model performance in just a few lines.
|
|
32
|
+
|
|
33
|
+

|
|
34
|
+

|
|
35
|
+
[](https://pepy.tech/project/hyperparameter-optimizer)
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 📦 Installation
|
|
40
|
+
|
|
41
|
+
Install from PyPI:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install hyperparameter-optimizer
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
With TensorFlow/Keras or PyTorch support:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install "hyperparameter-optimizer[tensorflow]"
|
|
51
|
+
pip install "hyperparameter-optimizer[torch]"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## ⚙️ Features
|
|
57
|
+
|
|
58
|
+
- ✅ Metaheuristic optimization using Particle Swarm Optimization (PSO), Pattern Search (PS), and a Genetic Algorithm (GA)
|
|
59
|
+
- ✅ Multi-objective optimization with NSGA-II (e.g. precision vs recall, accuracy vs training time), returning the Pareto front
|
|
60
|
+
- ✅ Supports continuous, integer, and categorical hyperparameters
|
|
61
|
+
- ✅ Compatible with any Scikit-learn estimator
|
|
62
|
+
- ✅ Native TensorFlow/Keras and PyTorch support (`KerasModel`, `TorchModel`)
|
|
63
|
+
- ✅ Any custom objective function `f(params, features, target) -> score`
|
|
64
|
+
- ✅ Custom scoring metrics
|
|
65
|
+
- ✅ Cross-validation built-in
|
|
66
|
+
- ✅ Verbose logging and full traceability
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## 📚 API Reference
|
|
71
|
+
|
|
72
|
+
### `HyperparameterOptimizer`
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
HyperparameterOptimizer(
|
|
76
|
+
obj_func, # Scikit-learn model/pipeline, KerasModel, TorchModel, or a function f(params, features, target) -> score.
|
|
77
|
+
params, # dictionary whose keys are the hyperparameter names, in the same order as `bounds`.
|
|
78
|
+
scoring, # scoring metric (e.g., 'accuracy'), or a list of metrics for optimizeNSGA2 (e.g., ['precision', 'recall']).
|
|
79
|
+
opt_type="max", # "max" (default) or "min"; with a list of metrics, one value for all or a list with one per metric.
|
|
80
|
+
cv=5, # number of cross-validation folds
|
|
81
|
+
verbose=1, # binary with a value of 1 (default) to show iteration information.
|
|
82
|
+
n_jobs=-1 # parallel jobs for Scikit-learn cross-validation (-1 = all cores).
|
|
83
|
+
)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
After a run, `optimizer.best_params` holds the best hyperparameters as a dict, and a Scikit-learn `obj_func` is left set to them (not refit).
|
|
87
|
+
|
|
88
|
+
### `optimizePSO`
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
optimizePSO(
|
|
92
|
+
features, # training features.
|
|
93
|
+
target, # training target.
|
|
94
|
+
nParticles, # number of particles in the swarm.
|
|
95
|
+
bounds, # list of (min, max) tuples or a categorical list of choices.
|
|
96
|
+
# if either min/max is non-integer, the algorithm shall consider them as floats (i.e., continuous).
|
|
97
|
+
w=0.5, # inertia weight.
|
|
98
|
+
c1=1, # cognitive weight.
|
|
99
|
+
c2=1, # social weight.
|
|
100
|
+
maxIter=20, # maximum number of iterations.
|
|
101
|
+
mutation_prob=0.1 # mtation probability -- for discrete hyperparameters.
|
|
102
|
+
)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### `optimizePS`
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
optimizePS(
|
|
109
|
+
features, # training features.
|
|
110
|
+
target, # training target.
|
|
111
|
+
bounds, # list of (min, max) tuples or a categorical list of choices.
|
|
112
|
+
# if either min/max is non-integer, the algorithm shall consider them as floats (i.e., continuous).
|
|
113
|
+
mesh_size_coeff=0.6, # mesh size coefficient.
|
|
114
|
+
acc_coeff=1, # acceleration/mesh expansion coefficient.
|
|
115
|
+
contr_coeff=0.5, # mesh contraction coefficient.
|
|
116
|
+
search_method="gps", # new points exploration method; either 'gps' or 'mads'.
|
|
117
|
+
min_mesh_ratio=0.001, # minimum mesh size as a percentage of parameter range.
|
|
118
|
+
maxIter=25 # maximum number of iterations.
|
|
119
|
+
)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### `optimizeGA`
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
optimizeGA(
|
|
126
|
+
features, # training features.
|
|
127
|
+
target, # training target.
|
|
128
|
+
popSize, # number of individuals in the population.
|
|
129
|
+
bounds, # list of (min, max) tuples or a categorical list of choices.
|
|
130
|
+
# if either min/max is non-integer, the algorithm shall consider them as floats (i.e., continuous).
|
|
131
|
+
crossover_prob=0.8, # probability that two parents are combined (blend crossover for numbers, uniform for categories).
|
|
132
|
+
mutation_prob=0.1, # probability that each gene of a child is mutated.
|
|
133
|
+
mutation_scale=0.1, # standard deviation of numeric mutations, as a fraction of the parameter range.
|
|
134
|
+
elitism=1, # number of best individuals copied unchanged into the next generation.
|
|
135
|
+
tournament_size=3, # number of individuals competing in each parent selection.
|
|
136
|
+
maxIter=20 # maximum number of generations.
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Identical individuals are evaluated only once, so repeated integer/categorical candidates cost nothing extra.
|
|
141
|
+
|
|
142
|
+
### `optimizeNSGA2`
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
optimizeNSGA2(
|
|
146
|
+
features, # training features.
|
|
147
|
+
target, # training target.
|
|
148
|
+
popSize, # number of individuals in the population (and maximum size of the returned front).
|
|
149
|
+
bounds, # list of (min, max) tuples or a categorical list of choices.
|
|
150
|
+
crossover_prob=0.9, # probability that two parents are combined.
|
|
151
|
+
mutation_prob=0.1, # probability that each gene of a child is mutated.
|
|
152
|
+
mutation_scale=0.1, # standard deviation of numeric mutations, as a fraction of the parameter range.
|
|
153
|
+
tournament_size=2, # number of individuals competing in each parent selection (by Pareto rank, then crowding).
|
|
154
|
+
maxIter=20 # maximum number of generations.
|
|
155
|
+
)
|
|
156
|
+
# returns: pareto_front, population, history
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Requires a list of metrics in `scoring`. Each entry of `pareto_front` is `{'params': {...}, 'scores': {...}}`, sorted best-first on the first objective; `optimizer.pareto_params` holds just the parameter dicts and `optimizer.NSGA2_allEvaluated` every unique solution evaluated. There is no single best solution, so the model is not modified: pick a point from the front and train with it.
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## 🚀 Quickstart
|
|
164
|
+
|
|
165
|
+
Here's a basic example of how to use **Hyperparameter Optimizer** with a Scikit-learn model (e.g., `RandomForestClassifier`):
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
from sklearn.datasets import load_iris
|
|
169
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
170
|
+
from hyperparameter_optimizer import HyperparameterOptimizer
|
|
171
|
+
|
|
172
|
+
# Load data
|
|
173
|
+
X, y = load_iris(return_X_y=True)
|
|
174
|
+
|
|
175
|
+
# Define parameter space
|
|
176
|
+
param_space = {
|
|
177
|
+
'n_estimators': [],
|
|
178
|
+
'max_depth': [],
|
|
179
|
+
'criterion': []
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
# Initialize the optimizer
|
|
183
|
+
optimizer = HyperparameterOptimizer(
|
|
184
|
+
obj_func=RandomForestClassifier(),
|
|
185
|
+
params=param_space,
|
|
186
|
+
scoring='accuracy',
|
|
187
|
+
opt_type='max',
|
|
188
|
+
cv=3,
|
|
189
|
+
verbose=1
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
# Run optimization
|
|
193
|
+
# [1] Particle Swarm Optimization
|
|
194
|
+
particles, Gbest_history, Gbest_pos, Gbest_score = optimizer.optimizePSO(
|
|
195
|
+
features = X,
|
|
196
|
+
target = y,
|
|
197
|
+
nParticles = 10,
|
|
198
|
+
bounds = [(10, 1000), (1, 10), ['gini', 'entropy']],
|
|
199
|
+
maxIter = 10
|
|
200
|
+
)
|
|
201
|
+
print("Best Params:", Gbest_pos)
|
|
202
|
+
print("Best Score:", Gbest_score)
|
|
203
|
+
|
|
204
|
+
# [2] Pattern Search Optimization
|
|
205
|
+
Gbest_history2, Gbest_pos2, Gbest_score2 = optimizer.optimizePS(
|
|
206
|
+
features = X,
|
|
207
|
+
target = y,
|
|
208
|
+
bounds = [(10, 1000), (1, 10), ['gini', 'entropy']],
|
|
209
|
+
mesh_size_coeff = 0.1,
|
|
210
|
+
acc_coeff = 1,
|
|
211
|
+
contr_coeff = 0.50,
|
|
212
|
+
maxIter = 10
|
|
213
|
+
)
|
|
214
|
+
print("Best Params:", Gbest_pos2)
|
|
215
|
+
print("Best Score:", Gbest_score2)
|
|
216
|
+
|
|
217
|
+
# [3] Genetic Algorithm Optimization
|
|
218
|
+
population, Gbest_history3, Gbest_pos3, Gbest_score3 = optimizer.optimizeGA(
|
|
219
|
+
features = X,
|
|
220
|
+
target = y,
|
|
221
|
+
popSize = 10,
|
|
222
|
+
bounds = [(10, 1000), (1, 10), ['gini', 'entropy']],
|
|
223
|
+
maxIter = 10
|
|
224
|
+
)
|
|
225
|
+
print("Best Params:", Gbest_pos3)
|
|
226
|
+
print("Best Score:", Gbest_score3)
|
|
227
|
+
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
|
|
232
|
+
## 🔥 TensorFlow/Keras and PyTorch
|
|
233
|
+
|
|
234
|
+
Wrap a function that **builds** the network in `KerasModel` or `TorchModel`. The optimizer then cross-validates natively: on every fold it builds a fresh model with the candidate hyperparameters, trains it and scores it on the held-out data. TensorFlow and PyTorch are only imported when you use these wrappers.
|
|
235
|
+
|
|
236
|
+
- The names `epochs`, `batch_size`, `learning_rate` and `optimizer` tune the training loop; every other name is passed to your build function.
|
|
237
|
+
- `task` is `"classification"` (default) or `"regression"`. For classification, use 1 output unit for 2 classes or one unit per class otherwise; labels can be any values (strings too).
|
|
238
|
+
- The loss defaults to binary/categorical cross-entropy or MSE to match the task, or pass your own with `loss=`.
|
|
239
|
+
- Scoring: `accuracy`, `balanced_accuracy`, `f1`, `f1_macro`, `f1_weighted`, `precision`, `recall`, `roc_auc`, `r2`, `neg_mean_squared_error`, `neg_root_mean_squared_error`, `neg_mean_absolute_error`, or a function `f(y_true, y_pred)`.
|
|
240
|
+
- Folds run one at a time. Each candidate trains `cv` networks, so keep `epochs`, `cv`, `nParticles` and `maxIter` modest.
|
|
241
|
+
|
|
242
|
+
**Keras** (outputs are probabilities by default, i.e. a sigmoid/softmax output layer; set `from_logits=True` otherwise):
|
|
243
|
+
|
|
244
|
+
```python
|
|
245
|
+
import keras
|
|
246
|
+
from hyperparameter_optimizer import HyperparameterOptimizer, KerasModel
|
|
247
|
+
|
|
248
|
+
def build(units, dropout):
|
|
249
|
+
return keras.Sequential([
|
|
250
|
+
keras.Input((X.shape[1],)),
|
|
251
|
+
keras.layers.Dense(units, activation="relu"),
|
|
252
|
+
keras.layers.Dropout(dropout),
|
|
253
|
+
keras.layers.Dense(1, activation="sigmoid"),
|
|
254
|
+
])
|
|
255
|
+
|
|
256
|
+
optimizer = HyperparameterOptimizer(
|
|
257
|
+
obj_func=KerasModel(build, epochs=20),
|
|
258
|
+
params={"units": [], "dropout": [], "learning_rate": [], "batch_size": []},
|
|
259
|
+
scoring="accuracy",
|
|
260
|
+
cv=3
|
|
261
|
+
)
|
|
262
|
+
optimizer.optimizePSO(X, y, nParticles=5, maxIter=5,
|
|
263
|
+
bounds=[(8, 128), (0.0, 0.5), (1e-4, 1e-2), [16, 32, 64]])
|
|
264
|
+
print(optimizer.best_params)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
**PyTorch** (outputs are logits by default, i.e. no final sigmoid/softmax; set `from_logits=False` otherwise; `device` defaults to CUDA when available):
|
|
268
|
+
|
|
269
|
+
```python
|
|
270
|
+
from torch import nn
|
|
271
|
+
from hyperparameter_optimizer import HyperparameterOptimizer, TorchModel
|
|
272
|
+
|
|
273
|
+
def build(hidden, dropout):
|
|
274
|
+
return nn.Sequential(nn.Linear(X.shape[1], hidden), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden, 3))
|
|
275
|
+
|
|
276
|
+
optimizer = HyperparameterOptimizer(
|
|
277
|
+
obj_func=TorchModel(build, epochs=30),
|
|
278
|
+
params={"hidden": [], "dropout": [], "learning_rate": [], "optimizer": []},
|
|
279
|
+
scoring="f1_macro",
|
|
280
|
+
cv=3
|
|
281
|
+
)
|
|
282
|
+
optimizer.optimizePS(X, y, bounds=[(8, 128), (0.0, 0.5), (1e-4, 1e-2), ["adam", "adamw", "sgd"]],
|
|
283
|
+
mesh_size_coeff=0.3, acc_coeff=2, contr_coeff=0.5, maxIter=10)
|
|
284
|
+
print(optimizer.best_params)
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
**Any other framework** – pass a plain function that trains and validates however you like and returns a score:
|
|
288
|
+
|
|
289
|
+
```python
|
|
290
|
+
from hyperparameter_optimizer import HyperparameterOptimizer
|
|
291
|
+
|
|
292
|
+
def objective(params, features, target):
|
|
293
|
+
... # train with params["lr"], params["layers"], ...
|
|
294
|
+
return validation_score
|
|
295
|
+
|
|
296
|
+
optimizer = HyperparameterOptimizer(objective, {"lr": [], "layers": []}, scoring=None)
|
|
297
|
+
optimizer.optimizePSO(X, y, nParticles=8, bounds=[(1e-4, 1e-1), (1, 4)])
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## 🎯 Multi-objective Optimization (NSGA-II)
|
|
303
|
+
|
|
304
|
+
Pass several metrics in `scoring` and call `optimizeNSGA2`. One cross-validation run computes all of them, so extra objectives cost no extra training. The result is the **Pareto front**: the configurations where no metric can improve without another getting worse.
|
|
305
|
+
|
|
306
|
+
- `opt_type` can be one value for all metrics or a list, e.g. `["max", "min"]`.
|
|
307
|
+
- `"fit_time"` is a special objective: the mean training time per fold in seconds (always minimized unless `opt_type` is a list).
|
|
308
|
+
- The precision/recall trade-off is driven mostly by the decision **threshold**, so tune it too: wrap a Scikit-learn classifier in `FixedThresholdClassifier` (Scikit-learn ≥ 1.5), or tune `"threshold"` directly on `KerasModel`/`TorchModel`.
|
|
309
|
+
- Works with every `obj_func` type; a plain function objective returns one value per metric.
|
|
310
|
+
|
|
311
|
+
```python
|
|
312
|
+
from sklearn.datasets import load_breast_cancer
|
|
313
|
+
from sklearn.linear_model import LogisticRegression
|
|
314
|
+
from sklearn.model_selection import FixedThresholdClassifier
|
|
315
|
+
from sklearn.pipeline import make_pipeline
|
|
316
|
+
from sklearn.preprocessing import StandardScaler
|
|
317
|
+
from hyperparameter_optimizer import HyperparameterOptimizer
|
|
318
|
+
|
|
319
|
+
X, y = load_breast_cancer(return_X_y=True)
|
|
320
|
+
model = FixedThresholdClassifier(make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)))
|
|
321
|
+
|
|
322
|
+
optimizer = HyperparameterOptimizer(
|
|
323
|
+
obj_func=model,
|
|
324
|
+
params={"estimator__logisticregression__C": [], "threshold": []},
|
|
325
|
+
scoring=["precision", "recall"],
|
|
326
|
+
cv=3
|
|
327
|
+
)
|
|
328
|
+
pareto_front, population, history = optimizer.optimizeNSGA2(X, y, popSize=16, maxIter=10,
|
|
329
|
+
bounds=[(0.001, 10.0), (0.05, 0.99)])
|
|
330
|
+
|
|
331
|
+
for point in pareto_front:
|
|
332
|
+
print(point["scores"], point["params"])
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
Accuracy against training time works the same way: `scoring=["accuracy", "fit_time"]`.
|
|
336
|
+
|
|
337
|
+
---
|
|
338
|
+
|
|
339
|
+
## 🧠 How It Works
|
|
340
|
+
|
|
341
|
+
This library leverages four optimization techniques—**Particle Swarm Optimization (PSO), Pattern Search (PS), a Genetic Algorithm (GA), and NSGA-II**—to explore the hyperparameter space effectively.
|
|
342
|
+
|
|
343
|
+
Particle Swarm Optimization simulates a group of particles (candidate solutions) moving through the search space. Each particle adjusts its position based on its own best-known position and the best-known position among its peers, enabling a balance between exploration and exploitation as the swarm converges toward an optimal solution.
|
|
344
|
+
|
|
345
|
+
Pattern Search is a derivative-free method that explores the neighborhood of a current solution by systematically evaluating a set of search directions. If an improved solution is found, the algorithm moves in that direction and repeats the process, enabling efficient local refinement without relying on gradient information.
|
|
346
|
+
|
|
347
|
+
A Genetic Algorithm evolves a population of candidate solutions over generations. The fittest candidates are chosen as parents by tournament selection, their hyperparameter values are combined through crossover and randomly perturbed through mutation, and the best candidates are carried over unchanged (elitism), so the population steadily moves toward better regions of the search space.
|
|
348
|
+
|
|
349
|
+
NSGA-II (Non-dominated Sorting Genetic Algorithm II) extends the genetic algorithm to several objectives at once. Instead of a single score, candidates are ranked into Pareto fronts by non-dominated sorting, and ties within a front are broken by crowding distance, which favors candidates in sparsely covered regions. Parents and children compete together each generation (elitism), so the population converges to a well-spread approximation of the Pareto front.
|
|
350
|
+
|
|
351
|
+
Together, these methods provide robust global and local search capabilities for hyperparameter tuning.
|
|
352
|
+
|
|
353
|
+
---
|
|
354
|
+
|
|
355
|
+
## 🤝 Contributing
|
|
356
|
+
|
|
357
|
+
Pull requests are welcome.
|
|
358
|
+
For major changes, please open an issue first to discuss what you would like to change.
|
|
359
|
+
|
|
360
|
+
---
|
|
361
|
+
|
|
362
|
+
## 📫 Contact
|
|
363
|
+
|
|
364
|
+
For feedback, bugs, or collaboration ideas:
|
|
365
|
+
|
|
366
|
+
- **GitHub**: [@real-ahmed-moussa](https://github.com/real-ahmed-moussa)
|
|
367
|
+
|
|
368
|
+
---
|
|
369
|
+
|
|
370
|
+
## ⭐️ Show Your Support
|
|
371
|
+
|
|
372
|
+
If you find this project useful, consider giving it a ⭐️ on [GitHub](https://github.com/real-ahmed-moussa/hyperparameter-optimizer)!
|
|
373
|
+
|
|
374
|
+
---
|
|
375
|
+
|
|
376
|
+
## 📜 License
|
|
377
|
+
|
|
378
|
+
This project is licensed under the **MIT License**.
|
|
379
|
+
© 2025 **Dr. Ahmed Moussa**
|