<?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 Ramez Shendy on Medium]]></title>
        <description><![CDATA[Stories by Ramez Shendy on Medium]]></description>
        <link>https://medium.com/@ramezrafa?source=rss-b2d04da74b7d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*veH_DJzkNbNQDiksEqct4A.jpeg</url>
            <title>Stories by Ramez Shendy on Medium</title>
            <link>https://medium.com/@ramezrafa?source=rss-b2d04da74b7d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:43:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramezrafa/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[Series Watcher: Your Offline Streaming Companion]]></title>
            <link>https://medium.com/@ramezrafa/series-watcher-your-offline-streaming-companion-3b34457db350?source=rss-b2d04da74b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b34457db350</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vlc]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[tkinter]]></category>
            <category><![CDATA[tv-series]]></category>
            <dc:creator><![CDATA[Ramez Shendy]]></dc:creator>
            <pubDate>Wed, 22 May 2024 08:38:15 GMT</pubDate>
            <atom:updated>2024-05-22T08:38:15.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*2bigy5S1GnzBpOdFonGz5g.png" /></figure><p>In the digital age, binge-watching has become a favorite pastime for many. But, what if you could enhance your viewing experience with a personalized touch? Enter <a href="https://github.com/ShendoxParadox/Series-Watcher">Series Watcher</a>, a Python application designed to elevate your series-watching sessions by adding smart features that simplify and enhance your offline streaming.</p><h4>What is Series Watcher?</h4><p>Series Watcher is a Python-based application that functions like a customized streaming service. It’s built to provide a seamless offline experience for watching series, remembering your progress, and offering playback controls that are typically found in more sophisticated streaming platforms.</p><h4>Key Features</h4><ol><li>Automatic Episode Playback: Continues playing from where you left off, including the exact second in the episode, ensuring you never lose your place.</li><li>Autoplay Next Episode: This feature in Series Watcher ensures a seamless binge-watching experience by automatically starting the next episode once the current one ends. This removes the need for manual intervention, allowing for uninterrupted viewing sessions.</li><li>Autoplay Next Season: This feature in Series Watcher automatically progress to the next season once the current season finishes, provided the seasons are organized in a folder structure.</li><li>Library of Three Different Series: Series Watcher currently supports a library of up to three different series. This feature allows users to manage and switch between multiple series seamlessly within the application. Each series is tracked independently, so users can resume watching from where they left off in any of the three series.</li><li>Episode Renaming: Automatically standardizes episode names, keeping your library neat and organized.</li><li>Playback Controls: Includes intuitive controls for play, pause, fast forward, rewind, and navigation between episodes.</li><li>Custom Skip Time: Allows you to set custom skip times for fast forwarding and rewinding, tailored to your preference.</li><li>Subtitle Selection: Enables you to choose from available embedded subtitles, enhancing your viewing experience.</li><li>Image Display: Displays an image from the series folder, adding a visual element to your browsing.</li><li>JSON State Saving: Saves the current state (season, episode, playback time, and root folder) to a JSON file, ensuring your progress is always remembered.</li><li>Modern UI: Features a user-friendly and visually appealing interface, making the application easy and pleasant to use.</li></ol><h4>Technical Requirements</h4><p>To get started with Series Watcher, you need:</p><ul><li>Python 3.9 or higher</li><li>python-vlc package</li><li>tkinter package</li><li>Pillow package</li></ul><h4>Installation and Usage</h4><p>Installing and running Series Watcher is straightforward:</p><ol><li>Clone the Repository:</li></ol><pre>git clone https://github.com/ShendoxParadox/Series-Watcher.git cd series-watcher</pre><ol><li>Create and Activate a Virtual Environment (Optional but Recommended):</li></ol><pre>python3 -m venv venv source venv/bin/activate</pre><ol><li>Install Dependencies:</li></ol><pre>pip install python-vlc pillow</pre><ol><li>Run the Application:</li></ol><pre>python watch_series.py</pre><p>After launching, you can browse for your series folder, use the playback controls, set custom skip times, and select subtitles as needed. The application provides a smooth and integrated experience for managing and watching your favorite series.</p><h4>Contributing and License</h4><p>Contributions to Series Watcher are welcomed. If you have improvements or new features to add, you can fork the repository and submit a pull request. The project is licensed under the MIT License, ensuring it remains open and accessible to the community.</p><h4>Final Thoughts</h4><p>Series Watcher is a testament to how open-source projects can provide innovative solutions for everyday problems. By combining functionality with a user-friendly interface, it offers a superior alternative to standard media players. Whether you’re a Python developer or a series enthusiast, Series Watcher is a tool worth exploring and contributing to.</p><p>For more details, visit the <a href="https://github.com/ShendoxParadox/Series-Watcher">Series Watcher repository</a> on GitHub.</p><p>Happy watching!</p><p>❓ Feel free to drop your question in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b34457db350" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is P-value and test statistic in statistical testing: A visual guide.]]></title>
            <link>https://medium.com/aimonks/what-is-p-value-and-test-statistic-in-statistical-testing-a-visual-guide-c363eec365cf?source=rss-b2d04da74b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c363eec365cf</guid>
            <category><![CDATA[t-test]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistical-testing]]></category>
            <category><![CDATA[p-value]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Ramez Shendy]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 18:37:05 GMT</pubDate>
            <atom:updated>2024-01-24T17:31:09.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkqCdN2vBZLDjRaU8vrrsg.png" /><figcaption>A histogram distribution of two similar data groups (Left), and the results of a two-tailed t-test to measure the statistical significance of the difference between these two groups (Right).</figcaption></figure><h3>Introduction and definitions</h3><h4>What is statistical testing?</h4><p>Statistical testing is a fundamental principle in the field of statistics, playing a key role in both scientific research and industrial applications. It serves as the basis for making informed decisions and drawing meaningful conclusions from data. This fundamental concept involves subjecting data to rigorous analysis, allowing hypotheses assessment, validate theories, and make predictions with a quantifiable degree of certainty. Statistical testing is the means by which a statistical significance of an experimental result is determined, and by that, distinguishing real effects from being nothing more than chance. In industry, it empowers organizations to optimize processes and make data-driven decisions that can have impacts on efficiency and profitability.</p><h4>What is statistical testing for?</h4><p>One crucial application is the comparison of statistical measures like the mean between two data groups, a process often known as hypothesis testing. By subjecting data to tests like the t-test or analysis of variance (ANOVA), it can be determined whether there exists a statistically significant difference between these groups. Statistical testing is essential in assessing the goodness-of-fit of data to specific probability distributions, such as the normal distribution. Statistical testing offers a wide array of applications beyond comparing means and assessing data distributions. Here are a few more examples:</p><ol><li><strong>A/B Testing:</strong> In online marketing and product development, A/B testing involves comparing two versions of a web page or app to determine which one performs better. Statistical tests are used to analyze user behavior data and ascertain if there’s a statistically significant difference in user engagement, conversion rates, or other key metrics between the two versions.</li><li><strong>Chi-Square Test:</strong> This test is employed to analyze categorical data and determine if there’s an association or independence between two or more categorical variables.</li><li><strong>Regression Analysis:</strong> Statistical tests, such as the F-test and t-test, are used in regression analysis to assess the significance of predictors in a regression model. This helps identify which variables have a statistically significant impact on the dependent variable, allowing for more robust modeling and prediction.</li><li><strong>Quality Control:</strong> In manufacturing and quality control processes, statistical testing is crucial for ensuring product quality and consistency. Techniques like control charts and hypothesis testing are used to monitor production processes and detect deviations that may indicate defects or variations in product quality.</li></ol><h4>What is test statistic and p-value in statistical testing?</h4><p>The test statistic is a numerical summary of sample data that measures the discrepancy between the observed data and what is expected under the null hypothesis, while the p-value provides a quantitative measure of the strength of evidence against the null hypothesis based on the test statistic. These two components are central to hypothesis testing, helping researchers and analysts make informed decisions about whether to accept or reject a null hypothesis in favor of an alternative hypothesis.</p><h3>Example and a visual guide (Python)</h3><p>In the following example, we will use visual aids to help understand the concepts of test statistic and p-value more intuitively. Grasping these ideas becomes easier when one can see them in action and learn through practical examples, making them less abstract and more comprehensible.</p><h4>T<strong>-test</strong></h4><p>The t-test is the statistical test used in this example and it’s a widely used statistical method that helps determine if there is a significant difference between the means of two groups or samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ae_4EauwItW6Qbo8N5m0QA.png" /><figcaption>t-test formula for two independent samples</figcaption></figure><p>T-test Assumptions:</p><ol><li><strong>Random Sampling:</strong> The data should be collected through random sampling to ensure its representativeness of the population.</li><li><strong>Normality:</strong> The data within each group or sample should follow a roughly normal distribution.</li><li><strong>Homogeneity of Variance:</strong> The variances of the two groups being compared should be roughly equal.</li><li><strong>Independence:</strong> Observations within each group should be independent of one another. The values in one group should not depend on or be influenced by the values in the other group.</li></ol><p><strong>Violations of any of these assumptions may affect the reliability of the test.</strong></p><p>Now that we’ve identified the t-test as our chosen statistical method and have a clear understanding of its underlying assumptions, let’s proceed to delve into a practical visual example using Python.</p><p><strong>Python imports:</strong></p><pre>import numpy as np ## for creating the samples<br>import scipy.stats as stats ## for the statitistical testing<br>import matplotlib.pyplot as plt ## for visualization</pre><p><strong>Generating the two samples:</strong></p><pre>n = 500 ## number of samples<br>group1 = np.random.normal(loc=10, scale=2, size=n)<br>group2 = np.random.normal(loc=10, scale=2, size=n)</pre><p>Consider these two generated samples are the price data for a specific vegetable in Euros, spanning various cities and local markets across two different countries (two groups).</p><p>These three lines of Python code can be understood as follows:</p><ul><li><strong>n</strong>=500 means that the number of samples that will be generated are 500 data samples for each group,</li><li><strong>np.random.normal</strong> function generates <strong>random</strong> (t-test assumption) <strong>normally distributed</strong> (t-test assumption) with parameters <strong>loc </strong>which is the mean of each group and <strong>equal</strong> <strong>scale </strong>(t-test assumption)<strong> </strong>which is the standard deviation of each group.</li><li>Values in each group are independent.</li></ul><p>Having satisfied all four assumptions of the t-test, we can confidently utilize this statistical method, assured that the outcomes will be reliable and accurate.</p><p><strong>Visualizing the Samples:</strong></p><pre>plt.hist(group1, bins=15, alpha=0.5, label=&#39;Group 1&#39;)<br>plt.hist(group2, bins=15, alpha=0.5, label=&#39;Group 2&#39;)<br>plt.xlabel(&#39;Value&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.title(&#39;Distributions of Two Groups&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_z9ZFJKXK7DtPiCI1FL-xw.png" /><figcaption>Two generated samples distribution</figcaption></figure><p>The image demonstrates that both sample distributions follow a normal distribution, and it’s noticeable that they have approximately equal means. We generated them randomly with the same mean (mean = 10) and standard deviation (SD) (SD = 2).</p><p><strong>Perform independent t-test (two tailed):</strong></p><p>Null Hypothesis: The two independent samples have identical average (expected) values.</p><p>alpha (The significance level) = 0.05, when you set alpha to 0.05 (or 5%), it means that you are willing to accept a 5% chance of making a Type I error, which is the error of incorrectly rejecting a true null hypothesis.</p><pre>t_statistic, p_value = stats.ttest_ind(group1, group2)</pre><p><strong>test statistic</strong> = -0.450<br><strong>p-value</strong> = 0.6527</p><p>With p-value &gt; alpha, we accept the null hypothesis that states that the two samples have identical means.</p><h4><strong>But what does this actually mean?</strong></h4><pre>## Generate the t-distribution with appropriate degrees of freedom<br>df = len(group1) + len(group2) - 2<br>x = np.linspace(-5, 5, 1000)  # Range of values for the t-distribution<br>t_dist = stats.t.pdf(x, df)<br><br>## Plot the t-distribution<br>plt.plot(x, t_dist, label=&#39;t-distribution&#39;)<br>plt.axvline(x=t_statistic, color=&#39;red&#39;, linestyle=&#39;--&#39;, label=&#39;t-statistic&#39;)<br><br>## Plot the p-value as the area<br>p_value_area = stats.t.cdf(t_statistic, df)<br>plt.fill_between(x, 0, t_dist, where=np.abs(x) &gt;= np.abs(t_statistic), color=&#39;red&#39;, alpha=0.3,<br>                 label=&#39;p-value&#39;)<br><br>## Plot annotations<br>plt.xlabel(&#39;t-value&#39;)<br>plt.ylabel(&#39;Probability Density&#39;)<br>plt.title(&#39;t-distribution with t-statistic and p-value&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAUc67urSzl5cBnrJCJ8TA.png" /><figcaption>The t-distribution along with the t-test test statistic and the p-value as the area under the curve.</figcaption></figure><p>The above code snippet do the following:</p><ol><li>Generate a probability density function for the t-distribution which is the statistical distribution used in the t-test.</li><li>Plot the vertical red line which corresponds to the test statistic we got from the above test (<strong>test statistic</strong> = -0.450)</li><li>Plot the p-value by shading the region under the distribution curve such that it represents the cumulative area below a specific test statistic value that we obtained, and because this is a two-tailed test, the p-value is doubled since the distribution is symmetrical.</li></ol><p>The total area of the shaded region in the above plot is the p-value (<strong>p-value</strong> = 0.6527).</p><p>Keep in mind that the p-value is a probability, and its values always fall within the range of 0 to 1.</p><h4>But what is the difference between one-tailed and two-tailed tests?</h4><p>One-tailed and two-tailed tests represent distinct strategies in hypothesis testing, and their selection depends on the particular research question and whether there is a specific expected direction for the effect under investigation.</p><p><strong>Two-Tailed Test:</strong></p><ol><li>Non-Directional Hypothesis: In a two-tailed test, you don’t make a specific prediction about the direction of the effect. You are interested in whether a parameter is different from a certain value, and you consider both greater and less than alternatives.<strong> In our example, this implies that we are testing whether there is a difference in the average prices between the two distinct countries. We are not anticipating that one country’s prices will be lower or higher than the other, instead, we are investigating the presence of any difference, regardless of its direction.</strong></li><li>Hypotheses: Null Hypothesis (H0): States that there is no effect or no difference. Alternative Hypothesis (Ha): Typically states that there is an effect or difference, without specifying the direction.</li><li>P-Value Interpretation: The p-value for a two-tailed test represents the probability of observing a result as extreme as the one in the sample, in either direction (greater or less than), assuming the null hypothesis is true. <strong>That is why the p-value is doubled in our case.</strong></li></ol><p><strong>One-Tailed Test:</strong></p><ol><li>Directional Hypothesis: In a one-tailed test, you have a specific expectation about the direction of the effect or difference you’re testing. You are interested in whether a parameter is greater than or less than a certain value, but not both.</li><li>Hypotheses: Null Hypothesis (H0): Typically states that there is no effect or no difference. Alternative Hypothesis (Ha): Specifies the direction of the effect and that it exists.</li><li>P-Value Interpretation: The p-value for a one-tailed test represents the probability of observing a result as extreme as the one in the sample, in the specified direction, assuming the null hypothesis is true.</li></ol><p>Now, let’s modify the mean of the first group and observe how this change impacts the outcomes.</p><pre>n = 500 ## number of samples<br>group1 = np.random.normal(loc=9.8, scale=2, size=n)<br>group2 = np.random.normal(loc=10, scale=2, size=n)</pre><p>Everything is the same as the previous experiment except for the change of the mean of the first group:</p><ul><li>mean of the first group = 9.8</li><li>mean of the second group = 10</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0D7DQov5UPiusAd09vNhQ.png" /></figure><p><strong>test statistic</strong> = -1.219<br><strong>p-value</strong> = 0.223<br><strong>Accept Null Hypothesis</strong> — The difference is insignificant</p><p>Now, let’s drastically decrease the mean of the first group and observe how this change impacts the outcomes.</p><ul><li>mean of the first group = 6</li><li>mean of the second group = 10</li></ul><pre>n = 500 ## number of samples<br>group1 = np.random.normal(loc=6, scale=2, size=n)<br>group2 = np.random.normal(loc=10, scale=2, size=n)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pmkm0sPErLoXWJmqP0YFMg.png" /></figure><p><strong>test statistic</strong> = -30.304<br><strong>p-value</strong> = 1.473e-143 &lt;&lt;&lt; alpha<br><strong>Reject Null Hypothesis</strong> — Significant difference between two groups</p><p><strong>In conclusion</strong>, the p-value in statistical testing serves as a critical metric that informs us about the strength of evidence against the null hypothesis. It is derived from the test statistic and is essentially the cumulative shaded area under the distribution curve associated with a specific statistical test. This area represents the probability of obtaining a test statistic as extreme or more extreme than the one observed in the sample data, assuming the null hypothesis is true. Importantly, in the context of a two-tailed test, this area is doubled to account for the possibility of significant effects in either direction from the null hypothesis. The p-value provides a clear and quantifiable measure of the evidence supporting or proving a hypothesis, aiding researchers and analysts in making informed decisions based on their data.</p><p>Full code can be found on:</p><p><a href="https://github.com/ShendoxParadox/T-test-with-visualization/blob/main/t_test_with_visualization.py">T-test-with-visualization/t_test_with_visualization.py at main · ShendoxParadox/T-test-with-visualization</a></p><p>👏 Clap for the story if you liked it.</p><p>❓ Feel free to drop your question in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c363eec365cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aimonks/what-is-p-value-and-test-statistic-in-statistical-testing-a-visual-guide-c363eec365cf">What is P-value and test statistic in statistical testing: A visual guide.</a> was originally published in <a href="https://medium.com/aimonks">𝐀𝐈 𝐦𝐨𝐧𝐤𝐬.𝐢𝐨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Traveling Salesman Problem (TSP) using Genetic Algorithm (Python)]]></title>
            <link>https://medium.com/aimonks/traveling-salesman-problem-tsp-using-genetic-algorithm-fea640713758?source=rss-b2d04da74b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fea640713758</guid>
            <category><![CDATA[traveling-salesman]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[route-optimization]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ramez Shendy]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 19:40:14 GMT</pubDate>
            <atom:updated>2024-01-24T17:31:45.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPhCcc76Q7dIetDSFRWHAw.png" /><figcaption>Image generated by the author.</figcaption></figure><h3><strong>Traveling Salesman Problem</strong></h3><p>For decades, the Traveling Salesman Problem (TSP) has been an intriguing challenge for mathematicians, computer scientists, and operations researchers. It involves determining the shortest route for a salesman to take to visit a set of cities and return to the starting point. As the number of cities increases, the complexity of the problem grows exponentially, which is known as a combinatorial explosion. Solutions for the TSP have been attempted through a variety of algorithms and techniques, such as dynamic programming, branch-and-bound, <strong>genetic algorithms</strong>, and simulated annealing.</p><p>The computational complexity of algorithms for solving the Traveling Salesman Problem (TSP) can vary significantly depending on the approach used. Here’s a brief overview of some common algorithms and their complexities:</p><pre>| Algorithm             | Approach                 | Complexity         |<br>|-----------------------|--------------------------|--------------------|<br>| Brute Force           | Exact                    | O(n!)              |<br>| Dynamic Programming   | Exact                    | O(n^2 * 2^n)       |<br>| Branch and Bound      | Exact                    | O(n!)              |<br>| Genetic Algorithms    | Heuristic                | Depends on params  |</pre><p><strong>The brute-force</strong> approach exhaustively explores all possible permutations of cities to find the optimal solution.</p><p>For a TSP with “n” cities, there are (n-1) choices for the second city, (n-2) choices for the third city, and so on until there is only one choice left for the last city. The total number of permutations is calculated as the factorial of (n-1), denoted as (n-1)!. For example, if there are 5 cities (n=5), the number of permutations is (5–1)! = 4! = 4 x 3 x 2 x 1 = 24. Since the salesman must return to the starting city to complete the tour. Therefore, after calculating the number of permutations, we multiply it by “n” to account for starting the tour from each of the “n” cities. In the example with 5 cities, we have 24 permutations for each starting city, resulting in a total of 24 x 5 = 120 possible tours to evaluate.</p><p>The time complexity is determined by the total number of permutations. Since the number of permutations is (n-1)! * n, the time complexity of the brute force method to solve the TSP is O((n-1)! * n) which can be simplified to <strong>O(n!)</strong>.</p><p><strong>Genetic Algorithms</strong> involve a heuristic process based on the concept of natural selection. These algorithms may not deliver the best possible solution, but they can quickly identify good approximations. It is difficult to estimate the amount of time it takes to complete a genetic algorithm since it is dependent on population size, number of generations, and other factors.</p><p>It is important to be aware that the Traveling Salesman Problem is an NP-hard problem, meaning no algorithm that is polynomial-time has been found to solve it. This is why the algorithms discussed above are either exact yet slow for larger instances or heuristic, providing close-to-accurate solutions quickly. This has caused the TSP to be a very interesting and difficult issue in the realm of computational optimization, causing scientists to keep on developing more effective and precise algorithms.</p><p>In this article, we shall discuss the solution of the TSP using genetic algorithms in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*uukb4t5NPgF-knAwHPV1Yw.gif" /><figcaption>GA Optimization (Image generated by the author).</figcaption></figure><h3>Genetic Algorithms (GAs):</h3><p>Genetic algorithms are a type of evolutionary algorithm inspired by the processes of natural selection and genetics. They are widely used for optimization and search problems. The main components of a genetic algorithm include:</p><h3><strong>Population</strong></h3><p>The optimization problem is composed of an array of possible solutions, known as a “population”. Every single solution is symbolized as a “chromosome” or “individual”. The population changes over time, and its quantity and variety can affect the effectiveness of the algorithm.</p><pre>def initial_population(cities_list, n_population = 250):<br>    <br>    &quot;&quot;&quot;<br>    Generating initial population of cities randomly selected from all <br>    possible permutations  of the given cities<br>    Input:<br>    1- Cities list <br>    2. Number of population <br>    Output:<br>    Generated lists of cities<br>    &quot;&quot;&quot;<br>    <br>    population_perms = []<br>    possible_perms = list(permutations(cities_list))<br>    random_ids = random.sample(range(0,len(possible_perms)),n_population))<br>    for i in random_ids:<br>        population_perms.append(list(possible_perms[i]))<br>        <br>    return population_perms</pre><p>The above function would initialize the required number of individuals, which together form the algorithm&#39;s initial population. Please note that each individual in our case is a probable solution, which means that each individual is a sequence of cities without any repetition, as the traveling salesman should not pass any city twice while completing his or her journey. One individual example could be: <strong>[Gliwice, Cairo, Rome, Krakow, Paris, Alexandria, Berlin, Tokyo, Hong Kong, Rio]</strong></p><p>As each individual is a probable solution, we need to evaluate this solution’s performance by measuring the total distance traveled by the salesman, as the distance traveled is the only metric that undergoes optimization in our example under the assumption that the lines or edges connecting the cities are straight lines and there are no better roads than the others. In real life, roads are not built in straight lines; some are wider than others, and some have traffic. These restrictions can be translated into time or the duration of the journey, but for simplicity, the only metric we’re optimizing for here is the total distance.</p><pre>def dist_two_cities(city_1, city_2):<br>    <br>    &quot;&quot;&quot;<br>    Calculating the distance between two cities  <br>    Input:<br>    1- City one name <br>    2- City two name<br>    Output:<br>    Calculated Euclidean distance between two cities<br>    &quot;&quot;&quot;<br>    <br>    city_1_coords = city_coords[city_1]<br>    city_2_coords = city_coords[city_2]<br>    return np.sqrt(np.sum((np.array(city_1_coords) - np.array(city_2_coords))**2))</pre><p>The above function calculates the Euclidean distance between two cities, which is the length of the edge connecting the two cities together.</p><pre>def total_dist_individual(individual):<br>    <br>    &quot;&quot;&quot;<br>    Calculating the total distance traveled by individual, <br>    one individual means one possible solution (1 permutation)<br>    Input:<br>    1- Individual list of cities <br>    Output:<br>    Total distance traveled <br>    &quot;&quot;&quot;<br>    <br>    total_dist = 0<br>    for i in range(0, len(individual)):<br>        if(i == len(individual) - 1):<br>            total_dist += dist_two_cities(individual[i], individual[0])<br>        else:<br>            total_dist += dist_two_cities(individual[i], individual[i+1])<br>    return total_dist</pre><p>This function calculates the total distance traveled by a single individual by utilizing the function that calculates the distance between two cities.</p><p>As of now, we can assess the performance of each individual, which is a potential solution to the problem. If we generate <strong>all</strong> the probable solutions to the problem and measure the total distance traveled by each solution (individual), we ‌then have a winner which is the individual with the least traveled distance. However, we would need enormous computational power and time as the complexity of the problem increases significantly as the number of cities increases. This approach of assessing the performance of all the potential solutions is called the brute force approach. In our example, we only generated a few individuals to start our GA optimization with.</p><h3><strong>Fitness Function</strong></h3><p>The fitness function assesses the quality of each individual in the population, assessing how well each potential solution solves the problem. This function guides the search process by giving higher scores to better solutions.</p><pre>def fitness_prob(population):<br>    &quot;&quot;&quot;<br>    Calculating the fitness probability <br>    Input:<br>    1- Population  <br>    Output:<br>    Population fitness probability <br>    &quot;&quot;&quot;<br>    total_dist_all_individuals = []<br>for i in range (0, len(population)):<br>        total_dist_all_individuals.append(total_dist_individual(population[i]))<br>        <br>    max_population_cost = max(total_dist_all_individuals)<br>    population_fitness = max_population_cost - total_dist_all_individuals<br>    population_fitness_sum = sum(population_fitness)<br>    population_fitness_probs = population_fitness / population_fitness_sum<br>    return population_fitness_probs</pre><p>This function converts the total distance traveled by an individual in the population into a probability. This can facilitate the next step of selecting the best-fit individuals.</p><h3><strong>Selection</strong></h3><p>In the selection process, individuals with higher fitness values have a higher probability of being chosen for reproduction. This is an emulation of the concept of “the strong prevail” from natural selection, where those with beneficial features have a greater likelihood of passing down their genes to the next generation. The selection approach used in this example is <strong>Roullette Wheel Selection</strong>.</p><pre>def roulette_wheel(population, fitness_probs):<br>    &quot;&quot;&quot;<br>    Implement a selection strategy based on proportionate roulette wheel<br>    Selection.<br>    Input:<br>    1- population<br>    2: fitness probabilities <br>    Output:<br>    selected individual<br>    &quot;&quot;&quot;<br>    population_fitness_probs_cumsum = fitness_probs.cumsum()<br>    bool_prob_array = population_fitness_probs_cumsum &lt; np.random.uniform(0,1,1)<br>    selected_individual_index = len(bool_prob_array[bool_prob_array == True]) - 1<br>    return population[selected_individual_index]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*N9at9Ds_8RmYd5uToEpaBg.gif" /><figcaption>Roullette Wheel Selection Method (Image generated by the author).</figcaption></figure><p>When selecting an individual based on its fitness, a random number between 0 and 1 is generated from a <strong>uniform</strong> <strong>distribution </strong>and this generated number will be used to select a certain individual. If the individual has a higher fitness, then it’s more likely to cover a bigger area as shown in the above circle. The uniform distribution to draw a number is used because, at this point, we don’t want to favor one individual over another but rather let their fitness probabilities give them a higher or lower chance of being chosen. In the above animation, it is clear that those with greater fitness are more likely to be selected. However, that does not mean that those who are less fit will never be chosen.</p><h3><strong>Crossover</strong></h3><p>Crossover is the process of creating new individuals by combining genetic information from two or more parent individuals. It emulates the genetic recombination that occurs during sexual reproduction in biology. Crossover points are selected on the parent chromosomes, and the genetic material is exchanged to create new <strong>offspring</strong>.</p><pre>def crossover(parent_1, parent_2):<br>    &quot;&quot;&quot;<br>    Implement mating strategy using simple crossover between two parents<br>    Input:<br>    1- parent 1<br>    2- parent 2 <br>    Output:<br>    1- offspring 1<br>    2- offspring 2<br>    &quot;&quot;&quot;<br>    n_cities_cut = len(cities_names) - 1<br>    cut = round(random.uniform(1, n_cities_cut))<br>    offspring_1 = []<br>    offspring_2 = []<br>    <br>    offspring_1 = parent_1 [0:cut]<br>    offspring_1 += [city for city in parent_2 if city is not in offspring_1]<br>    <br>    <br>    offspring_2 = parent_2 [0:cut]<br>    offspring_2 += [city for city in parent_1 if city is not in offspring_2]<br>    <br>    <br>    return offspring_1, offspring_2</pre><p>Here is the part where the selected individuals are mating or mixing to generate new ones (offspring). For example, if we have two individuals with 10 elements each, we can take the first 3 elements from the first individual and the last 7 elements from the second individual. Generally Selecting a subset of elements from one individual and the remaining elements from the other, ensuring that no duplicate elements are taken from the first individual. Choosing the number of offspring produced by each pair of parents can be considered part of the population management process. Additionally, the selection of how many elements to take from the first individual can be randomized using a uniform distribution. Although this choice might not have a specific philosophy behind it, using the uniform distribution ensures higher variability in the selection process, enabling the genetic algorithm to explore a more diverse set of solutions.</p><h3><strong>Mutation</strong></h3><p>Mutation introduces small random changes to the genetic information of individuals. It helps introduce new genetic material into the population, promoting exploration of the search space and preventing premature convergence to suboptimal solutions.</p><pre>def mutation(offspring):<br>    &quot;&quot;&quot;<br>    Implement mutation strategy in a single offspring<br>    Input:<br>    1- offspring individual<br>    Output:<br>    1- mutated offspring individual<br>    &quot;&quot;&quot;<br>    n_cities_cut = len(cities_names) - 1<br>    index_1 = round(random.uniform(0,n_cities_cut))<br>    index_2 = round(random.uniform(0,n_cities_cut))<br><br>    temp = offspring [index_1]<br>    offspring[index_1] = offspring[index_2]<br>    offspring[index_2] = temp<br>    return(offspring)</pre><p>In this code snippet, the mutation process is implemented using a straightforward switching step. A random element is selected, and it is swapped with another element which is also chosen randomly. This simple switching process enables the genetic algorithm to introduce mutation to selected individuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tUfgYZdUV5sxtD7L1IlqQw.gif" /><figcaption>Very low Mutation Rate (Image generated by the author).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*QdxLD95imf8VnrL5nlFHdQ.gif" /><figcaption>High Mutation Rate (Image generated by the author).</figcaption></figure><p>The mutation rate (The percentage of individuals that will experience mutation) can have a huge influence on the outcome and the optimization procedure. The two animations featured above demonstrate the impact of a high and low mutation rate before optimization is applied. In this case, what is happening is the sole influence of mutation, without taking into account the rest of the optimization process.</p><h3><strong>Replacement</strong></h3><p>Once selection, crossover, and mutation have occurred, the newly generated individuals (offspring) replace some of the original population. This replacement tactic ensures the population is maintained at a fixed size between generations, which is also a component of population management techniques.</p><p>By iteratively applying these components, genetic algorithms explore the search space, gradually improving the quality of solutions over generations. Through selection, crossover, and mutation, the algorithm can efficiently converge towards <strong>optimal</strong> or <strong>near-optimal</strong> solutions.</p><h3>GA Algorithm Parameters</h3><p><strong>Population Size</strong>: The population size defines the number of candidate solutions (individuals) present in each generation. A larger population size increases the diversity of the population, promoting exploration of the search space. However, it also leads to increased computation time. Finding the right balance is essential to striking a trade-off between exploration and exploitation.</p><p><strong>Crossover Rate:</strong> The crossover rate defines the probability of applying crossover (recombination) to create new offspring from selected parent individuals. Crossover helps combine beneficial traits from different parents and is crucial for exploration and maintaining diversity in the population.</p><p><strong>Mutation Rate:</strong> The mutation rate determines the probability of introducing random changes to the genetic information of individual chromosomes. Mutation aids in exploration, allowing the algorithm to escape local optima. However, setting a mutation rate too high can lead to excessive exploration and divergence from good solutions.</p><p><strong>Number of Generations:</strong> The number of generations determines how many iterations or cycles the genetic algorithm will run. Each generation produces a new set of individuals through selection, crossover, and mutation. A higher number of generations generally allows more time for the algorithm to explore the search space thoroughly.</p><p><strong>Termination Criteria:</strong> The termination criteria determine when the genetic algorithm stops running. Common termination criteria include reaching a maximum number of generations, finding a satisfactory solution, or reaching a predefined fitness level. Proper termination criteria help avoid unnecessary computation and improve efficiency.</p><pre>n_population = 250<br>crossover_per = 0.8<br>mutation_per = 0.2<br>n_generations = 200</pre><p>In the given code snippet, the algorithm parameters are specified as follows: The population size is set to 250 individuals. After the selection process, 80% of the selected individuals will undergo crossover, while only 20% of the resulting offspring will undergo mutation. The algorithm is set to terminate after 200 generations, meaning that the entire process, including selection, crossover, and mutation, will be repeated 200 times in an attempt to achieve convergence.</p><h4>Cities Coordinates</h4><pre>x = [0,3,6,7,15,10,16,5,8,1.5]<br>y = [1,2,1,4.5,-1,2.5,11,6,9,12]<br>cities_names = [&quot;Gliwice&quot;, &quot;Cairo&quot;, &quot;Rome&quot;, &quot;Krakow&quot;, &quot;Paris&quot;, <br>                &quot;Alexandria&quot;, &quot;Berlin&quot;, &quot;Tokyo&quot;, &quot;Hong Kong&quot;, &quot;Rio&quot;]<br>city_coords = dict(zip(cities_names, zip(x, y)))</pre><p>In the above code snippet, the cities are represented using (x, y) coordinates, where each pair (x, y) corresponds to a point on the Cartesian plane. It’s important to note that in real-world applications, cities are typically represented using <strong>longitude</strong> and <strong>latitude</strong> coordinates. Also, the city names used in this example are for illustration purposes only and do not reflect the actual distances between these cities but were chosen purely for the convenience of this demonstration. The last line of code creates a dictionary where each city name is the dictionary key and the corresponding (x, y) coordinates are the dictionary value.</p><h3>Putting it all together</h3><pre>import matplotlib.pyplot as plt<br>from itertools import permutations and combinations<br>from random import shuffle<br>import random<br>import numpy as np<br>import statistics<br>import pandas as pd<br>import seaborn as SNs<br></pre><p>These are the important libraries used in this example.</p><pre>def run_ga(cities_names, n_population, n_generations,<br>           crossover_per, mutation_per):<br>    <br>    population = initial_population(cities_names, n_population)<br>    fitness_probs = fitness_prob(population)<br>    <br>    parents_list = []<br>    for i in range(0, int(crossover_per * n_population)):<br>        parents_list.append(roulette_wheel(population,<br>                                           fitness_probs))<br><br>    offspring_list = []    <br>    for i in range(0,len(parents_list), 2):<br>        offspring_1, offspring_2 = crossover(parents_list[i], <br>                                             parents_list[i+1])<br><br>    #     print(offspring_1)<br>    #     print(offspring_2)<br>    #     print()<br><br>        mutate_threashold = random.random()<br>        if(mutate_threashold &gt; (1-mutation_per)):<br>            offspring_1 = mutation(offspring_1)<br>    #         print(&quot;Offspring 1 mutated&quot;, offspring_1)<br><br>        mutate_threashold = random.random()<br>        if(mutate_threashold &gt; (1-mutation_per)):<br>            offspring_2 = mutation(offspring_2)<br>    #         print(&quot;Offspring 2 mutated&quot;, offspring_2)<br><br><br>        offspring_list.append(offspring_1)<br>        offspring_list.append(offspring_2)<br><br>    mixed_offspring = parents_list + offspring_list<br><br>    fitness_probs = fitness_prob(mixed_offspring)<br>    sorted_fitness_indices = np.argsort(fitness_probs)[::-1]<br>    best_fitness_indices = sorted_fitness_indices[0:n_population]<br>    best_mixed_offsrping = []<br>    for i in best_fitness_indices:<br>        best_mixed_offsrping.append(mixed_offspring[i])<br><br><br>    for i in range(0, n_generations):<br>        # if (i%10 == 0):<br>            # print(&quot;Generation: &quot;, i)<br>        <br>        fitness_probs = fitness_prob(best_mixed_offsrping)<br>        parents_list = []<br>        for i in range(0, int(crossover_per * n_population)):<br>            parents_list.append(roulette_wheel(best_mixed_offsrping, <br>                                               fitness_probs))<br><br>        offspring_list = []    <br>        for i in range(0,len(parents_list), 2):<br>            offspring_1, offspring_2 = crossover(parents_list[i], <br>                                                 parents_list[i+1])<br><br>            mutate_threashold = random.random()<br>            if(mutate_threashold &gt; (1-mutation_per)):<br>                offspring_1 = mutation(offspring_1)<br><br>            mutate_threashold = random.random()<br>            if(mutate_threashold &gt; (1-mutation_per)):<br>                offspring_2 = mutation(offspring_2)<br><br>            offspring_list.append(offspring_1)<br>            offspring_list.append(offspring_2)<br><br><br>        mixed_offspring = parents_list + offspring_list<br>        fitness_probs = fitness_prob(mixed_offspring)<br>        sorted_fitness_indices = np.argsort(fitness_probs)[::-1]<br>        best_fitness_indices = sorted_fitness_indices[0:int(0.8*n_population)]<br><br>        best_mixed_offsrping = []<br>        for i in best_fitness_indices:<br>            best_mixed_offsrping.append(mixed_offspring[i])<br>            <br>        old_population_indices = [random.randint(0, (n_population - 1)) <br>                                  for j in range(int(0.2*n_population))]<br>        for i in old_population_indices:<br>#             print(i)<br>            best_mixed_offsrping.append(population[i])<br>            <br>        random.shuffle(best_mixed_offsrping)<br>            <br>    return best_mixed_offsrping</pre><p>The above function performs the algorithm’s steps in the following order:</p><ol><li>Initialize the population</li><li>Calculates fitness of individuals</li><li>Applies Roullette Wheel selection method to individuals</li><li>Performs crossover between selected individuals</li><li>Performs mutation on the resulting offspring</li><li>Replaces a subset of the old population with new offspring (Replacement)</li><li>Shuffles the new population and returns it</li><li>Repeat for number of generations and terminate</li></ol><pre>best_mixed_offsrping = run_ga(cities_names, n_population,<br>                              n_generations, crossover_per, mutation_per)<br><br>total_dist_all_individuals = []<br>for i in range(0, n_population):<br>    total_dist_all_individuals.append(total_dist_individual(best_mixed_offsrping[i]))<br><br>index_minimum = np.argmin(total_dist_all_individuals)<br>minimum_distance = min(total_dist_all_individuals)<br><br>shortest_path = best_mixed_offsrping[index_minimum]<br></pre><p>In the above code snippet, the algorithm is being executed with the specified inputs, the least distance that an individual has traveled is set in the minimum_distance variable as well as the path traversed to reach this distance.</p><p>The <strong>minimum_distance</strong> and the optimal solution is <strong>61.137</strong></p><p><strong>The shortest path</strong> is: <strong>Cairo → Gliwice → Tokyo → Rio → Hong Kong → Berlin → Paris → Alexandria → Krakow → Rome → Cairo</strong></p><h3>Optimum Solution Visualization</h3><pre>x_shortest = []<br>y_shortest = []<br>for city in shortest_path:<br>    x_value, y_value = city_coords[city]<br>    x_shortest.append(x_value)<br>    y_shortest.append(y_value)<br>    <br>x_shortest.append(x_shortest[0])<br>y_shortest.append(y_shortest[0])<br><br>fig, ax = plt.subplots()<br>ax.plot(x_shortest, y_shortest, &#39;--go&#39;, label=&#39;Best Route&#39;, linewidth=2.5)<br>plt.legend()<br><br>for i in range(len(x)):<br>    for j in range(i + 1, len(x)):<br>        ax.plot([x[i], x[j]], [y[i], y[j]], &#39;k-&#39;, alpha=0.09, linewidth=1)<br>        <br>plt.title(label=&quot;TSP Best Route Using GA&quot;,<br>          fontsize=25,<br>          color=&quot;k&quot;)<br><br>str_params = &#39;\n&#39;+str(n_generations)+&#39; Generations\n&#39;+str(n_population)+&#39; Population Size\n&#39;+str(crossover_per)+&#39; Crossover\n&#39;+str(mutation_per)+&#39; Mutation&#39;<br>plt.suptitle(&quot;Total Distance Travelled: &quot;+ <br>             str(round(minimum_distance, 3)) + <br>             str_params, fontsize=18, y = 1.047)<br><br>for i, txt in enumerate(shortest_path):<br>    ax.annotate(str(i+1)+ &quot;- &quot; + txt, (x_shortest[i], y_shortest[i]), fontsize= 20)<br><br>fig.set_size_inches(16, 12)    <br># plt.grid(color=&#39;k&#39;, linestyle=&#39;dotted&#39;)<br>plt.savefig(&#39;solution.png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEPTQlTMReh7ezcVtqow3g.png" /><figcaption>Optimal Solution (Image generated by the author).</figcaption></figure><h3>Convergence Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*eW8InpU-uvhlR2qXprkzbw.gif" /><figcaption>Convergence Process (Image generated by the author).</figcaption></figure><p>As demonstrated in the animation, the GA achieved convergence in far fewer generations than expected, as 200 generations was the initial assumed maximum. However, it is essential to adjust the number of generations to reach the best and most speedy outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*64N8DxeMcfVodzoC3-hq1w.gif" /><figcaption>Convergence Process (Image generated by the author).</figcaption></figure><p>In some situations, a genetic algorithm can become trapped in a local minimum, hindering its ability to find the global optimum. To address this, the mutation rate becomes a valuable parameter as it introduces random changes that aid in escaping local minima. However, while mutation can be effective in exploring new areas, excessive mutation can lead to divergence, as seen in the above animation, even after reaching a promising solution. Consequently, the selection of algorithm parameters becomes crucial in dealing with such challenges. Finding the right set of parameters is essential for achieving a stable, fast, and near-optimal solution. This process of searching for the best parameter configuration is vital to maximizing the algorithm’s performance and ensuring it converges efficiently towards the global minimum.</p><h3>Conclusion</h3><p>In conclusion, the application of genetic algorithms to solve the Traveling Salesman Problem (TSP) has proven to be a powerful and flexible approach. The algorithm operates by mimicking the principles of natural selection, employing components such as population, fitness evaluation, selection, crossover, and mutation. These mechanisms enable the genetic algorithm to explore the vast search space efficiently and gradually converge towards <strong>optimal</strong> or <strong>near-optimal</strong> solutions.</p><p>However, the success of a genetic algorithm in solving the TSP heavily depends on the careful selection of its parameters. The most critical parameters include ‌<strong>population size</strong>, <strong>mutation rate</strong>, <strong>crossover rate</strong>, and the <strong>number of generations</strong>. Each of these parameters influences the algorithm’s behavior and performance in distinctive ways. For instance, a larger population size promotes <strong>exploration</strong> but increases <strong>computation time</strong>, while a higher mutation rate helps <strong>escape local minima</strong> but might lead to <strong>divergence</strong> if set excessively.</p><p>Finding the right balance among these parameters becomes critical to achieving the best performance. An unsuitable parameter configuration can lead to bad performance, trapping the algorithm in suboptimal solutions, or excessive exploration that prolongs the optimization process unnecessarily.</p><p>Hence, researchers and practitioners must conduct thorough <strong>parameter tuning</strong> to identify the optimal combination for their specific GA instances. This process often involves experimentation and iterative refinement to strike a balance between exploration and exploitation. By selecting appropriate parameters, the genetic algorithm can efficiently explore the search space, escape local minima, and converge towards a stable, near-optimal solution in a timely manner.</p><p>GAs provide a robust and adaptable approach for solving the TSP, and their effectiveness is highly dependent on skillful parameter selection. By understanding the impact of each parameter, researchers can control the algorithm’s potential to tackle complex real-world traveling salesman scenarios effectively. As the field of optimization continues to evolve, refining genetic algorithms’ parameters will remain a critical aspect of maximizing their performance and relevance in solving a wide range of combinatorial optimization problems.</p><p>Please find the full code here:</p><p><a href="https://github.com/ShendoxParadox/TSP-Genetic-Algorithm">GitHub - ShendoxParadox/TSP-Genetic-Algorithm: This repository provides a solution to the classic Traveling Salesman Problem (TSP) using a genetic algorithm. The genetic algorithm is a heuristic optimization method inspired by the process of natural selection and genetic variation.</a></p><p>👏 Clap for the story if you liked it.</p><p>❓ Feel free to drop your question in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fea640713758" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aimonks/traveling-salesman-problem-tsp-using-genetic-algorithm-fea640713758">Traveling Salesman Problem (TSP) using Genetic Algorithm (Python)</a> was originally published in <a href="https://medium.com/aimonks">𝐀𝐈 𝐦𝐨𝐧𝐤𝐬.𝐢𝐨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>