<?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[learningdatascience - Medium]]></title>
        <description><![CDATA[exploring data science - Medium]]></description>
        <link>https://medium.com/learningdatascience?source=rss----80bcf0aa0871---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>learningdatascience - Medium</title>
            <link>https://medium.com/learningdatascience?source=rss----80bcf0aa0871---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:16:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/learningdatascience" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pandas Tips/Tricks — Return the 3 most frequent values of field A for each field B value.]]></title>
            <link>https://medium.com/learningdatascience/pandas-tips-tricks-return-the-3-most-frequent-values-of-field-a-for-each-field-b-value-34d7ff09708a?source=rss----80bcf0aa0871---4</link>
            <guid isPermaLink="false">https://medium.com/p/34d7ff09708a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[count]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[frequency]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Christopher Jose]]></dc:creator>
            <pubDate>Thu, 20 Jun 2019 18:39:23 GMT</pubDate>
            <atom:updated>2019-06-20T18:40:19.564Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pandas Tips/Tricks —<strong>Show a count of each of the 3 most frequent values of field A for each field B value.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJd4LHz8h5CylFKE-sCyow.png" /></figure><p>This blog post is for Python/Pandas users because we’re the best<br>(j/k everyone’s special).</p><p><strong>Task: </strong><br>Show a count of each of the 3 most frequent values of field A for each field B value.</p><p>1. Compute frequencies of field A values grouped by field B. <br>2. Show only the 3 highest counts of field A for each field B value</p><p><strong>Real World Example of Above Task: <br></strong>Say you have San Francisco housing project data: <a href="https://data.sfgov.org/Housing-and-Buildings/Housing-Inventories-2005-to-2018/jzn7-79x2">https://data.sfgov.org/Housing-and-Buildings/Housing-Inventories-2005-to-2018/jzn7-79x2</a>. Each row consists of a housing project, including the housing type (apartment, business, school) and completion status (Completed, Not Completed, etc).</p><p>The word “housing” appears to indicate not just a dwelling that people live in, but one where people conduct a particular activity (business, schooling, prayer, the arts, etc).</p><p>Suppose we’d like to show the 3 most frequent housing types and their counts for each project completion status.</p><p>In other words,<br>1. Count each housing type for each project completion status. <br>2. Show only the 3 highest counts of housing types for each project status.</p><p><strong>The Code</strong></p><pre>data.groupby([&#39;fieldB&#39;,&#39;fieldA&#39;]).size()<br>.reset_index(name=&#39;Count&#39;)<br>.sort_values([&#39;fieldB&#39;,&#39;Count&#39;],ascending=[1,0])<br>.groupby(&#39;fieldB&#39;).head(3)</pre><p><strong>The Code Using Example Housing Data</strong></p><pre>data.groupby([&#39;ACTION&#39;,&#39;EXT_USE2&#39;]).size()<br>.reset_index(name=&#39;Count&#39;)<br>.sort_values([&#39;ACTION&#39;,&#39;Count&#39;],ascending=[1,0])<br>.groupby(&#39;EXT_USE2&#39;).head(3)</pre><p>ACTION — Housing Project Completion Status<br>EXT_USE2 — Use of Project (Housing Type)</p><p>I modified the original EXT_USE field into EXT_USE2 since some categories had differing values representing the same thing, like “ARTIST LIVE/WORK” and ”ARTIST LIVE/ WORK”.</p><p>In the above, I sort the Count values (essential) AND the ACTION values (non-essential). Sorting the ACTION values is not essential to the problem statement, but just makes the output cleaner.</p><p><strong>1st Line of Code — data.groupby([‘fieldB’,’fieldA’]).size()</strong><br>This returns a <em>Series </em>object of the count of each distinct (Field B, Field A) value, sorted in descending order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*3qE0qgKTh6wztS_ITHInbg.png" /><figcaption>Create Series of Counts, Grouped by ACTION and EXT_USE2</figcaption></figure><p><strong>2nd Line of Code — reset_index(name=’Count’)</strong><br><em> reset_index()</em> turns the Series into a DataFrame with 3 columns. By default, the values column is annoyingly renamed to ‘0’ (but without the quotes, so you’d literally just reference it using <em>df[0]</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*ld3SpY__LiSaBfk6CGSAag.png" /><figcaption>Convert Series to DataFrame</figcaption></figure><p>Avoid this by supplying the argument <em>name=’Blah Blah’</em>,<em> </em>which renames it to ‘Blah Blah’ (or whatever peaks your fancy).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*yzY15BIvNZVc1XaMKCfJEw.png" /><figcaption>Rename the Count Field from 0 to Count</figcaption></figure><p><strong>3rd Line of Code — sort_values([‘fieldB’,’Count’],ascending=[1,0])</strong> <br>This sorts the DataFrame by ‘fieldB’ in ascending order, and then ‘Count’ in descending order. Sorting ‘fieldB’ is not essential to the problem statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*MtM9alZuow2k867IDuCp5Q.png" /><figcaption>Sort the DataFrame by ACTION and then by Count</figcaption></figure><p><strong>4th Line of Code — groupby(‘fieldB’).head(3)<br></strong>The magic sauce. For each ‘fieldB’ value, return the first 3 rows. We’ve already sorted counts in descending order for each fieldB value. We just need to pull the first 3 rows for each ‘fieldB’ value. Without the groupby(), we’d be pulling the first 3 rows of the entire DataFrame (what head(3) normally does), and not for each ‘fieldB’ value.</p><p><strong>Putting it all together <br></strong>The finale, since this is a symphonic masterpiece that’s been building to it’s inevitable, beautiful climax!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*Ms9YfV3erkH3wWoh9eEFwg.png" /></figure><p>Before you say, <em>“Wait! I see more than 3 rows for some ACTION values!”,</em></p><p>Look again!</p><p>This worked, it’s just that (for the keen-eyed analyst) the ACTION categories need to be wrangled/combined because they were entered slightly differently. CFC Issued was sometimes entered as ‘CFC ISSUED’ and ‘CFC_ISSUED’, and ‘FINAL_INSPECT_blah’ has a similar story.</p><p>So this result is not quite final! — Another task for another day, however!</p><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d7ff09708a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learningdatascience/pandas-tips-tricks-return-the-3-most-frequent-values-of-field-a-for-each-field-b-value-34d7ff09708a">Pandas Tips/Tricks — Return the 3 most frequent values of field A for each field B value.</a> was originally published in <a href="https://medium.com/learningdatascience">learningdatascience</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anomaly Detection Techniques in Python]]></title>
            <link>https://medium.com/learningdatascience/anomaly-detection-techniques-in-python-50f650c75aaf?source=rss----80bcf0aa0871---4</link>
            <guid isPermaLink="false">https://medium.com/p/50f650c75aaf</guid>
            <category><![CDATA[isolation-forests]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Christopher Jose]]></dc:creator>
            <pubDate>Mon, 13 May 2019 01:15:37 GMT</pubDate>
            <atom:updated>2020-07-31T22:28:50.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEuR_qcLl303CQA8PNcEqw.png" /><figcaption>Visual Representation of Local Outlier Factor Scores</figcaption></figure><p>I recently learned about several anomaly detection techniques in Python. These techniques identify anomalies (outliers) in a more mathematical way than just making a scatterplot or histogram and eyeballing it. If a point is an outlier with respect to its values across 30 features (a multivariate outlier), you can’t identify it using the above methods, which is where these techniques come in.</p><p><strong>Format of blog post (most techniques are formatted as follows):</strong></p><ol><li>Explanation of technique</li><li>Basic implementation in sklearn</li><li>Visualization showing anomalies identified using technique</li><li>Sources used in the above</li></ol><p><strong>Covered Techniques:</strong></p><ol><li>DBSCAN</li><li>Isolation Forests</li><li>Local Outlier Factor</li><li>Elliptic Envelope</li><li>One-Class Support Vector Machines</li></ol><p><strong>Some Definitions:</strong></p><ol><li>An <strong>outlier </strong>is an observation with at least one variable having an unusual value.</li><li>A <strong>univariate outlier </strong>is an observation with a variable that has an unusual value.</li><li>A <strong>multivariate outlier </strong>is an observation with at least two variables having unusual values.</li></ol><p>These techniques identify outliers, so either univariate or multivariate outliers.</p><p><strong>Several textbooks with discussed techniques:</strong></p><p>1. <a href="https://www.amazon.com/gp/product/1838826041/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1838826041&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=632b9452feba72f72ae8443307235155">Hands-On Machine Learning with scikit-learn and Scientific Python Toolkits (Released 7/24/2020)</a><em><br></em>Discusses DBSCAN, Isolation Forests, LOF, Elliptic Envelope (easy to read)</p><p>2. <a href="https://www.amazon.com/gp/product/B07Z1PHHQ9/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B07Z1PHHQ9&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=01008aa1c7202ee37629c85c3567b37c">Beginning Anomaly Detection Using Python-Based Deep Learning: With Keras and PyTorch 1st ed. 2019</a><br>Discusses Isolation Forests, One-Class SVM, and more (easy to read)</p><p>3.<a href="https://www.amazon.com/gp/product/3319475770/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=3319475770&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=86a36dc2080aac792ab28ca18a9e5fea"> Outlier Analysis 2nd ed. 2017 Edition</a><em><br></em>Discusses Isolation Forests, LOF, One-Class SVM, and more (harder to read)</p><p><strong>Dataset Used in Code Examples:<br></strong><a href="https://www.kaggle.com/akram24/mall-customers">https://www.kaggle.com/akram24/mall-customers</a></p><p><strong>Data Preprocessing:</strong></p><pre>data=data.drop(‘CustomerID’,axis=1)<br>data=data.rename(columns={<br> ‘Annual Income (k$)’:’Income’,<br> ‘Spending Score (1–100)’:’Spend_Score’})<br>df=pd.get_dummies(data)</pre><pre>from sklearn.preprocessing import MinMaxScaler<br>scaler = MinMaxScaler() <br>num2 = scaler.fit_transform(num)<br>num2 = pd.DataFrame(num2, columns = num.columns)</pre><h3><strong>DBSCAN (Density-Based Spatial Clustering of Applications with Noise)</strong></h3><p>This is a clustering algorithm (an alternative to K-Means) that clusters points together and identifies any points not belonging to a cluster as outliers. It’s like K-means, except the number of clusters does not need to be specified in advance.</p><p><strong>The method, step-by-step:</strong></p><ol><li>Randomly select a point not already assigned to a cluster or designated as an outlier. Determine if it’s a core point by seeing if there are at least <em>min_samples</em> points around it within <em>epsilon</em> distance.</li><li>Create a cluster of this core point and all points within <em>epsilon</em> distance of it (all directly reachable points).</li><li>Find all points that are within <em>epsilon</em> distance of each point in the cluster and add them to the cluster. Find all points that are within <em>epsilon</em> distance of all newly added points and add these to the cluster. Rinse and repeat. (i.e. perform “neighborhood jumps” to find all density-reachable points and add them to the cluster).</li></ol><p><strong>Lingo underlying the above:</strong></p><ol><li>Any point that has at least <em>min_samples</em> points within <em>epsilon</em> distance of it will form a cluster. This point is called a core point. The core point will itself count towards the <em>min_samples</em> requirement.</li><li>Any point within <em>epsilon</em> distance of a core point, but does not have <em>min_samples</em> points that are within <em>epsilon</em> distance of itself is called a borderline point and does not form its own cluster.</li><li>A border point that is within <em>epsilon</em> distance of multiple core points (multiple <em>epsilon</em> balls) will arbitrarily end up in just one of these resultant clusters.</li><li>Any point that is randomly selected that is not found to be a core point or a borderline point is called a noise point or outlier and is not assigned to any cluster. Thus, it does not contain at least <em>min_samples</em> points that are within <em>epsilon</em> distance from it or is not within <em>epsilon</em> distance of a core point.</li><li>The epsilon-neighborhood of point p is all points within <em>epsilon</em> distance of p, which are said to be directly reachable from p.</li><li>A point contained in the neighborhood of a point directly reachable from p is not necessarily directly reachable from p, but is density-reachable.</li><li>Any point that can be reached by jumping from neighborhood to neighborhood from the original core point is density-reachable.</li></ol><p><strong>Implementation Considerations:</strong></p><p>1. You may need to standardize / scale / normalize your data first.<br>2. Be mindful of data type and the distance measure. I’ve read that the gower distance metric can be used for mixed data types. I’ve implemented Euclidean, here, which needs continuous variables, so I removed gender.<br>3. You will want to optimize <em>epsilon</em> and <em>min_samples.</em></p><p><strong>Sklearn Implementation of DBSCAN:</strong></p><pre>from sklearn.cluster import DBSCAN<br>outlier_detection = DBSCAN(<br> eps = .2, <br> metric=”euclidean”, <br> min_samples = 5,<br> n_jobs = -1)</pre><pre>clusters = outlier_detection.fit_predict(num2)</pre><p>DBSCAN will output an array of -1’s and 0’s, where -1 indicates an outlier. Below, I visualize outputted outliers in red by plotting two variables.</p><pre>from matplotlib import cm<br>cmap = cm.get_cmap(‘Set1’)<br>num.plot.scatter(x=’Spend_Score’,y=’Income’, c=clusters, cmap=cmap,<br> colorbar = False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*maV8g4BhWuQloRiC383PlQ.png" /><figcaption>DBSCAN Outliers</figcaption></figure><p><strong>More Information on DBSCAN:</strong></p><p><strong>Textbook Links<br></strong>1. <a href="https://www.amazon.com/gp/product/1838826041/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1838826041&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=632b9452feba72f72ae8443307235155">Hands-On Machine Learning with scikit-learn and Scientific Python Toolkits (Released 7/24/2020)</a><em><br></em>2. <a href="https://www.amazon.com/gp/product/1492032646/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1492032646&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=0aa866bfd55f7baeb6bb886471af2142">Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow… (Released 10/2019)</a><em><br></em>3.<em> </em><a href="https://www.amazon.com/dp/3319675249/ref=as_li_ss_tl?ie=UTF8&amp;linkCode=ll1&amp;tag=learningdat0c-20&amp;linkId=b732001a0ac01b9492ad7cf6d36f511f&amp;language=en_US">Anomaly Detection Principles and Algorithms 2017 Edition</a></p><p><strong>Web Links</strong></p><ol><li><a href="https://mikulskibartosz.name/outlier-detection-with-scikit-learn-d9246b33d352">https://mikulskibartosz.name/outlier-detection-with-scikit-learn-d9246b33d352</a></li><li><a href="https://blog.dominodatalab.com/topology-and-density-based-clustering/">https://blog.dominodatalab.com/topology-and-density-based-clustering/</a></li><li><a href="http://mccormickml.com/2016/11/08/dbscan-clustering/">http://mccormickml.com/2016/11/08/dbscan-clustering/</a></li><li><a href="https://www.naftaliharris.com/blog/visualizing-dbscan-clustering/">https://www.naftaliharris.com/blog/visualizing-dbscan-clustering/</a></li><li><a href="https://www.quora.com/How-does-DBSCAN-algorithm-work">https://www.quora.com/How-does-DBSCAN-algorithm-work</a></li><li><a href="https://towardsdatascience.com/how-dbscan-works-and-why-should-i-use-it-443b4a191c80">https://towardsdatascience.com/how-dbscan-works-and-why-should-i-use-it-443b4a191c80</a></li><li><a href="https://medium.com/@elutins/dbscan-what-is-it-when-to-use-it-how-to-use-it-8bd506293818">https://medium.com/@elutins/dbscan-what-is-it-when-to-use-it-how-to-use-it-8bd506293818</a></li><li><a href="https://medium.com/@soroush.hashemi76/kmeans-vs-dbscan-d9d5f9dbee8b">https://medium.com/@soroush.hashemi76/kmeans-vs-dbscan-d9d5f9dbee8b</a></li></ol><h3><strong>Isolation Forests</strong></h3><p>For each observation, do the following:</p><ol><li>Randomly select a feature and randomly select a value for that feature within its range.</li><li>If the observation’s feature value falls above (below) the selected value, then this value becomes the new min (max) of that feature’s range.</li><li>Check if at least one other observation has values in the range of each feature in the dataset, where some ranges were altered via step 2. If no, then the observation is isolated.</li><li>Repeat steps 1–3 until the observation is isolated. The number of times you had to go through these steps is the isolation number. The lower the number, the more anomalous the observation is.</li></ol><p><strong>Sklearn Implementation of Isolation Forests:</strong></p><pre>from sklearn.ensemble import IsolationForest<br>rs=np.random.RandomState(0)<br>clf = IsolationForest(max_samples=100,random_state=rs, contamination=.1) <br>clf.fit(df)<br>if_scores = clf.decision_function(df)<br>if_anomalies=clf.predict(df)<br>if_anomalies=pd.Series(if_anomalies).replace([-1,1],[1,0])<br>if_anomalies=num[if_anomalies==1];</pre><p>Below, I plot a histogram of <em>if_scores </em>values<em>. </em>Lower values indicate observations that are more anomalous.</p><pre>plt.figure(figsize=(12,8))<br>plt.hist(if_scores);<br>plt.title(‘Histogram of Avg Anomaly Scores: Lower =&gt; More Anomalous’);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoH-nA-N_cPmjyz6EDaQzw.png" /></figure><p>Below, I plot observations identified as anomalies. These observations have <em>if_scores</em> values below the <em>clf.threshold_</em> value.</p><pre>cmap=np.array([&#39;white&#39;,&#39;red&#39;])<br>plt.scatter(df.iloc[:,1],df.iloc[:,2],c=&#39;white&#39;,s=20,edgecolor=&#39;k&#39;)<br>plt.scatter(if_anomalies.iloc[:,0],if_anomalies.iloc[:,1],c=&#39;red&#39;)<br>plt.xlabel(&#39;Income&#39;)<br>plt.ylabel(&#39;Spend_Score&#39;)<br>plt.title(&#39;Isolation Forests - Anomalies&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4u5AhBU0aWBaLjg6Pcmk3g.png" /><figcaption>Isolation Forest Outliers</figcaption></figure><p><strong>More Information on Isolation Forests:</strong></p><p><strong>Textbooks</strong><em><br></em>1.<em> </em><a href="https://www.amazon.com/gp/product/1838826041/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1838826041&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=632b9452feba72f72ae8443307235155">Hands-On Machine Learning with scikit-learn and Scientific Python Toolkits (Released 7/24/2020)</a><em><br></em>2.<a href="https://www.amazon.com/gp/product/B07Z1PHHQ9/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B07Z1PHHQ9&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=01008aa1c7202ee37629c85c3567b37c"> Beginning Anomaly Detection Using Python-Based Deep Learning: With Keras and PyTorch 1st ed. 2019</a><em><br>3</em><strong>.</strong><a href="https://www.amazon.com/gp/product/3319475770/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=3319475770&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=86a36dc2080aac792ab28ca18a9e5fea"> Outlier Analysis 2nd ed. 2017 Edition</a></p><p><strong>Web Links</strong></p><ol><li><a href="https://www.depends-on-the-definition.com/detecting-network-attacks-with-isolation-forests/">https://www.depends-on-the-definition.com/detecting-network-attacks-with-isolation-forests/</a></li><li><a href="https://stackoverflow.com/questions/45223921/what-is-the-range-of-scikit-learns-isolationforest-decision-function-scores">https://stackoverflow.com/questions/45223921/what-is-the-range-of-scikit-learns-isolationforest-decision-function-scores</a></li><li><a href="https://quantdare.com/isolation-forest-algorithm/">https://quantdare.com/isolation-forest-algorithm/</a></li><li><a href="https://medium.com/@hyunsukim_9320/isolation-forest-step-by-step-341b82923168">https://medium.com/@hyunsukim_9320/isolation-forest-step-by-step-341b82923168</a></li><li><a href="http://www.ncsa.illinois.edu/Conferences/LSST18/assets/pdfs/hariri_forest.pdf">http://www.ncsa.illinois.edu/Conferences/LSST18/assets/pdfs/hariri_forest.pdf</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html">https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html</a></li></ol><h3>Local Outlier Factor</h3><p>LOF uses density-based outlier detection to identify local outliers, points that are outliers with respect to their local neighborhood, rather than with respect to the global data distribution. The higher the LOF value for an observation, the more anomalous the observation.</p><p>This is useful because not all methods will not identify a point that’s an outlier relative to a nearby cluster of points (a local outlier) if that whole region is not an outlying region in the global space of data points.</p><p>A point is labeled as an outlier if the density around that point is significantly different from the density around its neighbors.</p><p>In the below feature space, LOF is able to identify P1 and P2 as outliers, which are local outliers to Cluster 2 (in addition to P3).</p><p><strong>Example of local vs global outliers:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*hit53p_S4DICBb7wFyW5Ig.png" /><figcaption>Local vs Global Outliers</figcaption></figure><p><strong>The method, step-by-step:</strong></p><p>For each point P, do the following:</p><ol><li><strong>Calculate distances</strong> between P and every other point (manhattan = |x1-x2| + |y1-y2|) = dist(p1,p2)</li><li><strong>Find the Kth closest point</strong> (Kth nearest neighbor’s distance=K-Dist(P))</li><li><strong>Find the K closest points</strong> (those whose distances are smaller than the Kth point), the K-distance neighborhood of P, Nk(P).</li><li><strong>Find its density</strong> (Local Reachability Density= LRDk(p) — a measure of how close its neighbors are to it), basically the inverse of the avg distance between point p and its neighbors. The lower the density, the farther p is from its neighbors.</li><li><strong>Find its local outlier factor</strong>, LOFk(p), as sum(reachability distances of neighbors to P) x sum(densities of neighbors). LOFk(P) is basically the sum of the distances between P and its neighboring points, weighted by the sum those points’ densities (how far they are from their k neighboring points).</li></ol><p><strong>Additional Details</strong></p><p><em>**</em> For step 2, If 2 points have the same distance to P, then just select one as the next closest, and the other as the next next closest.</p><p><em>**</em>For step 4, LRD = Local Reachability Density = inverse(avg reachability distance between P and its neighbors) &lt;= 1. The word reachability is used because if a neighbor is closer to P than it’s Kth neighbor, then the distance of the Kth neighbor is used instead as a means of smoothing</p><p><em>**</em>For step 4, each reachability distance of a point P’s k neighbors is reachdistk(n1&lt;-p) = max(distk(n1), dist(n1,p))<br><br><em>**</em>For step 4, total distances of neighboring points is divided by the number of neighboring points (or ||Nk(P)||), computed using the results of step 3</p><p><strong>Scenarios affecting LOF values:</strong></p><p>Higher LOF values indicate a greater anomaly level and that <br>LOFk(p) =<br>sum(reachability distances of its neighbors to P) x sum(neighbor densities)</p><p>The LOF for a point P will have a:</p><ol><li>High value if → P is far from its neighbors and its neighbors have high densities (are close to their neighbors) (LOF = (high distance sum) x (high density sum) = High value)</li><li>Less high value if -&gt; P is far from its neighbors, but its neighbors have low densities (LOF = (high sum) x (low sum) = middle value)</li><li>Less high value if -&gt; P is close to its neighbors and its neighbors have low densities (LOF = (low sum) x (low sum) = low value )</li></ol><p><strong>Adjusting K:</strong></p><ul><li>Increase K too much and you’re just looking for outliers with respect to the entire dataset, so points far away from the highest density regions could be misclassified as outliers, even though they themselves reside in a cluster of points.</li><li>Reduce K too much and you’re looking for outliers with respect to very small local regions of points. This could also lead to the misclassification as outliers.</li></ul><p><strong>Observing LOF Results with Varying K:</strong></p><p>The below code plots LOF scores as red circles around points for each of K=5, 30, and 70. The larger the LOF, the greater the radius of the circle, and the more anomalous the observation.</p><pre>def LOF_plot(k):<br> import seaborn as sns<br> from sklearn.neighbors import LocalOutlierFactor<br> var1,var2=1,2<br> clf = LocalOutlierFactor(n_neighbors=k, contamination=.1)<br> y_pred = clf.fit_predict(df)<br> LOF_Scores = clf.negative_outlier_factor_<br> <br> plt.title(“Local Outlier Factor (LOF), K={}”.format(k))<br> plt.scatter(df.iloc[:, var1], df.iloc[:, var2], color=’k’, s=3., label=’Data points’)<br> radius = (LOF_Scores.max() — LOF_Scores) / (LOF_Scores.max() — LOF_Scores.min())<br> plt.scatter(df.iloc[:, var1], df.iloc[:, var2], s=1000 * radius, edgecolors=’r’,<br> facecolors=’none’, label=’Outlier scores’)</pre><pre> plt.axis(‘tight’)<br> plt.ylabel(“{}”.format(df.columns[var1]))<br> plt.xlabel(“{}”.format(df.columns[var2]))<br> legend = plt.legend(loc=’upper left’)<br> legend.legendHandles[0]._sizes = [10]<br> legend.legendHandles[1]._sizes = [20]<br> plt.show();</pre><pre>LOF_plot(5)<br>LOF_plot(30)<br>LOF_plot(70)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXLJlpNcqtyf2iSC64Rk_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVU62i01W81lDUpav-NlZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kA3tnB9GS6n_-ori7aLkPQ.png" /></figure><p>From the above, observe how too small of a K results in too many points having high LOFs (circle radius does not fluctuate as much as one would think). Too high of a K results in those points in the four outer clusters having high LOFs because of being too far from the main cluster of points.</p><p>K=30 offers a balance of the two extremes. This value is selected in implementing the method below:</p><p><strong>Sklearn Implementation of Local Outlier Factor:</strong></p><pre>from sklearn.neighbors import LocalOutlierFactor<br>clf = LocalOutlierFactor(n_neighbors=30, contamination=.1)<br>y_pred = clf.fit_predict(df)<br>LOF_Scores = clf.negative_outlier_factor_<br>LOF_pred=pd.Series(y_pred).replace([-1,1],[1,0])<br>LOF_anomalies=df[LOF_pred==1]</pre><p>Observations predicted as anomalies have values of -1 in <em>clf.fit_predict(). </em>These<em> </em>observations have LOF scores less than the threshold (<em>clf.negative_outlier_factor_</em> &lt; <em>clf.threshold_</em>). Sklearn outputs negative LOF values.</p><pre>cmap=np.array([‘white’,’red’])<br>plt.scatter(num.iloc[:,1],num.iloc[:,2],c=’white’,s=20,edgecolor=’k’)<br>plt.scatter(LOF_anomalies.iloc[:,1],LOF_anomalies.iloc[:,2],c=’red’)<br> #,marker=’x’,s=100)<br>plt.title(‘Local Outlier Factor — Anomalies’)<br>plt.xlabel(‘Income’)<br>plt.ylabel(‘Spend_Score’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EkbWmkng3hfOBb53o9hsEQ.png" /><figcaption>LOF Outliers</figcaption></figure><p><strong>More Information on LOF:</strong></p><p><strong>Textbooks</strong><em><br></em>1<em>. </em><a href="https://www.amazon.com/gp/product/1838826041/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1838826041&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=632b9452feba72f72ae8443307235155">Hands-On Machine Learning with scikit-learn and Scientific Python Toolkits (Released 7/24/2020)</a><em><br></em>2.<a href="https://www.amazon.com/gp/product/3319475770/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=3319475770&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=86a36dc2080aac792ab28ca18a9e5fea"> Outlier Analysis 2nd ed. 2017 Edition</a><em><br></em>3<em>. </em><a href="https://www.amazon.com/dp/3319675249/ref=as_li_ss_tl?ie=UTF8&amp;linkCode=ll1&amp;tag=learningdat0c-20&amp;linkId=b732001a0ac01b9492ad7cf6d36f511f&amp;language=en_US">Anomaly Detection Principles and Algorithms 2017 Edition</a><br>4. <a href="https://www.amazon.com/Outlier-Detection-Applications-Perspective-Intelligent/dp/3030051250/ref=as_li_ss_tl?_encoding=UTF8&amp;pd_rd_i=3030051250&amp;pd_rd_r=5f079021-918c-4589-af25-eaa7143be4fd&amp;pd_rd_w=xlQjf&amp;pd_rd_wg=ZaxtF&amp;pf_rd_p=0b2db3d1-33eb-418a-9672-bb9bd54808e8&amp;pf_rd_r=CVJB3P9C5C8SEZXC52RG&amp;psc=1&amp;refRID=CVJB3P9C5C8SEZXC52RG&amp;linkCode=ll1&amp;tag=learningdat0c-20&amp;linkId=d9adb45fe7fdf95f29b880287d73432a&amp;language=en_US">Outlier Detection: Techniques and Applications 1st Ed. 2019 Edition</a></p><p><strong>Web Links</strong></p><ol><li><a href="http://www.cse.ust.hk/~leichen/courses/comp5331/lectures/LOF_Example.pdf">http://www.cse.ust.hk/~leichen/courses/comp5331/lectures/LOF_Example.pdf</a></li><li><a href="https://towardsdatascience.com/local-outlier-factor-for-anomaly-detection-cc0c770d2ebe">https://towardsdatascience.com/local-outlier-factor-for-anomaly-detection-cc0c770d2ebe</a></li><li><a href="https://medium.com/@mtngt/local-outlier-factor-example-by-hand-b57cedb10bd1">https://medium.com/@mtngt/local-outlier-factor-example-by-hand-b57cedb10bd1</a></li><li><a href="https://medium.com/@mtngt/local-outlier-factor-simple-python-example-8925dad97fe6">https://medium.com/@mtngt/local-outlier-factor-simple-python-example-8925dad97fe6</a></li><li><a href="https://scikit-learn.org/stable/auto_examples/neighbors/plot_lof_outlier_detection.html#sphx-glr-auto-examples-neighbors-plot-lof-outlier-detection-py">https://scikit-learn.org/stable/auto_examples/neighbors/plot_lof_outlier_detection.html#sphx-glr-auto-examples-neighbors-plot-lof-outlier-detection-py</a></li></ol><h3>Elliptic Envelope</h3><p>The Elliptic Envelope method fits a multivariate gaussian distribution to the dataset. Use the <em>contamination</em> hyperparameter to specify the percentage of observations the algorithm will assign as outliers.</p><p><strong>Sklearn Implementation of Elliptic Envelope:</strong></p><pre>from sklearn.covariance import EllipticEnvelope<br>clf = EllipticEnvelope(contamination=.1,random_state=0)<br>clf.fit(df)<br>ee_scores = pd.Series(clf.decision_function(df)) <br>ee_predict = clf.predict(df)</pre><p><em>ee_scores</em> contains fitted densities. <br><em>ee_predict </em>contains labels, where -1 indicates an outlier and 1 does not. Labels are calculated based on <em>clf.threshold_</em> and<em> ee_scores</em>.</p><pre>cmap=np.array([&#39;white&#39;,&#39;red&#39;])<br>plt.scatter(num.iloc[:,1],num.iloc[:,2],c=&#39;white&#39;,s=20,edgecolor=&#39;k&#39;)<br>plt.scatter(ee_anomalies.iloc[:,1],ee_anomalies.iloc[:,2],c=&#39;red&#39;)#,marker=&#39;x&#39;,s=100)<br>plt.title(&#39;Elliptic Envelope - Anomalies&#39;)<br>plt.xlabel(&#39;Income&#39;)<br>plt.ylabel(&#39;Spend_Score&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyO04Jd5ACt1STi9gryvLg.png" /><figcaption>Elliptic Envelope Outliers</figcaption></figure><p><strong>More information on Elliptic Envelope:</strong></p><p><strong>Text books<br></strong>1. <a href="https://www.amazon.com/gp/product/1838826041/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1838826041&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=632b9452feba72f72ae8443307235155">Hands-On Machine Learning with scikit-learn and Scientific Python Toolkits (Released 7/24/2020)</a></p><p><strong>Web Links</strong></p><ol><li><a href="http://sdsawtelle.github.io/blog/output/week9-anomaly-andrew-ng-machine-learning-with-python.html">http://sdsawtelle.github.io/blog/output/week9-anomaly-andrew-ng-machine-learning-with-python.htm</a></li><li><a href="https://chrisalbon.com/machine_learning/preprocessing_structured_data/detecting_outliers/">https://chrisalbon.com/machine_learning/preprocessing_structured_data/detecting_outliers/</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.covariance.EllipticEnvelope.html">https://scikit-learn.org/stable/modules/generated/sklearn.covariance.EllipticEnvelope.html</a></li></ol><h3><strong>One-Class Support Vector Machines</strong></h3><p>I have not fully looked into this method, but here is a basic implementation. The <em>nu </em>hyperparameter seems to be like the contamination hyperparameter in other methods. It sets the % of observations the algorithm will identify as outliers.</p><p><strong>Sklearn Implementation of One-Class SVM:</strong></p><pre>from sklearn import svm<br>clf=svm.OneClassSVM(nu=.2,kernel=’rbf’,gamma=.001)<br>clf.fit(df)<br>y_pred=clf.predict(df)</pre><p>Below, I plot observations identified as anomalies:</p><pre>num.plot.scatter(x=’Income’,y=’Spend_Score’, c=y_pred, cmap=cmap,<br> colorbar = False)<br>plt.title(‘One-Class SVM — Anomalies’);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrDvxDOwQdoz4m1Hmib-YQ.png" /><figcaption>One-Class SVM Outliers</figcaption></figure><p><strong>More Information on One-Class SVM:</strong></p><p><strong>Textbooks</strong><em><br></em>I.<em> </em><a href="https://www.amazon.com/gp/product/B07Z1PHHQ9/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B07Z1PHHQ9&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=01008aa1c7202ee37629c85c3567b37c">Beginning Anomaly Detection Using Python-Based Deep Learning: With Keras and PyTorch 1st ed. 2019</a><em><br></em>2.<a href="https://www.amazon.com/gp/product/3319475770/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=3319475770&amp;linkCode=as2&amp;tag=learningdat0c-20&amp;linkId=86a36dc2080aac792ab28ca18a9e5fea"> Outlier Analysis 2nd ed. 2017 Edition</a></p><p><strong>Web Links</strong></p><p>1. <a href="http://rvlasveld.github.io/blog/2013/07/12/introduction-to-one-class-support-vector-machines/">http://rvlasveld.github.io/blog/2013/07/12/introduction-to-one-class-support-vector-machines/</a><br>2. <a href="https://scikit-learn.org/stable/modules/generated/sklearn.svm.OneClassSVM.html">https://scikit-learn.org/stable/modules/generated/sklearn.svm.OneClassSVM.html</a></p><p><strong>Using K-Means Clustering for Anomaly Detection:</strong></p><p><a href="http://amid.fish/anomaly-detection-with-k-means-clustering">http://amid.fish/anomaly-detection-with-k-means-clustering</a><br><a href="https://towardsdatascience.com/time-series-of-price-anomaly-detection-13586cd5ff46">https://towardsdatascience.com/time-series-of-price-anomaly-detection-13586cd5ff46</a></p><p>Textbook links are affiliate links where I may earn a small commission. <br>Feel free to leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50f650c75aaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learningdatascience/anomaly-detection-techniques-in-python-50f650c75aaf">Anomaly Detection Techniques in Python</a> was originally published in <a href="https://medium.com/learningdatascience">learningdatascience</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>