forked from hyperactive-project/Hyperactive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid_sampler_example.py
More file actions
157 lines (135 loc) · 4.85 KB
/
Copy pathgrid_sampler_example.py
File metadata and controls
157 lines (135 loc) · 4.85 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"""
GridOptimizer Example - Exhaustive Grid Search
The GridOptimizer performs exhaustive search over a discretized parameter grid.
It systematically evaluates every combination of specified parameter values,
ensuring complete coverage but potentially requiring many evaluations.
Characteristics:
- Exhaustive search over predefined parameter grids
- Systematic and reproducible exploration
- Guarantees finding the best combination within the grid
- No learning or adaptation
- Best for small, discrete parameter spaces
- Interpretable and deterministic results
"""
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from hyperactive.experiment.integrations import SklearnCvExperiment
from hyperactive.opt.optuna import GridOptimizer
# Grid Search Methodology:
#
# 1. Parameter Discretization:
# - Each continuous parameter divided into discrete levels
# - Categorical parameters use all specified values
# - Creates n₁ × n₂ × ... × nₖ total combinations
#
# 2. Systematic Evaluation:
# - Every combination evaluated exactly once
# - No randomness or learning involved
# - Order of evaluation is deterministic
#
# 3. Optimality Guarantees:
# - Finds global optimum within the discrete grid
# - Quality depends on grid resolution
# - May miss optimal values between grid points
#
# 4. Computational Complexity:
# - Exponential growth with number of parameters
# - Curse of dimensionality for many parameters
# - Embarrassingly parallel
# === GridOptimizer Example ===
# Exhaustive Grid Search
# Load dataset - simple classification
X, y = load_iris(return_X_y=True)
print(f"Dataset: Iris classification ({X.shape[0]} samples, {X.shape[1]} features)")
# Create experiment
estimator = KNeighborsClassifier()
experiment = SklearnCvExperiment(estimator=estimator, X=X, y=y, cv=3)
# Define search space - DISCRETE values only for grid search
param_space = {
"n_neighbors": [1, 3, 5, 7, 11, 15, 21], # 7 values
"weights": ["uniform", "distance"], # 2 values
"metric": ["euclidean", "manhattan", "minkowski"], # 3 values
"p": [1, 2], # Only relevant for minkowski metric # 2 values
}
# Total combinations: 7 × 2 × 3 × 2 = 84 combinations
total_combinations = 1
for param, values in param_space.items():
total_combinations *= len(values)
# Search Space (Discrete grids only):
# for param, values in param_space.items():
# print(f" {param}: {values} ({len(values)} values)")
# Total combinations: calculated above
# Configure GridOptimizer
optimizer = GridOptimizer(
param_space=param_space,
n_trials=total_combinations, # Will evaluate all combinations
random_state=42, # For deterministic ordering
experiment=experiment,
)
# GridOptimizer Configuration:
# n_trials: matches total combinations
# search_space: automatically derived from param_space
# Systematic evaluation of every combination
# Run optimization
# Running exhaustive grid search...
best_params = optimizer.solve()
# Results
print("\n=== Results ===")
print(f"Best parameters: {best_params}")
print(f"Best score: {optimizer.best_score_:.4f}")
print()
# Grid Search Characteristics:
#
# Exhaustive Coverage:
# - Evaluated all parameter combinations
# - Guaranteed to find best configuration within grid
# - No risk of missing good regions
# Reproducibility:
# - Same grid → same results every time
# - Deterministic evaluation order
# - No randomness or hyperparameters
# Interpretability:
# - Easy to understand methodology
# - Clear relationship between grid density and accuracy
# - Results easily visualized and analyzed
# Grid Design Considerations:
#
# Parameter Value Selection:
# Include reasonable ranges for each parameter
# Use domain knowledge to choose meaningful values
# Consider logarithmic spacing for scale-sensitive parameters
# Start coarse, then refine around promising regions
#
# Computational Budget:
# Balance grid density with available compute
# Consider parallel evaluation to speed up
# Use coarse grids for initial exploration
#
# Best Use Cases:
# Small parameter spaces (< 6 parameters)
# Discrete/categorical parameters
# When exhaustive evaluation is feasible
# Baseline comparison for other methods
# When interpretability is crucial
# Parallel computing environments
#
# Limitations:
# Exponential scaling with parameter count
# May miss optimal values between grid points
# Inefficient for continuous parameters
# No adaptive learning or focusing
# Can waste evaluations in clearly bad regions
#
# Grid Search vs Other Methods:
#
# vs Random Search:
# + Systematic coverage guarantee
# + Reproducible results
# - Exponential scaling
# - Less efficient in high dimensions
#
# vs Bayesian Optimization:
# + No assumptions about objective function
# + Guaranteed to find grid optimum
# - Much less sample efficient
# - No learning from previous evaluations