<?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 ferhatmetin on Medium]]></title>
        <description><![CDATA[Stories by ferhatmetin on Medium]]></description>
        <link>https://medium.com/@ferhatmetin34?source=rss-8d2aef75e0fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*52GVKcIFV4S7z1GCP5m9EQ.jpeg</url>
            <title>Stories by ferhatmetin on Medium</title>
            <link>https://medium.com/@ferhatmetin34?source=rss-8d2aef75e0fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:40:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ferhatmetin34/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[20 Useful Python Libraries for Data Science Projects]]></title>
            <link>https://medium.com/datasciencearth/20-useful-python-libraries-for-data-science-projects-f393faad4419?source=rss-8d2aef75e0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f393faad4419</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-list]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[ferhatmetin]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 19:28:57 GMT</pubDate>
            <atom:updated>2021-06-10T10:06:45.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AS5f709K3Lqwl7UflIhiTQ.png" /></figure><p>Scikit-learn, Numpy, Pandas, Matplotlib, Plotly, Bokeh and Seaborn are some of the common Python libraries used in the field of data science. Let’s see some other libraries that can be useful for data science projects.</p><h3>1-Feature Engine</h3><p>Feature-Engine is a library for feature engineering and it allows us to select the variables we want to transform so it’s very easy to apply different engineering procedures to different feature subsets. Also, Feature-Engine transformers can be assembled within the Scikit-learn pipeline.</p><p>Feature-Engine includes transformers for:</p><ul><li>Variable transformation</li><li>Variable selection</li><li>Categorical variable encoding</li><li>Missing data imputation</li><li>Discretisation</li><li>Outlier capping or removal</li><li>Variable creation</li></ul><p>For the documentation and more:</p><p><a href="https://feature-engine.readthedocs.io/en/1.0.x/">Feature-engine: A Python library for Feature Engineering for Machine Learning - 1.0.2</a></p><h3>2-Yellowbrick</h3><p>Yellowbrick is a library for machine learning visualization. It extends the Scikit-Learn API to make model selection and hyperparameter tuning easier. It’s using Matplotlib for visualizations. Some visualizers: Precision-Recall Curves, Confusion Matrices, Residuals Plot, K-Elbow Plot, Silhouette Plot, Learning Curve, t-SNE Corpus Visualization…</p><p>For the documentation and more:</p><p><a href="https://www.scikit-yb.org/en/latest/">Yellowbrick: Machine Learning Visualization - Yellowbrick v1.5 documentation</a></p><h3>3-PDPbox</h3><p>Partial dependence plots shows the marginal effect one or two features have on the predicted outcome of a machine learning model (J. H. Friedman, 2001). PDPBox is a library for partial dependence plots.</p><p>For the documentation and more:</p><p><a href="https://github.com/SauceCat/PDPbox">SauceCat/PDPbox</a></p><h3>4-Eli5</h3><p>Eli5 is a Python package that helps to debug machine learning classifiers and explain their predictions. It helps to explain predictions of black-box estimators. It provides support for Scikit-Learn, Keras, xgboost, LightGBM, CatBoost…</p><p>For the documentation and more:</p><p><a href="https://eli5.readthedocs.io/en/latest/">Welcome to ELI5&#39;s documentation! - ELI5 0.11.0 documentation</a></p><h3>5-Researchpy</h3><p>Researchpy creates Pandas DataFrames that contains relevant statistical testing information that is required for academic research. It uses Pandas, Scipy, Numpy, Statmodels…</p><p>For the documentation and more:</p><p><a href="https://researchpy.readthedocs.io/en/latest/">Welcome to researchpy&#39;s documentation! - researchpy 0.3.2 documentation</a></p><h3>6-LIME</h3><p>LIME (Local Interpretable Model-agnostic Explanations) is an algorithm to explain predictions of black-box estimators and LIME library is one of the most popular Python libraries for model explainability.</p><p>For the documentation and more:</p><p><a href="https://github.com/marcotcr/lime">GitHub - marcotcr/lime: Lime: Explaining the predictions of any machine learning classifier</a></p><h3>7-SHAP</h3><p>SHAP (SHapley Additive exPlanations) is a game theoretic approach to explain the output of any machine learning model and Shap library allows us to visualize shapley values.</p><p>For the documentation and more:</p><p><a href="https://github.com/slundberg/shap">GitHub - slundberg/shap: A game theoretic approach to explain the output of any machine learning model.</a></p><h3>8-Missingno</h3><p>Missingno provides a small toolset of flexible and easy-to-use missing data visualizations and it helps us to get a quick visual summary of our dataset.</p><p>For the documentation and more:</p><p><a href="https://github.com/ResidentMario/missingno">GitHub - ResidentMario/missingno: Missing data visualization module for Python.</a></p><h3>9-Imblearn</h3><p>Imbalanced-learn (Imblearn) is an open source library relying on scikit-learn and provides tools when dealing with classification with imbalanced classes.</p><p>For the documentation and more:</p><p><a href="https://imbalanced-learn.org/stable/user_guide.html#user-guide">User guide: contents - Version 0.8.0</a></p><h3>10-Dataprep</h3><p>DataPrep allows us to prepare and visualize our data with a few lines of code. I think it could be an alternative to Pandas Profiling.</p><p>For the documentation and more:</p><p><a href="https://github.com/sfu-db/dataprep">GitHub - sfu-db/dataprep: Open-source low code data preparation library in python. Collect, clean and visualization your data in python with a few lines of code.</a></p><h3>11-Dython</h3><p>Dython is a set of data analysis tools that can let you get more insights about your data. Dython automatically find which features are categorical and which are numerical, compute a relevant measure of association between each and every feature, and also plot it all as a heatmap.</p><p>For the documentation and more:</p><p><a href="http://shakedzy.xyz/dython/">dython</a></p><h3>12-Statsmodels</h3><p>Statsmodels is a Python module that includes classes and functions for the estimation of many different statistical models as well as for conducting statistical tests, and statistical data exploration.</p><p>For the documentation and more:</p><p><a href="https://www.statsmodels.org/stable/examples/index.html">Examples - statsmodels</a></p><h3>13-Mlxtend</h3><p>Mlxtend (machine learning extensions) is a library that contains useful tools for data science tasks.</p><p>For the documentation and more:</p><p><a href="http://rasbt.github.io/mlxtend/#welcome-to-mlxtends-documentation">Home - mlxtend</a></p><h3>14- SciPy</h3><p>SciPy is an open-source software for mathematics, science, and engineering. It contains useful functions in areas such as linear algebra, optimization, signal processing and statistics.</p><p>For the documentation and more:</p><p><a href="https://www.scipy.org/docs.html">Documentation - SciPy.org</a></p><h3>15-Pandas Profiling</h3><p>It generates reports from a pandas dataframe for a quick exploratory data analysis.</p><p>For the documentation and more:</p><p><a href="https://github.com/pandas-profiling/pandas-profiling">GitHub - pandas-profiling/pandas-profiling: Create HTML profiling reports from pandas DataFrame objects</a></p><h3>16-Sweetviz</h3><p>Sweetviz is an open-source Python library that generates high-density visualizations to Exploratory Data Analysis with just two lines of code. Output is a fully self-contained HTML application.</p><p>For the documentation and more:</p><p><a href="https://github.com/fbdesignpro/sweetviz">GitHub - fbdesignpro/sweetviz: Visualize and compare datasets, target values and associations, with one line of code.</a></p><h3>17-Dtreeviz</h3><p>Dtreeviz is a library for decision tree visualization and model interpretation. It currently supports Scikit-Learn, XGBoost, Spark MLlib and LightGBM trees.</p><p>For the documentation and more:</p><p><a href="https://github.com/parrt/dtreeviz/">parrt/dtreeviz</a></p><h3>18-category_encoders</h3><p>It is a library that includes scikit-learn-style transformers for encoding categorical variables into numeric with different techniques. Some of the encoders : Count Encoder, CatBoost Encoder, James-Stein Encoder, Target Encoder …</p><p>For the documentation and more :</p><p><a href="https://contrib.scikit-learn.org/category_encoders/">Category Encoders - Category Encoders 2.2.2 documentation</a></p><h3>19-tslearn</h3><p>tslearn is a package that provides some machine learning tools for time series analysis . This package builds on scikit-learn, numpy and scipy libraries.</p><p>For the documentation and more:</p><p><a href="https://tslearn.readthedocs.io/en/stable/quickstart.html">Quick-start guide - tslearn 0.5.1.0 documentation</a></p><h3>20-sktime</h3><p>It is a unified framework for machine learning with time series. It provides specialized time series algorithms and scikit-learn compatible tools to build time series models.</p><p>For the documentation and more:</p><p><a href="https://www.sktime.org/en/latest/">Welcome to sktime - sktime documentation</a></p><p><strong>To see other published articles : </strong><a href="https://medium.com/datasciencearth"><em>https://medium.com/datasciencearth</em></a></p><p><strong>To see published Turkish articles :</strong> <a href="https://www.datasciencearth.com/"><em>https://www.datasciencearth.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f393faad4419" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datasciencearth/20-useful-python-libraries-for-data-science-projects-f393faad4419">20 Useful Python Libraries for Data Science Projects</a> was originally published in <a href="https://medium.com/datasciencearth">Data Science Earth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Genetic Algorithm-1]]></title>
            <link>https://medium.com/datasciencearth/genetic-algorithm-1-e52073005529?source=rss-8d2aef75e0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e52073005529</guid>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[ferhatmetin]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 22:11:07 GMT</pubDate>
            <atom:updated>2021-01-26T14:09:43.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*4qhc7bVRxbXyC9op6ke4IQ.png" /></figure><p>Genetic algorithm is a probabilistic search algorithm based on the modeling of genetic processes in living things. It was inspired by the science of genetics. Some of the concepts defined in genetic science are used by modeling in genetic algorithm. Let’s talk about these concepts briefly.</p><p><strong>Gene</strong>: the smallest structure that carries meaningful genetic information in its own right in the course of natural evolution is called a gene. In genetic algorithms, the gene represents the property of each element that makes up the chromosomes.</p><p><strong>Chromosome</strong> : It is formed by a combination of genes. It refers to one of the possible solutions to the problem.</p><p><strong>Population:</strong> the population is a set of chromosomes. Expresses a certain part of the possible solutions of the problem. The number of individuals in the population is determined at the beginning of the algorithm and remains constant.</p><p><strong>Selection</strong>: it defines how the population containing a certain number of solutions will proceed to the next iteration.</p><p><strong>Crossover</strong>: It is the formation of two new individuals by the displacement of a portion of the chromosomes of two individuals selected from the population. As a result of crossover, new individuals are formed that are not in the population.</p><p><strong>Mutation:</strong> a change in one or more genes of an individual to become a different individual.It is one of the operators that allows diversity to occur.</p><p><strong>Fitness Function</strong>: It is the objective function of the problem. The individuals to be passed on to the next generation are determined according to their fitness function values.</p><p><strong>IMPLEMENTATION STEPS</strong></p><p><strong>1-</strong>All possible solutions in the search space are encoded as arrays.</p><p><strong>2-</strong>Usually, a random set of solutions is chosen and considered the initial population.</p><p><strong>3</strong>-A fitness value is calculated for each array; the fitness values found indicate the solution quality of the arrays.</p><p><strong>4</strong>-A group of sequences is randomly selected according to a given probability value and the reproduction operation is performed.</p><p><strong>5-</strong>Crossover and mutation operations are performed by calculating the fitness values of new individuals.</p><p><strong>6-</strong>The above operations are continued throughout the pre-determined generation number.</p><figure><img alt="GA Flow" src="https://cdn-images-1.medium.com/max/427/1*CPGW0FwczVqPHx3RYPYKDg.png" /></figure><p><strong>GA OPERATORS</strong></p><p><strong>1-Encoding Of Chromosomes</strong></p><p>There are different encoding types developed for different problem types. Some of these are binary encoding, permutation encoding, value encoding, and tree encoding.</p><p><strong>a.Binary Encoding</strong></p><p>Each chromosome is a bit sequence of zeros and ones and is expressed by binary sequence. Every bit in this array has a property of the solution.</p><figure><img alt="Binary Encoding" src="https://cdn-images-1.medium.com/max/294/1*_-jLQTdrXJeqTmPOhcWZxQ.png" /></figure><p><strong>b.Permutation Encoding</strong></p><p>This coding is used in problems such as the Traveler salesman problem(TSP) and job sorting problems. Here each chromosome is a sequence of numbers.</p><figure><img alt="Permutation Encoding" src="https://cdn-images-1.medium.com/max/170/1*tiSFijd7Katb8Y2qZGIMLA.png" /></figure><p><strong>c.Value Encoding</strong></p><p>This encoding is used in problems involving complex numbers such as real. Binary coding is very difficult for such problems. Each chromosome is a sequence of values. These values are related to the problem; they can be real numbers, characters, or complex objects.</p><figure><img alt="Value Encoding" src="https://cdn-images-1.medium.com/max/562/1*6mvaC28A-yiqTKsFKXtxIA.png" /></figure><p><strong>d.Tree Encoding</strong></p><p>Tree encoding is often used to create programs and expressions in genetic programming. In tree coding, each chromosome consists of a tree structure that includes objects and Inter-object operations. Tree structure is used in languages such as Lisp and Prolog.</p><figure><img alt="Tree Encoding" src="https://cdn-images-1.medium.com/max/445/1*_82fliirJIC3s3mGJb-R_A.png" /></figure><p><strong>2 — Selection</strong></p><p>Chromosomes are chosen from within the population for crossover, to be parents.There are many ways to choose the best chromosomes. Roulette wheel selection, tournament selection, ranking selection and steady state selection are some of these.</p><p><strong>a.Roulette Wheel Selection</strong></p><p>The fitness values of all individuals in the community are summed and the probability of each individual being selected is the ratio of the fitness value to that total value. The better the chromosomes, the more likely they are to be selected. In this method, the highest fitness value is not guaranteed to be selected but there is a greater chance of being selected. In addition, these fitness values should not be negative because the negative probability means that there is no chance of choosing the solution. In a community where the majority of fitness values are negative, new generations may be caught at certain points. This is why ,a method called fitness scaling is applied. Roulette wheel selection can cause problems if the fitness values are very different. For example, if the fitness value of the best chromosome is 90% of the roulette wheel, the chances of other chromosomes being selected are lower.</p><figure><img alt="Roulette Wheel Selection" src="https://cdn-images-1.medium.com/max/381/1*EQdvUXosEoxR4aiq-gr3aw.png" /></figure><p><strong>b.Tournament Selection</strong></p><p>A random sequence is selected from the entire generation at a time. They will be in the tournament. In a tournament, whichever is better wins. Tournaments continue until the match pool is full. The random selection of chromosomes creates the possibility of co-selection of chromosomes with a low fitness value. In this case, chromosomes can be selected for the next generation, which is better than the rest of the population, even if they are mediocre. Thus, diversity in the population can be maintained.</p><figure><img alt="Tournament Selection" src="https://cdn-images-1.medium.com/max/221/1*bTrI51zJj36aiNtmhm4zgw.png" /></figure><p><strong>c.Rank Selection</strong></p><p>In this method, all sequences are sorted incrementally according to their fitness values. With an appropriate function, the highest compatible ones leave more copies in the pool, while the worst sequences fail to get copies. Search speed is high in this method.</p><figure><img alt="Rank Selection" src="https://cdn-images-1.medium.com/max/430/1*EWeY3nTro3AnTJVyLuHGKw.png" /></figure><p><strong>d.Steady State Selection</strong></p><p>It is used to ensure the displacement of a limited number of sequences within the population and to ensure that a sequence survives more than one generation.</p><figure><img alt="Steady State Selection" src="https://cdn-images-1.medium.com/max/386/1*uDxj5AaQP3RKx2Yya6gWNg.png" /></figure><p><strong>3-Crossover</strong></p><p>Crossover selects genes from parental chromosomes and creates a new progeny. This process randomly selects a crossover point and from this point on it allows the creation of new copies by changing the sub-sequences i.e. chromatids.</p><p><strong>a.Single Point Crossover</strong></p><p>For each sequence pair selected, a random location is chosen from the genes in between, except for the first and last gene. This is the crossover point. The genes that come after this point are mutually displaced in both sequences. For this operation, the arrays must be of the same length.</p><figure><img alt="Single Point Crossover" src="https://cdn-images-1.medium.com/max/380/1*SqgmrML0vjELgbDqzTL7nA.png" /></figure><p><strong>b.Two Point Crossover</strong></p><p>In this method, two random point are selected on the sequence, except for the first and last genes. The crossover process is the displacement of genes between these two selected points and genes are exchanged between these points.</p><figure><img alt="Two Point Crossover" src="https://cdn-images-1.medium.com/max/386/1*ADShOhDHAiKhmZy13zQkMw.png" /></figure><p><strong>c.Uniform Crossover</strong></p><p>Changes are made between randomly selected pairs of chromosomes using a probability value. Genes belonging to chromosomes are selected with a probability of 0.5. For example, if Xi&lt;0.5, the gene i is transferred from the first parent, and if Xi≥0.5, the gene i is transferred from the second parent.</p><figure><img alt="Uniform Crossover" src="https://cdn-images-1.medium.com/max/571/1*Q8ePIqK3e2jP5VVxZsnY0w.png" /></figure><p><strong>d.PMX Crossover</strong></p><p>A sub-sequence chosen randomly from the parents is copied, provided the child is in the same locations as the chromosome. The remaining positions are filled with other unused gene values. It is used in queue-based problems such as traveling salesman and vehicle routing.</p><figure><img alt="PMX Crossover" src="https://cdn-images-1.medium.com/max/202/1*K_b4WBg2jI2qY3P-astKlg.png" /></figure><p><strong>4-Mutation</strong></p><p>The mutation process is used to prevent the solutions of the problem in the population from falling into the local optima. There are many types of mutation such as inversion, reciprocal exchange, displacement and bit-flipping.</p><p><strong>a.Inversion Mutation</strong></p><p>In this method, two points are randomly selected among the genes belonging to the chromosome and the positions between the selected two points are shifted.</p><figure><img alt="Inversion Mutation" src="https://cdn-images-1.medium.com/max/173/1*hO6KglbQE3GKRH6IMs1xhQ.png" /></figure><p><strong>b.Reciprocal Exchange Mutation</strong></p><p>In this method, two bits chosen randomly from the chromosome are mutually displaced.</p><figure><img alt="Reciprocal Exchange Mutation" src="https://cdn-images-1.medium.com/max/185/1*OTPy4n_cj8iPe84jgLBMDw.png" /></figure><p><strong>c.Displacement Mutation</strong></p><p>It is implemented by placing a group of genes selected from the existing chromosome in a random location.</p><figure><img alt="Displacement Mutation" src="https://cdn-images-1.medium.com/max/215/1*1RO-kG9H4vnot86Ak2cTjw.png" /></figure><p><strong>d.Bit-Flipping</strong></p><p>The value of any gene on the chromosome is 1 to 0 or 0 to 1.</p><figure><img alt="Bit-Flipping" src="https://cdn-images-1.medium.com/max/172/1*n6KhhBLotLbDwBPOSLUcRQ.png" /></figure><p><strong>Parameters of Genetic Algorithm</strong></p><p>These are parameters that determine success of the algorithm in problem solving that must be determined before starting the algorithm.</p><p><strong>1.Crossover Probability</strong></p><p>Crossover is the probability of occurring in individuals in the population. It is usually a number between 0.6 and 1. Large proportions can cause good results to be overlooked. The small proportion leads to late reaching the result.</p><p><strong>2.Mutation Probability</strong></p><p>It is an operator that occurs less frequently than crossover. Values less than 0.5 are used usually.</p><p><strong>3.Population Size</strong></p><p>According to the structure of the problem is usually determined between 1 and 100. In cases where the chromosome sequence is long, the large population makes it difficult to find a solution.</p><p><strong>4.Stop Criterion</strong></p><p>The genetic algorithm may not always reach the best solution when trying to find a solution, but still a criterion must be set for the algorithm to stop. This criterion may be that the best solution in the population reaches a fixed value, approximating a certain value for the solution, attaining a certain number of iterations.</p><p><strong>GENETIC ALGORITHM EXAMPLE</strong></p><p>Let’s apply a genetic algorithm for the function f(x) = — x²+15x , to find the maximum value of f(x) in the range of [0,15] for x. For this sample, the crossover rate is 0.7 , the mutation rate is 0.01,the population size is 6, selection type is roulette wheel selection, crossover is single-point crossover and mutation type is bit-flipping.</p><p>Firstly, let’s determine our initial population. Since the x value can take values between 1 and 15, we can create chromosomes from 4 genes because we will create our chromosomes by using binary encoding. Since the population size is 6 and the number of genes is 4,let’s select 24 random numbers to create our first population, and from these random numbers, let’s say 1 for those greater than 0.5 and 0 for those smaller than 0.5.</p><figure><img alt="Random number, genes" src="https://cdn-images-1.medium.com/max/255/1*Zn9c-zHSb5J8zeprfEgEpg.png" /></figure><p>According to the determined random numbers, the chromosomes and their representation at decimal system will be as follows.</p><figure><img alt="chromosomes" src="https://cdn-images-1.medium.com/max/372/1*X_gXRthV3uVVmCD1_x84nA.png" /></figure><p>Now let’s calculate the fitness values for each chromosome.</p><p>Chromosome 1: -(9)² + 15x9 =54</p><p>Chromosome 2: -(10)²+15x10=50</p><p>Chromosome 3: -(2)² + 15x2 =26</p><p>Chromosome 4: -(8)² + 15x8 =56</p><p>Chromosome 5: -(4)² +15x4 = 44</p><p>Chromosome 6: -(1)² + 15x1=14</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*7QZmVX9-e1Yd4Aca226fPg.png" /></figure><p>Now in order to perform the roulette selection process, let’s divide each fitness value into the sum of these values and set separate possibilities for each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*djNmfusygxqyHFcAisQWvw.png" /></figure><p>For each chromosome, we determine a range of probabilities by summing the probabilities cumulatively. Then we draw 6 more random numbers to form chromosome pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*1drhUg1gQDHdYRI1VmUqEQ.png" /></figure><p>Let’s select according to the selected random numbers. For example, 0.544 corresponds to the probability range of the fourth chromosome. The first chromosome selected in this case is the fourth chromosome. If we choose the others in the same way, the pairs of chromosomes will be as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*L0jVmof2QhgHzJx9ZsOvgg.png" /></figure><p>Now let’s do the crossover. Our Crossover probability was given as 0.7. Let’s select 3 random numbers to determine which pair of chromosomes to crossover. Let these random numbers be 0.304, 0.506 and 0.317.</p><p>0,304 &lt; 0,7 , 0,506 &lt; 0,7 , 0,317 &lt; 0,7 so crossover is applied to all individuals. At which point the crossover will be applied is decided by random numbers again. 3 random numbers are selected because there are 3 points.</p><p>If these random numbers are in the range 0–0.333, let’s do crossover from the first point, 0.333–0.666 from the second point, 0.666–1 from the third point. According to this, the new chromosomes are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*DF4K8Yp9muwAK_R9rvOnXA.png" /></figure><p>We can express the chromosome status after the crossover as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*9ec9ZqD97dimX36Y_cCb3g.png" /></figure><p>Now let’s go through the mutation process and choose 6 random numbers to decide which chromosomes will be mutated and which will not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*AelCjCeO3TkV3VLvMMxM7g.png" /></figure><p>Since the probability of mutation is 0.01 and the random value for the last chromosome is 0.005, the last chromosome will mutate. Let’s draw random numbers again to determine which gene the mutation will occur in. Since there are 4 genes,the mutation occurs at the first point if the random number is in the range 0–0, 25, at the second point in the range 0.25–0.5, at the third point in the range 0.5–0.75, and at the fourth point in the range 0.75–1. Since the random value chosen for the mutation point is 0.725, this value is in the range 0.5–0.75. Therefore, the mutation will occur in the third gene. The value that is 0 will become 1.</p><p>Thus, with the mutation process, our new individuals will be as follows.If we specify new individuals on decimal system, they will be 10,8,8,9,4 and 3.</p><p>Now let’s find new fitness values.</p><p>Choromosome 1: -(10)² + 15x10 =50</p><p>Choromosome 2: -(8)²+15x8=56</p><p>Choromosome 3: -(8)² + 15x8 =56</p><p>Choromosome 4: -(9)² + 15x9 =54</p><p>Choromosome 5: -(4)² +15x4 = 44</p><p>Choromosome 6: -(3)² + 15x3=36</p><p>So the first iteration took place. Iterations continue according to the stop criterion.</p><p><strong>I can recommend some videos for better understanding of the genetic algorithm:</strong></p><p>Link to Patrick Winston’s genetic algorithm course:</p><p><a href="https://www.youtube.com/watch?v=kHyNqSnzP8Y&amp;t=771s">https://www.youtube.com/watch?v=kHyNqSnzP8Y&amp;t=771s</a></p><p>Link to Sadi Evren şeker’s genetic algorithm lecture video:</p><p><a href="https://www.youtube.com/watch?v=gL5iw5cvy0M">https://www.youtube.com/watch?v=gL5iw5cvy0M</a></p><p>Link to Derek Kane’s Data Science-Genetic Algorithms video:</p><p><a href="https://www.youtube.com/watch?v=lpD38NxTOnk">https://www.youtube.com/watch?v=lpD38NxTOnk</a></p><p><strong>REFERENCES</strong></p><p><em>Akpınar,Fatma,2019,İstanbul Teknik Üniversitesi Fen Bilimleri Enstitüsü Yüksek Lisans Tezi,Yerleştirme Rotalama Problemi için Bir Genetik Algoritma, Erişim adresi</em><strong><em>:</em></strong> <a href="https://polen.itu.edu.tr/bitstream/11527/5722/1/9855.pdf"><strong>https://polen.itu.edu.tr/bitstream/11527/5722/1/9855.pdf</strong></a></p><p><em>Emel,Taşkın,Gül Gökay,Çağatan,2012,Genetik Algoritmalar ve Uygulama Alanları,Uludağ Üniversitesi İktisadi ve İdari Bilimler Fakültesi Dergisi Cilt XXI Sayı 1,s.129–152. Erişim adresi</em>: <a href="https://www.researchgate.net/publication/312447324_Genetik_Algoritmalar_ve_Uygulama_Alanlari"><strong>https://www.researchgate.net/publication/312447324_Genetik_Algoritmalar_ve_Uygulama_Alanlari</strong></a></p><p><em>Nabiyev, Vasif Vagifoğlu (2012). Yapay Zeka. Ankara: Seçkin Yayınları., s. 606.</em></p><p><em>Karaboğa, Derviş,2006,Yapay Zeka Optimizasyon Algoritmaları,Nobel Akademik Yayıncılık</em></p><p><em>Çınar, D., 2007. Hidroelektrik Enerji Üretiminin Hibrid Bir Model ile Tahmini, Yüksek Lisans Tezi, İTÜ Fen Bilimleri Enstitüsü, İstanbul. Erişim adresi:</em> <a href="https://polen.itu.edu.tr/bitstream/11527/5850/1/7270.pdf"><strong>https://polen.itu.edu.tr/bitstream/11527/5850/1/7270.pdf</strong></a></p><p><em>Engin, O., 2001. Akış Tipi Çizelgeleme Problemlerinin Genetik Algoritma İle Çözüm Performansının Arttırılmasında Parametre Optimizasyonu, Doktora Tezi, İTÜ Fen Bilimleri Enstitüsü, İstanbul</em>. Erişim adresi: <a href="https://polen.itu.edu.tr/xmlui/bitstream/handle/11527/5897/1135.pdf?sequence=1&amp;isAllowed=y"><strong>https://polen.itu.edu.tr/xmlui/bitstream/handle/11527/5897/1135.pdf?sequence=1&amp;isAllowed=y</strong></a></p><p><em>Soni,Komar,Nitasha,Tapas,2014,Study of Various Mutation Operators in Genetic Algorithms, International Journal of Computer Science and Information Technologies, Vol. 5 Erişim adresi</em><strong><em>:</em> </strong><a href="http://ijcsit.com/docs/Volume%205/vol5issue03/ijcsit20140503404.pdf"><strong><em>http://ijcsit.com/docs/Volume%205/vol5issue03/ijcsit20140503404.pdf</em></strong></a></p><p><em>Suvay,Halime,2019,Sınav Çizelgeleme Probleminin Çözümü için Genetik Algoritma Yaklaşımı Yüksek Lisans Tezi,Sivas Cumhuriyet Üniversitesi Sosyal Bilimler Enstitüsü,Sivas,Erişim adresi: </em><a href="https://acikerisim.cumhuriyet.edu.tr/xmlui/bitstream/handle/20.500.12418/12058/10245372.pdf?sequence=1"><strong><em>https://acikerisim.cumhuriyet.edu.tr/xmlui/bitstream/handle/20.500.12418/12058/10245372.pdf?sequence=1</em></strong></a></p><p><em>Çayıroğlu, İbrahim,Optimizasyon Teknikleri, </em><a href="http://www.ibrahimcayiroglu.com/Dokumanlar/OptimizasyonTeknikleri/OptimizasyonTeknikleri-5.Hafta-Genetik_Algoritma.pdf"><strong><em>http://www.ibrahimcayiroglu.com/Dokumanlar/OptimizasyonTeknikleri/OptimizasyonTeknikleri-5.Hafta-Genetik_Algoritma.pdf</em></strong></a></p><p>Taşkın, Çağatan ve Emel Gül Gökay (2009). Sayısal Yöntemlerde Genetik Algoritmalar. Bursa: Alfa Aktüel Yayınları., s.52</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e52073005529" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datasciencearth/genetic-algorithm-1-e52073005529">Genetic Algorithm-1</a> was originally published in <a href="https://medium.com/datasciencearth">Data Science Earth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Map Visualization with Folium]]></title>
            <link>https://medium.com/datasciencearth/map-visualization-with-folium-d1403771717?source=rss-8d2aef75e0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1403771717</guid>
            <category><![CDATA[folium]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[ferhatmetin]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 22:09:53 GMT</pubDate>
            <atom:updated>2023-03-26T15:10:20.200Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is Folium?</h4><p>Folium is a library that uses JavaScript leaflet.js module in the background and it enables interactive map visualizations in Python. Now let’s examine some features in Folium.</p><h3>1. Map() and Tiles</h3><p>Firstly, let’s take the necessary steps to use the Folium library.</p><pre>pip install folium <br>#conda install -c conda-forge folium<br>import folium</pre><p>We use the Map() function to create a map. For this, we need to give latitude and longitude information to the function. For example, let us enter the approximate latitude and longitude of Istanbul.</p><pre>folium.Map(location=[41,29])</pre><p>Let’s look at the output without any parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*F0rocuWiv3XVDabZl0wK4Q.png" /><figcaption>Figure 1. Folium-Output-1</figcaption></figure><p>By default, “tiles” appears as ”OpenStreetMap” in the Map() function.This parameter allows us to change the style of the map. We can change this to Stamen Toner, CartoDB positron, Cartodb dark_matter, Stamen Watercolor or Stamen Terrain. we also adjust the size with the width and height parameters, and zoom_start lets you zoom in.</p><pre>folium.Map(location=[41,29],<br>tiles=&quot;Stamen Watercolor&quot;,<br> width=&quot;%100&quot;,<br>height=&quot;%100&quot;,<br>zoom_start=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*d7r68bEUP6zFP-GqRL6owA.png" /><figcaption>Figure 2. Folium-Output-2</figcaption></figure><pre>folium.Map(location=[41,29],tiles=&quot;Stamen Toner&quot;,<br>width=&quot;%100&quot;,<br>height=&quot;%100&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*gdvQwmfeXLaTHFN0Oo-7_Q.png" /><figcaption>Figure 3. Folium-Output-3</figcaption></figure><h3>2. Circle(),CircleMarker() ve Marker()</h3><p>We can use the Circle() function to circle the coordinates. Let’s look at the output by entering parameters such as radius and color.</p><pre>m = folium.Map(location=[41,29],tiles=&quot;Stamen Toner&quot;,<br>width=&quot;%100&quot;,<br>height=&quot;%100&quot;,<br>zoom_start=10)</pre><pre>folium.Circle(<br>radius=5000,<br>location=[41,29],<br>color=&#39;crimson&#39;,<br>fill=False,).add_to(m)<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*_8G_ny6KtXqBE8rvfAsTNg.png" /><figcaption>Figure 4. Folium-Output-4</figcaption></figure><p>Another way to do this is to use the CircleMarker() function.</p><pre>m = folium.Map(location=[41,29],tiles=&quot;Stamen Toner&quot;,width=&quot;%100&quot;,height=&quot;%100&quot;)</pre><pre>folium.CircleMarker(location=(41,29),radius=100, fill_color=&#39;red&#39;).add_to(m)<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*pgeQgVE4QQSba6AsjsoV-Q.png" /><figcaption>Figure 5. Folium-Output-5</figcaption></figure><p>Now let’s use the coordinates of Sakarya as an example and use the Marker() function to mark the location of the coordinates. Let’s set the location name by using the popup parameter.</p><pre>m = folium.Map(location=[40.75834,30.38001])<br>folium.Marker(location=[40.75834,30.38001], popup =  &#39;Sakarya&#39;).add_to(m)</pre><pre>folium.CircleMarker(location=(40.75834,30.38001),radius=100, fill_color=&#39;blue&#39;).add_to(m)</pre><pre>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*FBkSEyalvpY8DNpVmd_ibw.png" /><figcaption>Figure 6. Folium-Output-6</figcaption></figure><h3>3. MiniMap()</h3><p>Let’s call plugins from Folium firstly. In order to create a minimap, use the MiniMap() function.</p><pre>from folium import plugins<br>m = folium.Map(location=(42, 29), zoom_start=5)</pre><pre>minimap = plugins.MiniMap()<br>m.add_child(minimap)<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4FmNPTPZLZQG8UryUBI_Vg.png" /><figcaption>Figure 7. Folium-Output-7</figcaption></figure><h3>4. MarkerCluster()</h3><p>For this example, I used the data “number of natural gas subscribers by counties” in the IBB Open Data Portal. This data consists of county names and subscriber count data.Since we need coordinates of Istanbul districts, you can pull the coordinate information from Google Maps or get it from platforms like GitHub. Now let’s start loading data in Excel format. For that, we need the Pandas library. After loading the data, let’s observe the first 5 values.</p><pre>İmport pandas as pd<br>data_abone=pd.read_excel(&quot;ilcelere-gore-abone-  sayilari.xlsx&quot;,sheet_name=&quot;İlçe Abone Sayı&quot;)<br>data_abone.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*q0ZiBuO1Rv_cuFxqXSSbBQ.png" /><figcaption>Figure 8. Folium-Output-8</figcaption></figure><pre>data_koordinat=pd.read_excel(&quot;ilcelere-gore-abone-sayilari.xlsx&quot;,sheet_name=&quot;Koordinatlar&quot;)<br>data_koordinat.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*NUqFng-QqfxQ9vLhTCFWzw.png" /><figcaption>Figure 9. Folium-Output-9</figcaption></figure><p>Since there are columns with the same name, we can combine this data by using the merge() function in Pandas.</p><pre>data=pd.merge(data_abone,data_koordinat)<br>df=data.copy()<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*V99pdwuP2ta_UbapP5vbZg.png" /><figcaption>Figure 10. Folium-Output-10</figcaption></figure><p>The MarkerCluster() function is included in Plugins. Let’s give the location information as a parameter.</p><pre>m = folium.Map([42 ,29], zoom_start=5,width=&quot;%100&quot;,height=&quot;%100&quot;)<br>location=df[[&quot;Enlem&quot;,&quot;Boylam&quot;]]</pre><pre>plugins.MarkerCluster(location).add_to(m)</pre><pre>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Ej8YFmU5oBlaV53pROIUTg.png" /><figcaption>Figure 11. Folium-Output-11</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*olOnRovOm_XOCYBCfwRvyQ.png" /><figcaption>Figure 12. Folium-Output-12</figcaption></figure><h3>5. HeatMap()</h3><p>For heatmap, we can use heatmap() in Plugins. For that, we need to give the data in the appropriate format. Now let’s take the necessary steps and look at our output.</p><pre>df.Enlem=df.Enlem.astype(float)<br>df.Boylam=df.Boylam.astype(float)<br>heat_df=df[[&quot;Enlem&quot;,&quot;Boylam&quot;]]<br>heat_data=list(zip(df.Enlem, df.Boylam))<br>folium.plugins.HeatMap(heat_data).add_to(m)<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*cjsEt-quVR4Hiej6DkVfkQ.png" /><figcaption>Figure 13. Folium-Output-13</figcaption></figure><h3>6. GeoJson</h3><p>GeoJson in the Folium helps us border the coordinates we want. We need a json file with coordinates to draw the boundaries. You can find it from the platforms like Github or you can draw these boundaries yourself and create a json file by using geojson.io. For this example, let’s use the borders of Turkey except Cyprus.</p><pre>from folium import GeoJson<br>geo=r&quot;tr-cities.json&quot;<br>file = open(geo, encoding=&quot;utf8&quot;)<br>text = file.read()</pre><pre>m = folium.Map(width=&quot;%100&quot;,weight=&quot;%100&quot;)</pre><pre>GeoJson(text).add_to(m)<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*I286vZV89pj4W5LK641UWA.png" /><figcaption>Figure 14. Folium-Output-14</figcaption></figure><pre>m = folium.Map(tiles=&quot;Stamen Toner&quot;)</pre><pre>GeoJson(text,<br>       style_function=lambda feature: {    <br>        &#39;fillColor&#39;: &#39;#adff2f&#39;,           <br>        &#39;color&#39;:None, <br>        &#39;weight&#39;: 1,<br>        &#39;dashArray&#39;: &#39;4, 4&#39;<br>    }).add_to(m)<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*WzNzyeIvd9dDHghahpAJRA.png" /><figcaption>Figure 15. Folium-Output-15</figcaption></figure><pre>m = folium.Map(tiles=&quot;Cartodbdark_matter&quot;,width=&quot;%100&quot;,weight=&quot;%100&quot;)</pre><pre>GeoJson(text,).add_to(m)</pre><pre>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*TNWUJVvs0s9eEEnhewWynw.png" /><figcaption>Figure 16. Folium-Output-16</figcaption></figure><h3>7. Choropleth()</h3><p>For this example, I am going to use the data “population number according to place of birth” on the Turkish Statistical Institute’s website. Now let’s load the data and do the necessary cleaning.</p><pre>nufus=pd.read_excel(r&quot;pivot.xls&quot;)</pre><pre>nufus.drop(&quot;Unnamed: 2&quot;,axis=1,inplace=True)</pre><pre>nufus.drop(nufus[nufus[&quot;Sehir&quot;]==&quot;Yurtdışı&quot;].index,inplace=True)</pre><pre>nufus.drop(nufus[nufus[&quot;Sehir&quot;]==&quot;Bilinmeyen&quot;].index,inplace=True)</pre><pre>nufus.loc[nufus[&quot;Sehir&quot;]==&quot;Afyonkarahisar&quot;,&quot;Sehir&quot;]=&quot;Afyon&quot; </pre><pre>#I changed the name to Afyon as in the text file</pre><pre>nufus.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b6O3jbVGUaoULNsrYR2Wzw.png" /><figcaption>Figure 17. Folium-Output-17</figcaption></figure><p>Now let’s try to color the map by population.For this we can use the Choropleth () function. Here we can think of the parameter as key_on as a “primary key” i.e. an unique token for each property. It may be useful to open the text file to understand exactly what we should write.</p><pre>m = folium.Map([42 ,29],tiles=&quot;Cartodb Positron&quot;,     <br>                        zoom_start=5,<br>                        width=&quot;%100&quot;,<br>                        height=&quot;%100&quot;)<br>folium.Choropleth(<br>    geo_data=text,<br>    data=nufus,<br>    columns=[&#39;Sehir&#39;, &#39;Nufus&#39;],   <br>    legend_name=&#39;Dogum Yerine Gore Nufus (2019)&#39;,<br>    key_on=&#39;feature.properties.name&#39;<br>#‘feature.id’ or ‘feature.properties.statename’ <br>    ).add_to(m)</pre><pre>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*knHwfiiGvdNetWj7dc41Vw.png" /><figcaption>Figure 18. Folium-Output-18</figcaption></figure><h3>Implementation with Istanbul Airbnb Data</h3><p>Let’s upload our data and examine it briefly, as we did before.</p><pre>airbnb_data=pd.read_csv(&quot;airbnbIstanbul.csv&quot;)</pre><pre>airbnb_data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bxWUe6Brt-pngGgYYMrekw.png" /><figcaption>Figure 19. Folium-Output-19</figcaption></figure><pre>airbnb_data.isnull().sum().to_frame() #let’s look at missing values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*GOZI-SgYhX2OBKNM_FTn0g.png" /><figcaption>Figure 20. Folium-Output-20</figcaption></figure><p>The price, latitude and longitude data show no missing value. Now let’s map their accommodation places by using each coordinate data. For this we can use the MarkerCluster() function.</p><pre>m = folium.Map([42 ,29], zoom_start=5,width=&quot;%100&quot;,height=&quot;%100&quot;)<br>locations = list(zip(airbnb_data.latitude, airbnb_data.longitude))<br>cluster = plugins.MarkerCluster(locations=locations,                     <br>               popups=airbnb_data[&quot;neighbourhood&quot;].tolist())  <br>m.add_child(cluster)<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*NmXTp8oWUgVuzQs1yeIO9w.png" /><figcaption>Figure 21. Folium-Output-21</figcaption></figure><p>Now let’s do the same process using CircleMaker().</p><pre>m = folium.Map(location=[41,29],width=&quot;%100&quot;,height=&quot;%100&quot;)<br>for i in range(len(locations)):<br>    folium.CircleMarker(location=locations[i],radius=1).add_to(m)<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6DXpJRgBF5lssEhBsgF-Tw.png" /><figcaption>Figure 22. Folium-Output-22</figcaption></figure><p>Now our goal is to color the accommodation according to the prices. We need a colormap for that. We will give different colors for certain price ranges. To do this, let’s first assign the minimum and maximum prices to different variables.</p><pre>airbnb=airbnb_data[[&quot;latitude&quot;,&quot;longitude&quot;,&quot;price&quot;]]</pre><pre>min_price=airbnb_data[&quot;price&quot;].min()</pre><pre>max_price=airbnb_data[&quot;price&quot;].max()</pre><pre>airbnb[&quot;price&quot;].describe().to_frame()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*tv9LmKImX1Ty94vx1YXY9w.png" /><figcaption>Figure 23. Folium-Output-23</figcaption></figure><p>I created the colormap using cartil values. You can create it with different values and different colors.Then we can create our map using the Circle() function.</p><pre>m = folium.Map(location=[41,29],width=&quot;%100&quot;,height=&quot;%100&quot;)<br>colormap = cm.StepColormap(colors=[&#39;green&#39;,&#39;yellow&#39;,&#39;orange&#39;,&#39;red&#39;] ,#renkler<br>                           index=[min_price,105,190,327,max_price], #eşik değerler<br>                           vmin= min_price,<br>                           vmax=max_price)</pre><pre>for loc, p in zip(zip(airbnb[&quot;latitude&quot;],airbnb[&quot;longitude&quot;]),airbnb[&quot;price&quot;]):<br>      folium.Circle(<br>      location=loc,<br>      radius=2, #yarıçap<br>      fill=True, <br>      color=colormap(p)</pre><pre>).add_to(m)</pre><pre>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yL2QQKG5-mD8uRFi1mLcBQ.png" /><figcaption>Figure 24. Folium-Output-24</figcaption></figure><p><strong>In order to access the data sets I used in this article:</strong></p><p>Population number data by place of birth: <a href="http://tuik.gov.tr/PreTablo.do?alt_id=1059">Türkiye İstatistik Kurumu Web Sitesi</a></p><p>İstanbul Airbnb data: <a href="https://www.kaggle.com/kavanozkafa/airbnb-istanbul-dataset">Kaggle İstanbul Airbnb Verisi</a></p><p>Istanbul natural gas subscriber count data: <a href="https://data.ibb.gov.tr/">İBB Açık Veri Portalı</a></p><p>All codes : <a href="https://github.com/ferhatmetin34/Map-Visualization-with-Folium">https://github.com/ferhatmetin34/Map-Visualization-with-Folium</a></p><p><strong>In order to access the resources I used:</strong></p><p><a href="https://nbviewer.jupyter.org/github/python-visualization/folium/tree/master">https://nbviewer.jupyter.org/github/pythonvisualization/folium/tree/master</a></p><p><a href="https://pypi.org/project/folium">https://pypi.org/project/folium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1403771717" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datasciencearth/map-visualization-with-folium-d1403771717">Map Visualization with Folium</a> was originally published in <a href="https://medium.com/datasciencearth">Data Science Earth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Date Using Pandas]]></title>
            <link>https://medium.com/datasciencearth/working-with-date-using-pandas-9884c6f80525?source=rss-8d2aef75e0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9884c6f80525</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[ferhatmetin]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 21:07:27 GMT</pubDate>
            <atom:updated>2021-04-07T13:35:08.958Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with time series data, the date information may not be in the format we want, or we may want to produce new variables that can make our model better with the time information we have. Now let’s see how we can do this in Pandas.</p><p>In this article, we will use the electricity consumption data (January 2015 — June 2020) from <a href="https://seffaflik.epias.com.tr/transparency/">Epiaş Şeffaflık Platformu.</a> You can access the data<strong> </strong><a href="https://www.kaggle.com/ferhatmetin34/electricity-consumption-20152020"><strong>here.</strong></a></p><p>Let’s start by loading the necessary libraries and data.</p><pre>import pandas as pd # 1.0.3<br>import numpy as np<br>data=pd.read_csv(&quot;/kaggle/input/electricity-consumption-20152020/GercekZamanliTuketim-01072015-30062020.csv&quot;,<br>encoding= &#39;unicode_escape&#39;)</pre><pre>df=data.copy() # to copy just in case<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*37FCdlW8BSvfWs3pEPkB1Q.png" /></figure><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*DOGuXKNCTCOR9P92iZtvlw.png" /></figure><p>As you can see, there are some problems such as the name of the column indicating the amount of consumption, the number indicating the amount being in the format we use. The time information is also kept in a separate column. We can add this column to the date column for now, as we will obtain it ourselves later. Finally, we can change the date variable that appears as a categorical variable to date format and delete the “Saat” column. Now let’s do what we say.</p><pre>df.tuketim=df.tuketim.str.replace(&quot;.&quot;,&quot;&quot;)<br>df.tuketim=df.tuketim.str.replace(&quot;,&quot;,&quot;.&quot;)<br>df.tuketim=df.tuketim.astype(float)<br>df[&quot;Tarih&quot;]=df[&quot;Tarih&quot;]+&quot; &quot;+df[&quot;Saat&quot;]<br>df.Tarih=df.Tarih.apply(pd.to_datetime)<br>df=df.drop(&quot;Saat&quot;,axis=1)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*rjwX11MSkBN0S8mVR29wBA.png" /></figure><h3>1-Extracting Week, Month and Year</h3><p>Accessing to this information is very easy with the dt accessor used with the Pandas series. We can use dt.week to access what week of the year it is, dt.month to access what month is and dt.year to access what year it is.</p><pre>df[&quot;week&quot;]=df.Tarih.dt.week<br>df[&quot;month&quot;]=df.Tarih.dt.month<br>df[&quot;year&quot;]=df.Tarih.dt.year<br>df.sample(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*A1fDRv3F33bn-HUqM9fe5g.png" /></figure><h3>2- Extracting Semester and Quarter</h3><p>Similarly, we can get information about what quarter it is. With the help of the code below, we can access the information about the six-month period (semester).</p><pre>df[&quot;quarter&quot;]=df.Tarih.dt.quarter<br>df[&#39;semester&#39;] = np.where(df[&#39;quarter&#39;].isin([1,2]), 1, 2)<br>df.sample(7)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*0TMbyaMQty32XwTfRUjzrQ.png" /></figure><h3>3-Extracting Day,Day of Week and Day Names</h3><p>We can access this information as we did before. Days of the week are named starting at 0. For instance, it will be 0 for Monday and 6 for Sunday.</p><pre>df[&quot;day&quot;]=df.Tarih.dt.day<br>df[&#39;daysofweek&#39;] = df[&#39;Tarih&#39;].dt.dayofweek<br>df[&quot;day_name&quot;]=df.Tarih.dt.day_name()<br>df.sample(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*hk-cd7irEvVttPSR6a8PHA.png" /></figure><h3>4-Extracting Weekend</h3><p>If we want to get weekend information, we can use the” day_name “ column. Our value will be 1 if the day is saturday or sunday,if not 0.</p><pre>df[&#39;is_weekend&#39;] = np.where(df[&#39;day_name&#39;].isin([&#39;Sunday&#39;, &#39;Saturday&#39;]), 1,0)</pre><p>As a second way, we can use “daysofweek” column.In this case, if the day of the week is 5 or 6, that is, if it is greater than 4, it is the weekend.</p><pre>df[&quot;is_weekend&quot;]=df[&quot;daysofweek&quot;].apply(lambda x:1 if x&gt;4 else 0)<br>df.sample(7)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*4Y0CfbOZz19uGIHLS8xxNw.png" /></figure><h3>5-date_range() Function</h3><p>We can create time data at any time interval with date_range(). For example, let’s create hourly data for the date January 1, 2020.We can use the <em>H</em> symbol to express the frequency as hour. Because we set a 24-hour time, we can enter 24 for the periods parameter.</p><pre>data = pd.Series(pd.date_range(&#39;2020-1-1&#39;, periods=24, freq=&#39;H&#39;))<br>data = pd.DataFrame(dict(date=data))<br>data.head(7) #first seven rows</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*6QaTr6tvVNSiS6WQS185RQ.png" /></figure><p>If we want to create daily data for January, we can write this as follows:</p><pre>data = pd.Series(pd.date_range(&#39;2020-1-1&#39;, periods=31, freq=&#39;D&#39;))<br>data = pd.DataFrame(dict(date=data))<br>data.head(7)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*sbETUhIeFsBA4agaqpVqAw.png" /></figure><p>Now,let’s create a secondly data.</p><pre>data = pd.Series(pd.date_range(&#39;2020-1-1 8:01:00&#39;, periods=10, freq=&#39;S&#39;)) <br>data = pd.DataFrame(dict(date=data))<br>data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*WieBLyuewIm16p3ltJUkZg.png" /></figure><h3>6-Extracting Time,Minute,Second and Date</h3><pre>data[&#39;hour&#39;] = data[&#39;date&#39;].dt.hour<br>data[&#39;min&#39;] = data[&#39;date&#39;].dt.minute<br>data[&#39;sec&#39;] = data[&#39;date&#39;].dt.second<br>data[&quot;date_&quot;]=data[&quot;date&quot;].dt.date<br>data[&#39;time&#39;] = data[&#39;date&#39;].dt.time<br>data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*sVF317YXJm2W9XHnRBX2gA.png" /></figure><h3>7- resample() Function</h3><p>With this function, we can change the frequency of the time series data and resample it. In order to use this function, we need to assign the date data to the index.</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*KV1iMYeRJTMAsfNVi6WBHw.png" /></figure><pre>df.index=df.Tarih<br>df.drop(columns=[&quot;Tarih&quot;],axis=1,inplace=True)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*vCXVVbUthijQHN1CCgiHcQ.png" /></figure><p>Now let’s look at average annual consumption. For this, we need to set the rule parameter as “A”.</p><pre>df.resample(rule=&quot;A&quot;).mean()<br>#df.groupby(df_new.index.year).mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*X33TEe4H0hKSv7H49kbRhQ.png" /></figure><p>To see the average amount of consumption at the beginning of each month, we can write the following code:</p><pre>df.resample(rule=&quot;MS&quot;).mean().head(10) #first 10 rows</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*ecqTeCXJZ7ocdwlrKAP0QQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*gG6kA6E63PPTsOXbPnzlZA.png" /><figcaption>Figure-Pandas-Frequency-Alias <a href="https://pandas.pydata.org/pandas-docs/version/0.15/timeseries.html">https://pandas.pydata.org/pandas-docs/version/0.15/timeseries.html</a></figcaption></figure><h3>8 — shift() Function</h3><p>Shift index by desired number of periods with an optional time frequency. Let’s make <em>periods</em> parameter 1 without entering another parameter and see what happens.</p><pre>df.shift(1).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*fbSBmc-nsZmcF7s6PJACHA.png" /></figure><p>As you can see, the first value was down to the bottom line, and the first line received the NaN value.</p><pre>df.shift(periods=2,freq=&quot;D&quot;).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*7NNGdK-frVvxsVHktBQqRA.png" /></figure><p>In the above example, the indexes were changed with the indexes two days later.</p><h4>9 — rolling() Function</h4><p>Performs operations with the previous n data according to the specified time window. It can be used to calculate moving average. A window parameter is specified for this. For example, if this parameter is 7, the previous 7 values are averaged. the 7th day is also included in the average.</p><pre>df.rolling(window=7).mean().head(10)</pre><pre>#df.iloc[0:7].mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*SOIO6N_nN9l-8i9K4GLlvw.png" /></figure><h3>10 — expanding() Function</h3><p>This function, unlike rolling (), processes all data before the specified period.</p><pre>df.expanding(min_periods=7).mean().head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*TyHgw2jhvdJ9XvTOTmROpQ.png" /></figure><p><strong>REFERENCES</strong></p><p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/frame.html">DataFrame - pandas 1.3.5 documentation</a></p><p>Linkedn : <a href="https://www.linkedin.com/in/ferhatmetin/">https://www.linkedin.com/in/ferhatmetin/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9884c6f80525" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datasciencearth/working-with-date-using-pandas-9884c6f80525">Working with Date Using Pandas</a> was originally published in <a href="https://medium.com/datasciencearth">Data Science Earth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is SymPy?]]></title>
            <link>https://medium.com/datasciencearth/what-is-sympy-cb9977b64871?source=rss-8d2aef75e0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb9977b64871</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sympy]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[ferhatmetin]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 20:56:33 GMT</pubDate>
            <atom:updated>2021-01-26T14:08:54.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>SYMBOLIC MATHEMATICS OPERATIONS WITH SYMPY IN PYTHON</h3><p>SymPy is a Python library that we can perform symbolic math operations. SymPy benefits in many fields such as derivative, integral, differential, equation solving, matrix operations, and statistical operations. It also has useful functions in the fields of physics and chemistry.</p><p>First, let’s install our SymPy library and other necessary libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5N9_LFwXXjxgu4yaer5w6g.png" /><figcaption>Figure-1-Sympy-Installation</figcaption></figure><h3>1. Basic Operations</h3><p>To do some basic mathematical operations, let’s first define two symbols as x and y, then let’s look at the output of some symbolic mathematical operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*ozwqXFx7g2uM0K1Zomy5uQ.png" /><figcaption>Figure-2-Sympy-Symbols</figcaption></figure><p>In addition to basic symbols, SymPy allows to create symbols such as alpha, beta, and theta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*TTuQE33PiRDXJNTCWzQUCw.png" /><figcaption>Figure-3-Sympy-Symbols-2</figcaption></figure><p>Now let’s look at how integral representations are made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*0MmJT_KZJa3Q9lYgwmF3oA.png" /><figcaption>Figure-4-Sympy-Integral</figcaption></figure><p>SymPy also allows us to easily create derivative, limit, sum and multiplication symbols.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*mxcsJW-lPDjKpEzWmUhITw.png" /><figcaption>Figure-5-Sympy-Derivative-Limit-Sum-Product</figcaption></figure><p>We can also create an equality function with Eq (). If we want to see the result of the operation, we can use the doit() function. Another useful function is the evalf() function, which allows us to determine how many digits to calculate. To create a function, we can use Function().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*D_vQwDYuMStMIyTYrClXWg.png" /><figcaption>Figure-6-Sympy-Eq-evalf-doit</figcaption></figure><p>Binomial and factorial operations are also possible with SymPy. Now let’s see how we can do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*trH6uq98uGJWud0Cd7cffg.png" /><figcaption>Figure-7-Sympy-Binomial-Factorial</figcaption></figure><h3>2. Simplify(), Expand(),Factor(),Apart() ve Together()</h3><p>Simplify () briefly simplifies a mathematical expression. Let’s make this more understandable with examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*1XVvznXIBlurgKw865GaRw.png" /><figcaption>Figure-8-Sympy-Simplify</figcaption></figure><p>factor () divides polynomial expressions into irreducible factorizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*T8HTUl5E3jYgv9Xt0h5Vig.png" /><figcaption>Figure-9-Sympy-Factor</figcaption></figure><p>expand() function is the opposite of the factor () and factorizes a mathematical expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*TtB1SLW5bX3KW5vsdTJY3g.png" /><figcaption>Figure-10-Sympy-expand</figcaption></figure><p>Now let’s look at together() and apart() functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*WllNMQot_LQeO8YVG3aHfw.png" /><figcaption>Figure-11-Sympy-together-apart</figcaption></figure><h3>3. Solving Equation</h3><p>We can use the solveset() function to solve equations. If we want to specify a domain we can use the domain parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*J3O3A_rtxdGvEpql3akvNw.png" /><figcaption>Figure-12-Sympy-solveset</figcaption></figure><p>We can use the linsolve () function for linear equations and the nonlinsolve() function for nonlinear equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*S2UpAU5ktuQTlK6vL8AI9g.png" /><figcaption>Figure-13-Sympy-linsolve-nonlinsolve</figcaption></figure><h3>4. Matrix Operations</h3><p>The SymPy library allows you to easily perform many matrix operations. Now let’s see some of these.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*FcxQZu2CxNdgAb4sfnUw_Q.png" /><figcaption>Figure-14-Sympy-Matrix-Operations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*I9bH263boUTyJRnNScY7xA.png" /><figcaption>Figure-15-Sympy-Matrix-Operations-2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*HUD91-qicLXiaImNcWgNgw.png" /><figcaption>Figure-16-Sympy-Matrix-Operations-3</figcaption></figure><h3>5. Creating Graphs</h3><p>In SymPy, we can easily create a graph with the plot() function. Now let’s draw the -x chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*LiaJoGnUQjhRFD6d4HH-1Q.png" /><figcaption>Figure-17-Sympy-Creating-Plot</figcaption></figure><p>It is also possible to plot multiple functions at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*joEZUMdAuj2xSuFbm0QU2A.png" /><figcaption>Figure-18-Sympy-Creating-Plot-2</figcaption></figure><p>Now let’s draw the sigmoid function, which is used as the activation function in artificial neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*mm-gSoXxs2n_hjze_hTE-w.png" /><figcaption>Figure-19-Sympy-Creating-Plot-3</figcaption></figure><p>We can also draw three-dimensional graphs with SymPy. Now let’s draw the sigmoid function as 3D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*KFdargZ0HMKLPn3Jm2Kd5A.png" /><figcaption>Figure-20-Sympy-Creating-Plot-3D</figcaption></figure><p>The SymPy library is not limited to these, of course. There are many libraries available that have been developed using SymPy for fields such as physics, chemistry and optimization. More information about SymPy can be found <a href="https://docs.sympy.org/latest/tutorial/index.html">here</a> .</p><p>If you use Jupyter Notebook and want to save your work as a Word file, you can save your file as Markdown by following File&gt;Download as&gt;Markdown(.md) commands and then convert it to Word <a href="https://cloudconvert.com/md-to-docx">here</a>.</p><p>You can reach the Notebook that I prepared for this article <a href="https://www.kaggle.com/ferhatmetin34/symbolic-mathematics-operations-with-sympy">here</a> .</p><p>For my other articles :</p><p><a href="https://www.datasciencearth.com/author/ferhatmetin/">https://www.datasciencearth.com/author/ferhatmetin/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb9977b64871" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datasciencearth/what-is-sympy-cb9977b64871">What is SymPy?</a> was originally published in <a href="https://medium.com/datasciencearth">Data Science Earth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LOCAL OUTLIER FACTOR]]></title>
            <link>https://medium.com/datasciencearth/local-outlier-factor-7821b5651bc5?source=rss-8d2aef75e0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7821b5651bc5</guid>
            <category><![CDATA[outlier-detection]]></category>
            <category><![CDATA[outliers]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[ferhatmetin]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 20:45:24 GMT</pubDate>
            <atom:updated>2021-01-26T14:09:08.749Z</atom:updated>
            <content:encoded><![CDATA[<p>Local outlier factor is one of the methods used to detect outlier observations.Outlier detection methods can be distribution-based,depth-based,clustering-based and density-based. LOF allows to define outliers by doing density-based scoring. It is similar to the KNN (nearest neighbor search) algorithm. The difference is that we’re trying to find observations that are close together in KNN, but we’re trying to find observations that are not alike in LOF.</p><p>Local outlier factor algorithm can be divided into four parts:</p><ul><li>K-Distance and K-Neighbors</li><li>Reachability Distance</li><li>Local Reachability Density</li><li>Local Outlier Factor Calculation</li></ul><h3>K-Distance and K-Neighbors</h3><p>In order to find the distance between observations, it is necessary to determine the hyperparameter k. The k value here determines how many neighbors we’re looking at .k distances are calculated according to this k value. For example, if k=5, the distance to the nearest fifth neighbor is looked at.If we give a very small value to k, the algorithm becomes sensitive to noise,and if we give a large value, it may not recognize local anomalies.</p><figure><img alt="K-Distance (LOF)" src="https://cdn-images-1.medium.com/max/460/1*217TN2_-cgZ1d7hZUWhYUA.png" /><figcaption>Figure 1. k-Distance (k=3)</figcaption></figure><h3>Reachability Distance</h3><p>In short, it expresses the maximum of the distance of two points and the k-distance of the second point. The distance between the two points here can be Euclid,Minkowski,Manhattan, or any of the other distance measures.</p><p><strong>Reachability_Distance( a , b ) = max{ k-distance ( b ) , normal_distance ( a , b ) }</strong></p><h3>Local Reachability Density</h3><p>It refers to how far we need to go from the point we are at to reach the next point or set of points. The calculated reachability distances are used to calculate the local accessibility density. For all k closest neighbors of a, the reachability distances are calculated and the values found are summed and divided by the value of k. When the inverse of this value is taken, we calculate the density we are looking for.</p><p><strong>Local_reachability_density ( a ) = 1 / ( sum ( Reachability_Distance (a , n ) ) / k)</strong></p><p>The n here refers to neighbors up to K.</p><h3>Local Outlier Factor</h3><p>The local reachability densities found are compared to the local reacability densities of a’s nearest k neighbors. The density of each neighbor is summed up and divided by the density of a. The value found is divided by the number of neighbors i.e. k.</p><p><strong>LOF ( a ) =[ ( LRD (1st. neighbor) + LRD ( 2nd. neighbor ) + ….. + LRD ( kth. neighbor ) ) / LRD ( a ) ] / k</strong></p><p>Now let’s make a simple implementation for better understanding.</p><h3>Implementation</h3><p>Let’s say we have 4 points. These points are: a(1 , 1), b(1,0), c(3,2) and d(2,0). Let’s assume k is 2 and our distance measure is Manhattan. Now let’s find the distances between them.</p><p>[caption id=”” align=”aligncenter” width=”378&quot;]</p><figure><img alt="Manhattan Distance" src="https://cdn-images-1.medium.com/max/536/1*OnKwaQZo_yZsItaT-Mgp4w.png" /><figcaption>Figure 2. Manhattan Distance</figcaption></figure><p>distance(a,b) = 1 distance(a,d) = 2 distance(b,d) = 1</p><p>distance(a,c) = 3 distance(b,c) = 4 distance(c,d) = 3</p><p>We found the distances between the points.Now let’s find k-distances.Since k is 2, we need to look at the second nearest neighbor.</p><p>distance_2 (a) = d distance_2 (b) = a or d distance_2 ©= a or d distance_2(d) = a</p><p>Let’s look at the two nearest neighbors for each point.</p><p>N( a ) = { b, d } N( b ) = { a, d } N( c ) = { a, d } N( d ) = { a, b }</p><p>Now let’s calculate reachabilty distances for each point.</p><p><strong>reachabilty_distance(a,b)</strong> = max{ distance_2(b), distance(a,b) } = max{1,1} = 1</p><p><strong>reachabilty_distance(a,d)</strong>=max{ distance_2(d), distance(a,d) } = max{2,1} = 2</p><p><strong>reachabilty_distance(b,a)</strong>=max{ distance_2(a), distanceb,a) } = max{2,1} = 2</p><p><strong>reachabilty_distance(b,d)</strong>=max{ distance_2(d), distance(b,d) } =max{2,1} = 2</p><p><strong>reachabilty_distance(c,a)</strong>=max{ distance_2(a), distance(c,a) } = max{2,3} = 3</p><p><strong>reachabilty_distance(c,d)</strong>=max{ distance_2(d), distance(c,d) } = max{2,3} = 3</p><p><strong>reachabilty_distance(d,a)</strong>=max{ distance_2(a), distance(d,a) } = max{2,2} = 2</p><p><strong>reachabilty_distance(d,b)</strong>=max{ distance_2(b), distance(d,b) } = max{1,1} = 1</p><p>Now we can calculate the local reachability densities.</p><p><strong>LRD(a)</strong> = 1 / ( reachability_distance(a,b) + reachability_distance(a,d) ) / 2) = 2/3</p><p><strong>LRD(b)</strong> = 1 / (reachability_distance(b,a) + reachability_distance(b,d) ) / 2) = 1/2</p><p><strong>LRD(c)</strong> = 1 / (reachability_distance(c,a) + reachability_distance(c,d) ) / 2) = 1/3</p><p><strong>LRD(d)</strong> = 1 / (reachability_distance(d,a) + reachability_distance(d,b) ) / 2)= 2/3</p><p>Now that we’ve calculated the local reachability densities, all that’s left is to calculate the LOF scores.</p><p><strong>LOF(a)</strong> = ( ( LRD(b) + LRD(d) ) / LRD(a) ) / 2 = [(1/2 + 2/3) / (2/3) ] / 2 = 7/8 = 0,875</p><p><strong>LOF(b)</strong> = ( ( LRD(a) + LRD(d) ) / LRD(b) ) / 2 = [(2/3 + 2/3) / (1/2) ] / 2 = 4/3 = 1,333</p><p><strong>LOF(c)</strong> = ( ( LRD(a) + LRD(d) ) / LRD(c) ) / 2 = [(2/3 + 2/3) / (1/3) ] / 2 = 4/2 = 2</p><p><strong>LOF(d)</strong> = ( ( LRD(a) + LRD(b) ) / LRD(d) ) / 2 = [(2/3 + 1/2) / (2/3) ] / 2 = 7/8 = 0,875</p><p>We found the LOF scores manually. Now let’s do this in Python. Let’s call the libraries we need first.</p><pre>import numpy as np <br>import pandas as pd <br>import matplotlib.pyplot as plt <br>import seaborn as sns <br>from sklearn.metrics import pairwise_distances from sklearn.neighbors import LocalOutlierFactor</pre><p>Let’s place the coordinates of each point in the DataFrame.</p><pre>X=pd.DataFrame(np.array([[1,1],[1,0],[3,2],[2,0]]),<br>columns=[&quot;x&quot;,&quot;y&quot;],index=[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]) <br>X</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*zPxQBWvzHfvsN4Nm0k8_JA.png" /></figure><pre>pairwise_distances(X,metric=&quot;manhattan&quot;) # to check the distances</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*EHDI1-mygzhP2JxpjoYdHA.png" /></figure><pre>plt.scatter(X.x, X.y, color = &quot;r&quot;, s = 50); # to visualize<br>plt.grid() plt.title(&quot;Gözlem Birimleri&quot;); #for the title</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*9iGRppAuT-SGCJGcxEADaQ.png" /></figure><pre>LOF = LocalOutlierFactor(n_neighbors = 2,metric=&quot;manhattan&quot;) <br># (k number of neighbors,distance measure)</pre><pre>LOF.fit_predict(X) #to predict the outliers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*4PYdsVh8SeaH3S7HxyF0xQ.png" /></figure><pre>LOF.negative_outlier_factor_ <br>#let&#39;s multiply the negative scores by - and see the positive scores</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*jVblR1g7IOzztLdYbbwx0A.png" /></figure><p>As you can see, the scores are the same as the results we have found.</p><p>Values that are negative express outlier observations. In this case point c appears to be an outlier observation.LOF scores that are smaller than 1 indicate a denser region.Scores greater than 1 indicate outliers. But different decisions can be made according to data and problem. By determining a threshold value, the points below can be considered as non-outliers and the points above can be considered as outliers.</p><p>Resources I can recommend for better understanding:</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.LocalOutlierFactor.html">sklearn.neighbors.LocalOutlierFactor</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCAvKQHHNmcY&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCAvKQHHNmcY&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FCAvKQHHNmcY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/efbfc0184d33d52a9d359484ce9b5826/href">https://medium.com/media/efbfc0184d33d52a9d359484ce9b5826/href</a></iframe><p><strong>REFERENCES</strong></p><p>Hanxiang Dinga , Kun Dinga, , Jingwei Zhangb , Yue Wanga , Lie Gaoa , Yuanliang Lia , Fudong Chena , Zhixiong Shaoc , Wanbin Laia, 2018, Local outlier factor-based fault detection and evaluation of photovoltaic system</p><p>Markus M. Breunig, Hans-Peter Kriegel, Raymond T. Ng, Jörg Sander, 2000,LOF: Identifying Density-Based Local Outliers</p><p><a href="https://bit.ly/2Y24VWk">Local Outlier Factor | Simple Example By Hand / doedotdev Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7821b5651bc5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datasciencearth/local-outlier-factor-7821b5651bc5">LOCAL OUTLIER FACTOR</a> was originally published in <a href="https://medium.com/datasciencearth">Data Science Earth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>