hyperparameter-optimizer 0.1.0__py3-none-any.whl → 0.1.2__py3-none-any.whl

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.
@@ -1,24 +1,25 @@
1
1
  # Import Libraries
2
2
  from sklearn.model_selection import KFold, cross_val_score
3
+ import itertools
3
4
  import numpy as np
4
5
  import time
5
6
 
6
7
 
7
- """ [1] Defining the Optimization Main Class """
8
- """ ---------------------------------------- """
8
+ """ [1] Define the Core Hyperparameter Optimization Class """
9
9
  class HyperparameterOptimizer:
10
10
 
11
+ # [1] Initialization Method
11
12
  def __init__(self, obj_func, params, scoring, opt_type="max", cv=5, verbose=1):
12
13
  """
13
- The function defines a HyperparameterOptimizer instance.
14
-
15
- Inputs:
16
- obj_func: The machine learning model or pipeline being created.
17
- opt_type (str): Type of optimization: "max" for maximization (default) or "min" for minimization.
18
- params (dict): A dictionary of parameters for which the model is to be optimized.
19
- scoring (str): The method based on which the machine learning model is evaluated.
20
- cv (int): The number of cross-validation splits.
21
- verbose (int): A binary with a value of 1 (default) to show iteration information.
14
+ Initialize the HyperparameterOptimizer class with configuration settings.
15
+
16
+ Args:
17
+ obj_func: The machine learning model or pipeline to be optimized.
18
+ params (dict): Dictionary of hyperparameters and their search ranges.
19
+ scoring (str): Performance metric for evaluation.
20
+ opt_type (str): Optimization mode - "max" for maximization or "min" for minimization.
21
+ cv (int): Number of cross-validation folds.
22
+ verbose (int): Flag for verbosity (1 to enable logging).
22
23
  """
23
24
 
24
25
  self.obj_func = obj_func
@@ -29,9 +30,10 @@ class HyperparameterOptimizer:
29
30
  self.verbose = verbose
30
31
 
31
32
 
32
- def optimizePS(self, features, target, nParticles, bounds, w=0.5, c1=1, c2=1, maxIter=20, mutation_prob=0.1):
33
+ # [2] Particle Swarm Optimization Method
34
+ def optimizePSO(self, features, target, nParticles, bounds, w=0.5, c1=1, c2=1, maxIter=20, mutation_prob=0.1):
33
35
  """
34
- The function utilizes Particle Swarm (PS) optimization for finding the optimal values of the machine learning (ML) algorithm/pipeline hyperparameters.
36
+ The function utilizes Particle Swarm (PSO) optimization for finding the optimal values of the machine learning (ML) algorithm/pipeline hyperparameters.
35
37
 
36
38
  Args:
37
39
  features: A dataset containing the input features for the ML algorithm/pipeline.
@@ -39,16 +41,16 @@ class HyperparameterOptimizer:
39
41
  nParticles (int): The number of particles in the swarm.
40
42
  bounds (1darray): The bounds of the hyperparameter values [(x1_min, x1_max), (x2_min, x2_max), ... ]. The array dimension should be equal to the number of hyperparameters.
41
43
  w (float): The inertia weight.
42
- c1 (float): The cognitive weight.
43
- c2 (float): The social weight.
44
- maxIter (int): The maximum number of iterations.
45
- mutation_prob (float): The probability of mutation for non-numeric hyperparameters.
44
+ c1 (float): The cognitive component weight.
45
+ c2 (float): The social component weight.
46
+ maxIter (int): The maximum number of optimization iterations.
47
+ mutation_prob (float): The probability of mutation for categorical parameters.
46
48
 
47
49
  Outputs:
48
- population (Dataframe): The population used in the algorithm with their locations and values.
49
- Gbest_historry (ndarray): Values of optimal solutions in all the iterations.
50
- Gbest_pos (ndarray): The position of the optimal solution.
51
- Gbest_score (float): The score of the optimal solution.
50
+ population (Dataframe): The population used in the algorithm including their positions and values.
51
+ best_history (ndarray): Values of optimal solutions in all the iterations.
52
+ best_pos (ndarray): The position of the optimal solution.
53
+ best_score (float): The score of the optimal solution.
52
54
  """
53
55
 
54
56
  # 1. Start Optimization Time Recording
@@ -58,12 +60,13 @@ class HyperparameterOptimizer:
58
60
 
59
61
  # 2. Initialize Gbest Position and Score
60
62
  print("Initializing Global Best Position and Score . . .")
61
- Gbest_pos = None # Temporary Position of the Global Best Solution
62
- if self.opt_type=="max": # Maximization Problem
63
+ Gbest_pos = None # Temporary Position of the Global Best Solution
64
+ if self.opt_type=="max": # Maximization Problem
63
65
  Gbest_score = -1 * np.inf
64
- else: # Minimization Problem
66
+ else: # Minimization Problem
65
67
  Gbest_score = np.inf
66
68
 
69
+
67
70
  # 3. Initialize Particles
68
71
  print("Initializing Swarm Particles . . .")
69
72
  bounds = np.array(bounds, dtype=object)
@@ -92,19 +95,21 @@ class HyperparameterOptimizer:
92
95
  }
93
96
  particles.append(particle)
94
97
  # Update Gbest Position and Score
95
- if (score > Gbest_score) and (self.opt_type=="max"): # Maximization Problem
98
+ if (score > Gbest_score) and (self.opt_type=="max"): # Maximization Problem
96
99
  Gbest_pos = position
97
100
  Gbest_score = score
98
- elif (score < Gbest_score) and (self.opt_type=="min"): # Minimization Problem
101
+ elif (score < Gbest_score) and (self.opt_type=="min"): # Minimization Problem
99
102
  Gbest_pos = position
100
103
  Gbest_score = score
101
-
104
+
105
+
102
106
  # 4. Record Iterations' Optimal Gbest Values and Set Variable Values
103
- Gbest_history = [] # Keep Track of Objective Function Value of Each Iteration
107
+ Gbest_history = [] # Keep Track of Objective Function Value of Each Iteration
104
108
 
105
109
  # 4.1. Initialize Iterator
106
110
  iterator = 0
107
111
 
112
+
108
113
  # 5. Optimization Main Loop
109
114
  print("Starting Optimization Main Loop . . .")
110
115
  while iterator < maxIter:
@@ -122,39 +127,39 @@ class HyperparameterOptimizer:
122
127
  # 5.2.2. Update Velocity and Position
123
128
  for i in range(len(particle['position'])):
124
129
 
125
- if isinstance(bounds[i], (list, np.ndarray)): # Non-numeric types (strings, booleans, lists)
126
- # Skip velocity update for non-numeric types
127
- new_velocity[i] = 0 # Reset velocity to 0
130
+ if isinstance(bounds[i], (list, np.ndarray)): # Non-numeric Types (strings, booleans, lists)
131
+ # Skip Velocity Update for Non-numeric Types
132
+ new_velocity[i] = 0 # Reset Velocity to 0
128
133
 
129
- # Update position by randomly selecting a new value from the list
130
- if np.random.rand() < mutation_prob: # Apply mutation with probability
134
+ # Update Position by Randomly Selecting a New Value from the List
135
+ if np.random.rand() < mutation_prob: # Apply Mutation with Probability
131
136
  new_position[i] = np.random.choice(bounds[i])
132
137
  else:
133
- new_position[i] = particle['position'][i] # Keep the current value
138
+ new_position[i] = particle['position'][i] # Keep the Current Value
134
139
 
135
140
  else:
136
- # Calculate cognitive and social components
141
+ # Calculate Cognitive and Social Components
137
142
  r1, r2 = np.random.rand(2)
138
143
  cognitive = c1 * r1 * (particle['best_position'][i] - particle['position'][i])
139
144
  social = c2 * r2 * (Gbest_pos[i] - particle['position'][i])
140
145
 
141
- # Update velocity
146
+ # Update Velocity
142
147
  new_velocity[i] = w * particle['velocity'][i] + cognitive + social
143
148
 
144
- # Clip velocity to bounds
149
+ # Clip velocity to Bounds
145
150
  if isinstance(bounds[i][0], float) or isinstance(bounds[i][1], float): # Float range
146
151
  new_velocity[i] = np.clip(new_velocity[i], -np.abs(bounds[i][1] - bounds[i][0]), np.abs(bounds[i][1] - bounds[i][0]))
147
- else: # Integer range
152
+ else: # Integer Range
148
153
  new_velocity[i] = np.clip(new_velocity[i], -np.abs(bounds[i][1] - bounds[i][0]), np.abs(bounds[i][1] - bounds[i][0]))
149
154
  new_velocity[i] = int(new_velocity[i])
150
155
 
151
- # Update position
156
+ # Update Position
152
157
  new_position[i] = particle['position'][i] + new_velocity[i]
153
158
 
154
- # Clip position to bounds
155
- if isinstance(bounds[i][0], float) or isinstance(bounds[i][1], float): # Float range
159
+ # Clip Position to Bounds
160
+ if isinstance(bounds[i][0], float) or isinstance(bounds[i][1], float): # Float Range
156
161
  new_position[i] = np.clip(new_position[i], bounds[i][0], bounds[i][1])
157
- else: # Integer range
162
+ else: # Integer Range
158
163
  new_position[i] = np.clip(new_position[i], bounds[i][0], bounds[i][1])
159
164
  new_position[i] = int(new_position[i])
160
165
 
@@ -167,18 +172,18 @@ class HyperparameterOptimizer:
167
172
  score = self.eval_objfunc(particle['position'], features, target)
168
173
 
169
174
  # 5.2.4. Update Pbest
170
- if (score > particle['best_score']) and (self.opt_type=="max"): # Maximization Problem
175
+ if (score > particle['best_score']) and (self.opt_type=="max"): # Maximization Problem
171
176
  particle['best_score'] = score
172
177
  particle['best_position'] = particle['position'].copy()
173
- elif (score < particle['best_score']) and (self.opt_type=="min"): # Minimization Problem
178
+ elif (score < particle['best_score']) and (self.opt_type=="min"): # Minimization Problem
174
179
  particle['best_score'] = score
175
180
  particle['best_position'] = particle['position'].copy()
176
181
 
177
182
  # 5.2.5. Update Gbest
178
- if (score > Gbest_score) and (self.opt_type=="max"): # Maximization Problem
183
+ if (score > Gbest_score) and (self.opt_type=="max"): # Maximization Problem
179
184
  Gbest_pos = particle['position'].copy()
180
185
  Gbest_score = score
181
- elif (score < Gbest_score) and (self.opt_type=="min"): # Minimization Problem
186
+ elif (score < Gbest_score) and (self.opt_type=="min"): # Minimization Problem
182
187
  Gbest_pos = particle['position'].copy()
183
188
  Gbest_score = score
184
189
 
@@ -192,24 +197,26 @@ class HyperparameterOptimizer:
192
197
  print("Corresponding Optimum: {}".format(Gbest_score))
193
198
  print("------")
194
199
 
200
+
195
201
  # 6. Storing Optimization Variables in a Dictionary
196
- self.PS_attritbutes = {
197
- "Number of Iterations": iterator,
198
- "Number of Particles": nParticles,
199
- "Inertia Weight": w,
200
- "Cognitive Weight": c1,
201
- "Social Weight": c2
202
+ self.PSO_attritbutes = {
203
+ "Number of Iterations": iterator,
204
+ "Number of Particles": nParticles,
205
+ "Inertia Weight": w,
206
+ "Cognitive Weight": c1,
207
+ "Social Weight": c2
202
208
  }
203
209
 
210
+
204
211
  # 7. Storing Optimization Results in Callable Variables
205
- self.PS_Particles = particles
206
- self.PS_iterOptSols = {
207
- "Iterations' Index": np.arange(1, iterator+1),
208
- "Iteration's Optimum Value": Gbest_history
212
+ self.PSO_Particles = particles
213
+ self.PSO_iterOptSols = {
214
+ "Iterations' Index": np.arange(1, iterator+1),
215
+ "Iteration's Optimum Value": Gbest_history
209
216
  }
210
- self.PS_finalOptimalSol = {
211
- "Optimal Solution Variables' Values": Gbest_pos,
212
- "Optimal Solution Value": Gbest_score
217
+ self.PSO_finalOptimalSol = {
218
+ "Optimal Solution Variables' Values": Gbest_pos,
219
+ "Optimal Solution Value": Gbest_score
213
220
  }
214
221
 
215
222
  # Print a Closure Message
@@ -220,9 +227,235 @@ class HyperparameterOptimizer:
220
227
 
221
228
 
222
229
  return particles, Gbest_history, Gbest_pos, Gbest_score
223
-
224
230
 
225
- # Objective Function Evaluation Function
231
+
232
+ # [3] Pattern Search Optimization
233
+ def optimizePS(self, features, target, bounds, mesh_size_coeff, acc_coeff, contr_coeff, search_method='gps', min_mesh_ratio=0.001, maxIter=20):
234
+ """
235
+ The function utilizes Particle Swarm (PS) optimization for finding the optimal values of the machine learning (ML) algorithm/pipeline hyperparameters.
236
+
237
+ Args:
238
+ features: A dataset containing the input features for the ML algorithm/pipeline.
239
+ target: The target variable of the ML algorithm/pipeline.
240
+ bounds (1darray): The bounds of the hyperparameter values [(x1_min, x1_max), (x2_min, x2_max), ... ]. The array dimension should be equal to the number of hyperparameters.
241
+ mesh_size_coeff (float): The mesh size coefficient. For each dimension x_n, (1) when mesh_size_coeff >= 1: mesh_size_n = mesh_size_coeff * x_n_min
242
+ (2) when mesh_size_coeff < 1: mesh_size_n = mesh_size_coeff * x_n_max
243
+ acc_coeff (float): The acceleration/mesh expansion coefficient.
244
+ contr_coeff (float): The mesh contraction coefficient. Between [0, 1] and determines the percentage by which the mesh_size will be reduced if no better solutions are found.
245
+ search_method (str): 'gps' for Generalized Pattern Search (in all directions).
246
+ 'mads' for Mesh Adaptive Direct Search (in positive and all-negative directions).
247
+ min_mesh_ratio (float): Minimum mesh size as a percentage of parameter range.
248
+ maxIter (int): The maximum number of iterations.
249
+
250
+ Outputs:
251
+ best_history (ndarray): Values of optimal solutions in all the iterations.
252
+ best_pos (ndarray): The position of the optimal solution.
253
+ best_score (float): The score of the optimal solution.
254
+ """
255
+
256
+ # 1. Start Optimization Time Recording
257
+ print("Pattern Search hyperparameter optimization has started . . .")
258
+ start_time = time.time()
259
+
260
+
261
+ # 2. Initialize Best Position and Score
262
+ best_pos = None # Temporary Position of the Global Best Solution
263
+ if self.opt_type=="max": # Maximization Problem
264
+ best_score = -1 * np.inf
265
+ else: # Minimization Problem
266
+ best_score = np.inf
267
+
268
+
269
+ # 3. Initialize the Algorithm
270
+ print("Initializing Pattern Search . . .")
271
+
272
+ # 3.2. Define Initial Mesh Size
273
+ mesh_size = np.array([
274
+ 1 if isinstance(b, (list, np.ndarray)) else # If it's a list or array, assign a value of 1 to mesh size
275
+ (mesh_size_coeff*b[0] if mesh_size_coeff>=1 else mesh_size_coeff*b[1]) if isinstance(b[0], float) or isinstance(b[1], float) else # If it's a tuple of floats, treat as float range
276
+ int(mesh_size_coeff*b[0] if mesh_size_coeff>=1 else mesh_size_coeff*b[1]) # If it's a tuple of integers, treat as integer range
277
+ for b in bounds
278
+ ], dtype=object)
279
+
280
+ # 3.3. Initialize Base Point
281
+ base_point_pos = np.array([
282
+ np.random.choice(b) if isinstance(b, (list, np.ndarray)) else # If it's a list or array, choose randomly from it
283
+ np.random.uniform(b[0], b[1]) if isinstance(b[0], float) or isinstance(b[1], float) else # If it's a tuple of floats, treat as float range
284
+ np.random.randint(b[0], b[1] + 1) # If it's a tuple of integers, treat as integer range
285
+ for b in bounds
286
+ ], dtype=object)
287
+ base_point_score = self.eval_objfunc(base_point_pos, features, target)
288
+
289
+ # 3.4. Update Best Position and Score
290
+ best_pos, best_score = base_point_pos.copy(), base_point_score
291
+
292
+
293
+ # 4. Record Iterations' Optimal Gbest Values and Set Variable Values
294
+ best_history = [] # Keep Track of Objective Function Value of Each Iteration
295
+
296
+ # 4.1. Initialize Iterator
297
+ iterator = 0
298
+
299
+
300
+ # 5. Optimization Main Loop
301
+ print("Starting Optimization Main Loop . . .")
302
+ while iterator < maxIter:
303
+
304
+ # 5.1. Setting the Actual Number of Iterations Variable
305
+ iterator += 1
306
+ improved = False
307
+
308
+ # 5.2. Generate Pattern Vectors
309
+ pattern_vectors = []
310
+ for i, b in enumerate(bounds):
311
+ if isinstance(b, (list, np.ndarray)): # Categorical Parameter
312
+ current_idx = list(b).index(base_point_pos[i])
313
+ pattern_vectors.append([
314
+ (i, 1), # Next option
315
+ (i, -1) # Previous option
316
+ ])
317
+ else: # Numerical Parameter
318
+ if search_method == 'mads':
319
+ # MADS: Positive and Fully Negative Directions
320
+ pattern_vectors.append([0, 1])
321
+ else:
322
+ # GPS: Positive and Negative Vectors
323
+ pattern_vectors.append([-1, 0, 1])
324
+
325
+ # 5.3. Generate All Directions
326
+ all_directions = []
327
+ if search_method == 'mads':
328
+ positive_directions = list(itertools.product(*[[0, 1] if not isinstance(b, (list, np.ndarray)) else [0, 1] for b in bounds]))
329
+ positive_directions = [d for d in positive_directions if sum(d) == 1] # Only unit vectors
330
+ negative_direction = tuple([-1 if not isinstance(b, (list, np.ndarray)) else 0 for b in bounds])
331
+ all_directions = positive_directions + [negative_direction]
332
+ else:
333
+ all_directions = list(itertools.product(*[[-1, 0, 1] if not isinstance(b, (list, np.ndarray)) else [-1, 0, 1] for b in bounds]))
334
+ all_directions = [d for d in all_directions if sum(abs(x) for x in d) == 1] # Only unit vectors
335
+
336
+ # 5.4. Add Categorical Directions (replace numerical 0s with categorical moves)
337
+ final_directions = []
338
+ for direction in all_directions:
339
+ final_dir = []
340
+ cat_moves = []
341
+ has_numerical_move = False
342
+
343
+ for dim, move in enumerate(direction):
344
+ if isinstance(bounds[dim], (list, np.ndarray)): # Categorical
345
+ if move != 0:
346
+ cat_moves.append((dim, 1 if move > 0 else -1))
347
+ final_dir.append(0) # Placeholder
348
+ else: # Numerical
349
+ final_dir.append(move)
350
+ if move != 0:
351
+ has_numerical_move = True
352
+
353
+ if cat_moves and not has_numerical_move:
354
+ # Pure Categorical Move
355
+ for cat_dim, delta in cat_moves:
356
+ new_dir = final_dir.copy()
357
+ new_dir[cat_dim] = delta
358
+ final_directions.append(tuple(new_dir))
359
+ else:
360
+ # Numerical or Mixed Move
361
+ final_directions.append(tuple(final_dir))
362
+
363
+ final_directions = list(set([d for d in final_directions if any(x != 0 for x in d)]))
364
+
365
+ # 5.5. Evaluate All Directions
366
+ for direction in final_directions:
367
+ trial = base_point_pos.copy()
368
+ for dim, move in enumerate(direction):
369
+ if isinstance(bounds[dim], (list, np.ndarray)): # Categorical
370
+ if move != 0:
371
+ options = bounds[dim]
372
+ current_idx = list(options).index(trial[dim])
373
+ trial[dim] = options[(current_idx + move) % len(options)]
374
+ else: # Numerical
375
+ trial[dim] += mesh_size[dim] * move
376
+ # Enforce Bounds
377
+ if isinstance(bounds[dim][0], float):
378
+ trial[dim] = float(np.clip(trial[dim], *bounds[dim]))
379
+ else:
380
+ trial[dim] = int(np.clip(round(trial[dim]), *bounds[dim]))
381
+
382
+ score = self.eval_objfunc(trial, features, target)
383
+
384
+ # Check for Improvement
385
+ if (self.opt_type == "max" and score > best_score) or (self.opt_type == "min" and score < best_score):
386
+ best_score = score
387
+ best_pos = trial.copy()
388
+ base_point_pos = trial.copy()
389
+ improved = True
390
+
391
+ # 5.6. Update Mesh Size
392
+ if improved:
393
+ base_point_pos = best_pos.copy()
394
+ for i, b in enumerate(bounds):
395
+ if not isinstance(b, (list, np.ndarray)): # Numerical Only
396
+ mesh_size[i] *= acc_coeff
397
+ mesh_size[i] = min(mesh_size[i], (b[1] - b[0])) # Cap to Parameter Range
398
+ else:
399
+ for i, b in enumerate(bounds):
400
+ if not isinstance(b, (list, np.ndarray)): # Numerical Only
401
+ mesh_size[i] *= contr_coeff
402
+ if isinstance(b[0], float):
403
+ mesh_size[i] = max(mesh_size[i], 1e-6 * (b[1] - b[0]))
404
+ else:
405
+ mesh_size[i] = max(1, int(round(mesh_size[i])))
406
+
407
+ best_history.append(best_score)
408
+
409
+ # 5.7. Early Stopping
410
+ should_stop = True
411
+ for i, b in enumerate(bounds):
412
+ if not isinstance(b, (list, np.ndarray)):
413
+ param_range = b[1] - b[0]
414
+ if mesh_size[i] > min_mesh_ratio * param_range:
415
+ should_stop = False
416
+ break
417
+ if should_stop:
418
+ print(f"Stopping early: Mesh size < {min_mesh_ratio*100:.1f}% of parameter range.")
419
+ break
420
+
421
+ # 5.8. Printing
422
+ if self.verbose == 1:
423
+ print("Iteration #{}".format(iterator))
424
+ print("Corresponding Optimal Solution: {}".format(best_score))
425
+ print("Corresponding Optimum: {}".format(best_pos))
426
+ print("------")
427
+
428
+
429
+ # 6. Storing Optimization Variables in a Dictionary
430
+ self.PS_attritbutes = {
431
+ "Mesh Size Coefficient": mesh_size_coeff,
432
+ "Acceleration Coefficient": acc_coeff,
433
+ "Contraction Coefficient": contr_coeff,
434
+ "Search Method": search_method
435
+ }
436
+
437
+
438
+ # 7. Storing Optimization Results in Callable Variables
439
+ self.PS_iterOptSols = {
440
+ "Iterations' Index": np.arange(1, iterator+1),
441
+ "Iteration's Optimum Value": best_history
442
+ }
443
+ self.PS_finalOptimalSol = {
444
+ "Optimal Solution Variables' Values": best_pos,
445
+ "Optimal Solution Value": best_score
446
+ }
447
+
448
+
449
+ # 8. Print a Closure Message
450
+ end_time = time.time()
451
+ total_exec_time = end_time - start_time
452
+ print("Optimization Finished Successfully!")
453
+ print("Optimization Concluded in {} Seconds.".format(np.round(total_exec_time,3)))
454
+
455
+ return best_history, best_pos, best_score
456
+
457
+
458
+ # [4] Objective Function Evaluation Function
226
459
  def eval_objfunc(self, dec_vars, features, target):
227
460
  """
228
461
  The function is used to evaluate the objective function value in a Genetic Algorithm optimization process.
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.4
2
+ Name: hyperparameter-optimizer
3
+ Version: 0.1.2
4
+ Summary: A lightweight Python library for hyperparameter tuning using Metaheuristic algorithms.
5
+ Home-page: https://github.com/real-ahmed-moussa/hyperparameter-optimizer
6
+ Author: Dr. Ahmed Moussa
7
+ Author-email: ahmedyosrihamdy@gmail.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Requires-Python: >=3.7
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: numpy
16
+ Requires-Dist: scikit-learn
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: license
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ # Hyperparameter Optimizer
29
+
30
+ A lightweight and flexible Python library for hyperparameter tuning using metaheuristic techniques.
31
+ Currently, the library includes **Particle Swarm Optimization (PSO)** and **Pattern Search (PS)** only.
32
+
33
+ Designed for Scikit-learn-compatible models, this package offers an easy-to-use interface for optimizing model performance in just a few lines.
34
+
35
+ ![PyPI version](https://img.shields.io/pypi/v/hyperparameter-optimizer.svg)
36
+ ![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)
37
+ [![Downloads](https://static.pepy.tech/personalized-badge/hyperparameter-optimizer?period=total&units=international_system&left_color=grey&right_color=blue&left_text=Downloads)](https://pepy.tech/project/hyperparameter-optimizer)
38
+
39
+ ---
40
+
41
+ ## 📦 Installation
42
+
43
+ Install from PyPI:
44
+
45
+ ```bash
46
+ pip install hyperparameter-optimizer
47
+ ```
48
+
49
+ ---
50
+
51
+ ## ⚙️ Features
52
+
53
+ - ✅ Metaheuristic optimization using Particle Swarm Optimization (PSO) and Pattern Search (PS)
54
+ - ✅ Supports continuous, integer, and categorical hyperparameters
55
+ - ✅ Compatible with any Scikit-learn estimator
56
+ - ✅ Custom scoring metrics
57
+ - ✅ Cross-validation built-in
58
+ - ✅ Verbose logging and full traceability
59
+
60
+ ---
61
+
62
+ ## 📚 API Reference
63
+
64
+ ### `HyperparameterOptimizer`
65
+
66
+ ```python
67
+ HyperparameterOptimizer(
68
+ obj_func, # machine learning model or pipeline being created
69
+ params, # dictionary of parameters for which the model is to be optimized.
70
+ scoring, # scoring metric (e.g., 'accuracy')
71
+ opt_type="max", # type of optimization: "max" for maximization (default) or "min" for minimization.
72
+ cv=5, # number of cross-validation folds
73
+ verbose=1 # binary with a value of 1 (default) to show iteration information.
74
+ )
75
+ ```
76
+
77
+ ### `optimizePSO`
78
+
79
+ ```python
80
+ optimizePSO(
81
+ features, # training features.
82
+ target, # training target.
83
+ nParticles, # number of particles in the swarm.
84
+ bounds, # list of (min, max) tuples or a categorical list of choices.
85
+ # if either min/max is non-integer, the algorithm shall consider them as floats (i.e., continuous).
86
+ w=0.5, # inertia weight.
87
+ c1=1, # cognitive weight.
88
+ c2=1, # social weight.
89
+ maxIter=20, # maximum number of iterations.
90
+ mutation_prob=0.1 # mtation probability -- for discrete hyperparameters.
91
+ )
92
+ ```
93
+
94
+ ### `optimizePS`
95
+
96
+ ```python
97
+ optimizePS(
98
+ features, # training features.
99
+ target, # training target.
100
+ bounds, # list of (min, max) tuples or a categorical list of choices.
101
+ # if either min/max is non-integer, the algorithm shall consider them as floats (i.e., continuous).
102
+ mesh_size_coeff=0.6, # mesh size coefficient.
103
+ acc_coeff=1, # acceleration/mesh expansion coefficient.
104
+ contr_coeff=0.5, # mesh contraction coefficient.
105
+ search_method="gps", # new points exploration method; either 'gps' or 'mads'.
106
+ min_mesh_ratio=0.001, # minimum mesh size as a percentage of parameter range.
107
+ maxIter=25 # maximum number of iterations.
108
+ )
109
+ ```
110
+
111
+ ---
112
+
113
+ ## 🚀 Quickstart
114
+
115
+ Here's a basic example of how to use **Hyperparameter Optimizer** with a Scikit-learn model (e.g., `RandomForestClassifier`):
116
+
117
+ ```python
118
+ from sklearn.datasets import load_iris
119
+ from sklearn.ensemble import RandomForestClassifier
120
+ from hyperparameter_optimizer import HyperparameterOptimizer
121
+
122
+ # Load data
123
+ X, y = load_iris(return_X_y=True)
124
+
125
+ # Define parameter space
126
+ param_space = {
127
+ 'n_estimators': [],
128
+ 'max_depth': [],
129
+ 'criterion': []
130
+ }
131
+
132
+ # Initialize the optimizer
133
+ optimizer = HyperparameterOptimizer(
134
+ obj_func=RandomForestClassifier(),
135
+ params=param_space,
136
+ scoring='accuracy',
137
+ opt_type='max',
138
+ cv=3,
139
+ verbose=1
140
+ )
141
+
142
+ # Run optimization
143
+ # [1] Particle Swarm Optimization
144
+ particles, Gbest_history, Gbest_pos, Gbest_score = optimizer.optimizePSO(
145
+ features = X,
146
+ target = y,
147
+ nParticles = 10,
148
+ bounds = [(10, 1000), (1, 10), ['gini', 'entropy']],
149
+ maxIter = 10
150
+ )
151
+ print("Best Params:", Gbest_pos)
152
+ print("Best Score:", Gbest_score)
153
+
154
+ # [2] Pattern Search Optimization
155
+ Gbest_history2, Gbest_pos2, Gbest_score2 = optimizer.optimizePS(
156
+ features = X,
157
+ target = y,
158
+ bounds = [(10, 1000), (1, 10), ['gini', 'entropy']],
159
+ mesh_size_coeff = 0.1,
160
+ acc_coeff = 1,
161
+ contr_coeff = 0.50,
162
+ maxIter = 10
163
+ )
164
+ print("Best Params:", Gbest_pos2)
165
+ print("Best Score:", Gbest_score2)
166
+
167
+ ```
168
+
169
+ ---
170
+
171
+ ## 🧠 How It Works
172
+
173
+ This library leverages two optimization techniques—**Particle Swarm Optimization (PSO) and Pattern Search (PS)**—to explore the hyperparameter space effectively.
174
+
175
+ 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.
176
+
177
+ 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.
178
+
179
+ Together, these methods provide robust global and local search capabilities for hyperparameter tuning.
180
+
181
+ ---
182
+
183
+ ## 📜 License
184
+
185
+ This project is licensed under the **MIT License**.
186
+ © 2025 **Dr. Ahmed Moussa**
187
+
188
+ ---
189
+
190
+ ## 🤝 Contributing
191
+
192
+ Pull requests are welcome.
193
+ For major changes, please open an issue first to discuss what you would like to change.
194
+
195
+ ---
196
+
197
+ ## 📫 Contact
198
+
199
+ For feedback, bugs, or collaboration ideas:
200
+
201
+ - **GitHub**: [@real-ahmed-moussa](https://github.com/real-ahmed-moussa)
202
+
203
+ ---
204
+
205
+ ## ⭐️ Show Your Support
206
+
207
+ If you find this project useful, consider giving it a ⭐️ on [GitHub](https://github.com/real-ahmed-moussa/hyperparameter-optimizer)!
@@ -0,0 +1,6 @@
1
+ hyperparameter_optimizer/__init__.py,sha256=BQf_vmBr5UUCjfE8_Y_V75Mkr7Xac3H5rDpq3-eakQc,41
2
+ hyperparameter_optimizer/core.py,sha256=o-9lam9HMNWBNiRquGThMZnCdTjeIkkzqf7-n3IC5-I,26803
3
+ hyperparameter_optimizer-0.1.2.dist-info/METADATA,sha256=AS1iFtxOyIII5lZcaWcATq3eFDnltuMlKJKhJCqOO0Q,8739
4
+ hyperparameter_optimizer-0.1.2.dist-info/WHEEL,sha256=A8Eltl-h0W-qZDVezsLjjslosEH_pdYC2lQ0JcbgCzs,91
5
+ hyperparameter_optimizer-0.1.2.dist-info/top_level.txt,sha256=25Wd1D1OIdKZRL6FVRsMpb2Xja1dwS0JNh0ealHxwAY,25
6
+ hyperparameter_optimizer-0.1.2.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (78.1.0)
2
+ Generator: setuptools (80.7.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,34 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: hyperparameter-optimizer
3
- Version: 0.1.0
4
- Summary: A lightweight Python library for hyperparameter tuning using Metaheuristic algorithms.
5
- Home-page: https://github.com/real-ahmed-moussa/hyperparameter-optimizer
6
- Author: Dr. Ahmed Moussa
7
- Author-email: ahmedyosrihamdy@example.com
8
- License: MIT
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Operating System :: OS Independent
12
- Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
- Requires-Python: >=3.7
14
- Description-Content-Type: text/markdown
15
- Requires-Dist: numpy
16
- Requires-Dist: scikit-learn
17
- Dynamic: author
18
- Dynamic: author-email
19
- Dynamic: classifier
20
- Dynamic: description
21
- Dynamic: description-content-type
22
- Dynamic: home-page
23
- Dynamic: license
24
- Dynamic: requires-dist
25
- Dynamic: requires-python
26
- Dynamic: summary
27
-
28
- # hyperparameter-optimizer
29
- A lightweight Python library for hyperparameter tuning using Metaheuristic algorithms.
30
-
31
- ## Installation
32
-
33
- ```bash
34
- pip install hyperparameter-optimizer
@@ -1,6 +0,0 @@
1
- hyperparameter_optimizer/__init__.py,sha256=BQf_vmBr5UUCjfE8_Y_V75Mkr7Xac3H5rDpq3-eakQc,41
2
- hyperparameter_optimizer/core.py,sha256=4rJHJHQnUQVYsfIKrVA4EulyxaqxmeijTPvkpOTuycI,13617
3
- hyperparameter_optimizer-0.1.0.dist-info/METADATA,sha256=9tYrc3cawnh55vSfiPET5btf7gUPLieP1EzikvPVebo,1038
4
- hyperparameter_optimizer-0.1.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
5
- hyperparameter_optimizer-0.1.0.dist-info/top_level.txt,sha256=25Wd1D1OIdKZRL6FVRsMpb2Xja1dwS0JNh0ealHxwAY,25
6
- hyperparameter_optimizer-0.1.0.dist-info/RECORD,,