forked from hyperactive-project/Hyperactive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom_search_example.py
More file actions
57 lines (47 loc) · 1.93 KB
/
Copy pathrandom_search_example.py
File metadata and controls
57 lines (47 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
Random Search Example - Pure Random Sampling
Random search is one of the simplest optimization algorithms that samples parameters
randomly from the defined search space. Despite its simplicity, it's surprisingly
effective for many hyperparameter optimization tasks and serves as an excellent
baseline for comparison with more sophisticated algorithms.
Characteristics:
- No learning or adaptation between trials
- Uniform sampling from the search space
- Excellent baseline for comparison
- Works well in high-dimensional spaces
- Parallel-friendly (no dependencies between trials)
"""
import numpy as np
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from hyperactive.experiment.integrations import SklearnCvExperiment
from hyperactive.opt.gfo import RandomSearch
# Load dataset
X, y = load_wine(return_X_y=True)
print(f"Dataset: Wine classification ({X.shape[0]} samples, {X.shape[1]} features)")
# Create experiment
estimator = RandomForestClassifier(random_state=42)
experiment = SklearnCvExperiment(estimator=estimator, X=X, y=y, cv=3)
# Define search space
search_space = {
"n_estimators": list(range(10, 201, 10)), # Discrete integer values (reduced for speed)
"max_depth": list(range(1, 21)), # Discrete integer values
"min_samples_split": list(range(2, 21)), # Discrete integer values
"min_samples_leaf": list(range(1, 11)), # Discrete integer values
}
# Configure RandomSearch optimizer
optimizer = RandomSearch(
search_space=search_space,
n_iter=30,
random_state=42,
experiment=experiment
)
# Run optimization
# Random search samples each parameter independently and uniformly
# from its defined range or choices, making it simple but effective
best_params = optimizer.solve()
# Results
print("\n=== Results ===")
print(f"Best parameters: {best_params}")
print("Optimization completed successfully")