hyperparameter-optimizer 0.1.0__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.
@@ -0,0 +1 @@
1
+ from .core import HyperparameterOptimizer
@@ -0,0 +1,260 @@
1
+ # Import Libraries
2
+ from sklearn.model_selection import KFold, cross_val_score
3
+ import numpy as np
4
+ import time
5
+
6
+
7
+ """ [1] Defining the Optimization Main Class """
8
+ """ ---------------------------------------- """
9
+ class HyperparameterOptimizer:
10
+
11
+ def __init__(self, obj_func, params, scoring, opt_type="max", cv=5, verbose=1):
12
+ """
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.
22
+ """
23
+
24
+ self.obj_func = obj_func
25
+ self.params = params
26
+ self.scoring = scoring
27
+ self.opt_type = opt_type
28
+ self.cv = cv
29
+ self.verbose = verbose
30
+
31
+
32
+ def optimizePS(self, features, target, nParticles, bounds, w=0.5, c1=1, c2=1, maxIter=20, mutation_prob=0.1):
33
+ """
34
+ The function utilizes Particle Swarm (PS) optimization for finding the optimal values of the machine learning (ML) algorithm/pipeline hyperparameters.
35
+
36
+ Args:
37
+ features: A dataset containing the input features for the ML algorithm/pipeline.
38
+ target: The target variable of the ML algorithm/pipeline.
39
+ nParticles (int): The number of particles in the swarm.
40
+ 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
+ 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.
46
+
47
+ 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.
52
+ """
53
+
54
+ # 1. Start Optimization Time Recording
55
+ print("PS hyperparameter optimization has started . . .")
56
+ start_time = time.time()
57
+
58
+
59
+ # 2. Initialize Gbest Position and Score
60
+ 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_score = -1 * np.inf
64
+ else: # Minimization Problem
65
+ Gbest_score = np.inf
66
+
67
+ # 3. Initialize Particles
68
+ print("Initializing Swarm Particles . . .")
69
+ bounds = np.array(bounds, dtype=object)
70
+ particles = []
71
+ for _ in range(nParticles):
72
+ position = np.array([
73
+ np.random.choice(b) if isinstance(b, (list, np.ndarray)) else # If it's a list or array, choose randomly from it
74
+ np.random.uniform(low=b[0], high=b[1]) if isinstance(b[0], float) or isinstance(b[1], float) else # If it's a tuple of floats, treat as float range
75
+ np.random.randint(low=b[0], high=b[1] + 1) # If it's a tuple of integers, treat as integer range
76
+ for b in bounds
77
+ ], dtype=object)
78
+
79
+ velocity = np.array([
80
+ np.random.choice(b) if isinstance(b, (list, np.ndarray)) else # If it's a list or array, choose randomly from it
81
+ np.random.uniform(low=-(b[1] - b[0]), high=(b[1] - b[0])) if isinstance(b[0], float) or isinstance(b[1], float) else # If it's a tuple of floats, treat as float range
82
+ np.random.randint(low=-(b[1] - b[0]), high=(b[1] - b[0]) + 1) # If it's a tuple of integers, treat as integer range
83
+ for b in bounds
84
+ ], dtype=object)
85
+
86
+ score = self.eval_objfunc(position, features, target)
87
+ particle = {
88
+ 'position': position,
89
+ 'velocity': velocity,
90
+ 'best_position': position.copy(),
91
+ 'best_score': score
92
+ }
93
+ particles.append(particle)
94
+ # Update Gbest Position and Score
95
+ if (score > Gbest_score) and (self.opt_type=="max"): # Maximization Problem
96
+ Gbest_pos = position
97
+ Gbest_score = score
98
+ elif (score < Gbest_score) and (self.opt_type=="min"): # Minimization Problem
99
+ Gbest_pos = position
100
+ Gbest_score = score
101
+
102
+ # 4. Record Iterations' Optimal Gbest Values and Set Variable Values
103
+ Gbest_history = [] # Keep Track of Objective Function Value of Each Iteration
104
+
105
+ # 4.1. Initialize Iterator
106
+ iterator = 0
107
+
108
+ # 5. Optimization Main Loop
109
+ print("Starting Optimization Main Loop . . .")
110
+ while iterator < maxIter:
111
+
112
+ # 5.1. Setting the Actual Number of Iterations Variable
113
+ iterator += 1
114
+
115
+ # 5.2. Update Particle Values
116
+ for particle in particles:
117
+
118
+ # 5.2.1. Initialize New Velocity and Position
119
+ new_velocity = np.zeros(len(particle['velocity']), dtype=object)
120
+ new_position = np.zeros(len(particle['position']), dtype=object)
121
+
122
+ # 5.2.2. Update Velocity and Position
123
+ for i in range(len(particle['position'])):
124
+
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
128
+
129
+ # Update position by randomly selecting a new value from the list
130
+ if np.random.rand() < mutation_prob: # Apply mutation with probability
131
+ new_position[i] = np.random.choice(bounds[i])
132
+ else:
133
+ new_position[i] = particle['position'][i] # Keep the current value
134
+
135
+ else:
136
+ # Calculate cognitive and social components
137
+ r1, r2 = np.random.rand(2)
138
+ cognitive = c1 * r1 * (particle['best_position'][i] - particle['position'][i])
139
+ social = c2 * r2 * (Gbest_pos[i] - particle['position'][i])
140
+
141
+ # Update velocity
142
+ new_velocity[i] = w * particle['velocity'][i] + cognitive + social
143
+
144
+ # Clip velocity to bounds
145
+ if isinstance(bounds[i][0], float) or isinstance(bounds[i][1], float): # Float range
146
+ 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
148
+ 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
+ new_velocity[i] = int(new_velocity[i])
150
+
151
+ # Update position
152
+ new_position[i] = particle['position'][i] + new_velocity[i]
153
+
154
+ # Clip position to bounds
155
+ if isinstance(bounds[i][0], float) or isinstance(bounds[i][1], float): # Float range
156
+ new_position[i] = np.clip(new_position[i], bounds[i][0], bounds[i][1])
157
+ else: # Integer range
158
+ new_position[i] = np.clip(new_position[i], bounds[i][0], bounds[i][1])
159
+ new_position[i] = int(new_position[i])
160
+
161
+ # Fully Update Particle's Velocity and Position
162
+ particle['velocity'] = new_velocity
163
+ particle['position'] = new_position
164
+
165
+
166
+ # 5.2.3. Evaluate New Position
167
+ score = self.eval_objfunc(particle['position'], features, target)
168
+
169
+ # 5.2.4. Update Pbest
170
+ if (score > particle['best_score']) and (self.opt_type=="max"): # Maximization Problem
171
+ particle['best_score'] = score
172
+ particle['best_position'] = particle['position'].copy()
173
+ elif (score < particle['best_score']) and (self.opt_type=="min"): # Minimization Problem
174
+ particle['best_score'] = score
175
+ particle['best_position'] = particle['position'].copy()
176
+
177
+ # 5.2.5. Update Gbest
178
+ if (score > Gbest_score) and (self.opt_type=="max"): # Maximization Problem
179
+ Gbest_pos = particle['position'].copy()
180
+ Gbest_score = score
181
+ elif (score < Gbest_score) and (self.opt_type=="min"): # Minimization Problem
182
+ Gbest_pos = particle['position'].copy()
183
+ Gbest_score = score
184
+
185
+ # 5.3. Record Gbest Score
186
+ Gbest_history.append(Gbest_score)
187
+
188
+ # 5.4. Printing
189
+ if self.verbose == 1:
190
+ print("Iteration #{}".format(iterator))
191
+ print("Corresponding Optimal Solution: {}".format(Gbest_pos))
192
+ print("Corresponding Optimum: {}".format(Gbest_score))
193
+ print("------")
194
+
195
+ # 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
+ }
203
+
204
+ # 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
209
+ }
210
+ self.PS_finalOptimalSol = {
211
+ "Optimal Solution Variables' Values": Gbest_pos,
212
+ "Optimal Solution Value": Gbest_score
213
+ }
214
+
215
+ # Print a Closure Message
216
+ end_time = time.time()
217
+ total_exec_time = end_time - start_time
218
+ print("Optimization Finished Successfully!")
219
+ print("Optimization Concluded in {} Seconds.".format(np.round(total_exec_time,3)))
220
+
221
+
222
+ return particles, Gbest_history, Gbest_pos, Gbest_score
223
+
224
+
225
+ # Objective Function Evaluation Function
226
+ def eval_objfunc(self, dec_vars, features, target):
227
+ """
228
+ The function is used to evaluate the objective function value in a Genetic Algorithm optimization process.
229
+
230
+ Inputs:
231
+ dec_vars (ndarray): A list of decision variables that represent the parameters to be optimized for the objective function.
232
+ features: A matrix of features that are used as inputs for the objective function.
233
+ target: A vector of target values that the objective function aims to predict.
234
+
235
+ Outputs:
236
+ cv_accuracy_score (float): Accuracy of the objective function.
237
+ """
238
+
239
+ # Defining Cross-validation Object
240
+ kf = KFold(n_splits=self.cv, shuffle=True, random_state=1)
241
+
242
+ # Augment the Pipeline with Parameters from Decision Variables
243
+ p_index = 0
244
+ for key, value in self.params.items():
245
+ if key in self.obj_func.get_params():
246
+ self.obj_func.set_params(**{key: dec_vars[p_index]})
247
+ p_index += 1
248
+
249
+ # Evaluate Objective Function Value through Cross-validation [Time Consuming!]
250
+ cv_accuracy_score = cross_val_score(
251
+ self.obj_func,
252
+ features,
253
+ target,
254
+ cv=kf,
255
+ scoring= self.scoring,
256
+ error_score="raise",
257
+ n_jobs=-1
258
+ ).mean()
259
+
260
+ return cv_accuracy_score
@@ -0,0 +1,34 @@
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
@@ -0,0 +1,6 @@
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,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (78.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ hyperparameter_optimizer