<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shedrach Igemhokhai on Medium]]></title>
        <description><![CDATA[Stories by Shedrach Igemhokhai on Medium]]></description>
        <link>https://medium.com/@i.v.shedrach?source=rss-a184a23f567a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F5ZgX2WbtN--Mj6SeTqKyw.jpeg</url>
            <title>Stories by Shedrach Igemhokhai on Medium</title>
            <link>https://medium.com/@i.v.shedrach?source=rss-a184a23f567a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:20:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@i.v.shedrach/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[IMPLEMENTATION OF GENETIC ALGORITHMS(GA) FOR ENHANCED MODEL PERFORMANCE AND OPTIMAL RESULTS]]></title>
            <link>https://medium.com/@i.v.shedrach/implementation-of-genetic-algorithms-ga-for-enhanced-model-performance-and-optimal-results-93c5e7a510d8?source=rss-a184a23f567a------2</link>
            <guid isPermaLink="false">https://medium.com/p/93c5e7a510d8</guid>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shedrach Igemhokhai]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 19:32:58 GMT</pubDate>
            <atom:updated>2023-08-13T22:19:59.381Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey data enthusiasts! In my previous article, i implemented Metaheuristics algorithms, which includes Genetic algorithm (GA) and Particle Swarm Optimization (PSO) for hyperparameters tuning, where i used support vector regression as a case study , and we achieved remarkable results doing that.<br>However, i got a valuable feedback, that it’d be more appreciable and relatable if we explain GA some more and also code it from scratch, because in the previous article, i used the popular MEALPY library.<br>So, the aim of this article is to :<br>1. <em>Code the genetic algorithm from scratch.</em><br>2. <em>Implement the coded GA in tuning and optimizing the hyperparameters of Random Forest Regressor.</em><br>3. <em>Apply the coded GA in finding the optimal combination of the input feature values in our dataset that would yield the optimal target value.</em></p><p>Sound exciting ? Let’s delve into it !</p><p><strong><em>What is Genetic Algorithm ?</em></strong></p><p>GAs work by creating a <strong>population </strong>of possible solutions, each encoded as a <strong>chromosome </strong>made of <strong>genes</strong>. Each solution is assigned a <strong>fitness score</strong> based on how well it solves the problem. The fittest solutions are then selected to <strong>mate </strong>and produce <strong>offspring </strong>that inherit some genes from each parent. The offspring may also undergo <strong>mutation</strong> to introduce some variation. The process is repeated until a desired number of generations or a satisfactory solution is reached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*biT2RO1tyr9rZxmxApPAKg.png" /><figcaption>Image Credit : Towardsdatascience.com</figcaption></figure><p><strong><em>How does Genetic Algorithms work ?</em></strong></p><p>A GA works by repeatedly applying the following steps:</p><ol><li><strong>Selection</strong>: The chromosomes in the population are evaluated according to their fitness, and the best-performing chromosomes are selected to be parents of the next generation.</li><li><strong>Crossover</strong>: The parents exchange genetic material to create new chromosomes. This process is called crossover.</li><li><strong>Mutation</strong>: Some of the chromosomes in the new generation may be mutated, which means that some of their genes are randomly changed. This process helps to introduce new genetic material into the population and prevents it from becoming stagnant.</li><li><strong>Replacement</strong>: The new generation of chromosomes replaces the old generation. This process continues until a solution that meets the given fitness function is found, or until a maximum number of generations has been reached.</li></ol><p><strong>How do genetic algorithms find good solutions?</strong></p><p>GAs find good solutions by taking advantage of the principle of natural selection. The fittest chromosomes in the population are more likely to be selected to be parents of the next generation, and their genes are more likely to be passed on to their offspring. This process ensures that the population of chromosomes gradually evolves towards better and better solutions.</p><p>Here’s a simple Mathematical Explanation of Crossover and Mutation:</p><ol><li>Crossover (Recombination): Given two parent individuals, crossover combines their genetic information to create new offspring. The crossover point determines where the genetic material is exchanged. Mathematically, this can be represented as:</li></ol><p>Offspring = Parent1[:crossover_point] + Parent2[crossover_point:]</p><p>2. Mutation: Mutation introduces small random changes to an individual’s genetic information to maintain diversity. For binary-coded individuals, mutation might flip bits. For real-coded individuals, mutation might add a small random value. Mathematically:</p><p>Mutated_Gene = Gene + Random_Value</p><p><strong><em>What are the advantages of genetic algorithms?</em></strong></p><p>GAs have a number of advantages over other optimization algorithms, including:</p><ul><li>They are able to find good solutions to problems that are difficult or impossible to solve with traditional optimization algorithms.</li><li>They are relatively easy to implement and use.</li><li>They are able to find solutions to problems with a large number of variables.</li><li>They are able to find solutions to problems with noisy or incomplete data.</li></ul><p><strong><em>What are the disadvantages of genetic algorithms?</em></strong></p><p>GAs also have some disadvantages, including:</p><ul><li>They can be computationally expensive to run.</li><li>They can be slow to converge to a good solution.</li><li>They can be sensitive to the choice of parameters.</li><li>They can be difficult to interpret and explain.</li></ul><p><strong><em>When should I use a genetic algorithm?</em></strong></p><p>GAs are a good choice for optimization problems that are difficult or impossible to solve with traditional optimization algorithms. They are also a good choice for problems with a large number of variables or with noisy or incomplete data.</p><p>Here are some examples of problems that can be solved with genetic algorithms:</p><ul><li>Scheduling problems</li><li>Resource allocation problems</li><li>Combinatorial optimization problems</li><li>Financial forecasting problems</li><li>Medical diagnosis problems</li><li>Engineering design problems</li></ul><p>With this simple introduction in mind, let’s go into coding !<br>Lets start by importing the neccesary libraries :</p><pre>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.metrics import r2_score<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>import numpy as np</pre><p><strong>RandomForestRegressor </strong>is from scikit-learn&#39;s ensemble module and is used to create and train the Random Forest model. <strong>r2_score </strong>is used to calculate the coefficient of determination (R^2 score) for regression problems. <strong>train_test_split </strong>is used to split the dataset into training and testing sets. <strong>StandardScaler </strong>is used for feature scaling. <strong>numpy </strong>is used for numerical computations.</p><p><strong><em>Next, Data Loading and Preprocessing :</em></strong></p><pre># Load and preprocess your data<br>data = pd.read_excel(r&quot;C:\Users\USER\Desktop\datas\data 1.xlsx&quot;)<br>X = data.drop(columns=&quot;Y&quot;)<br>y = data[&quot;Y&quot;]<br><br>X1 = X.values<br>y1 = y.values.reshape(-1, 1)<br>X_train1, X_test1, y_train1, y_test1 = train_test_split(X1, y1, test_size=0.2, random_state=8)<br><br>sc = StandardScaler()<br>X_train1 = sc.fit_transform(X_train1)<br>X_test1 = sc.transform(X_test1)</pre><p>The data was read from an Excel file using <strong>pd.read_excel()</strong> (assuming <strong>pd </strong>is an alias for <strong>pandas</strong>). I then split the data into features <strong>X </strong>and target <strong>y</strong>. The features are converted to NumPy arrays using <strong>.values</strong>, and the target is reshaped to a 2D array using <strong>.reshape(-1, 1)</strong>. <br>The data was splitted into training and testing sets using <strong>train_test_split()</strong>. <strong>StandardScaler</strong> was initialized and fitted into the training features, to transform both training and testing features to have zero mean and unit variance.</p><p><strong><em>Next, we’d create a fitness function that’d be utilized in the GA :</em></strong></p><pre># Define the RF fitness function<br>def ran_forest_fitness(solution):<br>    n_estimators = int(solution[0])<br>    max_features = int(solution[1])<br>    min_samples_leaf = int(solution[2])<br>    max_depth = int(solution[3])<br><br>    rf = RandomForestRegressor(n_estimators=n_estimators, max_features=max_features,<br>                               min_samples_leaf=min_samples_leaf, max_depth=max_depth)<br>    rf.fit(X_train1, y_train1.ravel())<br>    y_predict = rf.predict(X_test1)<br>    fitness = -r2_score(y_test1, y_predict)  # Minimize negative R^2 score<br>    return fitness</pre><ul><li>you define a fitness function <strong>ran_forest_fitness()</strong> that takes a solution (a set of hyperparameters) and converts its components to integers. Then, you create a <strong>RandomForestRegressor </strong>with the specified hyperparameters and train it on the training data. After predicting on the test data, you calculate the negative R2 score as the fitness, aiming to minimize it (since the GA maximizes the fitness function).</li></ul><p>With all that done, let’s start coding the Genetic algorithm from scratch. For better understanding, we would do the coding in small steps.<br>Let’s start by definining the GA function.</p><pre>def genetic_algorithm(pop_size, num_generations, mutation_rate):</pre><p>The code above defines a function named <strong>genetic_algorithm</strong> that takes three arguments: <strong>pop_size </strong>(population size), <strong>num_generations</strong> (number of generations), and <strong>mutation_rate </strong>(probability of mutation).</p><pre>    population = np.random.uniform(low=lb, high=ub, size=(pop_size, len(lb)))</pre><ul><li><strong>population = np.random.uniform(low=lb, high=ub, size=(pop_size, len(lb)))</strong>: Here, you&#39;re initializing the population matrix with random values. The <strong>np.random.uniform()</strong> function generates random values between the specified lower and upper bounds (<strong>lb </strong>and <strong>ub</strong>) for each solution in the population. The <strong>size </strong>argument specifies the shape of the population matrix.</li></ul><pre>    for generation in range(num_generations):<br>        # Evaluate Fitness <br>        fitness = np.array([ran_forest_fitness(solution) for solution in population])<br>        <br>        # Find best solution in this generation<br>        best_index = np.argmax(fitness)<br>        best_fitness = fitness[best_index]   <br><br>        print(f&quot;Generation {generation + 1}: Best Fitness = {best_fitness:.4f}&quot;) </pre><p><strong>for generation in range(num_generations):</strong>: This starts a loop that iterates over each generation, from 0 to <strong>num_generations - 1</strong>.<br><strong>best_index = np.argmax(fitness)</strong>: This line finds the index of the solution with the highest fitness (lowest negative R2 score). It uses the <strong>np.argmax()</strong> function. <br><strong>best_fitness = fitness[best_index]</strong>: Here, you&#39;re retrieving the actual best fitness value using the index found in the previous line.<br><strong>print(f&quot;Generation {generation + 1}: Best Fitness = {best_fitness:.4f}&quot;)</strong>: This line prints the generation number and the best fitness value for that generation. The .<strong>4f</strong> format specifier is used to display the fitness value with four decimal places.</p><pre>        # Select indices for parents based on fitness<br>        parent_indices = np.argsort(fitness)[:pop_size // 2]<br>        <br>        # Get parents from the population array<br>        parents = population[parent_indices]</pre><p><strong>parent_indices = np.argsort(fitness)[:pop_size // 2]</strong>: This line sorts the fitness array in ascending order and selects the indices of the first half of the sorted fitness values. These indices will correspond to the parents selected for the next generation.<br><strong>parents = population[parent_indices]</strong>: Here, you&#39;re creating an array of parent solutions by selecting the solutions from the population using the indices obtained in the previous line.</p><pre>        # Create offspring through crossover and mutation<br>        offspring = []<br>        for _ in range(pop_size // 2):<br>            parent1, parent2 = np.random.choice(parent_indices, size=2, replace=False)<br>            parent1 = population[parent1]<br>            parent2 = population[parent2]<br>            crossover_point = np.random.randint(1, len(parent1) - 1)<br>            child = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))<br>            offspring.append(child)<br><br>        offspring = np.array(offspring)</pre><p><strong>offspring = []</strong>: This initializes an empty list to store the offspring solutions.</p><p><strong>for _ in range(pop_size // 2):</strong>: This loop iterates half of the population size (number of offspring to create).</p><p><strong>parent1, parent2 = np.random.choice(parent_indices, size=2, replace=False)</strong>: Two distinct parent indices are randomly chosen using <strong>np.random.choice()</strong>. The <strong>size </strong>argument specifies the number of choices to make.</p><p><strong>parent1 = population[parent1]</strong> and <strong>parent2 = population[parent2]</strong>: These lines retrieve the selected parent solutions from the population.</p><p><strong>crossover_point = np.random.randint(1, len(parent1) - 1)</strong>: A random crossover point is chosen between the second and second-to-last positions in the parent solutions.</p><p><strong>child = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))</strong>: This line creates a child solution by concatenating the first part of parent1 up to the crossover point with the second part of parent2 after the crossover point.</p><p><strong>offspring.append(child)</strong>: The child solution is added to the offspring list.<br><br><strong>offspring = np.array(offspring)</strong>: The list of offspring solutions is converted into a NumPy array for easier manipulation.</p><pre><br>        # Apply mutation<br>        mask = np.random.random(size=offspring.shape) &lt; mutation_rate<br>        mutation = np.random.uniform(low=lb, high=ub, size=offspring.shape)<br>        offspring[mask] = mutation[mask]</pre><p><strong>mask = np.random.random(size=offspring.shape) &lt; mutation_rate</strong>: A random mask is generated with the same shape as the <strong>offspring </strong>array. Elements in the mask are <strong>True </strong>with a probability of <strong>mutation_rate</strong>.</p><p><strong>mutation = np.random.uniform(low=lb, high=ub, size=offspring.shape)</strong>: New mutation values are generated within the bounds <strong>lb </strong>and <strong>ub</strong>.</p><p><strong>offspring[mask] = mutation[mask]</strong>: Elements in the offspring array are updated with the corresponding mutation values where the mask is <strong>True</strong>.</p><pre>        # Combine parents and offspring to form next generation<br>        population = np.vstack((parents, offspring))</pre><p><strong>population = np.vstack((parents, offspring))</strong>: The new population for the next generation is formed by stacking the parent and offspring arrays vertically.</p><pre>    # Find best solution overall<br>    best_index = np.argmax(fitness)<br>    best_solution = population[best_index]<br>    <br>    return best_solution</pre><p><strong>best_index = np.argmax(fitness)</strong>: Again, you find the index of the solution with the highest fitness.</p><p><strong>best_solution = population[best_index]</strong>: The best solution for the entire run of the algorithm is assigned by retrieving the solution with the best fitness.</p><p>Hurray! We’ve finally Coded the GA from scratch and this is what it looks like altogether :</p><pre>def genetic_algorithm(pop_size, num_generations, mutation_rate):<br>    # Initialize population<br>    population = np.random.uniform(low=lb, high=ub, size=(pop_size, len(lb)))<br>    <br>    # Main loop<br>    for generation in range(num_generations):<br>        # Evaluate fitness<br>        fitness = np.array([ran_forest_fitness(solution) for solution in population])<br>        <br>        # Find best solution in this generation<br>        best_index = np.argmax(fitness)<br>        best_fitness = fitness[best_index]<br>        <br>        print(f&quot;Generation {generation + 1}: Best Fitness = {best_fitness:.4f}&quot;)<br>        <br>        # Select indices for parents based on fitness<br>        parent_indices = np.argsort(fitness)[:pop_size // 2]<br>        <br>        # Get parents from the population array<br>        parents = population[parent_indices]<br><br>        # Create offspring through crossover and mutation<br>        offspring = []<br>        for _ in range(pop_size // 2):<br>            parent1, parent2 = np.random.choice(parent_indices, size=2, replace=False)<br>            parent1 = population[parent1]<br>            parent2 = population[parent2]<br>            crossover_point = np.random.randint(1, len(parent1) - 1)<br>            child = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))<br>            offspring.append(child)<br><br>        offspring = np.array(offspring)<br><br>        # Apply mutation<br>        mask = np.random.random(size=offspring.shape) &lt; mutation_rate<br>        mutation = np.random.uniform(low=lb, high=ub, size=offspring.shape)<br>        offspring[mask] = mutation[mask]<br><br>        # Combine parents and offspring to form next generation<br>        population = np.vstack((parents, offspring))<br>    <br>    # Find best solution overall<br>    best_index = np.argmax(fitness)<br>    best_solution = population[best_index]<br>    <br>    return best_solution</pre><p>Now, let’s see how the GA would work. We’d start by assigning values to the hyperparameters of the GA</p><pre># Hyperparameters for the genetic algorithm<br>population_size = 100<br>generations = 100<br>mutation_rate = 0.05</pre><p>The <strong>population_size</strong> determines how many solutions are in each generation, <strong>generations </strong>specifies how many generations the algorithm will run for, and <strong>mutation_rate </strong>controls the probability of mutation occurring during reproduction.</p><pre># Define the hyperparameter bounds<br>param_bounds = {<br>    &quot;n_estimators&quot;: list(range(100, 501)),<br>    &quot;max_features&quot;: list(range(1, 6)),<br>    &quot;min_samples_leaf&quot;: [1, 2, 3],<br>    &quot;max_depth&quot;: list(range(1, 6))<br>}</pre><p>In the above code we define the bounds for each hyperparameter of random forest regressor that the genetic algorithm will search for. For instance, <strong>n_estimators </strong>will be searched within the range of 100 to 500 in steps of 100.</p><p>Next, we’d set up the lower and upper bounds for each hyperparameter based on the defined parameter bounds.</p><pre>lb = [min(param_bounds[&quot;n_estimators&quot;]), min(param_bounds[&quot;max_features&quot;]),<br>      min(param_bounds[&quot;min_samples_leaf&quot;]), min(param_bounds[&quot;max_depth&quot;])]<br><br>ub = [max(param_bounds[&quot;n_estimators&quot;]), max(param_bounds[&quot;max_features&quot;]),<br>      max(param_bounds[&quot;min_samples_leaf&quot;]), max(param_bounds[&quot;max_depth&quot;])]</pre><p><strong>lb </strong>represents the lower bound of the random forest hyperparameters and is taken as the minimum value of each defined band<strong>. </strong><strong>ub</strong> on the other hand, represents the upper bound and is taken as the maximum value. The GA would randomly search for optimal values within the lower and upper bound.<br>Let’s run the genetic algorithm now.</p><pre># Run the genetic algorithm<br>best_solution = genetic_algorithm(population_size, generations, mutation_rate)<br>best_fitness = ran_forest_fitness(best_solution)<br>print(&quot;Best Fitness:&quot;, best_fitness)<br>print(&quot;Optimal Solution:&quot;, best_solution)</pre><p>Here we’re calling the <strong>genetic_algorithm() </strong>function with the specified hyperparameters. The best solution found by the algorithm is stored in <strong>best_solution</strong>. We’re then calculating the fitness of this best solution using the <strong>ran_forest_fitness()</strong> function and storing it in <strong>best_fitness</strong>. Finally, we’d be printing out the best fitness and the optimal solution.<br>The result would be printed out as follows :</p><pre>Generation 1: Best Fitness = -0.4567<br>Generation 2: Best Fitness = -0.7183<br>Generation 3: Best Fitness = -0.8177<br>Generation 4: Best Fitness = -0.6849<br>Generation 5: Best Fitness = -0.8236<br>Generation 6: Best Fitness = -0.7604<br>Generation 7: Best Fitness = -0.6349<br>Generation 8: Best Fitness = -0.7836<br>Generation 9: Best Fitness = -0.7847<br>Generation 10: Best Fitness = -0.7622<br>Generation 11: Best Fitness = -0.6739<br>Generation 12: Best Fitness = -0.8510<br>Generation 13: Best Fitness = -0.6649<br>Generation 14: Best Fitness = -0.6335<br>Generation 15: Best Fitness = -0.6717<br>Generation 16: Best Fitness = -0.8346<br>Generation 17: Best Fitness = -0.8196<br>Generation 18: Best Fitness = -0.6698<br>Generation 19: Best Fitness = -0.6808<br>Generation 20: Best Fitness = -0.7197<br>Generation 21: Best Fitness = -0.6651<br>Generation 22: Best Fitness = -0.8321<br>Generation 23: Best Fitness = -0.7270<br>Generation 24: Best Fitness = -0.7790<br>Generation 25: Best Fitness = -0.7489<br>Generation 26: Best Fitness = -0.7132<br>Generation 27: Best Fitness = -0.7917<br>Generation 28: Best Fitness = -0.7639<br>Generation 29: Best Fitness = -0.8607<br>Generation 30: Best Fitness = -0.6984<br>Generation 31: Best Fitness = -0.8647<br>Generation 32: Best Fitness = -0.8599<br>Generation 33: Best Fitness = -0.7836<br>Generation 34: Best Fitness = -0.6916<br>Generation 35: Best Fitness = -0.8110<br>Generation 36: Best Fitness = -0.6868<br>Generation 37: Best Fitness = -0.8323<br>Generation 38: Best Fitness = -0.8617<br>Generation 39: Best Fitness = -0.7697<br>Generation 40: Best Fitness = -0.8204<br>Generation 41: Best Fitness = -0.7449<br>Generation 42: Best Fitness = -0.8307<br>Generation 43: Best Fitness = -0.6928<br>Generation 44: Best Fitness = -0.7904<br>Generation 45: Best Fitness = -0.8787<br>Generation 46: Best Fitness = -0.6891<br>Generation 47: Best Fitness = -0.6891<br>Generation 48: Best Fitness = -0.6660<br>Generation 49: Best Fitness = -0.8580<br>Generation 50: Best Fitness = -0.8715<br>Generation 51: Best Fitness = -0.8593<br>Generation 52: Best Fitness = -0.8141<br>Generation 53: Best Fitness = -0.6851<br>Generation 54: Best Fitness = -0.7021<br>Generation 55: Best Fitness = -0.6798<br>Generation 56: Best Fitness = -0.8852<br>Generation 57: Best Fitness = -0.7181<br>Generation 58: Best Fitness = -0.8807<br>Generation 59: Best Fitness = -0.8039<br>Generation 60: Best Fitness = -0.8743<br>Generation 61: Best Fitness = -0.7059<br>Generation 62: Best Fitness = -0.8831<br>Generation 63: Best Fitness = -0.7794<br>Generation 64: Best Fitness = -0.8270<br>Generation 65: Best Fitness = -0.6840<br>Generation 66: Best Fitness = -0.6819<br>Generation 67: Best Fitness = -0.6451<br>Generation 68: Best Fitness = -0.7936<br>Generation 69: Best Fitness = -0.7868<br>Generation 70: Best Fitness = -0.8615<br>Generation 71: Best Fitness = -0.7934<br>Generation 72: Best Fitness = -0.7073<br>Generation 73: Best Fitness = -0.6955<br>Generation 74: Best Fitness = -0.7699<br>Generation 75: Best Fitness = -0.8555<br>Generation 76: Best Fitness = -0.8714<br>Generation 77: Best Fitness = -0.8601<br>Generation 78: Best Fitness = -0.6637<br>Generation 79: Best Fitness = -0.7992<br>Generation 80: Best Fitness = -0.8719<br>Generation 81: Best Fitness = -0.6899<br>Generation 82: Best Fitness = -0.6742<br>Generation 83: Best Fitness = -0.8064<br>Generation 84: Best Fitness = -0.8009<br>Generation 85: Best Fitness = -0.8877<br>Generation 86: Best Fitness = -0.6724<br>Generation 87: Best Fitness = -0.8023<br>Generation 88: Best Fitness = -0.8833<br>Generation 89: Best Fitness = -0.8544<br>Generation 90: Best Fitness = -0.8054<br>Generation 91: Best Fitness = -0.8519<br>Generation 92: Best Fitness = -0.6966<br>Generation 93: Best Fitness = -0.6829<br>Generation 94: Best Fitness = -0.8002<br>Generation 95: Best Fitness = -0.6621<br>Generation 96: Best Fitness = -0.8641<br>Generation 97: Best Fitness = -0.7931<br>Generation 98: Best Fitness = -0.6930<br>Generation 99: Best Fitness = -0.6801<br>Generation 100: Best Fitness = -0.7245<br>Best Fitness: -0.9255760603727354<br>Optimal Solution: [491.35970031   2.00836264   1.67244561   3.22552141]</pre><p>A fitness of 0.9255760603727354( R2 Score). That’s pretty impressive, yeah?</p><p>Ok, let’s print out the GA-searched optimal parameters.</p><pre>best_num_estimator = int(best_solution[0])<br>best_max_features = int(best_solution[1])<br>best_max_sample_leaf = int(best_solution[2])<br>best_max_depth = int(best_solution[3])</pre><p>Note, that we’re converting the optimal hyperparameter values to integers because random forest regressor only works with integer, but the GA optimal values for the parameters came as float.<br>Let’s print them out and see!</p><pre>print(&quot;Best Hyperparameters using Genetic Algorithm:&quot;)<br>print(&quot;n_estimators:&quot;, best_num_estimator)<br>print(&quot;max_features:&quot;, best_max_features)<br>print(&quot;max_samples_leaf:&quot;, best_max_sample_leaf)<br>print(&quot;max_depth:&quot;, best_max_depth)</pre><pre>Best Hyperparameters using Genetic Algorithm:<br>n_estimators: 418<br>max_features: 3<br>max_samples_leaf: 1<br>max_depth: 3</pre><p>Great! So that’s the hyperparameter values we’d be using to create our optimized model. Let’s go!</p><pre>rf_optimized = RandomForestRegressor(n_estimators=best_num_estimator, <br>                                     max_features=best_max_features, <br>                                     min_samples_leaf=best_max_sample_leaf,<br>                                     max_depth=best_max_depth)</pre><p>Next, we’d fit the model to the training data.</p><pre>rf_optimized.fit(X_train1, y_train1.ravel())</pre><p>Let’s run a prediction with our model on our test set and see how well it does.</p><pre>pred_test = rf_optimized.predict(X_test1)<br>from sklearn.metrics import r2_score<br>print(&quot;R^2 score of Test set prediction using GA:&quot;, r2_score(y_test1,pred_test))</pre><pre>R^2 score of Test set prediction using GA: 0.9351555067989351</pre><p>You would agree with me that an R2 score of 0.9351555067989351 is pretty impressive, yeah? This goes on to prove and validate how important hyperparameter tuning is, and how GA is awesome at doing that.</p><p>Next, I want to show you guys how you can not only use GA to fine-tune your model’s hyperparameter but also use it in finding the best feature value(in the case, X1,X2,X3,X4) would give us the optimal target value(Y, in this case)</p><p>Let’s start by fiting our optimized dataset to the entire dataset.</p><pre>model = rf_optimized.fit(X, y)</pre><p>Next, we’d define a new fitness function for our GA</p><pre># Create a function to be optimized by the algorithms<br>def obj_fun(X):<br>    results = model.predict(X.reshape(1, -1))  # Reshape X to match the number of features<br>    return -results  # Negative to maximize the prediction (Yield)</pre><p>This function takes the features of the dataset, use the optimised model to run a prediction on it and return the predicted value (results)</p><p>So, let replace our random forest fitness function with this new function in our GA. <br>Here you go :</p><pre>def genetic_algorithm(pop_size, num_generations, mutation_rate):<br>    # Initialize population<br>    population = np.random.uniform(low=lb, high=ub, size=(pop_size, len(lb)))<br>    <br>    # Main loop<br>    for generation in range(num_generations):<br>        # Evaluate fitness<br>        fitness = np.array([obj_fun(solution) for solution in population])<br>        <br>        # Find best solution in this generation<br>        best_index = np.argmax(fitness)<br>        best_fitness = fitness[best_index]<br>        <br>        print(f&quot;Generation {generation + 1}: Best Fitness = {best_fitness[0]:.4f}&quot;)<br>        <br>        # Select indices for parents based on fitness<br>        parent_indices = np.argsort(fitness)[:pop_size // 2].ravel()<br>        <br>        # Get parents from the population array<br>        parents = population[parent_indices]<br>        <br>        # Create offspring through crossover and mutation<br>        offspring = []<br>        for _ in range(pop_size // 2):<br>            parent1 = np.random.choice(parent_indices, size=1, replace=False)[0]<br>            parent2 = np.random.choice(parent_indices, size=1, replace=False)[0]<br>            parent1 = population[parent1]<br>            parent2 = population[parent2]<br>            crossover_point = np.random.randint(1, len(parent1) - 1)<br>            child = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))<br>            offspring.append(child)<br><br>        offspring = np.array(offspring)<br><br>        # Apply mutation<br>        mask = np.random.random(size=offspring.shape) &lt; mutation_rate<br>        mutation = np.random.uniform(low=lb, high=ub, size=offspring.shape)<br>        offspring[mask] = mutation[mask]<br><br>        # Combine parents and offspring to form next generation<br>        population = np.vstack((parents, offspring))<br>    <br>    # Find best solution overall<br>    best_index = np.argmax(fitness)<br>    best_solution = population[best_index]<br>    <br>    return best_solution</pre><p>Note that we replace <strong>ran_forest_fitness(solution) </strong>with <strong>obj_fun(solution)</strong></p><p>Next, we’d define the upper and lower bound of our features. Remember previously that it was with the hyperparameters of our choosen model.</p><pre>lb = [data[&#39;X1&#39;].min(), data[&#39;X2&#39;].min(),data[&#39;X3&#39;].min(), data[&#39;X4&#39;].min()]<br>ub = [data[&#39;X1&#39;].max(), data[&#39;X2&#39;].max(),data[&#39;X3&#39;].max(), data[&#39;X4&#39;].max()]</pre><p>We’d use the same GA parameters as used previously.</p><pre># Hyperparameters for the genetic algorithm<br>population_size = 100<br>generations = 100<br>mutation_rate = 0.05</pre><p>Before we run the Genetic algorithm, let’s first take a look at the row in the dataset with the maximum target value.</p><pre># Sort the DataFrame by the target column in descending order<br>sorted_data = data.sort_values(by=&#39;Y&#39;, ascending=False)<br># Select the first row (which will have the maximum value)<br>max_row = sorted_data.iloc[0]<br>max_row</pre><pre>X1     60.00<br>X2      3.00<br>X3    150.00<br>X4      6.00<br>Y      73.14<br>Name: 10, dtype: float64</pre><p>So, the maximum target value in our dataset is 73.14. Should our GA be successful with the optimization, we’d be able to optimized this value to a higher value than 73.14.<br>Let’s run the GA.</p><pre>Generation 1: Best Fitness = -43.7289<br>Generation 2: Best Fitness = -43.7753<br>Generation 3: Best Fitness = -75.7482<br>Generation 4: Best Fitness = -44.8461<br>Generation 5: Best Fitness = -45.7482<br>Generation 6: Best Fitness = -43.7753<br>Generation 7: Best Fitness = -68.7753<br>Generation 8: Best Fitness = -45.7482<br>Generation 9: Best Fitness = -45.7482<br>Generation 10: Best Fitness = -47.6869<br>Generation 11: Best Fitness = -45.6869<br>Generation 12: Best Fitness = -45.7482<br>Generation 13: Best Fitness = -45.7482<br>Generation 14: Best Fitness = -45.7482<br>Generation 15: Best Fitness = -44.8461<br>Generation 16: Best Fitness = -44.8461<br>Generation 17: Best Fitness = -45.7482<br>Generation 18: Best Fitness = -43.7753<br>Generation 19: Best Fitness = -43.7753<br>Generation 20: Best Fitness = -43.7753<br>Generation 21: Best Fitness = -59.7753<br>Generation 22: Best Fitness = -45.6869<br>Generation 23: Best Fitness = -44.8461<br>Generation 24: Best Fitness = -45.6869<br>Generation 25: Best Fitness = -45.7482<br>Generation 26: Best Fitness = -45.7482<br>Generation 27: Best Fitness = -43.7753<br>Generation 28: Best Fitness = -44.8461<br>Generation 29: Best Fitness = -45.7482<br>Generation 30: Best Fitness = -43.7753<br>Generation 31: Best Fitness = -45.6869<br>Generation 32: Best Fitness = -70.7753<br>Generation 33: Best Fitness = -45.6869<br>Generation 34: Best Fitness = -43.7753<br>Generation 35: Best Fitness = -69.7753<br>Generation 36: Best Fitness = -43.7289<br>Generation 37: Best Fitness = -43.7753<br>Generation 38: Best Fitness = -44.8461<br>Generation 39: Best Fitness = -58.7753<br>Generation 40: Best Fitness = -44.8461<br>Generation 41: Best Fitness = -44.8461<br>Generation 42: Best Fitness = -43.7753<br>Generation 43: Best Fitness = -45.6869<br>Generation 44: Best Fitness = -45.6869<br>Generation 45: Best Fitness = -43.7753<br>Generation 46: Best Fitness = -45.7482<br>Generation 47: Best Fitness = -43.7753<br>Generation 48: Best Fitness = -45.7482<br>Generation 49: Best Fitness = -43.7753<br>Generation 50: Best Fitness = -43.7753<br>Generation 51: Best Fitness = -45.6869<br>Generation 52: Best Fitness = -44.8461<br>Generation 53: Best Fitness = -44.8461<br>Generation 54: Best Fitness = -45.7482<br>Generation 55: Best Fitness = -44.8461<br>Generation 56: Best Fitness = -45.7482<br>Generation 57: Best Fitness = -43.7753<br>Generation 58: Best Fitness = -43.7753<br>Generation 59: Best Fitness = -43.7753<br>Generation 60: Best Fitness = -44.8461<br>Generation 61: Best Fitness = -45.6869<br>Generation 62: Best Fitness = -43.7753<br>Generation 63: Best Fitness = -45.6869<br>Generation 64: Best Fitness = -43.7753<br>Generation 65: Best Fitness = -43.7753<br>Generation 66: Best Fitness = -43.7753<br>Generation 67: Best Fitness = -45.7482<br>Generation 68: Best Fitness = -43.7753<br>Generation 69: Best Fitness = -45.7482<br>Generation 70: Best Fitness = -45.6869<br>Generation 71: Best Fitness = -44.8461<br>Generation 72: Best Fitness = -45.7482<br>Generation 73: Best Fitness = -44.8461<br>Generation 74: Best Fitness = -44.8461<br>Generation 75: Best Fitness = -43.7753<br>Generation 76: Best Fitness = -43.7753<br>Generation 77: Best Fitness = -44.8461<br>Generation 78: Best Fitness = -44.8461<br>Generation 79: Best Fitness = -44.8461<br>Generation 80: Best Fitness = -43.7753<br>Generation 81: Best Fitness = -43.7753<br>Generation 82: Best Fitness = -43.7753<br>Generation 83: Best Fitness = -43.7753<br>Generation 84: Best Fitness = -43.7753<br>Generation 85: Best Fitness = -43.7753<br>Generation 86: Best Fitness = -45.7482<br>Generation 87: Best Fitness = -43.7753<br>Generation 88: Best Fitness = -72.6869<br>Generation 89: Best Fitness = -45.7482<br>Generation 90: Best Fitness = -43.6386<br>Generation 91: Best Fitness = -43.7753<br>Generation 92: Best Fitness = -45.7482<br>Generation 93: Best Fitness = -44.8461<br>Generation 94: Best Fitness = -76.7753<br>Generation 95: Best Fitness = -44.8461<br>Generation 96: Best Fitness = -43.7753<br>Generation 97: Best Fitness = -77.2952<br>Generation 98: Best Fitness = -45.7482<br>Generation 99: Best Fitness = -43.7753<br>Generation 100: Best Fitness = -43.7753<br>Best Fitness: [-77.295166015625]<br>Optimal Solution: [67.49378792  4.40878968 88.5179989  11.13210093]</pre><p>With our GA successfully implemented, let’s see the results.</p><pre>print(&quot;Best Solution:&quot;)<br>print(&quot;X1:&quot;, op_best_solution[0])<br>print(&quot;X2:&quot;, op_best_solution[1])<br>print(&quot;X3:&quot;, op_best_solution[2])<br>print(&quot;X4:&quot;, op_best_solution[3])<br>print(&quot;Best Fitness(Y):&quot;, -op_best_fitness)  # Convert back to positive as it was negated for maximization</pre><pre>Best Solution:<br>X1: 67.49378792<br>X2: 4.40878968<br>X3: 88.5179989<br>X4: 11.13210093<br>Best Fitness(Y): [77.2951660156]</pre><p>Viola!, we just optimized our target yield from <strong>73.14</strong> to<strong> 77.2951660156</strong></p><p>How can optimization be applied in Business and Engineering ?</p><p><strong>Business Application: Supply Chain Optimization</strong></p><p>Imagine you’re managing a complex supply chain with multiple variables affecting efficiency and cost. From production schedules to inventory levels, transportation routes to order fulfillment, every decision impacts the bottom line. Employing Genetic Algorithms in this scenario could revolutionize your operations.</p><p>By encoding supply chain parameters into individuals and using a fitness function to evaluate costs and delivery times, you can apply GAs to find the most optimal configuration. The algorithm explores a multitude of options, factoring in various constraints, and discovers solutions that minimize costs and maximize delivery speed. This not only boosts profitability but also enhances customer satisfaction through timely and cost-effective delivery.</p><p><strong>Engineering Application: Structural Design Optimization</strong></p><p>In the realm of engineering, optimizing the design of complex structures is a critical challenge. Be it bridges, aircraft wings, or skyscrapers, finding the right balance between strength, weight, and cost is essential. Genetic Algorithms excel in tackling such intricate problems.</p><p>By representing structural parameters as genes and using fitness functions to evaluate factors like structural integrity, weight, and construction cost, GAs can evolve solutions that are both robust and efficient. The algorithm navigates through a vast solution space, fine-tuning designs by adjusting dimensions and materials, ultimately producing structures that meet or exceed engineering requirements while minimizing resource utilization.</p><p>In this article, we ventured into the fascinating world of Genetic Algorithms (GAs), harnessing their evolutionary power to optimize complex problems. We deciphered the fundamental principles of GAs, their genetic components, and their iterative process akin to nature’s evolution.</p><p>From demystifying the intricate mechanisms of GAs to crafting a GA from scratch, we empowered ourselves to fine-tune machine learning models, explore hyperparameter spaces, and even identify the most optimal combination of input features for desired outcomes.</p><h3><strong>Keep tabs for my next article, next sunday. Cheers!</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93c5e7a510d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of Metaheuristic algorithms for Hyperparameter tuning using support vector…]]></title>
            <link>https://medium.com/@i.v.shedrach/implementation-of-metaheuristic-algorithms-for-hyperparameter-tuning-using-support-vector-d701caf5d8fd?source=rss-a184a23f567a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d701caf5d8fd</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[particle-swarm]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <dc:creator><![CDATA[Shedrach Igemhokhai]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 11:28:21 GMT</pubDate>
            <atom:updated>2023-08-08T12:58:37.174Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Implementation of Metaheuristic algorithms for Hyperparameter tuning using support vector regression as a case study.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8NJhkPLgyOZq14LnWR0bg.jpeg" /></figure><p>Hyperparameter tuning is a critical step in the development of machine learning models. The right set of hyperparameters can significantly impact the performance of a model. In this article, we’ll explore the use of metaheuristic algorithms, specifically Genetic Algorithms (GA) and Particle Swarm Optimization (PSO), for hyperparameter tuning. We’ll apply these algorithms to optimize the hyperparameters of a Support Vector Regressor (SVR) using the MEALPY library.</p><h4>Introduction</h4><p>Metaheuristic algorithms are optimization techniques that help us find near-optimal solutions for complex problems. They mimic natural processes like evolution and swarm behaviour to explore and exploit solution spaces efficiently. In this tutorial, we’ll focus on <strong>Genetic Algorithms </strong>and <strong>Particle Swarm Optimization</strong>.</p><h3>Dataset and Preprocessing</h3><p>We’ll begin by loading and preprocessing our dataset. For this example, we’ll use the MEALPY library to optimize the hyperparameters of an SVR model for regression tasks. The dataset is loaded using Pandas, and data preprocessing steps include standard scaling and train-test splitting. <br>I would start by importing the necessary libraries.</p><pre>from sklearn.svm import SVR #Regression Model<br>import pandas as pd # For data wrangling<br>from sklearn.model_selection import train_test_split # For data splitting<br>from sklearn.preprocessing import StandardScaler # For normal distribution of the data <br>from sklearn.metrics import mean_squared_error,r2_score # For model evaluation<br>from mealpy.evolutionary_based.GA import BaseGA # metaheuristic algorithm for optimization and hyperparameter tuning<br>from mealpy.swarm_based.PSO import CL_PSO # metaheuristic algorithm for optimization and hyperparameter tuning<br>import numpy as np # for mathematical manipulation</pre><p>Now, let’s load our data into a pandas dataframe</p><pre>data = pd.read_excel(r&quot;C:\Users\USER\Desktop\datasets\data 1.xlsx&quot;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPXo6syyVOk-RFTgZbWHCw.png" /></figure><p>Next, We’d split and scale the data for modelling</p><pre>X = data.drop(columns=&quot;Y&quot;)<br>y = data[&quot;Y&quot;]<br><br>X1 = X.values<br>y1 = y.values.reshape(-1, 1)<br>X_train1, X_test1, y_train1, y_test1 = train_test_split(X1, y1, test_size=0.2, random_state=8)<br><br>sc = StandardScaler()<br>X_train1 = sc.fit_transform(X_train1)<br>X_test1 = sc.transform(X_test1)<br><br>sc_y = StandardScaler()<br>y_train1 = sc_y.fit_transform(y_train1)<br>y_test1 = sc_y.transform(y_test1)</pre><h4>Genetic Algorithm for Hyperparameter Tuning</h4><p>We’ll start with Genetic Algorithms for hyperparameter tuning. Genetic Algorithms simulate the process of natural selection to evolve a population of potential solutions to a problem. We’ll use MEALPY’s BaseGA to optimize the SVR hyperparameters. Lets start by defining our fitness function.</p><pre># Define the SVR fitness function<br>def svr_fitness(solution):<br>    kernel_encoded = int(solution[0])<br>    c = solution[1]<br>    gamma = solution[2]<br>    epsilon = solution[3]<br>    <br>    kernel_decoded = [&#39;linear&#39;, &#39;poly&#39;, &#39;rbf&#39;, &#39;precomputed&#39;][kernel_encoded]<br>    <br>    svr = SVR(C=c, kernel=kernel_decoded, gamma=gamma, epsilon=epsilon)<br>    svr.fit(X_train1, y_train1.ravel())<br>    y_predict = svr.predict(X_test1)<br>    fitness = - r2_score(y_test1, y_predict)  # Minimize negative R^2 score<br>    return fitness</pre><h4><strong>Defining the Hyperparameter Bounds</strong></h4><p>In the process of optimizing hyperparameters, it is essential to establish the ranges within which the parameters can be explored. This section defines the hyperparameter bounds, acting as a guide for the optimization algorithm. Each hyperparameter has a designated set of values that represent different configurations.</p><p><strong>1. Kernel </strong>: This hyperparameter determines the type of kernel to be used in the Support Vector Regression (SVR) model. It is encoded using integer values [0, 1, 2, 3], representing different kernel types: linear, polynomial (poly), radial basis function (rbf), and precomputed.</p><p><strong>2. C</strong> : The C parameter controls the trade-off between achieving a low training error and a low testing error. It represents the regularization strength and helps prevent overfitting. The range of values [100, 1000] is divided into increments of 100, providing a variety of regularization strengths to explore.</p><p><strong>3. Gamma</strong> : Gamma is a kernel coefficient for ‘rbf’ and ‘poly’ kernels. It defines the influence of each training example and affects the smoothness of the decision boundary. The values are sampled logarithmically in the range from 1e-10 to 1.</p><p><strong>4. Epsilon</strong> : Epsilon is the epsilon in the epsilon-insensitive loss function for SVR. It controls the margin of error tolerated in predicting the target values. Like gamma, epsilon values are logarithmically sampled in the range from 1e-3 to 1.</p><p>By defining these hyperparameter bounds, the optimization algorithm will systematically search through the specified parameter space to discover the combination of hyperparameters that leads to optimal model performance.</p><pre># Define the hyperparameter bounds<br>param_bounds = {<br>    &quot;kernel&quot;: [0, 1, 2, 3],  # 0: linear, 1: poly, 2: rbf 3: precomputed<br>    &quot;C&quot;: list(range(100, 1001, 100)),<br>    &quot;gamma&quot;: list(np.logspace(-10, 0, 10)),<br>    &quot;epsilon&quot;: list(np.logspace(-3, 0, 10))<br>}</pre><h4><strong>Defining the Optimization Problem</strong></h4><p>The heart of the hyperparameter tuning process lies in defining the optimization problem that the algorithm aims to solve. This section constructs the optimization problem dictionary, which serves as a blueprint for the metaheuristic algorithm to follow.</p><p><strong>fit_func </strong>: The fitness function is a pivotal component of the optimization process. It quantifies how well a set of hyperparameters performs in terms of model accuracy. In this case, `svr_fitness` is employed as the fitness function, evaluating the negative R² score of the SVR model’s predictions.</p><p><strong>lb </strong>: The lower bounds define the minimum permissible values for each hyperparameter. These bounds ensure that the algorithm explores a feasible range of hyperparameter configurations. The lower bounds are set using the minimum values extracted from `param_bounds`.</p><p><strong>ub </strong>: Conversely, the upper bounds establish the maximum allowable values for the hyperparameters. These bounds confine the exploration space within reasonable limits. The upper bounds are determined by the maximum values from `param_bounds`.</p><p><strong>minmax </strong>: This key determines whether the problem is one of minimization or maximization. For hyperparameter tuning, the goal is to minimize the fitness function (negative R² score), indicated by `”min”`.</p><p>By encapsulating these elements in the optimization problem dictionary, we equip the algorithm with the necessary instructions to iteratively search for hyperparameters that yield the best possible SVR model performance.</p><pre><br># Define the optimization problem dictionary<br>svr_problem = {<br>    &quot;fit_func&quot;: svr_fitness,<br>    &quot;lb&quot;: [min(param_bounds[&quot;kernel&quot;]), min(param_bounds[&quot;C&quot;]), min(param_bounds[&quot;gamma&quot;]), min(param_bounds[&quot;epsilon&quot;])],<br>    &quot;ub&quot;: [max(param_bounds[&quot;kernel&quot;]), max(param_bounds[&quot;C&quot;]), max(param_bounds[&quot;gamma&quot;]), max(param_bounds[&quot;epsilon&quot;])],<br>    &quot;minmax&quot;: &quot;min&quot;  # Minimize fitness (negative R^2)<br>}</pre><h3>Creating the Genetic Algorithm Model</h3><p>The Genetic Algorithm (GA) serves as the optimization engine to explore the hyperparameter space and identify the most promising configurations. This section outlines the process of constructing the GA model using the MEALPY library.</p><pre>epoch = 50            # Number of generations/epochs<br>pop_size = 100        # Size of the population in each generation<br>pc = 0.95             # Crossover probability<br>pm = 0.05             # Mutation probability<br><br># Instantiate the Genetic Algorithm model<br>ga_model = BaseGA(epoch, pop_size, pc, pm)</pre><ul><li><strong>epoch</strong>: The number of generations or iterations the GA will perform. Each generation involves the evolution of the population based on crossover and mutation.</li><li><strong>pop_size</strong>: The size of the population in each generation. A larger population can potentially lead to better exploration of the search space.</li><li><strong>pc</strong>: The probability of crossover, which determines how often individuals in the population will undergo crossover to create new offspring.</li><li><strong>pm</strong>: The probability of mutation, which defines the likelihood of introducing small random changes to individuals in the population.</li></ul><p>Having constructed the GA model, the next step involves solving the optimization problem using the genetic algorithm.</p><pre># Solve the optimization problem using the genetic algorithm<br>best_params, best_fitness = ga_model.solve(svr_problem)</pre><pre>2023/08/08 10:15:24 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: Solving single objective optimization problem.<br>2023/08/08 10:15:27 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 1, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.50302 seconds<br>2023/08/08 10:15:29 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 2, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.38361 seconds<br>2023/08/08 10:15:30 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 3, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.45136 seconds<br>2023/08/08 10:15:32 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 4, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.51826 seconds<br>2023/08/08 10:15:34 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 5, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 2.03275 seconds<br>2023/08/08 10:15:35 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 6, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.70323 seconds<br>2023/08/08 10:15:37 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 7, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.29202 seconds<br>2023/08/08 10:15:38 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 8, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.30940 seconds<br>2023/08/08 10:15:39 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 9, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.13348 seconds<br>2023/08/08 10:15:41 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 10, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.48909 seconds<br>2023/08/08 10:15:42 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 11, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 0.98406 seconds<br>2023/08/08 10:15:43 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 12, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.11401 seconds<br>2023/08/08 10:15:44 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 13, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.46043 seconds<br>2023/08/08 10:15:46 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 14, Current best: -0.8803839866677826, Global best: -0.8803839866677826, Runtime: 1.43844 seconds<br>2023/08/08 10:15:47 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 15, Current best: -0.8803839866677826, Global best: -0.8803839866677826, Runtime: 1.17525 seconds<br>2023/08/08 10:15:48 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 16, Current best: -0.8803839866677826, Global best: -0.8803839866677826, Runtime: 1.47366 seconds<br>2023/08/08 10:15:49 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 17, Current best: -0.8941071936072994, Global best: -0.8941071936072994, Runtime: 1.08602 seconds<br>2023/08/08 10:15:51 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 18, Current best: -0.8960245823511305, Global best: -0.8960245823511305, Runtime: 1.06896 seconds<br>2023/08/08 10:15:52 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 19, Current best: -0.9558305569023439, Global best: -0.9558305569023439, Runtime: 1.08948 seconds<br>2023/08/08 10:15:53 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 20, Current best: -0.9636627347273975, Global best: -0.9636627347273975, Runtime: 1.06011 seconds<br>2023/08/08 10:15:54 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 21, Current best: -0.9644962424849841, Global best: -0.9644962424849841, Runtime: 0.91661 seconds<br>2023/08/08 10:15:55 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 22, Current best: -0.9646775662235703, Global best: -0.9646775662235703, Runtime: 0.91448 seconds<br>2023/08/08 10:15:56 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 23, Current best: -0.9646775662235703, Global best: -0.9646775662235703, Runtime: 1.23127 seconds<br>2023/08/08 10:15:57 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 24, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.02627 seconds<br>2023/08/08 10:15:59 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 25, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 2.55495 seconds<br>2023/08/08 10:16:02 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 26, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 2.57574 seconds<br>2023/08/08 10:16:04 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 27, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 2.09470 seconds<br>2023/08/08 10:16:05 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 28, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 0.93346 seconds<br>2023/08/08 10:16:06 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 29, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.35720 seconds<br>2023/08/08 10:16:07 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 30, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.16948 seconds<br>2023/08/08 10:16:09 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 31, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.66557 seconds<br>2023/08/08 10:16:10 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 32, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.22858 seconds<br>2023/08/08 10:16:11 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 33, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.02662 seconds<br>2023/08/08 10:16:12 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 34, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.05620 seconds<br>2023/08/08 10:16:14 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 35, Current best: -0.9703544238550341, Global best: -0.9703544238550341, Runtime: 1.07375 seconds<br>2023/08/08 10:16:14 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 36, Current best: -0.9703544238550341, Global best: -0.9703544238550341, Runtime: 0.93133 seconds<br>2023/08/08 10:16:15 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 37, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.86276 seconds<br>2023/08/08 10:16:16 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 38, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.84094 seconds<br>2023/08/08 10:16:17 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 39, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.85900 seconds<br>2023/08/08 10:16:18 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 40, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.84072 seconds<br>2023/08/08 10:16:19 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 41, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.64984 seconds<br>2023/08/08 10:16:34 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 42, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 15.36737 seconds<br>2023/08/08 10:16:40 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 43, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 5.57040 seconds<br>2023/08/08 10:16:43 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 44, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 3.64214 seconds<br>2023/08/08 10:16:46 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 45, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 2.66113 seconds<br>2023/08/08 10:16:49 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 46, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 3.55517 seconds<br>2023/08/08 10:16:54 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 47, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 4.36036 seconds<br>2023/08/08 10:16:57 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 48, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 3.30097 seconds<br>2023/08/08 10:16:59 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 49, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 2.38395 seconds<br>2023/08/08 10:17:03 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 50, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 3.13199 seconds</pre><h4>Interpreting Optimal Hyperparameters</h4><p>After running the genetic algorithm, we obtain the optimal hyperparameters that enhance the performance of the Support Vector Regression (SVR) model. This section decodes and presents the best hyperparameter configuration, shedding light on the key choices that contribute to the model’s success.</p><pre>best_kernel_encoded = int(best_params[0])<br>best_c = best_params[1]<br>best_gamma = best_params[2]<br>best_epsilon = best_params[3]<br>best_kernel_decoded = [&#39;linear&#39;, &#39;poly&#39;, &#39;rbf&#39;, &#39;precomputed&#39;][best_kernel_encoded]<br><br>print(&quot;Best Hyperparameters using GA:&quot;)<br>print(&quot;Kernel:&quot;, best_kernel_decoded)<br>print(&quot;C:&quot;, best_c)<br>print(&quot;Gamma:&quot;, best_gamma)<br>print(&quot;Epsilon:&quot;, best_epsilon)<br>print(&quot;Best Fitness (R^2):&quot;, -best_fitness)  # Convert back to positive (R^2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EosSO39BQ-nnth_D3qVECg.png" /></figure><p>Next, We’d create an SVR model with the optimized hyperparameters from the Genetic Algorithm and evaluate its performance on both the test and train sets using the R² score.</p><pre># Create SVR model with optimized hyperparameters from GA<br>svr_optimized = SVR(kernel=best_kernel_decoded, C=best_c, gamma=best_gamma, epsilon=best_epsilon)<br>svr_optimized.fit(X_train1, y_train1.ravel())<br><br># Make predictions on train and test set and calculate R^2 score<br>pred_test = svr_optimized.predict(X_test1)<br>pred_train = svr_optimized.predict(X_train1)<br>r2_test = r2_score(y_test1, pred_test)<br>r2_train = r2_score(y_train1, pred_train)<br>print(&quot;R^2 score of Train set prediction using GA:&quot;, r2_train)<br>print(&quot;R^2 score of Test set prediction using GA:&quot;, r2_test)</pre><pre>R^2 score of Test set prediction using GA: 0.978509667165826<br>R^2 score of Train set prediction using GA: 0.9789348583806831</pre><p>The above Evaluation shows how powerful Genetic algorithm is, in the search for the optimal hyperparameters of a model. To further validate the prowess of metaheuristic algorithm for hyperparameters tuning, we’d briefly use the implementation of Particle swarm optimization(PSO), like we did with Genetic algorithm(GA)</p><pre>from mealpy.swarm_based.PSO import CL_PSO<br><br># Defining the PSO Algorithm<br>epoch = 50           # Number of generations/epochs<br>pop_size = 100       # Size of the swarm in each generation<br>c_local = 1.2        # Local cognitive coefficient<br>w_min = 0.4          # Minimum inertia weight<br>w_max = 0.9          # Maximum inertia weight<br>max_flag = 7         # Maximum number of particles to be replaced<br><br># Instantiate the PSO model<br>pso_model = CL_PSO(epoch, pop_size, c_local, w_min, w_max, max_flag)</pre><ul><li>c_local: The local cognitive coefficient, influencing the weight of a particle’s previous best position.</li><li>w_min and w_max: These define the minimum and maximum inertia weights, regulating the balance between exploration and exploitation.</li><li>max_flag: The maximum number of particles to be replaced during the iteration, enhancing diversity.</li></ul><p>With the PSO model instantiated, the next step involves solving the optimization problem using the Particle Swarm Optimization algorithm. This process mirrors the exploration of hyperparameter configurations, analogous to what the genetic algorithm undertook.</p><pre># Solve the optimization problem using the PSO algorithm<br>best_params_pso, best_fitness_pso = pso_model.solve(svr_problem)</pre><pre>2023/08/08 10:15:24 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: Solving single objective optimization problem.<br>2023/08/08 10:15:27 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 1, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.50302 seconds<br>2023/08/08 10:15:29 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 2, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.38361 seconds<br>2023/08/08 10:15:30 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 3, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.45136 seconds<br>2023/08/08 10:15:32 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 4, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.51826 seconds<br>2023/08/08 10:15:34 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 5, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 2.03275 seconds<br>2023/08/08 10:15:35 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 6, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.70323 seconds<br>2023/08/08 10:15:37 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 7, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.29202 seconds<br>2023/08/08 10:15:38 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 8, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.30940 seconds<br>2023/08/08 10:15:39 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 9, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.13348 seconds<br>2023/08/08 10:15:41 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 10, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.48909 seconds<br>2023/08/08 10:15:42 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 11, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 0.98406 seconds<br>2023/08/08 10:15:43 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 12, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.11401 seconds<br>2023/08/08 10:15:44 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 13, Current best: -0.8551661748697635, Global best: -0.8551661748697635, Runtime: 1.46043 seconds<br>2023/08/08 10:15:46 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 14, Current best: -0.8803839866677826, Global best: -0.8803839866677826, Runtime: 1.43844 seconds<br>2023/08/08 10:15:47 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 15, Current best: -0.8803839866677826, Global best: -0.8803839866677826, Runtime: 1.17525 seconds<br>2023/08/08 10:15:48 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 16, Current best: -0.8803839866677826, Global best: -0.8803839866677826, Runtime: 1.47366 seconds<br>2023/08/08 10:15:49 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 17, Current best: -0.8941071936072994, Global best: -0.8941071936072994, Runtime: 1.08602 seconds<br>2023/08/08 10:15:51 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 18, Current best: -0.8960245823511305, Global best: -0.8960245823511305, Runtime: 1.06896 seconds<br>2023/08/08 10:15:52 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 19, Current best: -0.9558305569023439, Global best: -0.9558305569023439, Runtime: 1.08948 seconds<br>2023/08/08 10:15:53 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 20, Current best: -0.9636627347273975, Global best: -0.9636627347273975, Runtime: 1.06011 seconds<br>2023/08/08 10:15:54 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 21, Current best: -0.9644962424849841, Global best: -0.9644962424849841, Runtime: 0.91661 seconds<br>2023/08/08 10:15:55 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 22, Current best: -0.9646775662235703, Global best: -0.9646775662235703, Runtime: 0.91448 seconds<br>2023/08/08 10:15:56 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 23, Current best: -0.9646775662235703, Global best: -0.9646775662235703, Runtime: 1.23127 seconds<br>2023/08/08 10:15:57 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 24, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.02627 seconds<br>2023/08/08 10:15:59 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 25, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 2.55495 seconds<br>2023/08/08 10:16:02 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 26, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 2.57574 seconds<br>2023/08/08 10:16:04 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 27, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 2.09470 seconds<br>2023/08/08 10:16:05 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 28, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 0.93346 seconds<br>2023/08/08 10:16:06 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 29, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.35720 seconds<br>2023/08/08 10:16:07 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 30, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.16948 seconds<br>2023/08/08 10:16:09 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 31, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.66557 seconds<br>2023/08/08 10:16:10 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 32, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.22858 seconds<br>2023/08/08 10:16:11 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 33, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.02662 seconds<br>2023/08/08 10:16:12 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 34, Current best: -0.9647564434251795, Global best: -0.9647564434251795, Runtime: 1.05620 seconds<br>2023/08/08 10:16:14 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 35, Current best: -0.9703544238550341, Global best: -0.9703544238550341, Runtime: 1.07375 seconds<br>2023/08/08 10:16:14 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 36, Current best: -0.9703544238550341, Global best: -0.9703544238550341, Runtime: 0.93133 seconds<br>2023/08/08 10:16:15 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 37, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.86276 seconds<br>2023/08/08 10:16:16 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 38, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.84094 seconds<br>2023/08/08 10:16:17 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 39, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.85900 seconds<br>2023/08/08 10:16:18 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 40, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.84072 seconds<br>2023/08/08 10:16:19 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 41, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 0.64984 seconds<br>2023/08/08 10:16:34 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 42, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 15.36737 seconds<br>2023/08/08 10:16:40 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 43, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 5.57040 seconds<br>2023/08/08 10:16:43 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 44, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 3.64214 seconds<br>2023/08/08 10:16:46 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 45, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 2.66113 seconds<br>2023/08/08 10:16:49 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 46, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 3.55517 seconds<br>2023/08/08 10:16:54 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 47, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 4.36036 seconds<br>2023/08/08 10:16:57 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 48, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 3.30097 seconds<br>2023/08/08 10:16:59 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 49, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 2.38395 seconds<br>2023/08/08 10:17:03 AM, INFO, mealpy.swarm_based.PSO.CL_PSO: &gt;Problem: P, Epoch: 50, Current best: -0.9719079046215082, Global best: -0.9719079046215082, Runtime: 3.13199 seconds</pre><p>Ok, let’s see the optimized hyperparameters and the perfomance as well</p><pre>pso_best_kernel_encoded = int(best_params_pso[0])<br>pso_best_c = best_params_pso[1]<br>pso_best_gamma = best_params_pso[2]<br>pso_best_epsilon = best_params_pso[3]<br>pso_best_kernel_decoded = [&#39;linear&#39;, &#39;poly&#39;, &#39;rbf&#39;, &#39;precomputed&#39;][pso_best_kernel_encoded]<br><br>print(&quot;Best Hyperparameters using PSO:&quot;)<br>print(&quot;Kernel:&quot;, pso_best_kernel_decoded)<br>print(&quot;C:&quot;, pso_best_c)<br>print(&quot;Gamma:&quot;, pso_best_gamma)<br>print(&quot;Epsilon:&quot;, pso_best_epsilon)<br>print(&quot;Best Fitness (R^2):&quot;, -best_fitness_pso)  # Convert back to positive (R^2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1ur_j0LTrQt1aRPzEtuLA.png" /></figure><p>Now, We’d create an SVR model with the optimized hyperparameters from the PSO algorithm and evaluate its performance on both the test and train sets using the R² score.</p><pre># Create SVR model with optimized hyperparameters from PSO<br>svr_optimized_pso = SVR(kernel=pso_best_kernel_decoded, C=pso_best_c, gamma=pso_best_gamma, epsilon=pso_best_epsilon)<br>svr_optimized_pso.fit(X_train1, y_train1.ravel())<br><br># Make predictions on train and test set and calculate R^2 score<br>pred_train_pso = svr_optimized_pso.predict(X_train1)<br>pred_test_pso = svr_optimized_pso.predict(X_test1)<br><br>r2_train_pso = r2_score(y_train1, pred_train_pso)<br>r2_test_pso = r2_score(y_test1, pred_test_pso)<br><br>print(&quot;R^2 score of Train set prediction using PSO:&quot;, r2_train_pso)<br>print(&quot;R^2 score of test set prediction using PSO:&quot;, r2_test_pso)</pre><pre>R^2 score of Train set prediction using PSO: 0.978840873734026<br>R^2 score of test set prediction using PSO : 0.9719079046215082</pre><p>Yeah, Good Performance, a proof of effective hyperparameter tuning by Metaheuristic algorithm.</p><h3>Conclusion</h3><p>In this project, we explored the implementation of metaheuristic algorithms, specifically Genetic Algorithms and Particle Swarm Optimization, for hyperparameter tuning. We used the MEALPY library to optimize the hyperparameters of an SVR model for regression tasks. Both Genetic Algorithms and Particle Swarm Optimization are powerful techniques for finding optimal or near-optimal solutions in complex optimization problems, and they can significantly improve the performance of machine learning models. By leveraging these algorithms, you can save time and effort in the process of hyperparameter tuning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d701caf5d8fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>