<?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 Konrad Myśliwiec on Medium]]></title>
        <description><![CDATA[Stories by Konrad Myśliwiec on Medium]]></description>
        <link>https://medium.com/@konradmy?source=rss-a0289d555dae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FCpISxKVe0Ye87Eti2T8uQ.jpeg</url>
            <title>Stories by Konrad Myśliwiec on Medium</title>
            <link>https://medium.com/@konradmy?source=rss-a0289d555dae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:12:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@konradmy/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[Unsupervised clustering data with graphs]]></title>
            <link>https://medium.com/@konradmy/unsupervised-clustering-data-with-graphs-4b70d652f61b?source=rss-a0289d555dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b70d652f61b</guid>
            <category><![CDATA[community-detection]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mnist]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Konrad Myśliwiec]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 17:36:50 GMT</pubDate>
            <atom:updated>2021-02-28T17:36:50.767Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use graph community detection algorithms to cluster MNIST digits dataset and get 95% accuracy.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*toFtDC0wlQqjuqZb" /><figcaption>Photo by <a href="https://unsplash.com/@comparefibre?utm_source=medium&amp;utm_medium=referral">Compare Fibre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article I will share a simple approach how one can build a graph from vectorised data and apply graph community detection algorithm to cluster this data. This is a toy example which clusters MNITS digits dataset, as this simple dataset is already labeled and allows us to check algorithm accuracy. I tried to reduce the description of the community detection algorithms as much as I can. Yet, if you are not interested in details of community detection algorithms at all, I would recommend to skip description of Louvain and Newman’s leading vector algorithms.</p><h3>MNIST digits dataset</h3><p>MNIST digits dataset is a set of 40k handwritten digits (0–9) with labels. It’s a well-known ‘hello world’ type dataset for data clustering and some image labelling machine learning algorithms. Each sample is a 28x28 pixels image represented as a 784 (28x28) length vector. Sample images below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*Ex78psyR5e57K98pLZbOYA.png" /><figcaption>Sample images from MNIST digits dataset.</figcaption></figure><h3>Community detection</h3><p>A network (graph) is considered to have a community structure if it’s nodes can be grouped into collections of nodes which are highly connected internally as compared to their connections to nodes outside a given community. Communities can be defined as overlapping (one node can belong to several communities) or non-overlapping (one node can only belong to one community). In our case we will consider the latter group.</p><p>It is shown in practice that such communities can define some functional units of nodes e.g. proteins with similar biological functions in protein-protein interaction network or some specific social groups like group of students taking the same course in social networks.</p><p>The concept of community is related to <strong>modularity¹</strong>. <strong>Modularity</strong> is a measure which allows to quantify the strength of identified communities in a given network. High modularity for a graph means dense connections between nodes in identified communities and sparse connections between nodes from different communities. Additionally, it’s value is normalised, so that it lies within range [-1 and 1]. Modularity is represented by the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*OsiMRKeAGdW9SKmfx9ZRBg.png" /><figcaption>Modularity formula. Latex code written by the author.</figcaption></figure><p>As the number and size of huge networks has increased significantly over the last decade (e.g. social networks), the study of communities detection have drawn an attention of many scientists. In this article we will make use of two well-known community detection algorithms: <strong>Louvain</strong> <strong>algorithm</strong> and <strong>Newman’s leading eigenvector algorithm</strong>.</p><h3>Community detection algorithms</h3><p><strong>Louvain algorithm</strong></p><p><strong>Louvain algorithm²</strong> is a method which miaximises modularity based on heuristics. It can be divided into two phases. During the first phase, different community is assigned to each node (one community for each node). Then, for each node <em>i</em> we assign community of it’s neighbour <em>j</em> and measure the gain in modularity, using the formula below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*_H2mtm3TBHxjUd6q1rhwrw.png" /><figcaption>Formula for modularity change in Louvain algorithm. Latex code by author.</figcaption></figure><p>If this gain is positive, then the node is removed from it’s community and moved to the neighbour’s community. If there is no gain, node stays within it’s community. When there is no further improvement of modularity to gain by moving any node in the network, the first phase stops. The second phase consists of creating <em>super-nodes</em> from identified communities — all of the nodes from a given community are merged into one super-node. The weights of the links between the new nodes are calculated by the sum of links’ weights between nodes of the two identified communities. Additionally, a self-loop is added for each super-node with weight equal to sum of the links’ weights between the nodes of this community. After this phase the first phase and then second phase can be reapplied. This algorithm is repeated until no further gains in modularity can be made.</p><p><strong>Newman’s leading eigenvector algorithm</strong></p><p><strong>Newman’s leading eigenvector algorithm¹</strong> generalises graph spectral partitioning method to community detection by maximising modularity measure instead of minimising the cut size. In short, it achieves this by finding the eigenvector corresponding to the highest eigenvalue of the modularity matrix of a particular graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*zua0-csb2RadXm0LtBcayw.png" /><figcaption>Modularity matrix formula. Latex code written by the author.</figcaption></figure><p>Then it assigns nodes to one of the two communities based on values in this eigenvector using the formula below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*ayiauheQKWGsdelAM7x51Q.png" /><figcaption>Formula for values in index vector. Latex code written by the author.</figcaption></figure><p>After the first pass of the algorithm, the network is divided into two groups. In order to divide it into more groups, the algorithm is run again but this time instead of maximising modularity, it maximises the difference between the modularities of the network before and after the subdivision. This difference is given by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*Fkl0lL-gjVRTd246wWSC5g.png" /><figcaption>Formula for additional modularity contribution from subdivision. Latex code written by the author.</figcaption></figure><p>The algortighm stops when no modularity gain can be achieved by subdivisions. <br>As we can see Newman’s leading vector method perform bisection of each community (and then subcommunities). Yet, this doesn’t constrain it from achieving good results.</p><h3>Building a graph from vectors</h3><p>Let&#39;s create a graph from MNIST dataset and build some intuition about it’s properties. We will use <a href="https://github.com/networkx/networkx"><strong><em>networkx</em></strong></a>, <a href="https://github.com/GiulioRossetti/cdlib"><strong><em>cdlib</em></strong></a> and <a href="https://github.com/taynaud/python-louvain"><strong><em>python-louvain</em></strong></a> libraries for working on graphs.</p><p><strong>Dimensionality reduction</strong></p><p>Before we start creating a graph we will reduce dimensionality of our dataset. These images (and thus vectors) share a lot of patterns — images are rather centred, so most of the variability is present in the centre of the images. Moreover, most of the images have white corners. Hopefully, dimensionality reduction will remove redundancy in our data. <br>Current dimensionality of our dataset is 784 (28x28), so let’s try to reduce it. Having played around with this model a bit, I found UMAP algorithm reducing dimensionality to 15 dimensions to be quite a good approach. Yet I only compared it with PCA, so there is a lot of space for exploration. Let’s write our code for dimensionality reduction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddb28e9c84a2b67153042dd00988a016/href">https://medium.com/media/ddb28e9c84a2b67153042dd00988a016/href</a></iframe><p><strong>Graph creation</strong></p><p>Now we can create a graph. We will consider each image as a node in our graph and create a link between two nodes based on their similarity, where the weight of the nodes’ edge will be a value measuring similarity between them. In order to proceed with this step we need to define a similarity measure between our vectors. In this case we will use simple cosine similarity as this measure seems to be the most accurate from the basic measures (the other measures considered as basic: Euclidean, Manhattan, Chebyshev). It is worth menioning that it is not the best idea to create a dense graph with every node connected to every other node. Thus, we will set a threshold which must be exceeded by a similarity between two images in order to create a link between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*_G8sAqxVXeYxmk7851bAGg.png" /><figcaption>Formula for adjacency matrix values for proposed model. Latex code written by the author.</figcaption></figure><p>In this example we will arbitrarily set up this threshold for 0.92 percentile of all similarities. I found it to be quite a good starting threshold on other datasets too. Code for graph creation below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29185850d1e9a5cbc20cee466032326e/href">https://medium.com/media/29185850d1e9a5cbc20cee466032326e/href</a></iframe><p><strong>Intuition</strong></p><p>Let’s pause for a moment to think what we have just created and build some intuition. We created a graph where, ideally, images are linked to each other only if they present the same digit. Unfortunately, we know that people have different handwriting styles and these digits are not perfectly written. See the example image below for digits “3” and “5”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*-WiJCNi30JExTddGAvZKVA.png" /><figcaption>Digits from MNIST dataset labeled as “3” and“5”, where “5” might slightly resemble “3”.</figcaption></figure><p>Yet, we might assume that handwritten digits follow normal distribution (multivariate) — most of them are written somehow similarly with some small number of outliers. So we are most likely to end up with a graph where nodes labeled with different digits are linked <strong><em>(e.g. digits “5” and “3” from above example)</em></strong>. However, we expect nodes which share the same label to be densely connected in comparison to nodes with different labels. This, actually sounds quite like the definition of <strong>modularity</strong>. <strong><em>Our hypothesis is that our algorithm should be able to divide our dataset based purely on graph structure and find the right communities</em></strong>.</p><p>We can expect sloppy scribbled digits to play roles of bridge nodes (which link nodes from different communities) in our network. Thanks to the graph structure our community algorithms should be able to assign nodes to the correct communities — some badly scribbled digit can relate to nodes representing two different digits <strong><em>(like image from the previous example might have a link to “3” and “5”)</em></strong> yet we expect them to be more densely linked to nodes which are even more densely linked to other nodes with their true category.</p><p>This also allows us to formulate <strong><em>another hypothesis, that our model’s ability to generalise should increase as the number of samples grows </em></strong>— which is true for many Machine Learning models, yet not always true for unsupervised models. The more samples we have, the more representative sample of the population we have and, as a consequence, connections between sloppy written digits as well as their connections to well written digits of the same label might increase, allowing our model to distinguish these groups even better.</p><h3><strong>Results</strong></h3><p>Let’s run our model and check it’s results. Before this, let’s pick up any other well-known clustering model which will serve us as a benchmark. In this case we will use DBSCAN as our benchmark model. Precisely we will use an sklearn implementation of DBSCAN.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c08f9fa6bab3942c128ed901969ac309/href">https://medium.com/media/c08f9fa6bab3942c128ed901969ac309/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e72149eeee3eb8d721cc7a68866865bf/href">https://medium.com/media/e72149eeee3eb8d721cc7a68866865bf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5075d44e1b89abcb6796000743f9829b/href">https://medium.com/media/5075d44e1b89abcb6796000743f9829b/href</a></iframe><p>We also need to keep in mind that our models are not aware of labels as this is unsupervised method. We will simply assume that the label of a specific cluster is the most common true label for vectors (images) in this cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbe326ff7e9f70aebe1de3dc5474e63d/href">https://medium.com/media/fbe326ff7e9f70aebe1de3dc5474e63d/href</a></iframe><p>As we want to have proper clusters which can identify digits 0–9, we will set a constrain on number of output clusters to lie within the range 10–12 clusters. I believe it’s not too bad to keep one or two more clusters if there are one or two digits that each is written in two significantly different ways. This means that we will try to tweak our models (DBSCAN and graph clustering) to get 10–12 clusters as a result.</p><p><strong>500 images</strong></p><p>When we run <strong>DBSCAN</strong> on first 500 images we get <strong>11</strong> clusters with accuracy score of <strong>0.688</strong> and NMI ~<strong>0.6975</strong>. The algorithm has it’s parameters tuned a bit so that <em>eps=0.45</em>, <em>min_samples=4</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*TaL2gxgeHfl85-xJyx1PjQ.png" /><figcaption>Screenshot of jupyter notebook script and output for DBSCAN algorithm run on 500 size sample. Code written by the author.</figcaption></figure><p><strong>Louvain</strong> algorithm with default threshold returns 11 clusters and scores <strong>0.756</strong> accuracy and ~<strong>0.6984</strong>. Not so bad as for such a simple approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*PsMy6HWDpmkqR6h4UlLZCw.png" /><figcaption>Screenshot of jupyter notebook script and output for louvain algorithm run on 500 size sample. Code written by the author.</figcaption></figure><p><strong>Newman’s leading eigenvector</strong> algorithm gives us 10 clusters and scores <strong>0.744</strong> <strong>accuracy</strong> and ~<strong>0.7008</strong> NMI. In order to keep constraint for number of clusters the threshold was set up for 0.9983 by grid search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*2u9s0RAOzByszLtNMgFZQg.png" /><figcaption>Screenshot of jupyter notebook script and output for Newman’s leading vector algorithm run on 500 size sample. Code written by the author.</figcaption></figure><p><strong>20 000 images</strong></p><p>This time let’s try running our models on the sample comprised of 20 000 images.</p><p>If we run DBSCAN, we receive 10 clusters with <strong>accuracy</strong> value of <strong>0.6947</strong> and NMI ~<strong>0.7995.</strong> This gives us quite nice increase in NMI and small increase in accuracy. The algorithm is tuned in order to meet our constraints on number of clusters — <strong><em>eps=0.24</em></strong>, <strong><em>min_samples=8</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*8qB3vV_uGZoRwM_UewuYxA.png" /><figcaption>Screenshot of jupyter notebook script and output for DBSCAN algorithm run on 20 000 size sample. Code written by the author.</figcaption></figure><p>When we run our Louvain algorithm we receive 10 clusters and accuracy score of <strong>0.9468</strong> and NMI ~<strong>0.8900</strong>. This time in order to keep constraint for number of clusters the threshold was set up for 0.9991 by grid search. This is quite nice accuracy, but let’s see if we can do better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*NMP0_aC2UftMpDpuXwRodw.png" /><figcaption>Screenshot of jupyter notebook script and output for Louvain algorithm run on 20 000 size sample. Code written by the author.</figcaption></figure><p>After running <strong>Newman’s leading eigenvector</strong> algorithm on 20 000 images sample we get 10 clusters with accuracy ~<strong>0.9522</strong> and NMI ~<strong>0.8941</strong>. As previously the threshold was set up for 0.9991 by grid search. <br>This is quite a nice result, isn’t it? <strong>95% of accuracy</strong> with unsupervised learning without bringing up Deep Learning!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*sUD7Rkt-vmfkrGg7FziWDQ.png" /><figcaption>Screenshot of jupyter notebook script and output for Newman’s leading vector algorithm run on 20 000 size sample. Code written by the author.</figcaption></figure><p>Let’s now check what score <strong>Newman’s leading eigenvector</strong> algorithm can achieve on the first 500 digits this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*Z2Oib6jHgRsz_VeIXLehzg.png" /></figure><p>We can see that this time our algorithm scores <strong>0.944 accuracy</strong> and <strong>0.8971 NMI</strong> on the same first 500 digits which it scored <strong>0.744</strong> <strong>accuracy</strong> and ~<strong>0.7008</strong> NMI when it’s run only on 500 digits sample. This confirms one of our hypothesis that enriching graph by more nodes, we provide it both more accurate distribution of vectors and the graph structure which is closer to reality, which results in better data clustering.</p><p><strong>Wrongly assigned classes</strong></p><p>Let’s have a quick look at a few images which were wrongly classified by our best algorithm (Newman’s leading eigenvector).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*2vBX6wXOodFxN2Rrp30qbw.png" /><figcaption>Wrongly assigned classes by Newman’s leading eigenvector algorithm ran on 20 000 sample size. T — Ground Truth label, A — Assigned label.</figcaption></figure><p>As we can see, some of these wrongly assigned labels are quite extreme cases. 4th and 5th images from the first row and the whole second row might be misleading even to a human eye. Personally, I would also consider the last digit from the 2nd row as “1”. It shows that our algorithm in most cases is confused by sloppy writing.</p><p><strong>Graphs visualisation</strong></p><p>As any work on data without any visualisation doesn’t count let’s draw some a graph created by us first with true labels, and then with labels assigned by our algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*OLGzBHk701FNUaDLwJuHsg.png" /><figcaption>Created graph with ground truth labels for first 500 images. Image create by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*zseFnXoSqax12nlloZQsog.png" /><figcaption>Created graph with labels assigned by Newman’s leading eigenvector trained on first 500 images. Image create by the author.</figcaption></figure><p><strong>Graphs size and complexity</strong></p><p>The graph created for first 500 labels consists of <strong>500 nodes</strong> and <strong>9628 edges</strong>. However, when we increased the number of nodes to 20 000 we get <strong>20 000 nodes</strong> and <strong>5 671 546 edges</strong>. <br>It’s important to keep in mind that the complexity of community detection algorithms is based on number of edges and nodes. Thus, in the presented example we worked only on 20 000 size sample. In theory, according to [1], Louvain algorithm has complexity O(E), where E is the number of edges. While Newman’s Leading Eigenvector method has complexity O(N(N + E)), where E is the number of edges and N is the number of nodes, according to [2]. <br>Additionally, we also need to create a graph in networkx, which adds additional overhead. Networkx is written in Python and looking at the benchmark in this <a href="https://www.timlrx.com/blog/benchmark-of-popular-graph-network-packages">article</a>, it’s not the fastest graph library. Yet quite a lot depends on the implementation of the algorithm. Having run these algorithms on my computer, Louvain algorithm (with graph creation) takes on average: 0.22 and 905 seconds respectively for 500 and 20 000 samples, while Newman’s Leading eigenvector algorithm (with graph creation) takes on average 0.22 and 126 seconds respectively for 500 and 20 000 samples. This shows that networkx’s implementation of Louvain algorithm definitely doesn’t run O(E). So keep this in mind if you plan to run this code on your local machine.</p><h3><strong>Summary</strong></h3><p>We created a graph from vectors in our dataset by representing each vector (image) in our dataset as a node and creating a link between nodes if cosine similarity between two vectors (images) is grater than arbitrarily set threshold. As a result, we reached <strong>95% of accuracy</strong> using Newman’s leading eigenvector community detection method for clustering the data.</p><p>Although the accuracy is really amazing, we need to keep in mind that MNIST digits dataset is not the most difficult dataset for clustering. It was used here as a toy example as it provides ground true labels to verify it’s accuracy. This method might contain some flaws which might be pronounced on different datasets. Thus, it would be interesting to see how it works on different examples and explore other similarity measures as well as new dimensionality reduction methods.</p><p>Anyway, algorithms on graphs are fun, so it’s been fascinating experience so far. Please share your thoughts in comments! Here is a <a href="https://github.com/konradmy/graph_clusteriser/blob/main/mnist_digits/jupyter/mnist_graph_clusteriser.ipynb">link</a> the the repo with code in jupyter notebook.</p><h3>References</h3><p>[1] M. E. J Newman, Finding community structure in networks using the eigenvectors of matrices, Phys. Rev. E 74, 036104 (2006)— <a href="https://doi.org/10.1103/physreve.74.036104">DOI</a></p><p>[2] Blondel, V.D.; Guillaume, J.-L.; Lambiotte, R.; Lefebvre, E. Fast unfolding of communities in large networks. J. Stat. Mech. Theory Exp. 2008,2008, P10008 — <a href="http://dx.doi.org/10.1088/1742-5468/2008/10/P10008">DOI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b70d652f61b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>