<?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 Revag on Medium]]></title>
        <description><![CDATA[Stories by Revag on Medium]]></description>
        <link>https://medium.com/@revag2014?source=rss-c6ca3409c0c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WaWHSZx5d5vf08Xt.jpg</url>
            <title>Stories by Revag on Medium</title>
            <link>https://medium.com/@revag2014?source=rss-c6ca3409c0c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:36:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@revag2014/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[DBSCAN — an Easy Clustering Algorithm and also how to optimize it Using grid search]]></title>
            <link>https://medium.com/@revag2014/dbscan-an-easy-clustering-algorithm-and-also-how-to-optimize-it-using-grid-search-69a382b63e85?source=rss-c6ca3409c0c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/69a382b63e85</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dbscan]]></category>
            <category><![CDATA[grid-search]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <dc:creator><![CDATA[Revag]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 21:55:32 GMT</pubDate>
            <atom:updated>2023-08-08T21:55:32.398Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>DBSCAN — an Easy Clustering Algorithm and also how to optimize it Using grid search</strong></h3><p>DBSCAN stands for “Density-Based Spatial Clustering of Applications with Noise.”</p><p>It is a powerful Non-supervised clustering algorithm that can be used to find clusters in a dataset</p><p>If you are not interested in the math behind the algorithm below given is an easy way of understanding how it works</p><p>Alright, imagine you have a bunch of colourful pebbles. You want to put the pebbles that are close to each other into groups, but you don’t know how many groups there should be.</p><p>DBSCAN is like a friendly robot helper that helps you with this.</p><p>The robot starts by picking a pebble, and then it looks at the other pebbles around it. If there are many pebbles really close to the one it picked, the robot puts all of those pebbles in a special group.</p><p>Then it moves to the next pebble and does the same thing, making more groups if it finds more close pebbles.</p><p>The robot is smart and knows that some pebbles might be all by themselves, like on a big empty space. It doesn’t put those pebbles in any group.</p><p>And it’s also careful not to mix pebbles from different groups together.</p><p>So, DBSCAN is like a pebble-sorting robot that makes groups of pebbles that are really close to each other, and it doesn’t make groups for pebbles that are far away.</p><p>This helps you see which pebbles are hanging out together!</p><p><strong>DBSCAN </strong>can be implemented using the sklearn library from python.This article will give you an overview of how This clustering algorithm can be implemented using python</p><p>For easy implementation we are using a built in dataset from sklearn’s datasets collection called California Housing prices</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*E-RilOd6dmMWLCEf" /></figure><p>Next we need to convert this sklearn dataset into a Pandas Dataframe.The below function does this for us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*edho5JS379c5YRJV" /></figure><p>Now looking at the dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*AwNBfAT-ce3lGPTg" /></figure><p>Although we can use many sets of features for our clustering for the demonstration here we will be limiting the features to Latitude and Longitude as more than 2 dimensional graph will be difficult for us to visualise although 3d plots are an option</p><p>Lets visualise the Latitude vs Longitude on a graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*szVebHp6nXQPXQVj" /></figure><p>Now lets extract our required features from the dataframe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/0*r-Ku91Egzufc6YBJ" /></figure><p>From the graph above we can see that both latitude and longitude falls within a scale and is not too far so we omit the scaling part here but if we are to use this with any other features whose values vary a lot then it is advised to scale these features using an appropriate scaler</p><p>Step 2 : now we need to convert the lat long data frame to a numpy array</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*R0Yq4bUi3CYFiCSu" /></figure><p>Step 3 : Create the model ,we import the DBSCAN class from sklearn.clusters module</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*3SBIbA47enAbYZui" /></figure><p>DBSCAN is a density based clustering algorithm so it tries to find the clusters where the density of the points is high</p><p>The next question will be what does this model return , The model will return a list containing labels for each set of points</p><p>Step 4: now we must use the labels returned by the model to plot and cluster the points</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*_UBejtIjCDXHPcR3" /></figure><p>To find the number of clusters we use the value_counts function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/0*NVPFChr9yY8OimMG" /></figure><p>Here -1 shows the outliers or in other words number of points that doesn’t belong to any category</p><p>To plot this we are using a plotly.express library as it is an easy way of plotting these clusters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*MVBu-TR4dD9fmCvQ" /></figure><p>If you are getting an error that plotly is not found the try</p><p>pip install plotly==5.15.0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m_YVi-LeE8MzlCQp" /></figure><p>Now we see that the model did not do anything special as it labelled the entire dataset as a single cluster</p><p><strong>Using Hyper parameters</strong></p><p>As mentioned earlier DBSCAN has a few hyperparameters which ensures the best results</p><p>Most of the time you will be tuning these 2 hyper parameters i.e</p><p><strong>Epsilon (ε)</strong>: This is also called the “eps” parameter. When DBSCAN looks at a dot, it draws a circle around it with a radius of epsilon.</p><p>If there are enough dots inside that circle, they become a group. Choosing the right</p><p>epsilon depends on how spread out your dots are.</p><ul><li><strong>MinPoints</strong>: This is the minimum number of dots that should be inside the circle for DBSCAN to consider them a group. If there are fewer dots than this number, the dot might be considered as noise or an outlier. The MinPoints value helps control how strict or lenient the algorithm is when forming groups.</li></ul><p>Here we got 3 types of data points.</p><p><strong>Core Point </strong>: A point is a core point if it has more than MinPts points within eps.</p><p><strong>Border Point </strong>: A point which has fewer than MinPoints within eps but it is in the</p><p>neighbourhood of a core point.</p><p><strong>Noise</strong> : A point which is not a core point or border point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*F6yqSQT0jtrJILKx" /></figure><p>These two hyperparameters, epsilon and MinPoints, help you fine-tune how DBSCAN works on your data. You might need to try different values to see what works best for your data</p><p>You can check the detailed documentation on dbscan and its parameters here :<a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.htm">https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.htm</a>l</p><p>Now you have an idea of how these parameters affect the model and our results</p><p>So lets train a new model that takes in these parameters and we can check if it will give us a good result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*hv1BNpCqlhWiVU1g" /></figure><p>Here we gave epsilon as 0.2 and minimum number of samples as 20</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*gJzm0kykckfuqH0a" /></figure><p>As we can see here it did split these points into few clusters ,lets plot these and see the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*-AMqGYQy_63INyFh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y2_nduS1sVfebbAQ" /></figure><p>So here we just gave some values to the model as parameters and the changes were significant</p><p>So in our quest to find the best possible model we now have to define a way to compare 2 models so that we can say one is better than the other</p><p>There are a few methods by which we can compare different clustering models and one we are going to use here is the<strong> Silhouette Score</strong></p><p><strong>Silhouette Score</strong></p><p>The silhouette score is a way to measure how good the clusters are when you use a clustering algorithm like DBSCAN. It helps you understand how well-separated the clusters are and how similar the objects within each cluster are.</p><p>Imagine you have used DBSCAN to group some dots on a map. The silhouette score works like this:</p><ul><li><strong>Distance and Similarity</strong>: For each dot, the silhouette score considers two things:</li><li>How close the dot is to other dots in its own cluster (a measure of cohesion).</li><li>How far the dot is from dots in other clusters (a measure of separation).</li><li><strong>Silhouette Value</strong>: The silhouette value ranges from -1 to 1:</li><li>If the silhouette value is close to 1, it means the dot is well inside its own cluster and far from other clusters. This is good!</li><li>If the silhouette value is close to 0, it means the dot is on the border between clusters.</li><li>If the silhouette value is negative, it means the dot might be in the wrong cluster.</li><li>Average Silhouette Score: To get the overall silhouette score for all the dots, you take the average of all the individual silhouette values.</li></ul><p>Now let’s dive into to evaluate these models and compare them based on this Silhouette Score</p><p>Step 5 : evaluate the model</p><p>Silhouette score can be fetched from sklearn.metrics library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*BLQxO-2tQaQrSVTl" /></figure><p>Here we got a score of 0.35 that’s not bad for this dataset but it can be improved further by changing the value of epsilon and min_samples of the model</p><p>So the next question arise as how can we find the best values of epsilon and min_samples</p><p>There are many methods via this can be done but here we are going to use the easiest one ie a simple variation of <strong>Grid Search</strong></p><p><strong>Grid Search:</strong></p><p>Grid search is a technique used in machine learning to find the best combination of hyperparameters for a model.</p><p>Think of hyperparameters as settings that control how a machine learning algorithm works. For example, in the DBSCAN clustering algorithm, the hyperparameters are the “epsilon” (circle size) and “MinPoints” (minimum number of points in a cluster).</p><p>Grid search works like this:</p><ul><li><strong>Making a Grid</strong>: Imagine you have a grid, like a table. Along the rows, you list different values for one hyperparameter (like different epsilon values), and along the columns, you list values for another hyperparameter (like different MinPoints values).</li><li><strong>Trying All Combinations</strong>: Grid search then tries out every possible combination of these values. It trains and evaluates your model with each combination.</li><li><strong>Finding the Best</strong>: After trying out all the combinations, it checks which combination gives the best performance. This could be measured using something like the silhouette score, accuracy, or any other relevant metric.</li><li><strong>Picking the Winner </strong>: The combination that gives the best performance is considered the winner. These are the hyperparameters you should use for your model</li></ul><p>Here we are going to implement a version of Gridsearch where we are going to try all possible combinations of epsilon and min_samples within a range ,This can be done by mainly 4 steps</p><p>1 .creating a list a numpy array of these parameters with desired range</p><p>2. Converting these list to a combination list containing hyperparameters</p><p>3.passing each set of parameters and training the model</p><p>4.calculate the scores of each model and then using it find the best n — models</p><p>Step 6: finding the best set of hyper-parameters</p><p>As shown in the above steps we create 2 lists of both epsilon and min_samples and use iter tools to generate a combination</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*WViZ9TVpoSXlTRIH" /></figure><p>Here we have 240 such combinations to try and get a good result from them</p><p>Now to implement grid search we pass this combinations list and the function should give us the best set of parameters ,and the best model based on silhouette score</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B8cp2GyHRVlXk0tF" /></figure><p>Here we have given a minimum and maximum limit for the number of clusters formed but mostly that upper cap is not needed but here for demonstration purposes we use it.</p><p>So we now need to get best parameters and labels by passing our combinations list and training data onto the function defined above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*CHYz4rSAqVJ8ATzB" /></figure><p>It takes few minutes to complete as it needs to compute the score for 240 combinations after completion best para will have a dictionary that contains the details of best model along with the score</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cpEWGRMUIyEitWIO" /></figure><p>Now we got our best set of hyper parameters</p><p>Epsilon as 0.32</p><p>Min_samples as 18</p><p>Score of 0.656</p><p>Also we got our labels.lets add these labels to our dataframe and this to see our improvement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*QUMczDv6BQot8FMy" /></figure><p>Now we got 4 clusters ,lets plot them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*gDRAr7GLh8nFR4tl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mdgBc-lbcZh4PnJw" /></figure><p>This way we can use grid search for DBSCAN to get better results than random guessing</p><p>Here we have used only 2 features to form clusters but when there are multiple features we will have to rely silhouette score or other scores</p><p>generally DBSCAN fails when used upon higher dimensionality data</p><p>Also another way will be to reduce the components to its principle components and then use clustering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69a382b63e85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>