1
|
|
|
""" |
2
|
|
|
RandomSearchSk Optimizer Example |
3
|
|
|
|
4
|
|
|
This example demonstrates how to use the RandomSearchSk optimizer with |
5
|
|
|
sklearn integration and threading backend for parallel execution. |
6
|
|
|
""" |
7
|
|
|
|
8
|
|
|
import numpy as np |
9
|
|
|
from scipy.stats import uniform, randint |
10
|
|
|
from sklearn.datasets import load_iris |
11
|
|
|
from sklearn.svm import SVC |
12
|
|
|
from hyperactive.opt import RandomSearchSk |
13
|
|
|
from hyperactive.experiment.integrations import SklearnCvExperiment |
14
|
|
|
|
15
|
|
|
# Load iris dataset and create sklearn experiment |
16
|
|
|
X, y = load_iris(return_X_y=True) |
17
|
|
|
sklearn_experiment = SklearnCvExperiment( |
18
|
|
|
estimator=SVC(), |
19
|
|
|
X=X, |
20
|
|
|
y=y, |
21
|
|
|
) |
22
|
|
|
|
23
|
|
|
# Define parameter distributions for random search |
24
|
|
|
# Mix of discrete and continuous distributions |
25
|
|
|
param_distributions = { |
26
|
|
|
"C": uniform(loc=0.1, scale=10), # Continuous uniform distribution |
27
|
|
|
"gamma": ["scale", "auto"] + list(np.logspace(-4, 1, 20)), # Mixed discrete/continuous |
28
|
|
|
"kernel": ["rbf", "poly", "sigmoid"], # Discrete choices |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
# Random search with threading backend |
32
|
|
|
random_search = RandomSearchSk( |
33
|
|
|
param_distributions=param_distributions, |
34
|
|
|
n_iter=30, # Number of random samples |
35
|
|
|
random_state=42, # For reproducible results |
36
|
|
|
backend="threading", # Use threading backend for parallelization |
37
|
|
|
backend_params={ |
38
|
|
|
"n_jobs": 2, # Use 2 threads |
39
|
|
|
}, |
40
|
|
|
experiment=sklearn_experiment, |
41
|
|
|
) |
42
|
|
|
|
43
|
|
|
best_params = random_search.run() |
44
|
|
|
print(f"Best params: {best_params}, Score: {random_search.best_score_:.4f}") |
45
|
|
|
|