<?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 AMA on Medium]]></title>
        <description><![CDATA[Stories by AMA on Medium]]></description>
        <link>https://medium.com/@amaboh?source=rss-84831e473140------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ERC63tTprtJANtJDYkqlIw.jpeg</url>
            <title>Stories by AMA on Medium</title>
            <link>https://medium.com/@amaboh?source=rss-84831e473140------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:00:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amaboh/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[Enhancing Graph Vanilla Neural with Convolutional Neural Networks, basis of GCN]]></title>
            <link>https://medium.com/@amaboh/enhancing-graph-vanilla-neural-with-convolutional-neural-networks-basis-of-gcn-d6716477c9e0?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6716477c9e0</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[gnn]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gcn]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 11:03:15 GMT</pubDate>
            <atom:updated>2024-07-09T11:03:15.053Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been busy lately getting my hands dirty with Gemini Pro and LLMs, and keeping up with the pace of ML and AI these days is a challenging task combined with writing insightful articles. That aside, I am delighted to continue our exploration into GNNs from our previous article on Vanilla neural networks. I hope you are as excited as me to dissect the Graph Convolutional Neural Network (GCN), which is the standard benchmark for most research when handling graph-like data.</p><h4><strong>Introduction to GCN</strong></h4><p>The GCN architecture was introduced by Kipf and Welling in 2017 to overcome the limitations of the Vanilla Graph Neural Network by borrowing some concepts from the Convolutional Neural Networks (CNN) architecture and applying them to graph data. As we all know, CNNs have been applied extensively in analyzing and processing imaging data and are foundational for most deep learning on images. We covered the vanilla graph neural network in the previous article with the Facebook Page-Page dataset; we will proceed to use the same dataset to explore how GCN architecture overcomes some of the limitations of the previous architecture.</p><h4><strong>Understanding the GCN Formula</strong></h4><p>Like most ML enthusiasts I like to always examine the formulas of most ML models but most of the time it looks daunting and confusing. However, when you understand the formula it saves you a great deal of time from reading about the architecture as the formula contains 1000 words in at most 20 characters. Below is the original formula of the GNN architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*TReoQUTK-pjHCM2s5yV_rA.png" /><figcaption>Forward propagation equation for graph convolutional networks image credit <a href="https://sid-arcidiacono.medium.com/?source=post_page-----53badade0ce9--------------------------------">Sid Arcidiacono</a></figcaption></figure><p>Though the formula seems self-explanatory, it becomes more intuitive when approached from the lens of linear algebra with visualization that illustrates some of these annotations and simplifies this complex long formula to the elements below which is less complex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*WjVVRyjze6Tn95h_L4Kd-A.png" /></figure><h4><strong>Simplifying the GCN Formula</strong></h4><p>I guess some of these formulas would not make sense to you now but as you read through we will piece them up together, and connect the dots in such a way that when you next look at the formula back you will be able to piece it together like a Lego brick which fits perfectly to make a castle. Let’s proceed to analyze how computer vision models like CNN influence the architecture of GCN, such that next you see the image of a connected graph, you will have a mental model of how Convolution Neural Networks are applied to graph data which is at the core of Graph Convolutional Neural Networks.</p><h4><strong>From CNNs to GCNs: An Analogy</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*pqJRaLAX4D1aMKRboVGciA.png" /><figcaption><em>Left: image in Euclidean space. Right: graph in non-Euclidean space. (Zhou et al. 2020)</em></figcaption></figure><p>From the image above, our goal is to teach a computer to make sense of data present in the form to the right based on how it already knows how it learned to analyze the image to the left. However, please note this is not transfer learning but simple we are using this analogy because it makes it easy to understand how GCN architecture is built using the CNN model. Let’s proceed to explore how Convolution Neural Networks influence the architecture of GCN in the following order</p><p>1. A brief review of convolutional neural networks</p><p>2. Explanation and implementation of graph convolutional layers</p><h4><strong>A Brief Review of Convolutional Neural Networks</strong></h4><p>Convolutional Neural Networks are widely used for pattern recognition for data in a grid-like structure like images. At the core of CNN are the convolutional layers which apply a set of learnable filters also known as kernels to map features as inputs. Below we have the main components of the CNN architecture.</p><blockquote>i. Convolutional layers: Apply a set of learnable filters (kernels) to the input, producing feature maps.</blockquote><blockquote>ii. Activation layers (e.g. ReLU): Introduce non-linearity to the network.</blockquote><blockquote>iii. Pooling layers: Reduce the spatial size of the feature maps, providing some degree of translation invariance.</blockquote><blockquote>iv. Fully connected layers: Perform classification based on the learned features.</blockquote><h4><strong>The CNN Kernel and Convolution Process</strong></h4><p>As a quick reminder, the CNN’s kernel, also known as the filter, is a small matrix of numbers used to extract certain features from the input image. The kernel functions by convolving across the input image, and a dot product is calculated between the kernel and the corresponding patch of the input image represented below with the gray-scale matrix. This enables the kernel to detect and learn the features anywhere in the input image with the CNN model through backpropagation and gradient descent.</p><p>If we look at the image of the dog below, a portion of the image is selected with a 3x3 grid structure representing the pixels in an image, and a kernel is applied to it, which is updated through backpropagation. The results are then summed to create a single value, which is then stored in the center of the output feature map, and this process is repeated for the other missing values shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*a4mp7IHPYLh5NwqwrvvfSg.png" /><figcaption>Convolutional Neural Network, image credit Sorouch Mehraban</figcaption></figure><h4><strong>Mapping CNN Concepts to Graph Data</strong></h4><p>From the above diagram, we can look at the grid structure of the selected portion of the image above with the 3 X 3 grid matrix as a connected graph with the squares representing nodes all connected to the center graph. So if we were to proceed to apply convolution to a graph, how do we go about this? The answer is to simply look at the gridlike feature map of an image as a graph, where the square boxes are nodes connected by edges to the center node. This simple analogy helps us use CNNs to map graph data as interconnected pixels of an image as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*wLlmG-To9ZhQPx9h7eCvKA.png" /></figure><p>Thus from the graph above we can observe all nodes are connected to the center node with the node values as pixel values. The weights of the edges are represented by the images of the kernel and when we proceed to do a dot product of the pixel image and kernels, we end up with the same result as that of CNN.</p><h4><strong>Applying Convolution to Graphs</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*BKPIQiguMli4UHA16XOZGQ.png" /></figure><p>Given that we now have a mental model of a graph from an image, where the nodes represent the pixels and the directed edge weights are the kernel values, this provides us with a graph network. So we could view this network as a friendship network, which we’ve used in previous articles to illustrate how our friends influence our success. Thus, the center node represents you, the individual, and the other nodes are your friends. So, we would proceed to calculate the weighted average of the neighboring nodes (your friends) and the strength of your relationship to determine your level of success. When we look at the Kernel values, we notice that the value of the center node 52 is not included in this weighted average calculation, which represents a successful iteration. This is a tricky aspect because this value represents the current state of that node and is not factored in. From the friendship network perspective, this represents your present level of success, represented by 52, with the weighted sum of the neighboring nodes being an indicator of your friend’s cumulative influence on your success. However, failure to include your present state is saying only your friend’s influence has an impact on your success without taking into account your present state. Thus, to take this into account, we proceed to add a self-loop by multiplying the value of the kernel 3.11 by the present state (52 * 3.11), and we now get the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4npHaanvh03C5_iERsOqg.png" /></figure><h4><strong>Challenges with Non-Uniform Graph Structures</strong></h4><p>The illustrations above showed how CNN is mapped to graph-like data, which is simple information passing between nodes to the node itself, but now we have two problems:</p><p>i. First, only the center node is updated and none of the other node’s values are updated.</p><p>ii. Not all graphs are uniform structures as in the case above or have the same number of neighbors as in image or tabular data.</p><p>Graphs have different shapes and sizes known as the topology of a graph, and this would be quite challenging for us to model based on the previous assumptions, as seen with the different topologies below.</p><h4><strong>Applying GCN to Graphs with Varying Topologies</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jM0Lmw8_irdoRHSv37IxHg.png" /></figure><p>Let’s proceed to use the second graph above to illustrate how we can apply GCN to a graph with three nodes. In this case, our graph values would not be a single value but rather a 2-dimensional vector for each node. Let’s proceed to label the nodes in this graph as 1, 2, and 3 respectively. One crucial question is how we represent the relationship between these nodes in this graph. To represent the relationship between the nodes in this graph, we will use the adjacency matrix, which we covered in the second article of this series on GNNs (see Exploring Graph Properties). The adjacency matrix depicts the edge relationship between two nodes and other nodes or itself (self-loop), represented by 1 where there exists a relationship and 0 where there is none, denoted in the diagram below as AH. The two-dimensional vectors which represent the values of the nodes are also represented in the matrix H.</p><p>Going forward, we simply do matrix multiplication of AH, which is analogous to information passing between the nodes and itself, given that the adjacency matrix maps the relationships between the nodes and the self-loop to incorporate the present state. So we proceed to multiply the first row of matrix A by the first column of matrix H.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*ULTwKBxnFU3PBAWRJz-ecA.png" /></figure><p>Going forward we simply do matrix multiplication of AH which is analogous to information passing between the nodes and itself given that the adjacency matrix maps the relationships between the nodes and the self-loop to incorporate the present state. So we proceed to multiply the first row of the matrix A by the first column of matrix H.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*Gw2AofnezzlRZD9gnajWyg.png" /></figure><h4><strong>Matrix Multiplication and Information Passing</strong></h4><p>From now henceforth this is just a simple matrix multiplication operation to enable information to pass between connected nodes depicted in the adjacency matrix. From the operation below we observe that the result of N1 in green shows N1 + N2 which illustrates that N1 is connected to N2 and itself as seen in the adjacency matrix A. The same conclusion can be made for node N2 which is connected to nodes 1, node 2, and itself (self-loop).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j322RtcGydtrpgK5XgrOlg.png" /></figure><p>Now, we then to treat all the channels and nodes the same. However, this is not the case with real graphs, and we have to account for the following two scenarios based on the following questions:</p><p>1. What if the information in some channels is more important than others? For example, is the information of one channel like the first channel containing 3, 8, and 5 more important than 7, -1, and 5?</p><p>2. What if the information of one node is more important than the others, like Node 1 with 3 and 7 being more important than Node 2 and Node 3?</p><p>To account for the effects of a scenario like the first one, where one channel is more important than the other, we simply proceed with a weighted multiplication, as seen below, and do backpropagation, which enables the algorithm to learn which channel is more important. For us to map from one space to another, we simply change the vectors in the weightings from two to three columns or shrink to one column and multiply AHW.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Kjns2atHPh32Rv4t6c18Q.png" /></figure><h4><strong>The Simplified GCN Formula</strong></h4><p>Well, my dear friend, this is graph convolutional neural AHW, which entails simply multiplying the adjacency matrix by the node values and weights. So I guess the initial formula at the beginning looks less confusing now from this perspective. Let’s break down the original formula based on a simplified formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*K-w191neWbPDN9fp34ecQw.png" /></figure><p>This is the original formula seen above, which is comprised of the following variables:</p><p>1. <strong>A Tilda</strong>: Represents the adjacency matrix plus self (Node), which we explained earlier was to preserve the information of the node (current state).</p><p>2. <strong>D Tilda</strong>: On the other hand, is a sum of all the nodes that takes into account all neighbors of the nodes in the adjacency matrix. This is the main difference with the GNN layer we saw in the previous article. This is done to serve as a normalization of the node neighbors and thus mitigate the difference between nodes with higher neighbors and those with lower neighbors. By dividing the nodes by their neighbors, we help resolve this problem, with N1 being divided by 3, N2 by 2, and N3 by 2.</p><p>3. <strong>Sigma formula</strong>: The sigma formula at the beginning is simply the activation function ReLU, which adds nonlinearity to the algorithm.</p><h4><strong>Implementation and Performance Comparison</strong></h4><p>In our previous article where we introduced the basic GNN architecture, which took the graph features into consideration, we experienced a significant boost in performance compared to the Node2Vec model. So let’s proceed to implement the GCN model on the same dataset as earlier to determine its performance.</p><h3>Graph Convolutional Network compared to Vanilla Graph Neural Network.</h3><p>We used the Citeseer and Facebook Page-Page datasets to implement the Graph Linear Layer model in our previous article, thus we will proceed to use the same dataset for this comparison. We will analyze the node degrees in these datasets because the main difference between these two architectures is that GCN considers node degrees to weigh feature importance, as seen earlier. Thus, our expectation is for node degrees to vary significantly for this architecture to have good performance.</p><h4><strong>Implementing GCN with PyTorch on Citeseer and Facebook Page-to-Page Dataset</strong></h4><p>If you’ve made it thus far in this article, it’s time to get your hands dirty with some coding exercises where we take our learnings from the architecture and theoretical foundation of GCN into implementing this model in Pytorch. We would proceed to compare how this model compares to the vanilla GNN architecture from our previous article in this series on both the Citeseer and Facebook Page-to-Page datasets.</p><blockquote><strong>Setting Up the Environment</strong></blockquote><blockquote><em>First, we need to install the necessary libraries. We’ll be using torch_geometric, a library that extends PyTorch to handle graph-related computations efficiently.</em></blockquote><pre>!pip install torch_geometric</pre><blockquote><strong>Importing Necessary Libraries</strong></blockquote><blockquote><em>We start by importing the necessary libraries and modules for our implementation.</em></blockquote><pre>from torch_geometric.datasets import Planetoid<br>from torch_geometric.utils import degree<br>from collections import Counter<br>import matplotlib.pyplot as plt</pre><blockquote><strong>Loading the Citeseer Dataset</strong></blockquote><blockquote><em>Next, we load the Citeseer dataset using Planetoid, a popular benchmark dataset in graph neural networks research.</em></blockquote><pre># import Citeseer dataset<br>datasets = Planetoid(root=&quot;.&quot;, name=&quot;Citeseer&quot;)<br>data = datasets[0]</pre><p><strong>Analyzing Node Degrees</strong></p><p>To better understand the dataset, we compute the number of neighbors (degree) for each node and visualize it.</p><pre># Compute the number of neighbors for each node<br>degrees = degree(data.edge_index[0]).numpy()<br>numbers = Counter(degrees)<br><br>fig, ax = plt.subplots()<br>ax.set_xlabel(&quot;Node Degree&quot;)<br>ax.set_ylabel(&quot;Number of nodes&quot;)<br>ax.bar(numbers.keys(), numbers.values())<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_dW7CEX4joQROz27ZEt4Q.png" /><figcaption>Number of nodes with nodes degrees in Citeseer dataset</figcaption></figure><p>From the image above we realize that our dataset is left-skewed with a long tail to the left which ranges from 1 neighbor (1380 nodes) to 440 neighbors (1 node). As a result of this uneven distribution, the normalization process would be used to handle this scaling difference.</p><blockquote><strong>Loading the Facebook Page-to-Page Dataset</strong></blockquote><blockquote><em>Similarly, we load the Facebook Page-to-Page dataset.</em></blockquote><pre>from torch_geometric.datasets import FacebookPagePage<br>from torch_geometric.transforms import NormalizeFeatures<br><br>dataset_fb = FacebookPagePage(root=&#39;./data&#39;)<br>data_fb = dataset_fb[0]</pre><blockquote><strong>Analyzing Node Degrees in Facebook Dataset</strong></blockquote><blockquote><em>We perform the same degree analysis on the Facebook dataset.</em></blockquote><pre>degrees_fb = degree(data_fb.edge_index[0]).numpy()<br>numbers_fb = Counter(degrees_fb)<br><br>fig, ax = plt.subplots()<br>ax.set_xlabel(&quot;Node Degree&quot;)<br>ax.set_ylabel(&quot;Number of nodes&quot;)<br>ax.bar(numbers_fb.keys(), numbers_fb.values())<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9H-xl5SQjkdjKmuyBLyj9g.png" /><figcaption>Number of nodes with nodes degrees in the Facebook Page-Page dataset</figcaption></figure><p>We can observe that this dataset is more skewed than the Citeseer dataset with nodes ranging from 1 to 709.</p><blockquote><strong>Defining the GCN Model</strong></blockquote><blockquote><em>We would not be building the GCN network from scratch though that can be done because luckily Pytorch Geometric has one already which we shall simply import.</em></blockquote><blockquote><em>Here, we define the GCN model using PyTorch. The model consists of two graph convolutional layers with a ReLU activation function in between.</em></blockquote><pre>import torch<br>import torch.nn.functional as F<br>from torch_geometric.nn import GCNConv<br><br>def accuracy(pred_y, y):<br>    pred_y = pred_y.argmax(dim=1)<br>    return ((pred_y == y).sum() / len(y)).item()<br><br>class GCN(torch.nn.Module):<br>    def __init__(self, in_channels, hidden_channels, out_channels):<br>        super(GCN, self).__init__()<br>        self.gconv1 = GCNConv(in_channels, hidden_channels)<br>        self.gconv2 = GCNConv(hidden_channels, out_channels)<br><br>    def forward(self, x, edge_index):<br>        x = self.gconv1(x, edge_index)<br>        x = F.relu(x)<br>        x = self.gconv2(x, edge_index)<br>        return F.log_softmax(x, dim=1)<br><br>    def fit(self, data, epochs):<br>        criterion = torch.nn.CrossEntropyLoss()<br>        optimizer = torch.optim.Adam(self.parameters(), lr=0.01, weight_decay=5e-4)<br><br>        self.train()<br>        for epoch in range(epochs+1):<br>            optimizer.zero_grad()<br>            out = self(data.x, data.edge_index)<br>            loss = criterion(out[data.train_mask], data.y[data.train_mask])<br>            acc = accuracy(out[data.train_mask], data.y[data.train_mask])<br>            loss.backward()<br>            optimizer.step()<br>            if epoch % 20 == 0:<br>                val_loss = criterion(out[data.val_mask], data.y[data.val_mask])<br>                val_acc = accuracy(out[data.val_mask], data.y[data.val_mask])<br>                print(f&#39;Epoch: {epoch:03d}, Loss: {loss:.4f}, Val Loss: {val_loss:.4f}, Acc: {acc:.4f}, Val Acc: {val_acc:.4f}&#39;)<br><br>    @torch.no_grad()<br>    def test(self, data):<br>        self.eval()<br>        out = self(data.x, data.edge_index)<br>        acc = accuracy(out[data.test_mask], data.y[data.test_mask])<br>        return acc</pre><blockquote><strong>Training and Evaluating the GCN Model on Citeseer Dataset</strong></blockquote><blockquote><em>We instantiate the GCN model and train it on the Citeseer dataset.</em></blockquote><pre>gcn = GCN(datasets.num_features, 16, datasets.num_classes)<br>print(gcn)<br>gcn.fit(data, epochs=100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2btn88eZYVFv9T57RnGIBw.png" /><figcaption>GCN complete model run on Facebook Citeseer dataset</figcaption></figure><p>We can already observe a significant improvement compared to the previous GNN architecture.</p><p><strong>Preparing and Training on the Facebook Page-to-Page Dataset</strong></p><p>We apply the necessary transformations and train the GCN model on the Facebook Page-to-Page dataset.</p><pre>from torch_geometric.transforms import NormalizeFeatures, RandomNodeSplit<br>dataset_fb = FacebookPagePage(root=&#39;./data&#39;, transform=RandomNodeSplit(num_train_per_class=20, num_val=0.1, num_test=0.1))<br>data_fb = dataset_fb[0]<br><br>gcn = GCN(dataset_fb.num_features, 16, dataset_fb.num_classes)<br>print(gcn)<br>gcn.fit(data_fb, epochs=100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtQ3VjVZZwAKtD8nsPzIYQ.png" /><figcaption>GCN complete model run on Facebook Page-Page dataset</figcaption></figure><p>As can be observed from the table below the GCN architecture has a significant boost on this classification task on both datasets. We can observe a 7% to 9% change from GNN to GCN architecture if you run this model 10 times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*SQzbNipD9TPeqIek8mT4dg.png" /></figure><p>It is important to note that though we used the GCN architecture here for a classification task, we can also proceed to use this for a regression task.</p><p>One of the questions that we did not answer earlier from the section “Applying GCN to Graphs with Varying Topologie” was about the importance of one node over another. We will be exploring this in the next article by exploring Graph Attention Networks another variant of GNNs.</p><p>See you in the next article and happying graphing.</p><p><strong><em>Previous article in series:</em></strong></p><p>From graph topology to Node Features with Neural Networks <a href="https://medium.com/@amaboh/from-graph-topology-to-node-features-with-neural-networks-83b51c3a4019">https://medium.com/@amaboh/from-graph-topology-to-node-features-with-neural-networks-83b51c3a4019</a></p><p><a href="https://course.fast.ai/">Practical Deep Learning for Coders</a>: Lesson 8, <a href="https://course.fast.ai/Lessons/lesson8.html">https://course.fast.ai/Lessons/lesson8.html</a></p><p><strong><em>References</em></strong></p><p>Aleksa G. (2021). Graph Convolutional Networks (GCN) GNN Paper Explain: Available at: <a href="https://www.youtube.com/watch?v=VyIOfIglrUM&amp;list=PLBoQnSflObckArGNhOcNg7lQG_f0ZlHF5&amp;index=3&amp;ab_channel=AleksaGordi%C4%87-TheAIEpiphany">https://www.youtube.com/watch?v=VyIOfIglrUM&amp;list=PLBoQnSflObckArGNhOcNg7lQG_f0ZlHF5&amp;index=3&amp;ab_channel=AleksaGordi%C4%87-TheAIEpiphany</a></p><p>T.Kipf (2016). T. Kipf’s Website Graph Convolutional Neural Networks, Available at: <a href="https://tkipf.github.io/graph-convolutional-networks/">https://tkipf.github.io/graph-convolutional-networks/</a></p><p>T. N. Kipf and M. Welling, <em>Semi-Supervised Classification with Graph Convolutional Networks</em>. arXiv, 2016. DOI: 10.48550/ARXIV.1609.02907. Available at : <a href="https://arxiv.org/abs/1609.02907">https://arxiv.org/abs/1609.02907</a></p><p>Soroush M. (2023): Graph Convolutional Networks (GNC): Available at: <a href="https://www.youtube.com/watch?v=eLcGehfjvgs&amp;t=407s&amp;ab_channel=SoroushMehraban">https://www.youtube.com/watch?v=eLcGehfjvgs&amp;t=407s&amp;ab_channel=SoroushMehraban</a></p><p><strong><em>Resources</em></strong></p><p>Colab Notebook of GCN on Citeseer and Facebook dataset: <a href="https://docs.google.com/presentation/d/1ifJaf0QbYfWeEiIAux-2exTVa4X4lzH2ULbxv50ug1I/edit?usp=sharing">https://docs.google.com/presentation/d/1ifJaf0QbYfWeEiIAux-2exTVa4X4lzH2ULbxv50ug1I/edit?usp=sharing</a></p><p>Sketches and illustrations on GCN: <a href="https://docs.google.com/presentation/d/1ifJaf0QbYfWeEiIAux-2exTVa4X4lzH2ULbxv50ug1I/edit?usp=sharing">https://docs.google.com/presentation/d/1ifJaf0QbYfWeEiIAux-2exTVa4X4lzH2ULbxv50ug1I/edit?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6716477c9e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From graph topology to Node Features with Neural Networks.]]></title>
            <link>https://medium.com/@amaboh/from-graph-topology-to-node-features-with-neural-networks-83b51c3a4019?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/83b51c3a4019</guid>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 15:26:13 GMT</pubDate>
            <atom:updated>2024-07-09T10:46:33.757Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous article on Node2Vec based on Word2Vec with the skip-gram architecture, the networks (graph) we covered in the architecture involved just the network topology with the nodes and edges. However, nodes and edges in a network also have features that are essential in providing valuable insights through embeddings. Node and edge features can be represented in a tabular format that makes it suitable for machine learning models like neural networks.</p><p>In this article, our focus will be on utilizing node features in a tabular format to implement a Vanilla Neural Network based on two popular graph datasets namely Citeseer and Facebook Page-Page. We would first proceed to implement a Vanilla Neural Network without topological information which would serve as our base model for both datasets, and subsequently utilize the topological information in the Neural Network leading to our first GNN architecture involving both node and edge features.</p><h4>Review of Citeseer and Facebook Page-Page Dataset</h4><h4>Citeseer Dataset</h4><p>The Citeseer dataset is a citation network dataset that is commonly used as a benchmark for evaluating node classification in network anaysis. The key points about the Citeseer dataset are:</p><blockquote><strong>The key characteristics of the Citeseer dataset are:</strong></blockquote><blockquote>The Citeseer dataset contains 3,327 scientific publications categorized into 6 classes[1][2][4][5].<br>- Each publication (node) is represented by a 3,703-dimensional word vector feature[1][2].<br>- The dataset contains 4,732 citation relationships (edges) between the publications, forming a directed graph[2].</blockquote><p>The Citeseer dataset has been used to assess the performance of GNN models like GCN, GCNII, EGAT, and CEN-DGCNN in tasks such as node classification[1][2].Compared to smaller datasets like Cora, the Citeseer dataset has denser node neighborhoods, making it more challenging for GNN models to learn effective node representations.</p><p>The Citeseer dataset, along with the Cora dataset, are representative of real-world citation networks and have been widely used as benchmark datasets for evaluating the performance of various GNN models[1][4][5].</p><h4>Facebook Page-Page Dataset</h4><p>The Facebook page-to-page dataset is a graph dataset that represents the connections between verified Facebook pages. The key points about this dataset are:</p><blockquote><strong>The key characteristics of the Facebook Page-Page dataset are:</strong></blockquote><blockquote>- It is an undirected graph, where the nodes represent official Facebook pages and the edges represent mutual likes between the pages.[1][2][3]<br>- The dataset was collected through the Facebook Graph API in November 2017 and includes pages from 4 categories: politicians, governmental organizations, television shows, and companies.[2][3]<br>- The dataset has been used for tasks such as multi-class node classification to predict the category of a Facebook page based on its connections and features.[2]<br>- The dataset contains information on the number of nodes (pages) and edges (mutual likes) for each category, such as 7,057 nodes and 89,455 edges for government pages, and 50,515 nodes and 819,306 edges for artist pages.[3]<br>- The dataset has been used in research on graph embedding and self-clustering techniques for social network analysis.[3]</blockquote><p>Thus, the Facebook page-to-page dataset is a valuable resource for like-minded graph enthusiasts like yourself or researchers studying the structure and dynamics of graphs using verified Facebook pages and their interconnections.</p><h4>Implementing Vanilla Neural Networks for Node Classification</h4><p>As we observed earlier these datasets have node features that offer more information compared to the Zachary’s Karate Club dataset. Thus this enables us to represent these features in tabular format and to proceed to use the Multilayer Perceptron architecture which is a basic neural network architecture but opens up many possibilities.</p><p>For now, we would stick with just a basic MLP and represent our node features in a tabular dataset. This would suffice for our classification tasks and serve as a base model given that this does not take into consideration the topological structure of of graph. Subsequently, we would proceed to add the topological structure and benchmark the result to the ones obtained without the topical structure in this section.</p><blockquote><strong>A brief detour to explain MLP architecture</strong></blockquote><blockquote>The multilayer perceptron (MLP) is a feedforward neural network, meaning information flows from the input layer through the hidden layers to the output layer, it enables the learning of complex non-linear relationships in data through backpropagation training.</blockquote><blockquote>- It consists of an input layer, one or more hidden layers, and an output layer. Each layer is composed of interconnected nodes (neurons) that use a nonlinear activation function.</blockquote><blockquote>- The hidden layers allow the MLP to learn complex, non-linear relationships in the data. The more hidden layers, the more complex patterns the MLP can model.</blockquote><blockquote>- The connections between nodes have numeric weights that are tuned during the training process using a backpropagation algorithm. Backpropagation allows the MLP to learn by adjusting the weights to minimize the error between the predicted and actual outputs.</blockquote><p><strong>step-by-step implementation</strong></p><ol><li>Let’s proceed to install and import the necessary libraries, and datasets, and set the seed for reproducibility.</li></ol><pre>pip install torch, torch_geometric</pre><pre>import torch<br>from torch.nn import Linear<br>import torch.nn.functional as F<br>import pandas as pd<br><br>import torch_geometric.transforms as T<br>dataset_cs = Planetoid(root=&quot;./&quot;, name=&quot;Citeseer&quot;)<br>data_cs = dataset_cs[0]<br><br><br><br>df_cs = pd.DataFrame(data_cs.x.numpy())<br>df_cs[&#39;label&#39;] = pd.DataFrame(data.y)<br>df_cs.head(5)</pre><p>2. Define our MLP architecture with input, hidden, and output dimensions, and initialize our model.</p><pre># Define MLP class<br>class MLP(torch.nn.Module):<br>    ##Multilayer Perceptron<br>    def __init__(self, dim_in, dim_h, dim_out):<br>        super().__init__()<br>        self.linear1 = Linear(dim_in, dim_h)<br>        self.linear2 = Linear(dim_h, dim_out)<br><br>    def forward(self, x):<br>        x = self.linear1(x)<br>        x = torch.relu(x)<br>        x = self.linear2(x)<br>        return F.log_softmax(x, dim=1)<br><br># Initialize MLP<br>model = MLP(dim_in=your_input_dimension, dim_h=your_hidden_dimension, dim_out=your_output_dimension)</pre><p>3. Define loss function and optimizer. However, because we going to be training our model on two datasets, this is just for illustration, we would overwrite this in the training function so that on each run it is reset and previous runs on another dataset do transfer to a new run.</p><pre>criterion = torch.nn.CrossEntropyLoss()<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)</pre><p>4. Define the training loop in the train function, which takes the model, data, and number of epochs as inputs.</p><pre># Define training function<br>def train(model, data, epochs):<br>  <br>    # define loss function and optimizer<br>    criterion = torch.nn.CrossEntropyLoss()<br>    optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)<br>    <br>    model.train()<br>    for epoch in range(epochs + 1):<br>        optimizer.zero_grad()<br>        out = model(data.x)<br>        loss = criterion(out[data.train_mask], data.y[data.train_mask])<br>        acc = accuracy(out[data.train_mask].argmax(dim=1), data.y[data.train_mask])<br>        loss.backward()<br>        optimizer.step()</pre><p>4. Define the testing function, test, which is used to evaluate the model&#39;s performance on the test set.</p><pre>def test(model, data):<br>    model.eval()<br>    out = model(data.x)<br>    acc = accuracy(out.argmax(dim=1)[data.test_mask], data.y[data.test_mask])<br>    return acc </pre><p>5. Train the model using your data.</p><pre>train(model, data_cs, epochs=100) </pre><p>6. Test the trained model on the test set and print the test accuracy.</p><pre># Test the model<br>test_accuracy = test(model, data_cs)<br>print(f&#39;Test Accuracy: {test_accuracy*100:.2f}%&#39;)</pre><p>After training our model on the <strong><em>CiteSeer data</em></strong> and running our test we get an accuracy of<strong> 55.40%, </strong>and it is worth noting our model does not include the network topology just the node features.</p><p>Using the same model we would proceed to train and test our model on the Facebook Page-Page dataset and we obtain an accuracy of <strong>62.10%.</strong></p><blockquote><strong>Vanilla Neural network results on node features without network topology</strong></blockquote><blockquote>i. Citeseer Accuracy: <strong>55.3%</strong></blockquote><blockquote>ii. Facebook Page-Page Accuracy: <strong>62.10%</strong></blockquote><p>We can observe that there’s a difference between the results obtained from the Citeseer and Facebook Page-page datasets despite their similarity. Thus we can now proceed to include both node features and network topology.</p><h4>Implementing a simplified Graph Neural network for Node Classification Task</h4><p>It is worth understanding the key difference between GNNs and other deep learning architectures that use linear layers as seen in previous implementations, and architectures like CNN (convolutional Neural Network) used for computer vision and imaging to recognize patterns in images and RNN (Recurrent Neural Networks) used for sequence and patterns recognition. As noted in our first article in this series, Graphs are peculiar due to their connectivity and sparse nature making nodes not only relations with other nodes but also features. Our previous implementation of the Vanilla Neural Network takes into consideration only the node features without their connectivity/relations with other nodes in the network which is not representative.</p><p>Thus, at the core of GNN is that the representation of a node is influenced not only by its features but also by the features of its neighboring nodes. <strong>Here’s why this matters</strong></p><ul><li><strong>Capturing Relationships:</strong> Graphs are all about relationships between entities. Understanding a node requires understanding how it’s connected to others.</li><li><strong>Shared Information:</strong> Nodes in a neighborhood often share similarities or influence each other (think of social networks, citation networks, etc.).</li></ul><blockquote><strong>Demystifying the maths in GNN</strong></blockquote><blockquote><strong>1. The Basic Linear Layer: </strong>Let&#39;s recall that the basic linear layer in a neural network transforms an input vector ‘x’ using a weight matrix ‘W’: and is represented as | new_representation = W * x</blockquote><blockquote>However, this is a limitation with graphs, where each node has its input vector (its features). A standard linear layer doesn’t consider how nodes relate to each other.</blockquote><blockquote>2.Graph Neural Network Layer: In a graph neural network, the input vectors are node features, but nodes are interconnected, unlike in traditional neural networks.</blockquote><blockquote>To capture the context of a node, we need to consider its neighbors. Let’s denote the set of neighbors of node <em>i</em> as <em>Ni</em>​.</blockquote><blockquote>The equation for the graph linear layer involves summing the features of neighboring nodes weighted by a shared weight matrix <em>W</em>. We also consider the central node’s features by adding self-loops to the adjacency matrix.</blockquote><blockquote>The updated equation for the graph linear layer is:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*0F5_UvALF-0K2F2euRV0dQ.png" /></figure><blockquote>Here, <em>A</em> is the adjacency matrix representing connections between nodes, and <em>xj</em>​ are the features of neighboring nodes.</blockquote><blockquote>By performing matrix multiplication, this equation efficiently aggregates features from neighboring nodes, including the central node.</blockquote><p>We would proceed to implement our Graph Neural Network with PyTorch in the following steps</p><ul><li>Graph Neural Network layer aggregates information from the node’s neighbors to compute the node’s output,</li><li><strong>Adjacency Matrix Creation</strong></li><li>Implementing <strong>VanillaGNN Class</strong></li></ul><ol><li><strong>Vanilla Graph Neural Network Layer</strong></li></ol><pre>class VanillaGNNLayer(torch.nn.Module):<br>    def __init__(self, dim_in, dim_out):<br>        super().__init__()<br>        self.linear = Linear(dim_in, dim_out, bias=False)<br><br>    def forward(self, x, adjacency):<br>        x = self.linear(x)<br>        x = torch.sparse.mm(adjacency, x)<br>        return x</pre><ul><li>__init__(self, dim_in, dim_out): Initializes the layer, taking input and output feature dimensions. A basic linear transformation as seen previously in the vanilla Neural Network class (Linear(dim_in, dim_out, bias=False)) is used for simplicity.</li><li>forward(self, x, adjacency):</li></ul><p><strong>Linear Transformation:</strong> x = self.linear(x) applies the linear layer to the input features to learn node embeddings.</p><p><strong>Neighborhood Aggregation:</strong> torch.sparse.mm(adjacency, x) is the key operation. The sparse adjacency matrix dictates how features from neighbor nodes are summed to update node representations.</p><p>2. <strong>Adjacency Matrix Creation</strong></p><pre>from torch_geometric.utils import to_dense_adj<br><br>adjacency = to_dense_adj(data_cs.edge_index)[0]<br>adjacency += torch.eye(len(adjacency))<br>adjacency</pre><ul><li>to_dense_adj(data.edge_index)[0]: Converts the edge index representation (coordinates of edges) to a dense adjacency matrix. This is necessary for the matrix multiplication to work correctly.</li><li>adjacency += torch.eye(len(adjacency)): Critically, adding the identity matrix ensures self-loops for each node, allowing them to incorporate their own features.</li></ul><p>3. <strong>VanillaGNN Class</strong></p><pre>class VanillaGNN(torch.nn.Module):<br>    &quot;&quot;&quot;Vanilla Graph Neural Network&quot;&quot;&quot;<br>    def __init__(self, dim_in, dim_h, dim_out):<br>        super().__init__()<br>        self.gnn1 = VanillaGNNLayer(dim_in, dim_h)<br>        self.gnn2 = VanillaGNNLayer(dim_h, dim_out)<br><br>    def forward(self, x, adjacency):<br>        h = self.gnn1(x, adjacency)<br>        h = torch.relu(h)<br>        h = self.gnn2(h, adjacency)<br>        return F.log_softmax(h, dim=1)</pre><p>Let’s proceed to implement our train and test our model after initiating the model. One key difference in the training and test loop which differs from the implementation earlier of the Vanilla Neural network, is the addition of the adjacency matrix in the test and train function.</p><blockquote><strong>Vanilla Graph Neural network results with node features and network topology</strong></blockquote><blockquote>i. Citeseer Accuracy:<strong> 62.60%</strong></blockquote><blockquote>ii. Facebook Page-Page Accuracy: <strong>84.53%</strong></blockquote><p>We can proceed to compare the results obtained after using the simplified MLP architecture which consisted of just node features and the Vanilla GNN which included both node features with topology of the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*1Gbj8e43RQRuVCnl3cxk6Q.png" /><figcaption>Figure 2. Comparison of accuracy score</figcaption></figure><p>Thus it is obvious that using a GNN architecture significantly boosts our accuracy. Though our GNN is a simple implementation that uses some algebra the results are significant and clearly illustrate the importance of node features and topology of the network.</p><p>I hope you enjoyed reading this article and now have clarity on the GNN architecture. We will be enhancing this architecture in the next article by exploring Graph Convolutional Neural Networks a variant of GNN.</p><p>Previous articles:</p><p><a href="https://medium.com/@amaboh/neighborhood-reconstruction-with-deepwalk-to-create-node-embeddings-d7acdfcf61b1">Neighborhood reconstruction with DeepWalk to create embeddings</a></p><p><a href="https://medium.com/@amaboh/exploring-graph-properties-and-their-role-in-graph-neural-networks-33ca04c6cebd">Exploring graph properties and their role in Graph Neural Networks</a></p><p>References:</p><p>1. Facebook Page-Page Dataset<br><a href="https://github.com/Andreaierardi/SocialNetworkAnalysis-project">https://github.com/Andreaierardi/SocialNetworkAnalysis-project</a><br><a href="https://paperswithcode.com/dataset/facebook-page-page">https://paperswithcode.com/dataset/facebook-page-page</a><br><a href="https://snap.stanford.edu/data/gemsec-Facebook.html">https://snap.stanford.edu/data/gemsec-Facebook.html</a><br><a href="https://networkx.org/nx-guides/content/exploratory_notebooks/facebook_notebook.html">https://networkx.org/nx-guides/content/exploratory_notebooks/facebook_notebook.html</a><br><a href="https://towardsdatascience.com/multilayer-perceptron-explained-with-a-real-life-example-and-python-code-sentiment-analysis-cb408ee93141">https://towardsdatascience.com/multilayer-perceptron-explained-with-a-real-life-example-and-python-code-sentiment-analysis-cb408ee93141</a></p><p>2. Citeseer dataset<br><a href="https://journalofbigdata.springeropen.com/articles/10.1186/s40537-023-00876-4">https://journalofbigdata.springeropen.com/articles/10.1186/s40537-023-</a><br><a href="https://arxiv.org/html/2401.15444v1">https://arxiv.org/html/2401.15444v1</a><br><a href="https://www.datacamp.com/tutorial/comprehensive-introduction-graph-neural-networks-gnns-tutorial">https://www.datacamp.com/tutorial/comprehensive-introduction-graph-neural-networks-gnns-tutorial</a></p><p><a href="https://networkrepository.com/citeseer.php">https://networkrepository.com/citeseer.php</a>.</p><p>3. Pytorch workflow fundamentals: <a href="https://www.learnpytorch.io/01_pytorch_workflow/">https://www.learnpytorch.io/01_pytorch_workflow/</a></p><p>Colab notebook: <a href="https://colab.research.google.com/drive/14gTL2MdWcnZVa2B5ToCX6AshDmGeC0BU?usp=sharing">https://colab.research.google.com/drive/14gTL2MdWcnZVa2B5ToCX6AshDmGeC0BU?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83b51c3a4019" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From DeepWalk with Random Walks to Biased Random Walks with Node2Vec to improve Embeddings]]></title>
            <link>https://medium.com/@amaboh/from-deepwalk-with-random-walks-to-biased-random-walks-with-node2vec-to-improve-embeddings-582a859ed935?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/582a859ed935</guid>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[node2vec]]></category>
            <category><![CDATA[gnn]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 16:17:33 GMT</pubDate>
            <atom:updated>2024-04-07T16:04:37.294Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous article on <a href="https://medium.com/@amaboh/neighborhood-reconstruction-with-deepwalk-to-create-node-embeddings-d7acdfcf61b1"><em>Neighborhood Reconstruction with DeepWalk to create Node Embeddings </em></a>we were able to take a deep dive into the architecture of DeepWalk with the core components being Word2Vec (skip-gram) and Random Walk. We explored the importance of random walks in exploring the edge node relationship in the graph to convert graphs into vector representations known as embeddings for downstream machine learning tasks.</p><p>Let’s proceed to use our previous knowledge to build upon and learn how Node2Vec architecture uses DeepWalk to improve node embeddings and how the two architectures differ. For those reading this article with no knowledge of graph representation algorithms like Breadth-first Search (BFS) and Depth-first Search, I would advise you to go read the second article in this GNN series as it would provide you with a good foundational knowledge to piece together some of the concepts covered in this article like <em>homophily</em> and structural <em>equivalence</em>.</p><p>In this article, we are going to proceed in the following order.</p><ul><li>Review Node2Vec paper node2vec by Aditya G. and Jure L. (2016).</li><li>Step-by-step implementation of Node2Vec</li><li>Case study implementation</li></ul><h3>Review of the research paper on Node2Vec</h3><p>The problem that the authors of node2vec sought to address in their paper, involved manual feature engineering and limited representations.</p><ol><li><strong>Manual Feature Engineering:</strong> Traditionally, analyzing networks (graphs) in machine learning has required manually designing features to describe the characteristics of nodes (e.g., their importance, and role in the network). This process is time-consuming and domain-specific, and the quality of features heavily influences prediction tasks.</li><li><strong>Limited Representations:</strong> Existing feature learning approaches weren’t able to capture the <em>complex relationships</em> and <em>structures</em> found within networks. The authors wanted a way to represent nodes that accurately reflected their position and function within the broader graph.</li></ol><p>In essence, the goal of Node2Vec is to represent each node as a low-dimensional vector that captures its structural role and position in the network, as well as its relationship to other nodes. Node2Vec builds upon DeepWalk by using Word2Vec (with skip-gram model used in NLP) and biased random walks instead of uniform random walks as seen in DeepWalk.</p><p>Node2vec leverages a flexible biased random walk strategy, which explores the network’s neighborhood efficiently, striking a balance between local and global information. This allows it to capture both the local community structure and the broader network topology, resulting in rich and informative node representations.</p><p>The authors demonstrate how Node2Vec is a scalable and versatile solution for feature learning in networks, enabling a wide range of downstream applications such as node classification, link prediction, and clustering. This is demonstrated by the effectiveness of node2vec on several real-world network datasets such as social networks, citation networks, and protein-protein interaction networks. The result of node2vec outperforms existing state-of-the-art methods for network representation learning on various tasks, such as node classification, link prediction, and community detection.</p><p>Though we’ve learned that biased random walk is the core component of Node2Vec, how do we proceed to implement biased random walks and what core concepts does this approach introduce that make it more efficient?</p><p>First, let’s review the concepts of Homophily and structural equivalence mentioned earlier. Hopefully, you’ve reviewed DFS and BFS as suggested earlier as these are related to Homophily and structural equivalence respectively.</p><h4>How homophily and structural equivalence enable neighborhood sampling</h4><p>Let’s proceed to use the proverb “Show me your friends and I will tell you who you are” to describe homophily and structural equivalence after which we would use BFS and DFS to explore the neighborhood of a graph to demonstrate these concepts.</p><p><strong>Homophily:</strong> This concept implies that similar nodes are more likely to be connected by suggesting that individuals tend to associate with others who share similar characteristics or attributes. In the context of the proverb above, if someone’s friends possess certain qualities, interests, or behaviors, it’s likely that the individual shares those traits as well. For example, if someone’s friends are academically inclined, adventurous, or artistic, it implies that the person in question also values these qualities or activities, reflecting homophily.</p><p><strong>Structural Equivalence:</strong> It implies that nodes are structurally equivalent if they share many of the same neighbors. Structural equivalence refers to individuals who occupy similar positions or roles within a network, regardless of their attributes. In social networks, individuals who have the same pattern of connections, relationships, or interactions can be considered structurally equivalent. In the context of the proverb, if someone’s friends exhibit similar social connections, affiliations, or roles within a community or network, it suggests that the individual occupies a comparable position or role within that social structure, indicating structural equivalence.</p><p>By combining both homophily and structural equivalence, we can understand the proverb as implying that an individual’s social connections not only reflect their attributes and interests (homophily) but also their position or role within a social network (structural equivalence). In essence, the types of friends someone chooses to associate with can provide insights into both their characteristics and their place within the broader social fabric.</p><p>We would proceed to use a social network depicting friendships to illustrate the <em>sampling strategy </em>which involves exploring nodes in the graph from Juan’s node as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qc0A0qOEuvg5B6Mba0zTaQ.png" /><figcaption>Figure 1. Friendship network</figcaption></figure><ul><li>Let’s consider the closest nodes to Juan in terms of connections, and this would represent the neighborhood of <em>Juan, </em>noted N(Juan), and represented as N(Juan) = {Jacie, John, Julia},</li><li>One other sampling strategy would be to select nodes that are not adjacent to previous nodes first. In this case the neighborhood of Juan, would be N(Juan) = {Julia, Jeff, Jade};</li></ul><p>In the first scenario, a Breath-first search is implemented which focuses on the local network around the node Juan signifying structural equivalence seen earlier. In the second scenario, a Depth-first Search is implemented which highlights the opposite of homophily through sequences of distance nodes. Using this approach random walks can sample nodes far from source nodes leading to less representation. Thus the goal is to seek a trade-off between homophily and structural equivalence for understanding certain graphs.</p><p>The key innovation of node2vec is its flexibility in exploring different types of network neighborhoods using biased random walks. By adjusting two parameters, p and q, node2vec can smoothly interpolate between breadth-first search (BFS) and depth-first search (DFS) strategies, allowing it to capture both local and global network structures.</p><h4>Illustrating Biased random walks</h4><p>As we recall from the earlier paragraphs Random Walks uses uniformly distributed probabilities to randomly select nodes sequentially in a graph. From the Random walk algorithm, we implemented in the previous article on DeepWalk to walk, we had a starting point and predefined length, and nodes that appeared together like words in a sentence under the homophily hypothesis are similar.</p><p>The objective of biasing our randomness in Node2Vec is to achieve the following</p><ul><li>Explore the local neighborhood of a node, visiting nearby nodes and staying close to the previous point similar to BFS</li><li>Explore deeper into the network, following longer paths and visiting more distant nodes similar to DFS.</li></ul><p>Using part of the friendship network figure previously, let’s proceed to demonstrate how to parametrize bias randomness with a graph depicting a friend traveling abroad to visit her friends in the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2vwNQGcWP8wzjCDOfL_0Tw.png" /><figcaption>Figure 3. Illustration of a Random Graph</figcaption></figure><p>When we travel to a country we all have that friend who connects all of us (our reference person) in this case above the node <strong><em>Juan</em></strong> is that person in the network and the current node, with the previously visited node(person) being <strong><em>Julia</em></strong>, and the future node(next person to visit) being <strong><em>Jacie. </em></strong>The unnormalized transition probability for Juan to visit Jacie as seen on the graph from node <strong><em>Juan</em></strong> to node <strong><em>Jacie</em></strong> is noted as <strong><em>π Juan Jacie.</em></strong></p><p>π Juan Jacie = ∂(Julia, Jacie) • <strong><em>w (</em></strong>Juan Jacie), where ∂(Julia, Jacie) is the search bias between Juan and Jacie, and <strong><em>w (</em></strong>Juan Jacie) is the weighted edge between Juan and Jacie.</p><p>In DeepWalk, we have <strong>∂(a, b) = 1 </strong>for any pairs of nodes <strong>a</strong> and <strong>b. </strong>While in Node2Vec, the value of <strong>∂(a, b) </strong>is defined based on the distance between the nodes and two additional parameters we mentioned earlier: P which is the return parameter, and q, the in-out parameter. With their objective to approximate DFS and BFS, respectively.</p><p>Here is how the value of <strong>∂(a, b) is defined.</strong></p><p><strong>∂(a, b) = </strong><em>1/p if d (ab) = 0</em> | <em>1 if d(ab) =1</em> | <em>1/q if d(ab) = 2</em></p><p>Here, <em>d(ab) </em>is the shortest path distance between nodes <em>a </em>and <em>b</em>. We can update the unnormalized transition probability from the previous graph as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PK3A8WC_ACEjoRxwyDX3fQ.png" /><figcaption>Figure 4: Graph with transition probabilities</figcaption></figure><p>Let’s proceed to examine the graph in Figure 4 above using Juan’s trip to New York to visit her friends:</p><ul><li>Our visit (walk) starts from node <strong><em>Julia</em></strong> and proceeds to node <strong><em>Juan</em></strong>. The probability of going back to visit Julia is <strong>P</strong> which measures the return probability to node <strong><em>Julia</em></strong>. The higher the probability <strong>P</strong>, the more the random walk will seek to explore new nodes (acting like deja vu) rather than revisiting the same nodes and hence behave like DFS.</li><li>We have as 1 the unnormalized transition probability of visiting Jacie, which is the measure of going to node Jacie, given that node <strong><em>Juan</em></strong> is the intermediate neighborhood of our previous node <strong><em>Julia</em></strong>.</li><li>Lastly, <strong><em>q </em></strong>measures the probability of visiting <strong><em>John. </em></strong>The higher the probability of going to node John the more random walk will focus on nodes that are close to the previous acting like BFS and contrary to what we saw earlier with the return probability.</li></ul><p>As always the best way to learn is to get your hands dirty, and we would proceed with Zachary’s Karate club which we used previously in DeepWalk to implement this architecture of biased random walk and the different parameters.</p><h3>Step-by-step implementation of Node2Vec</h3><h4><strong>Implementing Biased Random Walks</strong></h4><p>It is worth mentioning that Zachary’s club is an unweighted graph, and thus the reason for the transition probability to be determined by the search bias.</p><p>It is worth reminding you that the code implementation of the bias random walk below is part of the Node2Vec architecture for generating random walks on the graph. The goal of biasing random walks is to explore the graph in a way that balances breadth-first search (BFS) and depth-first search (DFS) strategies as seen previously.</p><p>The core components of our Node2Vec code implementation is.</p><p>The next_node() function takes in four parameters: the previous node, the current node, and two bias parameters p and q. The function calculates the transition probability of moving to the next node based on these parameters and returns the next node.</p><p>The random_walk() function generates a random walk of a specified length starting from a given node. The function calls the next_node() function to determine the next node in the walk based on the previous and current nodes and the bias parameters p and q.</p><blockquote><strong>Next Node function parameters:</strong></blockquote><blockquote>previous: The node visited before the current node.</blockquote><blockquote>current: The node the walk is currently at.</blockquote><blockquote>p: Controls the bias towards returning to the previous node.</blockquote><blockquote>q: Controls the bias of exploring other areas of the graph.</blockquote><blockquote><strong>Logic:</strong></blockquote><blockquote>Get the neighboring nodes of the current node.</blockquote><blockquote>Calculate alpha values: Higher alpha means a higher probability of selecting that neighbor.</blockquote><blockquote>- alpha = 1/p if the neighbor is the previous node (bias to go back).</blockquote><blockquote>- alpha = 1 if the neighbor is connected to the previous node (homophily).</blockquote><blockquote>- alpha= 1/q otherwise (exploration).</blockquote><blockquote>Normalize alpha values into probabilities.</blockquote><blockquote>- Use np.random.choice to select the next node based on the calculated probabilities.</blockquote><pre>import networkx as nx<br>import random<br>import numpy as np<br><br># Setting random seeds for reproducibility<br>random.seed(0)<br>np.random.seed(0)<br><br># Generating an Erdos-Renyi graph as an example network<br>#Parameters: <br><br># 10: Number of nodes (members of the karate club). <br>#  0.3: Probability of an edge existing between any two nodes.<br># seed=1: Ensures the same graph structure is generated each time.<br># directed=False: Edges have no direction (undirected graph).<br><br><br>G = nx.erdos_renyi_graph(10, 0.3, seed=1, directed=False)<br><br><br><br>def next_node(previous, current, p, q):<br>    &quot;&quot;&quot;<br>    Randomly selects the next node in a graph based on the previous node, the current node, <br>    and the two parameters p and q.<br>    &quot;&quot;&quot;<br>    neighbors = list(G.neighbors(current))<br>    alphas = []<br>    for neighbor in neighbors:<br>        if neighbor == previous:<br>            alpha = 1/p<br>        elif G.has_edge(neighbor, previous):<br>            alpha = 1<br>        else:<br>            alpha = 1/q<br>        alphas.append(alpha)<br>    probs = [alpha / sum(alphas) for alpha in alphas]<br>    next = np.random.choice(neighbors, size=1, p=probs)[0]<br>    return next</pre><blockquote><strong>Random walk function paremeters.</strong></blockquote><blockquote>start: The starting node ID of the random walk.</blockquote><blockquote>length: How many steps to take in the walk.</blockquote><blockquote>Calls the next_node function to get the next node at each step.</blockquote><blockquote>Converts node IDs to strings for consistency (optional).</blockquote><pre>def random_walk(start, length, p, q):<br>    &quot;&quot;&quot;<br>    Generates a random walk in the graph starting from the given node with the specified length,<br>    p, and q parameters for biasing the random walk.<br>    &quot;&quot;&quot;<br>    walk = [start]<br>    for i in range(length):<br>        current = walk[-1]<br>        previous = walk[-2] if len(walk) &gt; 1 else None<br>        next = next_node(previous, current, p, q)<br>        walk.append(next)<br>    return [str(x) for x in walk]<br><br># Testing the random_walk function with different parameters<br></pre><p>Let’s proceed to explore the parameters <strong><em>p </em></strong>and<strong><em> q as </em></strong>we adjust between BFS and DFS.</p><pre>print(&quot;Case 1 &quot; , random_walk(0, 8, p=1, q=1))  # Unbiased random walk<br>print(&quot;Case 2 &quot; , random_walk(0, 8, p=1, q=10))  # Bias towards returning to previous node<br>print(&quot;Case 3 &quot; , random_walk(0, 8, p=10, q=1))  # Bias towards exploring new nodes</pre><p>Output:</p><pre>Case 1  [0, 4, 3, 6, 2, 1, 0, 4, 0]<br>Case 2  [0, 1, 0, 9, 0, 9, 0, 9, 1]<br>Case 3  [0, 9, 4, 6, 1, 0, 4, 5, 2]</pre><h4>From DeepWalk to Node2Vec</h4><p>As seen in the section we now know how biased random walks work and we can proceed to assemble the Node2Vec which is quite similar to DeepWalk covered in the previous article. If we use the same code implementation of Node2Vec and parametrize <strong><em>p = 1</em></strong> and <strong><em>q =1</em> </strong>we would have a DeepWalk.</p><p>Just a quick reminder that our objective remains the same as in the previous article with Zachary’s Karate Club in DeepWalk to discern the affiliation of members in distinct groups namely “Mr. Hi” and “Officer”. The embeddings generated by Node2Vec would be used for downstream classification tasks with Random Forest as seen in the previous article of DeepWalk Architecture.</p><blockquote><strong>step 1:</strong> Data Preparation: We transform node labels into numerical values, laying the groundwork for subsequent analysis.</blockquote><pre>import networkx as nx<br>from gensim.models.word2vec import Word2Vec<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score<br><br># Load the dataset<br>G = nx.karate_club_graph()<br><br># Transform node labels into numerical values<br>labels = []<br>for node in G.nodes:<br>    label = G.nodes[node][&#39;club&#39;]<br>    labels.append(1 if label == &#39;Officer&#39; else 0)</pre><blockquote><strong>Step 2</strong>: Generating Random Walks: <em>With our, we use our biased random walk function with parameters </em><em>p and </em><em>q, to traverse the network landscape, capturing nuanced relationships between nodes.</em></blockquote><pre># Generate biased random walks<br>walks = []<br>for node in G.nodes:<br>    for _ in range(80):<br>        walks.append(random_walk(node, 10, 3, 2))</pre><blockquote><strong>Step 3: </strong>Node Embeddings with Word2Vec: <em>Using Word2Vec, we transform random walks into meaningful node embeddings. The skip-gram model, guided by hierarchical softmax, learns continuous representations of nodes, encapsulating their structural context within the network</em></blockquote><pre># Create Word2Vec model<br>node2vec = Word2Vec(walks,<br>                    hs=1,<br>                    sg=1,<br>                    vector_size=100,<br>                    window=10,<br>                    workers=2,<br>                    min_count=1,<br>                    seed=0)<br><br># Train the Word2Vec model<br>node2vec.train(walks, total_examples=node2vec.corpus_count, epochs=30, report_delay=1)</pre><blockquote><strong>Step 4:</strong> Classification with Random Forest: <em>Armed with node embeddings, we deploy a Random Forest classifier to discern the club affiliations of members. By training the classifier on a subset of nodes and evaluating its accuracy on test data, we gain insights into the efficacy of our approach.</em></blockquote><pre># Create masks for training and testing data<br>train_mask = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]<br>test_mask = [0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33]<br><br># Train the Random Forest classifier<br>clf = RandomForestClassifier(random_state=0)<br>clf.fit(node2vec.wv[train_mask], labels[train_mask])<br><br># Evaluate the classifier<br>y_pred = clf.predict(node2vec.wv[test_mask])<br>accuracy = accuracy_score(y_pred, labels[test_mask])<br>print(f&#39;Node2Vec accuracy: {accuracy*100:.2f}%&#39;)</pre><p>Output:</p><pre>Node2Vec accuracy: 95.45%</pre><p>Through iterative experimentation with parameters p and q, we unravel the interplay between biased random walks and network structure, paving the way for deeper understanding and discovery. If we carry out a lot experimentation with varying values of p and q, and in the case of DeepWalk where we have (p=1, and q = 1) we would observe that it has the worst performance. This is the case for this dataset but not is not always the case as non-biased random walks can lead to better performance on another dataset.</p><h3>Case study: Utilizing Node2Vec for recommendation</h3><p>Graph Neural Networks (GNNs) have emerged as powerful tools in recommendation systems, offering innovative approaches to understanding and leveraging complex relational data. At the core of many recommendation systems lies the concept of vector similarity, which forms the foundation of models like Word2Vec. Originally designed for natural language processing as seen in DeepWalk architecture, Word2Vec learns vector representations of words in a continuous vector space, capturing semantic similarities between words based on their context. This idea has been extended to recommendation systems, where items such as movies or products are represented as vectors in a high-dimensional space, enabling comparisons based on their similarity.</p><p>To implement a movie recommendation system using GNNs, we first need a suitable dataset. In this example, we utilize the MovieLens dataset, a popular choice among researchers and practitioners. This dataset contains user ratings for various movies, providing valuable insights into user preferences. By processing this data, we construct a graph where nodes represent movies and edges denote connections between movies that are liked by the same users. This encoding approach captures the relational structure of the data, facilitating the learning of meaningful embeddings using techniques like Node2Vec.</p><p>The code implementation begins by loading the MovieLens dataset and filtering highly-rated movies. We then construct a graph representation of the movie dataset, where nodes correspond to movies and edges represent connections between movies liked by the same users. Using the Node2Vec algorithm, we learn embeddings for each movie in the graph, capturing their semantic similarities. Finally, we provide a function to recommend movies similar to “ The God Father” which is my All Time best movie by providng the to query the trained Node2Vec model. This approach demonstrates the power of GNNs in recommendation systems, offering personalized and relevant recommendations based on the underlying relational structure of the data.</p><blockquote>Code implementation</blockquote><pre># Importing necessary libraries<br>import pandas as pd<br>import networkx as nx<br>from node2vec import Node2Vec<br><br># Loading MovieLens dataset<br>ratings = pd.read_csv(&#39;ml-100k/u.data&#39;, sep=&#39;\t&#39;, names=[&#39;user_id&#39;, &#39;movie_id&#39;, &#39;rating&#39;, &#39;unix_timestamp&#39;])<br>movies = pd.read_csv(&#39;ml-100k/u.item&#39;, sep=&#39;|&#39;, usecols=range(2), names=[&#39;movie_id&#39;, &#39;title&#39;], encoding=&#39;latin-1&#39;)<br><br># Filtering highly-rated movies<br>ratings = ratings[ratings.rating &gt;= 4]<br><br># Constructing the movie graph<br>G = nx.Graph()<br>for group in ratings.groupby(&quot;user_id&quot;):<br>    user_movies = list(group[1][&quot;movie_id&quot;])<br>    for i in range(len(user_movies)):<br>        for j in range(i+1, len(user_movies)):<br>            G.add_edge(user_movies[i], user_movies[j])<br><br># Training Node2Vec model<br>node2vec = Node2Vec(G, dimensions=64, walk_length=20, num_walks=200, p=2, q=1, workers=1)<br>model = node2vec.fit(window=10, min_count=1, batch_words=4)<br><br># Recommendation function<br>def recommend(movie):<br>    movie_id = str(movies[movies.title == movie].movie_id.values[0])<br>    for id in model.wv.most_similar(movie_id)[:5]:<br>        title = movies[movies.movie_id == int(id[0])].title.values[0]<br>        print(f&#39;{title}: {id[1]:.2f}&#39;)<br><br># Example usage<br>recommend(&#39;Godfather, The (1972)&#39;)</pre><blockquote>Output:</blockquote><pre>Usual Suspects, The (1995): 0.65<br>Fargo (1996): 0.63<br>Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb (1963): 0.55<br>It&#39;s a Wonderful Life (1946): 0.54<br>One Flew Over the Cuckoo&#39;s Nest (1975): 0.53</pre><p>In the field of network analysis, Node2Vec stands as a beacon of innovation, illuminating the path to uncover hidden patterns and structures within networks. With its versatile capabilities, Node2Vec empowers researchers and practitioners alike to unlock the secrets of complex networks, offering unprecedented insights into the dynamics of social interactions.</p><p>Previous article:<a href="https://medium.com/@amaboh/neighborhood-reconstruction-with-deepwalk-to-create-node-embeddings-d7acdfcf61b1"><em> Neighborhood Reconstruction with DeepWalk to Create Node Embeddings</em></a></p><h4><strong>References:</strong></h4><ol><li>A. Grover and J. Leskovec, <em>node2vec: Scalable Feature Learning for Networks</em>. arXiv, 2016. DOI: 10.48550/ARXIV.1607.00653. Source: <a href="https://arxiv.org/abs/1607.00653">https://arxiv.org/abs/1607.00653</a></li><li>Maxime L. (2023), Hands-On Graph Neural Networks Using Python</li><li>Youtube: Philipp Bruneberg (2023): Graph Embeddings (node2vec) Explained — How nodes get mapped to vectors, Available: <a href="https://www.youtube.com/watch?v=pS_POUVFXvk&amp;ab_channel=PhilippBrunenberg">https://www.youtube.com/watch?v=pS_POUVFXvk&amp;ab_channel=PhilippBrunenberg</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=582a859ed935" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neighborhood Reconstruction with DeepWalk to Create Node Embeddings]]></title>
            <link>https://medium.com/@amaboh/neighborhood-reconstruction-with-deepwalk-to-create-node-embeddings-d7acdfcf61b1?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7acdfcf61b1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[deepwalk]]></category>
            <category><![CDATA[word2vec]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 10:42:54 GMT</pubDate>
            <atom:updated>2024-03-25T10:42:54.057Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://medium.com/@amaboh/exploring-graph-properties-and-their-role-in-graph-neural-networks-33ca04c6cebd">article</a>, we covered some of the foundational concepts about graph properties and concepts, and I hope you are as excited as I am to explore one of the most groundbreaking works in the field of Graph Neural Networks as we dive into the building blocks of DeepWalk, but first, what is Neighborhood reconstruction.</p><h4><strong>What is Neighborhood Reconstruction?</strong></h4><p>Neighborhood reconstruction methods aim to learn node embeddings by capturing the local graph structure and relationships between nodes. These methods employ an encoder-decoder framework, where an encoder(ENC) maps nodes to low-dimensional embeddings, and a decoder reconstructs information about each node’s neighborhood in the original graph. We will just provide a brief overview of the different methods below, and dive into DeepWalk which is the focus of this article, please feel free to explore the reference section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*0pt45ju1kOZmrY4w" /><figcaption>Figure 1 — Node embedding illustration which maps nodes to a low-dimensional embedding space.</figcaption></figure><h4>Neighborhood reconstruction methods</h4><p><strong>1. An Encoder-Decoder Perspective:</strong> The concept of encoding and decoding graphs in the context of node embeddings has been evolving. The framework of encoding and decoding graphs involves mapping nodes to low-dimensional embeddings and using a decoder to reconstruct information about each node’s neighborhood.<br> <br><strong>2. Factorization-based approaches:</strong> This includes methods like Laplacian one of the earliest factorization-based approaches introduced by Belkin and Niyogi in 2002 eigenmaps and inner-product methods which optimize embeddings to capture node similarity based on adjacency or higher-order neighborhood information. Other methods like Graph Factorization, GraRep, and HOPE have been developed more recently, with publications ranging from 2013 to 2016.,</p><p><strong>3. Random walk embeddings:</strong> Explores methods like DeepWalk introduced by Perozzi et al. in 2014, pioneered the use of random walks for learning node embeddings and node2vec proposed by Grover and Leskovec in 2016, which learn embeddings by capturing the statistics of random walks over the graph, enabling the modeling of node co-occurrence patterns.</p><p>Let me know if you need further clarification or assistance!</p><p>Before diving into DeepWalk I would like to motivate your learning by illustrating the problem DeepWalk aims to solve, which is graph representation using the Zachary Karate Club dataset which is to GNN as “Hello world” is to programming or as MNIST (LeCun et al) is to computation vision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*22aC9zigsIeQSTvhnuxjJA.png" /><figcaption>Figure 2 — Zachary’s Karate Club</figcaption></figure><p>If you’ve been studying GNNs then obviously Zachary’s Karate Club needs no introduction, and for those without prior knowledge. The Zachary Karate Club dataset is a well-known social network dataset that captures the interactions among members of a university karate club. It was originally compiled by Wayne W. Zachary, a social psychologist, in the early 1970s.</p><p>In 1977, Zachary published a paper titled “An Information Flow Model for Conflict and Fission in Small Groups,” in which he analyzed the dynamics of the karate club he had been observing. The karate club experienced a significant event during Zachary’s study: a conflict between the instructor (Mr. Hi) and the club president (John A.). This conflict ultimately led to the club splitting into two separate factions, with members aligning themselves either with the instructor or the president.</p><p>Zachary’s dataset captures the social interactions between club members before and after the split.</p><p>As seen in the illustration of the graph above, while it is easy to visualize the graph with connected nodes bringing it to low dimensional space is a complex task given the sparse nature of the graph. Thus how do we capture this information on node connectivity in the graph given the sparse nature of the nodes? This is where DeepWalk comes in!</p><h4>What is DeepWalk?</h4><p>DeepWalk is a graph representation algorithm embedding algorithm that captures nodes’ connectivity into a lower dimensional space for downstream machine learning tasks (classification) using <strong>Word2Vec</strong> and <strong>Random Walks</strong>.</p><p>DeepWalk was published by Perozzi et al.( 2014) using some inspiration from the advances in NLP, notably <strong>Word2Vec</strong> to perform graph modeling. Thus, the main idea of DeepWalk is to use similar techniques used in language modeling to model graphs.</p><h4>Word2Vec for Language Modelling</h4><p>I first came across Word2Vec during my Master’s dissertation when I was trying different embedding methods for sentiment analysis on the Beauty Product Review Dataset and surprisingly a friend of mine was working on a Large Language problem too.</p><p>Word2Vec is a language modeling technique proposed by Tomas et al (2013) used to translate words into vectors known as embeddings from large text datasets. The text tokens are represented by one-hot encoded vectors.</p><p>The paper proposed two methods of sampling which are CBOW(Continuous Bag of Words) and the Skip-Gram model.</p><ul><li><strong>Continuous bag-of-words model</strong>: predicts the middle word based on surrounding context words. The context consists of a few words before and after the current (middle) word. This architecture is called a bag-of-words model as the order of words in the context is not important.</li><li><strong>Continuous skip-gram model</strong>: predicts words within a certain range before and after the current word in the same sentence. A worked example of this is given below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3zAVWm40Ddc_5R-LSFxZw.png" /><figcaption>Figure 3 — CBoW and Skip-Gram Architectures</figcaption></figure><p>Our focus would be on the Skip-gram model because this is what is used in the Deep Walk model.</p><h4>How skip-gram model works</h4><p>Skip-gram is used to produce high-quality word embeddings, by training a task to predict the correct context words given a target word. Thus the training objective of the model is to maximize the probability of predicting context words given a target word. In a case where we have a sequence of words<em> w1, w2,…, wT, </em>the objective can be written as the average log probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*dVs16PMV02yZc6GV.png" /></figure><p>Where C is the size of the training context. The softmax function is used in the basic skip-gram model used the softmax function for the calculate the probability of context word embedding given a target word embedding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*_GEvRrVB3CZuHDE3.png" /></figure><p>where v and v ’ are the target and context vector representations of words and W is the vocabulary size.</p><p>Here’s how the Skip-Gram model works:</p><ul><li>Define a window size (e.g., 2) to specify the number of context words to consider.</li><li>For each target word in the training corpus, select a window of context words.</li><li>Feed the target word as input to the Skip-Gram model, which consists of an input layer, a hidden layer, and an output layer.</li><li>The input layer represents the target word as a one-hot vector.</li><li>The hidden layer learns to represent the target word as a dense vector.</li><li>The output layer predicts the context words based on the target word.</li><li>The model is trained to minimize the difference between the predicted context words and the actual context words, using back-propagation and stochastic gradient descent.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*TAkiYbQOjlDk2KxX.jpg" /><figcaption>Figure 4— Word2Vec Architecture</figcaption></figure><p>For a practical illustration of how Word2Vec works, we can use the gensim library which is also used in the official implementation of DeepWalk, though you can also find implementations in tensorflow with keras or Pytorch. I am a big fan of Josh Stammer from StatQuest and I hope to make this short implementation fun like his Youtube videos which is to keep it simple and short.</p><pre># Step 1: Install gensim and import Word2Vec class<br>!pip install -qU gensim<br>from gensim.models.word2vec import Word2Vec<br><br># initialize text<br>text = &quot;&quot;&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu sem scelerisque, dictum eros aliquam, accumsan quam. Pellentesque tempus, lorem ut semper fermentum, ante turpis accumsan ex, sit amet ultricies tortor erat quis nulla. Nunc consectetur ligula sit amet purus porttitor, vel tempus tortor scelerisque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Quisque suscipit ligula nec faucibus accumsan. Duis vulputate massa sit amet viverra hendrerit. Integer maximus quis sapien id convallis. Donec elementum placerat ex laoreet gravida. Praesent quis enim facilisis, bibendum est nec, pharetra ex. Etiam pharetra congue justo, eget imperdiet diam varius non. Mauris dolor lectus, interdum in laoreet quis, faucibus vitae velit. Donec lacinia dui eget maximus cursus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus tincidunt velit eget nisi ornare convallis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec tristique ultrices tortor at accumsan.<br>&quot;&quot;&quot;.split()<br><br># Step 2: Initialize a skip-gram Word2Vec model<br>model = Word2Vec([text],<br>                 sg=1,             # Skip-gram<br>                 vector_size=10,<br>                 min_count=0,<br>                 window=2,<br>                 workers=2,<br>                 seed=0)<br><br># Step 3: Check the shape of the weight matrix<br>print(f&#39;Shape of W_embed: {model.wv.vectors.shape}&#39;)<br><br># Step 4: Train the model for 10 epochs<br>model.train([text], total_examples=model.corpus_count, epochs=10)<br><br># Step 5: Print a word embedding to see the result<br>print(&#39;Word embedding =&#39;)<br>print(model.wv[0])<br><br># Step 6: Activate H-Softmax in gensim<br>model_hs = Word2Vec([text],<br>                    sg=1,           # Skip-gram<br>                    hs=1,           # H-Softmax<br>                    vector_size=10,<br>                    min_count=0,<br>                    window=2,<br>                    workers=2,<br>                    seed=0)</pre><p>output:</p><pre>Word embedding =<br>[ 0.07156403  0.03257632  0.00209916 -0.04374931 -0.03398107 -0.08656936<br> -0.09047253 -0.0955243  -0.06482638  0.0660186 ]</pre><p>This implementation covers the basic steps of initializing, training, and configuring the Word2Vec model for DeepWalk using Gensim, but it is worth noting that softmax can be costly to train on larger vocabulary size like hundreds of words and that is why H-softmax was proposed. Step 6 shows us how to activate H-Softmax by setting hs=1 in the Word2Vec initialization, which enables the use of hierarchical softmax for word prediction.</p><h4>DeepWalk</h4><p>As noted earlier this was proposed by folks from Google in 2014, and ever since has become very popular. Though a lot of advances have been made since then, it remains a relatively easy and reliable baseline for its ease of implementation. With inspiration from NLP, in which language models, words are represented as sparse vectors, with mostly zeros and a one for the word being represented. Similarly, in graphs, vertices and their connections are encoded, where connected vertices have ones and non-connected ones have zeros. However, because graphs do not have a sequential pattern like sentences and hence transforming sparse graph representations into dense feature spaces is done using DeepWalk</p><p>The core idea of DeepWalk is to take context windows of vertices in the graph, akin to context pairs in sentences. By traversing the graph via random walks, sequences similar to sentences are constructed, capturing the graph’s structure and relationship between vertices based on the concept of <em>network homophily hypothesis( Nodes close to each other are similar)</em>.</p><p>The algorithm slides a context window over the graph and uses a Skip Gram model from Word2Vec illustrated previously to encode vertices into a low-dimensional space. This transformation aims to preserve the shortest path distance between nodes and their labels, typically representing community memberships. Thus in the case of graphs, rather than words we have nodes as our data, and this is the reason why we use random walks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*86gWUnkVsK5umO8K.jpg" /><figcaption>Figure 5 — Sentences represented as graphs, image source Maxime (2023)</figcaption></figure><h4><strong>Step-by-step Implementation of Random Walk</strong></h4><ol><li>Graph Generation: A random graph with 10 nodes is generated using the Erdos-Renyi model, which creates edges between nodes with a probability of 0.3. This graph is visualized using matplotlib, providing a visual representation of the randomly generated structure.</li><li>Random Walk Implementation: A function named random_walk is defined, which simulates a random walk on the graph. It takes two parameters: the starting node (start) and the length of the walk (length). At each step, the function randomly selects a neighboring node from the current node&#39;s neighbors using np.random.choice and appends it to the walk. This process continues until the specified length of the walk is reached.</li><li>Execution of Random Walk: The random_walk function is called with a starting node of 0 and a walk length of 10. The resulting walk sequence is printed, showing the nodes visited during the random walk.</li><li>Analysis: The resulting list from the random walk reveals the sequence of nodes visited, indicating how certain nodes are often found together. This observation, such as nodes 0 and 9 appearing together, suggests similarities between these nodes in the graph’s structure. This homophilic relationship between nodes is what DeepWalk aims to capture, making it suitable for graph-based representation learning tasks.</li></ol><p>Below is the code implementation of the</p><pre># Import required libraries<br>import networkx as nx<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import random<br><br># Initialize random number generator for reproducibility<br>random.seed(0)<br><br># Generate a random graph with 10 nodes and probability of edge creation as 0.3<br>G = nx.erdos_renyi_graph(10, 0.3, seed=1, directed=False)<br><br># Plot the random graph<br>plt.figure(dpi=300)<br>plt.axis(&#39;off&#39;)<br>nx.draw_networkx(G,<br>                 pos=nx.spring_layout(G, seed=0),<br>                 node_size=600,<br>                 cmap=&#39;coolwarm&#39;,<br>                 font_size=14,<br>                 font_color=&#39;white&#39;<br>                 )<br>plt.show()<br><br># Function to implement random walks on the graph<br>def random_walk(start, length):<br>    # Initialize the walk with the starting node<br>    walk = [str(start)]<br>    <br>    # Perform random walk for specified length<br>    for i in range(length):<br>        # Get neighbors of the current node<br>        neighbors = [node for node in G.neighbors(start)]<br>        <br>        # Randomly select the next node from neighbors<br>        next_node = np.random.choice(neighbors, 1)[0]<br>        <br>        # Append the next node to the walk<br>        walk.append(str(next_node))<br>        <br>        # Update the current node for the next step<br>        start = next_node<br>    <br>    return walk<br><br># Execute random walk with starting node 0 and length 10<br>print(random_walk(0, 10))</pre><p>Output:</p><pre>[&#39;0&#39;, &#39;1&#39;, &#39;0&#39;, &#39;9&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;3&#39;, &#39;6&#39;, &#39;7&#39;, &#39;3&#39;]</pre><p>As we can observe nodes 0 and 3 are frequently found next to each other, and according to the <em>homophily hypothesis </em>means that they are similar<em>.</em></p><h4><strong>Implementation of DeepWalk</strong></h4><p>We now have all the building blocks to implement DeepWalk, and to proceed to solve the problem illustrated earlier with the Zachary Karate Club. Thus, using Random walk and Word2Vec with Skip-gram, we would create node embeddings of the karate Club and subsequently use an ML algorithm for a classification task.</p><p>We would proceed to explore Zachary’s Karate Club, a realm of connections and affiliations studied by the intrepid Wayne W. Zachary in the 1970s. This club, studied by Wayne W. Zachary in the 1970s, offers insights into how people interact and form groups.</p><p><strong>I. Getting Started with Random Walk:</strong></p><pre>G = nx.karate_club_graph()</pre><pre>labels = []<br>for node in G.nodes:<br>    label = G.nodes[node][&#39;club&#39;]<br>    labels.append(1 if label == &#39;Officer&#39; else 0)</pre><p>Let’s proceed to visualize the network:</p><pre>plt.figure(figsize=(12,12), dpi=300)<br>plt.axis(&#39;off&#39;)<br>nx.draw_networkx(G,<br>                 pos=nx.spring_layout(G, seed=0),<br>                 node_color=labels,<br>                 node_size=800,<br>                 cmap=&#39;coolwarm&#39;,<br>                 font_size=14,<br>                 font_color=&#39;white&#39;<br>                 )<br>plt.show()</pre><p>Exploring Connections: Now, let’s explore how members interact within the club. We take walks through the network, randomly moving from one member to another:</p><pre>walks = []<br>for node in G.nodes:<br>    for _ in range(80):<br>        walks.append(random_walk(node, 10))</pre><p>We can peek into one of these walks:</p><pre>print(walks[0])</pre><p>This walk shows the path taken by a member through the club.</p><p><strong>II. Modeling the Network with Word2Vec</strong></p><p>To understand the relationships better, we use Word2Vec. It helps us find patterns in the walks we took:</p><pre>model = Word2Vec(walks,<br>                 hs=1,   # Hierarchical softmax<br>                 sg=1,   # Skip-gram<br>                 vector_size=100,<br>                 window=10,<br>                 workers=2,<br>                 seed=0)</pre><p>We train our model to learn from the walks:</p><pre>model.train(walks, total_examples=model.corpus_count, epochs=30, report_delay=1)</pre><p>Finally, let’s see what our model tells us. We can find which members are most similar to a chosen one:</p><pre>print(&#39;Nodes that are the most similar to node 0:&#39;)<br>for similarity in model.wv.most_similar(positive=[&#39;0&#39;]):<br>    print(f&#39;   {similarity}&#39;)</pre><p>Output: Below we have the output of nodes that are most similar to node 0.</p><pre>Nodes that are the most similar to node 0:<br>   (&#39;17&#39;, 0.6424034237861633)<br>   (&#39;4&#39;, 0.5844610929489136)<br>   (&#39;10&#39;, 0.5792854428291321)<br>   (&#39;3&#39;, 0.5659441351890564)<br>   (&#39;11&#39;, 0.5636734366416931)<br>   (&#39;5&#39;, 0.5312074422836304)<br>   (&#39;6&#39;, 0.5308884978294373)<br>   (&#39;7&#39;, 0.5130414962768555)<br>   (&#39;1&#39;, 0.5081695318222046)<br>   (&#39;16&#39;, 0.5029702186584473)</pre><p>Now, let’s take our exploration further by visualizing node classes and using machine learning to classify them. To begin, let’s visualize the high-dimensional embeddings of our nodes in 2D using t-SNE. This technique helps us see how nodes are grouped based on their similarities.</p><p><strong>III. Visualizing Node Classes with t-SNE</strong></p><pre>from sklearn.manifold import TSNE<br><br># Create arrays for embeddings and labels<br>nodes_wv = np.array([model.wv.get_vector(str(i)) for i in range(len(model.wv))])<br>labels = np.array(labels)<br><br># Train t-SNE model<br>tsne = TSNE(n_components=2,<br>            learning_rate=&#39;auto&#39;,<br>            init=&#39;pca&#39;,<br>            random_state=0).fit_transform(nodes_wv)<br><br># Plot the 2D vectors with labels<br>plt.figure(figsize=(6, 6), dpi=300)<br>plt.scatter(tsne[:, 0], tsne[:, 1], s=100, c=labels, cmap=&quot;coolwarm&quot;)<br>plt.show()</pre><p>We can observe from the plot that they’re are two classes with a line separating both, giving us valuable insights into the structure of our network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*VjBwz-JPEuRy7GTaAsRyDQ.png" /><figcaption>Figure 6 — t-SNE plot of Nodes in Zarachy’s Karate Club</figcaption></figure><p>Given that we already have a representation on the network in a lower dimensional representation we can proceed to use ML algorithms for downstream tasks such as a classification task. This brings us to our original problem at the beginning of this article with the Karate Club which motivated you to want to learn more about DeepWalk.</p><p><strong>IV. Classifying Node Classes with Random Forest</strong></p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score<br><br># Define train and test data masks<br>train_mask = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]<br>test_mask = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 30, 31, 32, 33]<br><br># Train Random Forest classifier<br>clf = RandomForestClassifier(random_state=0)<br>clf.fit(nodes_wv[train_mask], labels[train_mask])<br><br># Evaluate classifier<br>y_pred = clf.predict(nodes_wv[test_mask])<br>accuracy = accuracy_score(y_pred, labels[test_mask])<br><br>print(f&quot;Accuracy Score: {accuracy}&quot;)</pre><p>Our classifier achieves an impressive accuracy score of 94.73%, showcasing the effectiveness of DeepWalk in classifying nodes based on their embeddings. This demonstrates the power of DeepWalk in both unsupervised learning, by discovering similarities between nodes, and supervised learning, by using embeddings for classification tasks.</p><p>In the previous article, we developed our foundational knowledge of some of the concepts of GNN, and in this article, we dove into the architecture of DeepWalk a foundational graph representation algorithm. In the next article, we’ll proceed to leverage our understanding of DeepWalk to discover interesting ways to improve the quality of our embeddings with biased random walks leading to Node2Vec. I guess you are as excited as myself but it’s worth going for a walk now and later jump to Youtube to watch a video about Node2Vec as you patiently wait for the next episode of our journey into GNN. 🚀</p><p>Previous article:<em> </em><a href="https://medium.com/@amaboh/exploring-graph-properties-and-their-role-in-graph-neural-networks-33ca04c6cebd"><em>Exploring Graph Properties and Their Role in Graph Neural Networks</em></a></p><h4>References:</h4><ol><li>Grover, A., &amp; Leskovec, J. (2016). Node2vec: Scalable Feature Learning for Networks. In <em>Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining</em> (KDD ’16) (pp. 855–864). ACM.</li></ol><p>2. LeCun et al. (1998) <a href="https://paperswithcode.com/paper/gradient-based-learning-applied-to-document">Gradient-based learning applied to document recognition</a>, source: <a href="https://ieeexplore.ieee.org/document/726791">https://ieeexplore.ieee.org/document/726791</a></p><p>3. Maxime L. (2023) Hands-on Graph Neural Networks Using Python, Chapter 3: Creating Node Representation with DeepWalk,</p><p>3. TensorFlow: Word2Vec source, <a href="https://www.tensorflow.org/text/tutorials/word2vec">https://www.tensorflow.org/text/tutorials/word2vec</a></p><p>4. Perozzi, B., Al-Rfou, R., &amp; Skiena, S. (2014). DeepWalk: Online learning of social representations. In <em>Proceedings of the 20th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining</em> (KDD ’14) (pp. 701–710). ACM.</p><p>5. William L. (2020), Graph Representation Learning; Source: <a href="https://www.cs.mcgill.ca/~wlh/grl_book/files/GRL_Book.pdf">https://www.cs.mcgill.ca/~wlh/grl_book/files/GRL_Book.pdf</a></p><p>6. Zachary’s Karate club, Wikepedia, source: <a href="https://en.wikipedia.org/wiki/Zachary%27s_karate_club">https://en.wikipedia.org/wiki/Zachary%27s_karate_club</a></p><p>7. Implementing word2vec in Pytorch, Mushai W. (2021) source: <a href="https://muhark.github.io/python/ml/nlp/2021/10/21/word2vec-from-scratch.html">https://muhark.github.io/python/ml/nlp/2021/10/21/word2vec-from-scratch.html</a></p><h4>Code:</h4><p>Google collab: <a href="https://colab.research.google.com/drive/1T47tz2PreecUNktRAk-TAwmeFGbDSrEy?usp=sharing">https://colab.research.google.com/drive/1T47tz2PreecUNktRAk-TAwmeFGbDSrEy?usp=sharing</a></p><h4>Abbreviations:</h4><p>MNIST: Modified National Instute of Standards and Technology</p><p>NLP: Natural Language Processing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7acdfcf61b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Graph Properties and Their Role in Graph Neural Networks]]></title>
            <link>https://medium.com/@amaboh/exploring-graph-properties-and-their-role-in-graph-neural-networks-33ca04c6cebd?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ca04c6cebd</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gnn]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 10:38:33 GMT</pubDate>
            <atom:updated>2024-03-17T10:38:33.584Z</atom:updated>
            <content:encoded><![CDATA[<p>This article builds upon the previous article which introduces <a href="https://medium.com/@amaboh/simplifying-graph-learning-gnns-understanding-the-basics-and-their-applications-ae152eed57a3">Graph Machine Learning and foundations of GNNs</a>. From our previous article, we recall that a graph enables us to visualize complex data structures between entities so we can understand the relationships between these entities. The main topics we will cover in this article are graph properties, graph concepts, and graph algorithms. So after reading this article, you be able to understand what are the different components of graphs, the different types of graphs, and foundational knowledge of how graph algorithms work.</p><h4><strong>What are the properties of a Graph?</strong></h4><p>A graph is composed of a set of objects known as <strong>vertices</strong> or <strong>nodes</strong>, and connected via <strong>edges</strong> which serve as links or relations. Graphs are commonly represented using the following notation</p><h4><strong>G = (V, E)</strong></h4><p><strong>G</strong> is the Graph, <strong>V</strong> represents the set of vertices, and <strong>E</strong> is a set of edges. The nodes in a graph represent any objects and the edges are relationships between the nodes. Thus on the map of a country, the cities would be nodes and roads would be edges, for a social network people would represent nodes and their friendship status would be edges. Relationships between nodes define the flow of information from one node to another and to understand the connectivity of nodes via edges, this brings us to the concept of directed and undirected graphs.</p><p><strong>Directed and Undirected Graphs</strong></p><p>The <strong>directed graph</strong> also known as a digraph is when an edge connects one node to the other with a particular orientation where information flows from the source node to the destination node. This can be thought of as one-way streets in a city from High Street Center A to High Street Center B. Thus you can only travel from A to B in a car but not from B to A. This is similar to how information flows in a directed graph, in which there is a particular flow orientation of flow of information.</p><figure><img alt="Directed and undirected graphs" src="https://cdn-images-1.medium.com/max/1000/0*BYzeqFXlnhGQRkme.jpg" /><figcaption>Fig. 1 Directed and Undirected graphs, Image credit simple snippet</figcaption></figure><p>Where as in an <strong>undirected graph</strong> the edge connects both edges with no particular direction, thus information flows in either direction and as result theres no order in which nodes are visited. In this case a two-way streets can be thought of as an undirected graph, in which cars can go in direction and this reflects the flow of information in undirected graphs.</p><p><strong>Weighted Graphs</strong></p><p>This property of the graph is fundamental in defining the strength of a relationship between nodes and thus is used to associate a cost to an edge between nodes. This can be used to represent factors such as distance between nodes, cost, relationship strength, or cost. In our previous illustration of a road network above this can be used to represent distance between cities. This is commonly associated with binary graphs in which there is an existence or nonexistence of relationships between nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*WzqQ7Vc36j7htbB9.jpg" /><figcaption>Figure 1.2 Un-weighted and Weighted graph, Image credit Simple snippet</figcaption></figure><p><strong>Connected Graphs</strong></p><p>A connected graph is formally defined as G if an only if for every pair of vertices U and V in G, there exists an edge from U to V. On the contrary a graph is disconnected if there is two vertices are not connected in the graph. This concept is fundamental in graph theory as it relates to a graph’s structure and function.</p><h4>Types of graphs</h4><ol><li><strong><em>Tree</em></strong>: A tree is a connected, undirected graph with no cycles. This means that there is only one path between any two nodes. An example of a tree is a family tree, where each person is connected to their ancestors and descendants, but there are no loops or cycles.</li><li><strong><em>Rooted Tree:</em></strong> A rooted tree is a tree with a designated root node, where all other nodes are connected to it by a unique path. An example of a rooted tree is a company’s organizational chart, where the CEO is the root node, and all other employees are connected to the CEO through a unique chain of command.</li><li><strong><em>Directed Acyclic Graph (DAG)</em></strong>: A DAG is a directed graph with no cycles. This means that the edges can only be traversed in one direction, and there are no loops or cycles. An example of a DAG is a task dependency graph in project management, where each task depends on the completion of other tasks, but there are no circular dependencies.</li><li><strong><em>Bipartite Graph</em></strong>: A bipartite graph is a graph where the vertices can be divided into two disjoint sets, such that all edges connect vertices in different sets. An example of a bipartite graph is a job placement graph, where one set of vertices represents job seekers, and the other set represents job openings, and edges represent job applications.</li><li><strong><em>Complete Graph: </em></strong>A complete graph is a graph where every pair of vertices is connected by an edge. An example of a complete graph is a social network where everyone is friends with everyone else, and all possible connections are present. Another example is a fully connected computer network, where every device is connected to every other device.</li></ol><figure><img alt="Illustration of common types of graphs" src="https://cdn-images-1.medium.com/max/1000/0*1ZYSrnmm-qln3hW4.jpg" /><figcaption>Figure 2.1 Common type of graphs, Image credit Maxime L. (2023)</figcaption></figure><h4>Fundamental Graph Concepts</h4><p><strong>Degree of a node (Node degree): </strong>This is the simplest node-level statistic to examine which represents the number of edges incident to a node <strong><em>V</em></strong>, and is usually denoted as <strong><em>deg(V). </em></strong>The concept of Node Degree differs between directed and undirected graphs.</p><ul><li>For undirected graphs, the number of edges that are connected to a node represents the degree of the vertex denoted <strong><em>deg(V), </em></strong>and if the node is connected to itself also known as a self-loop this adds two degrees<strong><em>.</em></strong></li><li>A <strong>directed graph </strong>is composed of <strong><em>indegree</em></strong> and <strong><em>outdegree. </em></strong>The indegree of a node is the number of edges that point towards it, while the outdegree is the number of edges that start from it. In this case, a self-loop adds one to both the indegree and outdegree. The concept of indegree and out-degree is important in analyzing the flow of information within a directed graph.</li></ul><p><strong>Node neighbors</strong>: The neighbor of a node is closely related to node degree, as it measures how many neighbors a node has. Though these measures provide us with relative information about the importance of a node in a network, it is thus not sufficient to determine the importance of a node in a network. When two nodes share at least one common neighbor this is referred to as <strong><em>adjacent, </em></strong>which can be combined with neighbors to determine a <strong>path </strong>between nodes or to identify clusters in a network.</p><p>We use degrees and paths to calculate a measure known as <strong><em>centrality</em></strong> which in simple terms is the importance of a node in a network.</p><h4>Graph measures</h4><p>As observed above centrality is an important measure that informs us of the importance of a node in a network and is useful in identifying key nodes, and how their connectivity influences the flow of information in a network. Let’s examine the different measures of centrality.</p><ul><li><strong><em>Degree centrality </em></strong>is defined as the degree of the node, thus a high degree of centrality indicates that a node has more connections to other nodes in the graph and as a result yields more influences in a graph.</li><li><em>Closeness Centrality </em>is a measure of the proximity of a node to all other nodes in the graph. Thus this translates to the average length of the shortest path between the target node and all other nodes in the graph. This can be thought of as the node in the network which can reach all other nodes in the network faster. For example, if you live in London and use the Tube, you can think of the station that can reach all other stations quicker as the closeness centrality.</li><li><strong><em>Betweenness centrality</em></strong> is a count of the number of times a node lies on the shortest path between pairs of nodes in a graph. Thus in an arts brokerage network of buyers and sellers, the auction house connects more buyers and sellers with the shortest sale period can be thought of as the bridge between different parts of the graph.</li></ul><h3>Graph representations</h3><h4><strong>Adjacency Matrix</strong></h4><p>The adjacency matrix is a common way to represent edges in a graph, using a square matrix where each square represents a row and column a node in the graph. The cell intersection of row i and column j denoted (i, j) indicates if there exists an edge between node i and node j represented by 1, and 0 if there’s no edge. In an unweighted graph, the value of the cell is represented as either 1 (if there exists an edge) or 0 (if there is no edge), while in a weighted graph, the value in the cell can be represented by the weight or cost of the edge between nodes.</p><p>An adjacency matrix is a common way to represent a graph in computer science and mathematics. It is a square matrix where each row and column corresponds to a node in the graph, and the value in the cell at the intersection of row i and column j indicates whether there is an edge between node i and node j.</p><p>In an unweighted graph, the value in the cell is typically either 1 (if there is an edge) or 0 (if there is no edge). In a weighted graph, the value in the cell can represent the weight or cost of the edge between the nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*bdgxkmtt4j8vgu0n.png" /><figcaption>Figure 2.2 Adjacency Matrix, Undirected and Directed, Image credit Source.com</figcaption></figure><p><strong>Advantages of using an adjacency matrix representation</strong>:</p><p>1. Easy to implement: An adjacency matrix can be easily implemented using a two-dimensional array or a list of lists.<br>2. Constant time edge queries: Once the matrix is constructed, checking whether there is an edge between two nodes can be done in constant time by simply looking up the corresponding cell in the matrix.<br>3. Easy to represent weighted graphs: The weight or cost of an edge can be easily represented by storing its value in the corresponding cell of the matrix.</p><p>Disadvantages of using an adjacency matrix representation:</p><p>1. Space complexity: For a graph with n nodes, an adjacency matrix requires O(n²) space, which can be prohibitive for large graphs.<br>2. Inefficient for sparse graphs: An adjacency matrix can be inefficient for representing sparse graphs, where the number of edges is much smaller than the number of possible edges. In such cases, most of the cells in the matrix will be empty, leading to wasted space.<br>3. Slow for adding or removing vertices: Adding or removing a vertex from the graph requires adding or removing a row and column from the matrix, which can be a slow operation for large matrices.</p><p>The adjacency matrix representation is a good choice for small to medium-sized graphs where constant time edge queries and easy weight representation are important.</p><h4>Edge list</h4><p>An edge list is another way to represent a graph, where a list of pairs of nodes represents an edge between the two nodes.</p><p>In an unweighted graph, each pair simply contains the two nodes that are connected by the edge. In a weighted graph, each pair can also include the weight or cost of the edge.</p><p>Advantages of using an edge list representation:</p><p>1. Space efficiency: For sparse graphs, an edge list can be a more space-efficient representation than an adjacency matrix, as it only stores information about the edges that exist in the graph.<br>2. Easy to add or remove edges: Adding or removing an edge from the graph can be done simply by adding or removing a pair from the list.<br>3. Easy to represent weighted graphs: The weight or cost of an edge can be easily represented by storing its value along with the pair of nodes.</p><p>Disadvantages of using an edge list representation:</p><p>1. Slow edge queries: Checking whether there is an edge between two nodes requires searching through the entire list, which can be slow for large graphs.<br>2. Difficult to represent certain types of graphs: An edge list is not well-suited for representing certain types of graphs, such as directed graphs with self-loops or multigraphs with multiple edges between the same pair of nodes.<br>3. Less intuitive: An edge list may be less intuitive to work with than an adjacency matrix, as it does not provide a visual representation of the graph.</p><p>An edge list can be a good choice for sparse graphs where space efficiency and ease of adding or removing edges are important.</p><h4>Adjacency List</h4><p>An adjacency list is a common way to represent a graph with a collection of lists or arrays using a dictionary, where each list corresponds to a node in the graph as a key and contains the nodes that are adjacent to it as the values in a list.</p><p>In an unweighted graph, each list simply contains the nodes that are connected to the corresponding node. In a weighted graph, each list can also include the weight or cost of the edge between the nodes.</p><p>Advantages of using an adjacency list representation:</p><p>1. Space efficiency: For sparse graphs, an adjacency list can be a more space-efficient representation than an adjacency matrix, as it only stores information about the edges that exist in the graph.<br>2. Fast edge queries: Checking whether there is an edge between two nodes can be done quickly by simply checking whether one node is in the other node’s list.<br>3. Easy to add or remove edges: Adding or removing an edge from the graph can be done simply by adding or removing a node from the appropriate list.</p><p>Disadvantages of using an adjacency list representation:</p><p>1. Difficult to represent weighted graphs: While an adjacency list can represent a weighted graph by including the weight or cost of the edge along with the node in the list, this can make the representation more complex and less intuitive to work with.<br>2. Difficult to represent certain types of graphs: An adjacency list is not well-suited for representing certain types of graphs, such as directed graphs with self-loops or multigraphs with multiple edges between the same pair of nodes.<br>3. Less intuitive: An adjacency list may be less intuitive to work with than an adjacency matrix, as it does not provide a visual representation of the graph.</p><p>Overall, the choice of graph representation depends on the specific needs of the application. An adjacency list can be a good choice for sparse graphs where fast edge queries and ease of adding or removing edges are important. However, for dense graphs or graphs where ease of representation is important, other representations such as an adjacency matrix or edge list may be more appropriate.</p><h4>Graph Algorithms</h4><p>Let’s proceed to explore two fundamental graph traversal algorithms critical in GNNs because they provide a way to traverse and explore the graph structure, which is crucial for many GNN algorithms and would enable us to develop effective and efficient GNN architectures.</p><h4>Breadth-first Search</h4><p>BFS provides an efficient way to explore graph structure in a way that the algorithm starts at a root node and ensures that all nodes at a particular level or distance are visited before moving on to nodes at a greater distance. This is important for GNN algorithms that rely on aggregating information from neighboring nodes in a graph, as it ensures that information is propagated evenly across the graph.</p><p>The BFS uses a Queue data structure and works by keeping track of visited nodes in a queue of visited nodes by marking them as visited. The algorithm then dequeues the next node in the queue and explores all its neighbors, adding them to the queue if they haven’t been visited yet.</p><p>In the context of a mail delivery agent distributing mail in a 3-floor apartment building with 4 apartments on each floor, BFS can be used to find the shortest path from the building entrance to each apartment. The algorithm starts at the entrance and explores all the apartments on the ground floor before moving on to the next floor, using a queue to keep track of the next set of apartments to visit. By exploring the building level by level, BFS ensures that the delivery agent takes the shortest possible route to deliver mail to every apartment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62V5DIgvBH4z45P7l8cUQA.png" /><figcaption>Fig 1.2 Breadth-first Search (BFS) and Depth-first Search (DFS). Image credit Geeks for Geeks</figcaption></figure><p>BFS is important in finding the shortest path between two nodes in an unweighted graph and verifying if a graph is connected. Applications of BFS can be found in web crawlers, social network analysis, and finding the shortest path in a network.</p><p>The time complexity of the Breadth-First Search (BFS) algorithm is O(|V| + |E|), where |V| is the number of vertices (or nodes) in the graph and |E| is the number of edges.</p><p>This is because, in BFS, each vertex and edge are visited exactly once. During the traversal, each vertex is enqueued and dequeued once, which takes O(|V|) time. Additionally, for each edge, we check if the adjacent vertex has been visited before or not, which takes O(|E|) time. Since we are doing a constant amount of work for each vertex and edge, the total time complexity of BFS is O(|V| + |E|).</p><h4>Depth-first Search</h4><p>Depth-first Search (DFS) is a graph traversal algorithm that explores the graph by going as deep as possible along each branch before backtracking. The algorithm starts at a root node and explores each edge to reach a new node, then recursively applies the same process to the new node until it reaches a dead end, at which point it backtracks to explore the next edge.</p><p>Here’s a step-by-step breakdown of the DFS algorithm:</p><p>1. Choose a starting node (root node) and mark it as visited.<br>2. Explore one of its unvisited adjacent nodes, mark it as visited, and push it onto a stack.<br>3. Repeat step 2 until we reach a node that has no unvisited adjacent nodes.<br>4. If the stack is not empty, pop the top node from the stack and repeat step 2 for that node.<br>5. If the stack is empty, the algorithm terminates.</p><p>DFS can be implemented using either recursion or a stack data structure. The recursive implementation involves making a recursive call for each unvisited adjacent node, while the iterative implementation uses a stack to keep track of the nodes to be explored.</p><p>DFS is useful for a variety of graph-related problems, such as finding connected components, detecting cycles, and topological sorting. It has a time complexity of O(|V| + |E|), where |V| is the number of vertices and |E| is the number of edges in the graph. This is because each vertex and edge is visited exactly once during the traversal.</p><h4><strong>Hands-on implementation in Python for BFS and DFS</strong></h4><p><strong>Requirements; </strong>Python &gt; 3.8, NetworkX</p><p>Install NetworkX library</p><pre>pip install networkx</pre><p>Instantiate a Graph</p><pre># Using NetworkX to create a graph<br>graph = nx.Graph()<br>graph.add_edges_from([(0, 1), (0, 2), (1, 2), (1, 3), (2, 4)])  # Sample graph edges<br><br>print(&quot;Breadth-First Search:&quot;)<br>bfs(graph, 0)<br><br>print(&quot;\nDepth-First Search:&quot;)<br>dfs(graph, 0)</pre><h4><strong>BFS implementation and step-by-step explanation</strong></h4><ol><li><strong>Initialization:</strong> Sets up the visited set and the queue.</li><li><strong>Iteration:</strong> While the queue has nodes:</li></ol><ul><li>Remove the first node from the queue.</li><li>Process the node (in this case, print it).</li><li>Add unvisited neighbors to the queue and mark them as visited.</li></ul><pre>def bfs(graph, start_node):<br>  &quot;&quot;&quot;<br>  Performs Breadth-First Search on a NetworkX graph.<br><br>  Args:<br>    graph: The NetworkX graph to search.<br>    start_node: The starting node for the search.<br><br>  Returns:<br>    An ordered list of nodes visited in BFS order.<br>  &quot;&quot;&quot;  <br>  visited = set()<br>  queue = []<br>  visited.add(start_node)<br>  queue.append(start_node)<br><br>  while queue:<br>    current_node = queue.pop(0)<br>    print(current_node, end=&quot; &quot;)<br><br>    for neighbor in graph.neighbors(current_node):<br>      if neighbor not in visited:<br>        visited.add(neighbor)<br>        queue.append(neighbor)</pre><h4><strong>DFS implementation and step by step explanation</strong></h4><ol><li>Initialization Sets up the visited set and the stack.</li><li>Iteration: While the stack has nodes:</li></ol><ul><li>Remove the last node from the stack.</li><li>Process the node (print it in this case).</li><li>Add unvisited neighbors to the stack and mark them as visited</li></ul><pre>def dfs(graph, start_node):<br>  &quot;&quot;&quot;<br>  Performs Depth-First Search on a NetworkX graph.<br><br>  Args:<br>    graph: The NetworkX graph to search.<br>    start_node: The starting node for the search.<br><br>  Returns:<br>    An ordered list of nodes visited in DFS order.<br>  &quot;&quot;&quot;  <br>  visited = set()<br>  stack = []<br>  visited.add(start_node)<br>  stack.append(start_node)<br><br>  while stack:<br>    current_node = stack.pop()<br>    print(current_node, end=&quot; &quot;)<br><br>    for neighbor in graph.neighbors(current_node):<br>      if neighbor not in visited:<br>        visited.add(neighbor)<br>        stack.append(neighbor)</pre><p>OK guys that’s all for now see you in the next episode where we go through a pioneer ML algorithm on Graphs, called DeepWalk. I can’t help but think that Micheal Jackson’s Moonwalk also inspired ML enthusiasts at the time.</p><h4><strong>References:</strong></h4><ol><li>Maxime L. (2023) Hands-on Graph Neural Networks Using Python, Chapter 2: Graph Theory for Neural Neural Networks,</li><li>Geek for Geeks (2021), Breath for search and depth for Search, <a href="https://www.geeksforgeeks.org/difference-between-bfs-and-dfs/">https://www.geeksforgeeks.org/difference-between-bfs-and-dfs/</a></li><li>Simple Snippets (2021), WHat is a graph Data Structure, <a href="https://simplesnippets.tech/what-is-a-graph-data-structure-important-graph-terms-properties/">https://simplesnippets.tech/what-is-a-graph-data-structure-important-graph-terms-properties/</a></li><li>Study (2023), Representation of graphs, <a href="https://study.com/academy/lesson/adjacency-representations-of-graphs-in-discrete-math.html">https://study.com/academy/lesson/adjacency-representations-of-graphs-in-discrete-math.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ca04c6cebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Graph Learning (GNNs): Understanding the Basics and Their Applications.]]></title>
            <link>https://medium.com/@amaboh/simplifying-graph-learning-gnns-understanding-the-basics-and-their-applications-ae152eed57a3?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae152eed57a3</guid>
            <category><![CDATA[gnns-series]]></category>
            <category><![CDATA[graph-machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 18:59:11 GMT</pubDate>
            <atom:updated>2024-03-16T03:30:15.085Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are reading this, I guess you just started your journey into GNNs which stand for Graph Neural Networks and somehow the subject looks complex so you would love to have a simplified explanation of what they are and how they work.</p><p>Perhaps you may be familiar with the topic but need a refresher. Well, my journey into GNNs started with my dissertation in which I was interested in developing an inclusive recommendation system using GNNs with heterogeneous data. However, this is not the topic of this article (which will be covered at the end of this series on GNN). Doing research is quite interesting, intriguing, and sometimes frustrating because this journey took all over the internet from YouTube videos of Standford’s Lecture on GNNs by Juke Luskevoc CS224W, Aleksa Gordic&#39;s Youtube <a href="https://www.youtube.com/watch?v=uFLeKkXWq2c&amp;list=PLBoQnSflObckArGNhOcNg7lQG_f0ZlHF5&amp;ab_channel=AleksaGordi%C4%87-TheAIEpiphany">playlist on GNNs</a>, books like Graph Representation learning by William H., Hands-on GNNs Using Python by Maxime L., and a lot of other resources.</p><p>However, I realized that GNNs are kind of complex and with a lot of writing on the subject highly technical and sometimes can be like a physician talking to someone from an arts background just because the Lingua Franca of GNN is itself complex still. Thus the goal of this series of articles is to make GNNs intuitive and second nature by providing you with a mental model to visualize and approach graph problems using GNNs.</p><h4><strong>Why bother studying GNNs</strong></h4><p>It is always interesting to acquire new knowledge but why bother to go through the hassle of learning about GNNS. It is simple GNNs have a wide variety of applications that are at the heart of some of the apps we use daily and are at the forefront of some groundbreaking scientific advancements in the last decade, some of which include</p><ul><li>Alpha fold by Deep Mind to solve the protein folding challenge which could accelerate the discovery of new drugs.</li><li>Google Maps ETA (Estimated Time of Arrival), which enables most of us daily plan our commute time and route daily so as not to be late for an interview, business meeting, or date.</li><li>Pinterest recommendation systems that recommend relevant Pins to users based on their topic of interest.</li><li>Determining the Effects of different interactions of drugs taken together by patients during treatment to enable efficient medication recommendation.</li><li>Fraud prevention for banks and fintech by detecting fraudulent behaviors and activities on customer accounts.</li></ul><p>I hope now that you have a glimpse of some of the problems that can be solved using GNNs as illustrated above this has stimulated your curiosity if this is your first time learning about GNNs. While with those with domain knowledge this is like deja vu but the possibilities of GNNs are kind of limitless given the amount of relational data available today in nearly all domains and across industries, disciplines and sectors. In short, most problems can be solved using GNNs if we can formulate the problem as Graphs. So what are Graphs and how can we formulate a problem into a graph?</p><p>One of my best description is that of Juke L. (2021) which states that graph are a general language of analyzing entities with relation or interaction. Thus, what this means is graph is composed of c or vertices which could be an object that are connected to each other through edges, thus giving a structural relationship of mapping entities and their relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLfKY7Xj11ePse_gBoUT7g.png" /><figcaption>Figure 1.1 Illustration of a Graph</figcaption></figure><p>From the defiation and illustration above we can already conceive how many underlying types of graph around us such as family tree, disease pathway, computer networks, food web, transportation networks. Thus with this powerful underlying structure of graphs we can analyze entities and their relationships to uncover insights about their underlying structures and patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gx9_HVtAG_G5Z7_YTIylaw.png" /><figcaption>Fig 1.2 Jure Leskovec, Stanford CS224W: Machine Learning with Graphs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95sU7R4lA_EzTmoQe13qOg.png" /><figcaption>Fig 1.2 Jure Leskovec, Stanford CS224W: Machine Learning with Graphs</figcaption></figure><p>We observe from the examples above that the graphs in this domain are explicit as they simply just pop out or are intuitive. However, because of the versatile nature of graphs, we can formulate problems as graphs implicitly in other domains where there are fewer structural relationships between entities. As we can see in the image below, an image can be represented as a graph where pixels are nodes and edges between nodes are used to map relationships and can be used for graph-based image and computer vision tasks. Moreso, we also have graphs in domains such as NLP involving text analysis and generation. However, in a context where the underlying structure is dynamic and evolving where we do not have a fixed structure, such that the nodes and edges keep changing we can use other graphs and machine learning to derive valuable insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*KoSdJ3aXvrf1onLi" /><figcaption>Fig 1.3 Spatial temporary Graphs</figcaption></figure><h4><strong>Graph Machine Learning Tasks</strong></h4><p>So probable one of the questions which should come to mind by now is how do we understand complex domains that have relational data but which is not explicit. Thus, we can to answer the question of how do we take advantage of relational structure for better predictions. This is where graph machine learning comes into play, which is simple the application of machine learning on graph data. When I talk about use machine learning for predictions of graph, what I am simple referring to is either use ML of graph to predict links between pairs of graphs, node labels, generate graphs and subgraphs. The predictions mentioned previously are the some of the most common machine learning tasks on graphs are include.</p><ul><li><strong>Node classification:</strong> This is simple same as classification problems in machine learning and in the case of graphs, this involves predicting the class of a node in a graph. In the case of a movie and actor graph, this can categories movies based on their characteristics into either Horror, Action or Thriller, while actors into different awards. Thus the model is trained to make predictions on unlabeled nodes based on labeled nodes and their attributes.</li><li><strong>Relation prediction:</strong> This is a common is commonly referred to as link prediction which is very commonly used for recommendation systems when applying machine learning applications on graphs, and it entails predicating missing links between pairs of nodes in a graph. This can also be used in knowledge graphs where the goal is to complete a graph with missing links, by mapping relationship between entities based on their relationship.</li><li><strong>Graph classification: </strong>This is also referred to this as clustering and community detection n this task, the input is a graph, and the objective is to develop a classifier that accurately predicts the class of the graph. Thus this involves categorizing graphs into different classes. This can useful in domains such as molecular biology in which molecules represent representing a substance can be used to predict their properties for drug design.</li><li><strong>Graph generation</strong>: This is process in which a new graph is generated after training on properties of graph data. One of the major application of this is in drug discovery.</li></ul><p>In machine learning we are verse the 3 main types of machine learning such as supervised, semi-supervised and unsupervised machine learning which are mostly use to define machine learning problem and use a suitable ML algorithm to propose a solution to the problem. I guess from reading the different types tasks above used on graphs we can pause and take a quick guess of the type of ML to which each belongs.</p><p><strong>Supervised learning on Graphs:</strong> When using supervised learning we have the labeled data we are trying to predict or classify which is use to train our model. Thus we can see graph task such as Node Classification and Relation prediction belong to supervised learning, given that in Node Classification, the neighboring nodes label and features are use to learn features of surrounding nodes and classify nodes or make predictions base on neighborhood similarity</p><p><strong>Unsupervised learning on Graphs: </strong>As a quick reminder<strong> </strong>is in unsupervised learning we have unlabeled data and the objective of the ML algorithm is to uncover hidden patterns and similarities between entities by group them. Thus graph classification task is type of unsupervised learning for graphs as in involves grouping nodes based on their relations using edges between nodes detect communities.</p><p><strong>Semi-supervised learning: </strong>In this case we have part of the labeled data and the other part is unlabeled. Thus, the ML algorithm is used to train part of the labeled graph and the nodes features learned during training is intend used to generate new graphs based on the underlying similarity of the neighborhood know as <em>structural equivalence</em> in graph machine learning (more on this later).</p><p><strong>Graph Learning Techniques</strong></p><p>Now that we can formulate the different graph tasks into the different types of machine learnings, let’s proceed to examine the different families of graph learning techniques.</p><p><strong>i. Graph signal processing</strong> involves the use of traditional signal processing to graphs such as Fourier transform and spectral analysis to grahs, with the objective of discovering intrinsic properties of graphs (connectivuty and structure).</p><p><strong>ii. Matrix factorization</strong> is used to identify patterns in graphs that explain relationships in the original matrix, given that it seeks to find dimensional representation in a large matrices leading to compact and interpretable representation of data.</p><p><strong>iii. Random walk </strong>is mathematical technique used to stimilate movements in graphs between entities through their edges. Thus this stimulated movements in the graph enable information gathering about the relationships between nodes.</p><p><strong>iv. Deep learning </strong>is the use of neural networks with several layers in machine learning task, and is used to effectively encode and represent graph data as vectors.</p><p>The techniques mentioned above are very powerful but are not mutually exclusive and are in practice are oftenly combined to form hybrid models.</p><h4><strong>Graph Data Representation</strong></h4><p>Now that we have a good foundation of the different graph tasks, machine learning types and graph learning techniques, it is important that we look an the fundamental building block which is obviously the data. How is graph data represented when presented in tabular data as is the case with most of our datasets in comma separated values or sheets. When we use spreadsheets to represent data, in mostly in rows denoting an entity and columns denoting their attributed or features, and if we are using a relational database we denoted the relationships with foreign keys. However, most tabular datasets observations involve analyses of entities though with explicit information encoded which denoted relationship between entities, and this is the where graph datasets become a powerful to map relationships as edges between entities.</p><p>From the dataset above we can observe that there are 5 members of the family with 3 features. We can observe from the table above that tabular data does not have edges where as on the graph counterpart it allows us to understand the relationships between the family. Thus the relationship between nodes is vital in gaining deep insights into the data, and is the reason why graph data is increasing in popularity in the deep learning community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Tgsyxvv-pWkKgYtV.jpg" /><figcaption>Figure 1.4 Representation of Family tree in Tabular versus a graph dataset.</figcaption></figure><p>Building upon our knowledge of graph data and the different types of tasks, notable with deep learning, we would proceed to examine GNNs.</p><h4><strong>Introduction to GNNs</strong></h4><p><strong>What are GNNs?</strong></p><p>GNNs which stand for Graph Neural Networks are a kind of deep learning architecture which is designed and optimise for graph-structured data. Most traditional data process text, images which have a sequence like pattern, graphs are sparse and heterogeneous and GNNS are explicitly designed to process and analyze this kind of datasets.</p><p><strong>How do GNNs work?</strong></p><p>GNNs, or Graph Neural Networks, work by creating a vector representation of each node in a graph, utilizing information from various sources. This representation includes the original node features, edge features, and global features. For instance, in a social network, a node’s features could be name, age, and gender, while edge features might represent the strength of relationships between nodes, and global features could be network-wide statistics.</p><p>Unlike traditional machine learning techniques, GNNs enrich the original node features with attributes from neighboring nodes, edges, and global features, resulting in a more comprehensive and meaningful representation. These new node representations are then used to perform specific tasks, such as node classification, regression, or link prediction.</p><p>GNNs achieve this by defining a graph convolution operation that aggregates information from neighboring nodes and edges to update the node representation. This process is repeated iteratively, allowing the model to learn more complex relationships between nodes as the number of iterations increases.</p><p>There are various types of GNNs and GNN layers, each with its unique structure and method of aggregating information from neighboring nodes. When choosing the right GNN architecture for a particular problem, it’s essential to understand the characteristics of the graph data and the desired outcome.</p><p>GNNs are most effective when applied to specific, high-complexity problems where learning good representations is critical to solving the task. They require a substantial amount of data to perform effectively. While traditional machine learning techniques might be a better fit for smaller datasets, they do not scale as well as GNNs. GNNs can process larger datasets thanks to parallel and distributed training and can exploit additional information more efficiently, leading to better results.</p><p><strong>Source:</strong></p><ul><li>Yang L. et al (2015) , Graph-based Facial Affect Analysis: A Review. Source: <a href="https://arxiv.org/pdf/2103.15599.pdf">https://arxiv.org/pdf/2103.15599.pdf</a></li><li>William L. Hamilton (2020), Graph Representation Learning. Source: <a href="https://www.cs.mcgill.ca/~wlh/grl_book/files/GRL_Book.pdf">https://www.cs.mcgill.ca/~wlh/grl_book/files/GRL_Book.pdf</a></li><li>CS224W: Machine Learning with Graphs, Jure Leskovec, Standford University 2023. Source: <a href="https://web.stanford.edu/class/cs224w/slides/01-intro.pdf">https://web.stanford.edu/class/cs224w/slides/01-intro.pdf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae152eed57a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing CI/CD for Machine learning Projects when deploying models into production]]></title>
            <link>https://medium.com/@amaboh/understanding-ci-cd-for-machine-learning-when-shipping-models-into-production-44341e4aaa41?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/44341e4aaa41</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 05:01:23 GMT</pubDate>
            <atom:updated>2024-07-28T16:16:09.287Z</atom:updated>
            <content:encoded><![CDATA[<p>For data scientists with a background in software engineering or Software Engineers, the concept of CI/CD which stands for Continuous Integration and Continuous Deployment is not a new concept but a necessity when shipping software into production with different tests involved.</p><p>While I would like to go straight to explaining the difference between CI/CD for traditional software engineering versus machine learning. I feel it’s important for data scientists who do not have an understanding of what CI/CD entails to understand why this practice is crucial when developing and shipping applications to end users.</p><p>This Article is composed of 6 different parts and for better comprehension, it would be best to proceed sequentially as the next part builds upon the knowledge of the previous part. However, if you already have some background knowledge in some of the areas and would like to jump ahead to other areas of interest you can also do so.</p><ul><li><strong>Part 1</strong>: Understanding CI/CD in traditional software engineering</li><li><strong>Part 2</strong>: CI/CD in Machine Learning — The Differentiators</li><li><strong>Part 3:</strong> Hands-on with CI/CD in a Machine Learning Context</li><li><strong>Part 4</strong>: Advanced CI/CD Techniques for ML</li><li><strong>Part 5</strong>: Applying CI/CD to a Real ML Project</li><li><strong>Part 6:</strong> Automating ML Workflows with GitHub Actions</li></ul><h3><strong>Part 1: Understanding CI/CD in traditional software engineering</strong></h3><h4><strong>The Essentials of CI/CD</strong></h4><p>CI which stands for Continuous integration is the first part in the CI/CD pipeline which entails making several code updates to a code repository through commits, after which the code goes through some testing such as unit testing or smog test to verify bugs and ensure that the code pushed to the repository adheres to best practices. While the CD stands for Continuous deployment and is the build process that the code pushed to the remote repository goes through to make it available to end users. Given that we now have a good understanding of what CI/CD is about and its importance, let’s build on this foundational knowledge to make a difference between CI/CD in software engineering and Machine learning.</p><p>It is worth knowing that before CI/CD companies like Ticket Master used to build, test, and publish pipeline deployments within two hours but with CI/CD it is now shortened to 8 minutes. I hope this provides you with some context of the importance of CI/CD in terms of a faster software development lifecycle. Moreover, when several software engineers are working on a project repository they may be working on one or several components of the software/ app, thus making several changes to the code base. The process of managing these changes to ensure high-quality code is shipped with fewer bugs and high performance can be cumbersome if done manually in a team of software engineers or just a single engineer working on a project. Thus the practice of CI/CD enables high-quality code to be shipped meeting specific standards by different teams of engineers collaborating on the code repository, thereby enabling</p><ul><li>Faster and more frequent code deployments because standardizing builds and tests through automation enables engineers to have less time debugging while having more time to optimize the code for performance.</li><li>Effortless collaboration is independent of the environment as a result of software engineers having access to the development and testing environment without fear of bringing the software behind schedule by setting up specific environments for minor or major code changes.</li><li>Reduced development costs and gains in productivity because of the standardization of development and testing tools can lead to a reduction of extra costs associated with managing and licensing different applications. The productivity gains result from improved collaboration as a result of automated builds and tests.</li></ul><p>Thus CI/CD makes it easier for software engineers to deliver code changes more frequently and reliably thereby shortening the software development cycle. This entails automating and integrating code changes, and confirming that the code is valid and error-free before integrating it into the repository, which helps detect bugs and speed up new releases. Now that we have an idea of what CI/CD entails in traditional software development.</p><p>To have a clear understanding of CI/CD in machine learning we would break up the CI from the CD so we can distinguish what processes are involved in the CI/CD pipeline of ML development.</p><h3>Part 2: CI/CD in Machine Learning — The Differentiators</h3><h4><strong>Difference of CI/CD in traditional software vs ML</strong></h4><p>In traditional software engineering as in machine learning the management of source code is usually done with an online code repository management tool like GitHub, GitLab, or BitBucket. Thus when new code changes are made to the code repository this triggers different <strong><em>events</em></strong> based on the kind of activity, and this is the case with traditional software engineering where code changes are the principal triggers of CI/CD. This could involve making a pull request or push to code through tools like GitHub actions leading to test, building, and deploying the code. This practice is commonly referred to as GitOps (weights and Bias, 2023).</p><p>On the other hand, CI/CD in ML is not only triggered by code but also by changes to the model and data, such as the addition of new features to the data that would motivate the development of a new model, or retrain a model thus triggering the CI/CD workflow. Other events could be new feature labels, drift in the model(s), model training, and model training and hyperparameter tuning take a much longer time with significantly higher compute resources in terms of GPUs or TPUs.</p><p>While testing and deployment are different, observability and logging requirements differ too with experiment tracking and model monitoring to address these requirements. More so, in traditional software, only code is versioned whereas in ML in addition to code versioning, models and datasets are versioned as well. More so given the experimental and probabilistic nature of ML as opposed to the deterministic nature of traditional software, experiment tracking is a vital process in the CI/CD pipeline of ML engineering.</p><p>Experiment tracking is vital for the success of an ML development lifecycle as it provides insights into other artifacts such as data and model versioning. Experiment tracking is a process of recording, organizing, and analyzing the results of ML experiments. This entails managing all the different experiments and their components, such as parameters, metrics, models, and other artifacts to gain insights into which parameters and combinations of hyperparameters and other experimental settings lead to better-performing models with tools like Weight and Bias and Neptune AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*EFBtpJPg4paPY0x7pghqbg.png" /><figcaption>image credit (W&amp;B) Effective MLOPs course</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Dozwuose4XML1c19tONiuw.png" /><figcaption>image credit (W&amp;B) Effective MLOPs course</figcaption></figure><p>As seen in the diagram above illustrating the difference between CI/CD in traditional software and ML, one of the easiest ways to get started is using GitOps which is centered around changes to code and observability with experiment tracking.</p><h3>Part 3: Hands-On with CI/CD in ML</h3><h4>Implementing CI/CD in a Machine Learning Context</h4><p><strong>What is GitOps and its role in ML CI/CD:</strong> GitOps is a process that automates infrastructure provisioning through updates to code repository with different git events such as push, pull, merges, etc using a Git workflow with CI/CD. Thus when code is merged, the CI/CD pipeline triggers a change in the environment, thus this can be used to implement tests to ensure quality code is merged with the main branch, check the model quality before making commits, and configure for different development environments. Thus, we can say GitOps uses version control as an operational environment relying on DevOps practices such as CI/CD to automate infrastructure (GitLabs, 2023).</p><h4>Practical example using GitHub Actions</h4><p>Now would be a better time to get our hands dirty by seeing how to implement a CI/CD pipeline in a project using the components covered in this article such as GitOps and Experimenting with tracking with open-source version control code repository GitHub and with Weights &amp; Bias respectively, and I’ll provide some reference which you can explore for a deeper understanding on workflow orchestration, data versioning, and deepening your comprehension about MLOPs as a whole.</p><p>When implementing CI/CD workflow with GitOps via GitHub Actions it is tempting sometimes to use Github Action as an orchestration tool which is a bad practice because it can not handle all aspects of ML workflow.</p><p>GitHub Actions is core to the successful operationalization and implementation of GitOps as it enables the automation of the CI/CD platform to build, test, and deploy pipeline, and this is done through workflows(Gitlabs). Thus the events we mentioned earlier are triggered by GitHub Actions when one of such events occurs on your code repository. One of the best ways to learn about these events is just to google “events that trigger GitHub actions”. Here you will see a list of events that can trigger a workflow such as check_run, create, delete, etc.</p><p>Well before we dive into using GitHub Actions for machine learning workflows, it’s worth having some basic understanding of how GitHub Actions are created and the file structure.</p><h4><strong>How to create a GitHub Action</strong></h4><p>GitHub actions reside in the folder name: <strong><em>&lt;filename&gt;/.github/workflows/&lt;github-action-file&gt;.yaml.</em></strong></p><p>The file is located in the workflows folder inside dot “.github” and must end with a “.yaml” extension that is human-friendly to read. The YAML file serves as the executable piece of command on how to execute the GitHub Actions based on the occurrence of an event. Let’s use this greetings example below to explain the file structure of a GitHub Action YAML file to run a “hello, bonjour”. This example is a modified version found on the GitHub <a href="https://docs.github.com/en/actions/quickstart">quickstart </a>page of creating your first workflow.</p><p>Create the following file in GitHub in your main file folder .github/workflows/continuous-integration.yaml</p><pre>name: learn-github-actions<br><br>on: [push]<br>jobs:<br>  first-job-on-github:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: hello<br>      - run: |<br>          echo &quot;🎉 Hello, bonjour&quot;</pre><p>let&#39;s explore the contents of the YAML file above and understand what each line of code represents, so this would enable us to have some foundational knowledge to write custom GH Action workflows suited for adapted to our needs.</p><blockquote><strong>name</strong>: This is the identifier given to the action in the workflow and can be given whatever name you choose.</blockquote><blockquote><strong>on</strong>: This is used to specify the different types of events on which the workflow can be triggered and serves as the first point of entry to cause a workflow to run. To get a list of completely different events that trigger workflows just google “Events that trigger workflow”, there you’ll see a complete list. It is worth mentioning that different activity types exist on which a workflow can be triggered such as push, pull_request, labels, and brach_protection just to name a few. See a complete list <a href="https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#onevent_nametypes">here</a></blockquote><blockquote><strong>jobs</strong>: This refers to the different actions to be completed and if you are familiar with airflow DAGs, jobs are synonymous with nodes in a DAG(Directed Acyclic Graph). Thus Jobs run sequentially and outputs from one can be used as input to the next job.</blockquote><blockquote><strong>job-name:</strong> In our case above we use first-job-on-github.</blockquote><blockquote><strong>runs-on</strong>: This is also known as the runner which is the newly-provisioned virtual machine with an operating system on which your workflow would be executed. There are three options available inclusive of the Ubuntu-lastest, we have Microsoft Windows and macOS runners.</blockquote><blockquote><strong>steps</strong>: This defines the sequence of tasks to be executed as part of a job and can be thought of as workers in nodes given each step represents an individual task.</blockquote><blockquote><strong>name:</strong> This is used to give a name to each step and can be used for reference.</blockquote><blockquote><strong>run</strong>: This keyword is used to execute the command on the runner or run a shell command.</blockquote><p>This example above serves as a good starting point to understand the different components of a GH action file but this is very limited as this does not have access to environment files and scripts. This brings us to a concept called third-party workflows, which are predefined workflows created by individuals or organizations (others apart from GitHub). Third-party actions are to GitHub Actions like third-party images are to Docker Hub. One of the most popular GitHub Actions used to access environment variables and scripts is `checkout`.</p><p><strong>Running GitHub Actions with Python Script and Environment Variable</strong></p><p>The previous illustration above of the GH Action YAML file enabled us to get familiar with the file structure of GH Actions. However, we noticed the limitations of not being able to run a Python script because our GH Action does not have access to any Python script or environment variable, and to resolve this we mention using a third-party action called ‘checkout’. We would proceed to write a small Python program that checks the version of the Wandb library using a GH action file with checkout and explains its function.</p><p><em>&lt;repo name&gt;/.github/workflows/ci.yaml</em></p><pre>name: learn-github-actions<br><br>on: [push]<br>jobs:<br>  first-job-on-github:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: hello<br>        run: |<br>          echo &quot;hello, bonjour&quot; <br>      - name: run python script<br>        run: |<br>          pip install -r requirements.txt<br>          python ci.py</pre><p><em>&lt;repo name&gt;/client/test/ci.py</em></p><pre>import wandb<br>print(f&#39;This version of wandb is: {wandb.__version__}&#39;)</pre><p><em>requirements.txt</em></p><pre>wandb</pre><blockquote>As we can notice above most of the code is similar to the first GH Action YAML file in the previous section. However, we’ve added -uses: actions/checkout@v3. The keyword actions is the GitHub repo with all third-party predefined workflows in the location actions; checkout is used to give access to content repos to GH action and @v3 is used to highlight the version. The second step above with the -name: run python script is used to execute the install the requirements.txt file and run the python script.</blockquote><p>To see the results of the Github Action, in your repository Go to Actions &gt;&gt; All workflows &gt;&gt; Create Create ci.yaml &gt;&gt; first-job-on-github, and you should have a screen similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*YBCt-9LSRXyYXVuTAtLe3Q.png" /><figcaption>Screenshot of GitHub Action job</figcaption></figure><p><em>Congratulations</em> on successfully implementing your first GH Action workflow, though this looks very simple, it is essential to successfully create a GH action. There are four main components to look out for in a Github action on, uses, run pip install -r requirements.txt python ci.yaml.</p><blockquote>on: Event type <strong><em>(1)</em></strong></blockquote><blockquote>uses: actions/checkout@v3 <strong><em>(2)</em></strong></blockquote><blockquote>run: | pip install -r requirements.txt <strong><em>(3)</em></strong></blockquote><blockquote>python ci.yaml <strong><em>(4)</em></strong></blockquote><p>Though this workflow above runs on any push request it does not help to enforce policies in our workflow. Thus this brings us to the concept of implementing tests which is critical for branch protection, ensuring that quality code is shipped, and for observability for machine learning.</p><h3>Part 4: Advanced CI/CD Techniques for ML</h3><h4>Testing and Quality Assurance in ML pipelines</h4><p><strong>What is testing and how does it enable branch protection?</strong></p><p>As observed in the previous script above any changes to the code would trigger the code to run the script. However, in a scenario in which you are part of a team working on a code repository for a production app, as the repository manager you would not just accept any changes to be merged with the main repository as this may lead to spaghetti-like code. Thus, to ensure that high-quality code is pushed to the production or testing environment, we can standardize this by using unit tests or smoke tests which are used to gate pull requests. We make use of branch protection which accepts changes only when certain tests are passed. Below we will illustrate a simple version of how branch protection works with some basic test implementation on our previous app.</p><p>Testing is crucial for CI/CD in that ensures the quality and reliability of our code delivery process. Though there exist other types of tests like integration and regression tests, our focus here would be unit and smoke tests.</p><p><strong>Unit tests </strong>are considered the first step in implementing testing in the development phase of the CI/CD pipeline (Bob, 2017). The focus is unit tests involve testing discrete functions at the source code level, in which tests are written to assess a function by making assertions against the results returned.</p><p><strong>Smoke tests </strong>on the other hand are end-to-end functional tests designed to verify basic and critical functionalities of a code base. Thus in CI/CD, smoke tests are used in the application build to ensure that essential features are working as expected. Smoke test helps create fast feedback loops that are vital in the software development cycle.</p><p>To enforce policies in our repository we would proceed to gate Pull request by implementing unit test in our case above by making just two changes, one to our code repository another to activate branch protection, and activating branch protection.</p><p>i) In our python ci.py file add the following line below which checks the version of Wandb version</p><pre><br>assert wandb.__version__ == &#39;2.1.01&#39;, f&#39;Expected version 2.1.01, but got {wandb.__version__}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_elCHP_YYAb-MaNeNUg6Zw.png" /><figcaption>screen shot job failure</figcaption></figure><p>When we click on first-job-on-github we realize that the error message is due to the wrong version of the Wandb library which shows that 2.2.01 is the right version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*Ny8tfJvakcV4MywyBJEugA.png" /></figure><p>ii) We would proceed to make just two changes in our YAML File. First, we would change the event to be for a pull request. Secondly, for clean file structure, we move our Python script to a source/test folder and thus add the folder path to our GitHub Action Yaml file as follows</p><pre>name: learn-github-actions<br><br>on: [pull_request]<br>jobs:<br>  first-job-on-github:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: hello<br>        run: |<br>          echo &quot;hello, bonjour&quot; <br>      - name: run python script<br>        run: |<br>          pip install -r requirements.txt<br>          python source/ci.py #(ii)<br></pre><p>However, we can still merge our code to our main repository despite the failure and this kind of behavior does not enforce best practices. For us to enforce our test by making sure that any code to be merged with the main repo meets certain standards by passing the test, we need to enforce our test by gating pull requests through branch protection.</p><p><strong>How to activate branch protection</strong></p><ol><li>Go to settings on your repo &gt;&gt;</li><li>Click on branches to the left panel &gt;&gt;</li><li>In the branch name pattern box type in main &gt;&gt;</li><li>Choose Require status checks to pass before merging by click checkbox &gt;&gt;</li><li>Proceed to enter the name of the job, which in our case is first-job-on-github.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QRMz2NA9u_m2eEx19SC-Q.png" /><figcaption>Step-by-step guide on screen-shot on brach protection</figcaption></figure><p>After this, we can make some random changes in the Readme, and open a PR in the terminal or GH console. Given the simplicity of the GH web UI, I’ll advise proceeding with the Web console, and don’t forget to fetch or pull the remote changes as you deem fit after completing the merge.</p><blockquote>Given that we intentionally put in the wrong version of the Wandb library, this job would fail as seen below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*lN8PHzOTgpWIg_sv-bEPSg.png" /><figcaption>Screen shot of failure message</figcaption></figure><blockquote>To proceed to correct this and ensure that the test passes all checks, we just need to change the Wandb version to the correct one from the print statement with the version number, which in my case is 0.16.1. This would eventually lead to us passing the test and thus we can merge the new PR to our main branch as seen below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*DF72bT-zkrd4Yb7iX7UznQ.png" /></figure><p>Ok, so far we have covered some key concepts on GitOps that would be critical to implementing CI/CD pipelines for machine learning. Other concepts like special characters, secrets, and environmental variables have not been covered yet. We would proceed to explain them as they arise because given the long nature of this article, going through each of these would make this long article much longer.</p><h3>Part 5: Applying CI/CD to a Real ML Project</h3><p>In what context can the workflow that we’ve gone through be applied in machine learning, in this case, involves a model and data? Well, imagine a case in which you are part of a team with 3 machine-learning engineers developing a computer vision model or recommendation system and you are all working to get great results in terms of metrics. One of your colleagues just finished training a model that yields some promising results and is excited to ship it to the model registry in this case the repository, and the same can be said of the other member of your team. However, there is no way to determine which model is better compared to the present model before shipping to the model registry. Thus setting up a good CI/CD process for our machine-learning pipeline can enable us to have some observability of our models and avoid guessing. This is where tools like Weights &amp; Bias, and the GitHub API can help us achieve this objective.</p><p><strong>Implementing CI/CD for a Machine Learning project using GitOps</strong></p><p>To follow along open the the <a href="https://github.com/amaboh/Effective-MLOPS">GitHub repo </a>and then let&#39;s go over the Projects file structure.</p><pre>&gt; Effective-MLOPS<br>  &gt; .github/workflows<br>      model_report.yml<br>  &gt; data<br>  &gt; notebooks<br>  &gt; source/tests<br>      model_comparison.py<br>  &gt; .env<br>  &gt; .gitignore<br>    README.md<br>    requirements.txt</pre><blockquote>notebooks: This folder holds our Jupyter Notebook, given that we would not go through this in detail it suffices to know this is where we train our different ML models and log the different metrics to Wandb.</blockquote><blockquote>source/test : this folder contains our Python script which generates the report comparing the baseline model to the challenger/new model.</blockquote><blockquote>.github/workflows: This folder contains the model_report.yaml file which serves as the automation script that triggers the model_comparison.py file.</blockquote><p><strong>Getting Started: Prerequisites and Setup:</strong></p><p>To replicate our setup, even before you proceed to clone our repo we would first need to obtain Wandb API keys.</p><p><strong>Create a Weights &amp; Bias account and obtain your WandB API keys</strong>: Go to <a href="https://wandb.ai/">https://wandb.ai</a> and create your account, after which you can go to settings where you can obtain your API keys which would be used as an environment variable locally and as a secret on GitHub (we would cover GH secrets later).</p><p><strong>Cloning the repository</strong></p><ul><li><strong>Command</strong>: Clone our project from GitHub using git clone <a href="https://github.com/amaboh/Effective-MLOPS.">https://github.com/amaboh/Effective-MLOPS</a>.git</li><li><strong>Navigation</strong>: Change to the project directory with cd Effective-MLOPS.</li><li><strong>Install dependencies</strong>: To install all dependencies run pip install -r requirements.txt</li><li><strong>API key and environment variables</strong>: Create a dot env file and store your Wandb API keys in this format WANDB_API_KEY=&#39;API KEY&#39;.</li></ul><p><strong>Running different experiments and logging metrics to Wandb</strong></p><ul><li><strong>Navigation</strong>: Change the directory to thenotebooks folder and start the jupyter notebook kernel from the terminal. Given that the focus of this tutorial is not on model development, we would just proceed to execute the files in the notebook cv_model_development.ipynb file. One of the important parts in the notebook is the initialization of the Wandb library to log the metrics and for the first run start with the tag tags=[&#39;baseline&#39;], this would serve as the baseline model. On the second run, you can adjust the learning rate, number of epochs, and optimizer as you which. However, for the tag you can use a descriptive name like challenger as seen heretags=[&#39;challenger&#39;].</li></ul><pre>run = wandb.init(<br>    # Set the project where this run will be logged<br>    project=&quot;Effective_MLOPs_CICD_CV&quot;,<br>    # Track hyperparameters and run metadata<br>    tags=[&#39;baseline&#39;],<br>    config={<br>        &quot;learning_rate&quot;: lr,<br>        &quot;epochs&quot;: N_EPOCHS,<br>        &quot;optimizer&quot;: &quot;Adam&quot;,<br>    })</pre><p>After this, you should be able to visualize the metrics of the two different model runs in your Wandb project dashboard as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Brc_TANRygX20lVkFDnVXg.png" /><figcaption>screen shot: Model runs</figcaption></figure><p>As seen above we have randomly generated names to represent the names of the different runs as dulcet-dawn-6, skilled-firefly-5, smart-blaze-4, etc.</p><p>To view a comparison report in the notebook of the model runs that have been generated in the Wandb project dashboard. In the ipython notebook at the bottom of the proceed to replace the project and entity (1) with those in your Wandb project account, and use the generated names of the runs in your dashboard to replace &#39;skilled_firefly-5&#39; and &#39;dulcet-dawn-6&#39; as seen in code below (2).</p><pre>import wandb.apis.reports as wr<br><br>PROJECT = &#39;Effective_MLOPs_CICD_CV&#39;<br>ENTITY = &#39;avri&#39;<br><br>report = wr.Report( #(1)<br>    entity=ENTITY,<br>    project=PROJECT,<br>    title = &quot;Compare Runs&quot;,<br>    description=&quot;comparing runs of model&quot;<br>)<br><br>pg = wr.PanelGrid(<br>    runsets=[<br>        wr.Runset(ENTITY, PROJECT, &quot;Run Comparison&quot;).set_filters_with_python_expr(&quot;Name in [&#39;skilled-firefly-5&#39;, &#39;dulcet-dawn-6&#39;]&quot;) #(2)<br>    ],<br>    panels=[<br>        wr.RunComparer(diff_only=&#39;split&#39;, layout={&#39;w&#39;: 24, &#39;h&#39;: 15}),<br>    ]<br>)<br><br>report.blocks = report.blocks[:1] + [pg] + report.blocks[1:]<br>report.save()</pre><p>The report generated after running these lines of codes is the same report we are going to be implementing in CI/CD pipelines, which would eventually enable us to determine if a new model or experiment run by a team member meets a certain threshold before pushing the model to the model registry. Thus the notebook serves for experimentation and also proof of concept but now we need to enforce this by using GH actions. However, before that, we need to write the Python script that would be triggered to generate the report based on certain events.</p><p><strong>Script for Model Comparison report</strong></p><p>We can find the model_comparison.py file in source/tests and this script contains two functions that would be used to generate the report. The first function get_baseline_run gets the baseline report and the second function compare_runs is similar to the clast code block in the jupyter notebook which generated the comparison report. We would proceed to declare our environment variables in the GH Action YAML file subsequently. This is the complete code block below of the model_comparison.py file: To test the script below run python3 model_comparison.py and you should see a report link return in the terminal.</p><pre>import os, wandb<br>import wandb.apis.reports as wr<br><br>assert os.getenv(&#39;WANDB_API_KEY&#39;), &#39; Set the WANDB_API_KEY env variable&#39;<br><br><br>def get_baseline_run(entity=&#39;avri&#39;, project=&#39;Effective_MLOPs_CICD_CV&#39;, tag=&#39;baseline&#39;):<br>    &quot; Get baseline run using tags&quot;<br>     <br>    api = wandb.Api()<br>    runs = api.runs(f&#39;{entity}/{project}&#39;, {&quot;tags&quot;: {&quot;$in&quot;: [tag]}})<br>    assert len(runs) == 1, &#39;There must be exactly one run with the tag baseline&#39;<br>    return runs[0]<br><br>def compare_runs(entity=&#39;avri&#39;, <br>                 project=&#39;Effective_MLOPs_CICD_CV&#39;, <br>                 tags=&#39;baseline&#39;,<br>                 run_id=None):<br>    &#39;Compare current run to baseline run.&#39;<br>    <br>    #enables us to overrise args with env varibales<br>    <br>    entity = os.getenv(&#39;WANDB_ENTITY&#39;) or entity<br>    project = os.getenv(&#39;WANDB_PROJECT&#39;) or project<br>    tag = os.getenv(&#39;BASELINE_TAG&#39;) or tag<br>    run_id = os.getenv(&#39;RUN_ID&#39;) or run_id<br>    assert run_id, &#39;You must set the RUN_ID environment variable or pass a `run_id` argument&#39;<br><br>    baseline = get_baseline_run(entity=entity, project=project, tag=tag)<br>    report = wr.Report(entity=entity, project=project,<br>                       title=&#39;Compare Runs&#39;,<br>                       description=f&quot;A comparison of runs, the baseline run name is {baseline.name}&quot;) <br><br>    pg = wr.PanelGrid(<br>        runsets=[wr.Runset(entity, project, &quot;Run Comparison&quot;).set_filters_with_python_expr(f&quot;ID in [&#39;{run_id}&#39;, &#39;{baseline.id}&#39;]&quot;)],<br>        panels=[wr.RunComparer(diff_only=&#39;split&#39;, layout={&#39;w&#39;: 24, &#39;h&#39;: 15}),]<br>    )<br>    report.blocks = report.blocks[:1] + [pg] + report.blocks[1:]<br>    report.save()<br>    <br>    if os.getenv(&#39;CI&#39;): # is set to `true` in GitHub Actions https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables<br>        with open(os.environ[&#39;GITHUB_OUTPUT&#39;], &#39;a&#39;) as f: # write the output variable REPORT_URL to the GITHUB_OUTPUT file<br>            print(f&#39;REPORT_URL={report.url}&#39;, file=f)<br>    return report.url<br><br>if __name__ == &#39;__main__&#39;:<br>    print(f&#39;The comparison report can found at: {compare_runs()}&#39;)</pre><h3>Part 6: Automating ML Workflows with GitHub Actions</h3><p>Though we’ve been able to implement the script to generate the report as seen in part 5 this is not efficient as it’s been triggered manually. Thus, we need to make this process automatic and accessible by all members working on this project and this takes us to GH Actions.</p><h4><strong>GitHub Action YAML file to automate report generation</strong></h4><p>This file contains the GH Action workflow that generates and posts the model report as a comment on GH issues in response to /wandbcomment.</p><pre>name: model_report<br>on: issue_comment<br><br>permissions:<br>  contents: read<br>  issues: write<br>  pull-requests: write<br><br>jobs:<br>  generate_model_report:<br>    if: (github.event.issue.pull_request != null) &amp;&amp; contains(github.event.comment.body, &#39;/wandb&#39;)<br>    runs-on: ubuntu-latest<br>    steps:       <br><br>    - name: Get repo contents<br>      uses: actions/checkout@v3<br><br>    <br>    - name: install dependencies<br>      run: pip install ghapi wandb<br><br>    - name: Parse value from the command<br>      id: get-runid-value<br>      shell: python<br>      run: |<br>        import re, os<br>        comment = os.getenv(&#39;PR_COMMENT&#39;, &#39;&#39;)<br>        match = re.search(&#39;/wandb[\s+](\S+)&#39;, comment)<br><br>        with open(os.environ[&#39;GITHUB_OUTPUT&#39;], &#39;a&#39;) as f:<br>          if match:<br>            print(f&#39;VAL_FOUND=true&#39;, file=f)<br>            print(f&#39;RUN_ID={match.group(1)}&#39;, file=f)<br>          else:<br>            print(f&#39;VAL_FOUND=false&#39;, file=f)<br>      env:<br>        PR_COMMENT: ${{ github.event.comment.body }}<br><br><br>    - name: Generate the comparison report<br>      if: steps.get-runid-value.outputs.VAL_FOUND == &#39;true&#39;<br>      id: wandb-report<br>      run: python ./source/tests/model_comparison.py<br>      env:<br>        WANDB_ENTITY: avri<br>        WANDB_PROJECT: Effective_MLOPs_CICD_CV<br>        BASELINE_TAG: baseline<br>        RUN_ID: &quot;${{ steps.get-runid-value.outputs.RUN_ID }}&quot;<br>        WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}<br><br>    - name: Make a comment with the GitHub API<br>      uses: actions/github-script@v6<br>      if: steps.wandb-report.outcome == &#39;success&#39; <br>      with:<br>        script: |<br>           var msg = `A comparison between the linked run and baseline is available [in this report](${process.env.REPORT_URL})`<br>           github.rest.issues.createComment({<br>              issue_number: context.issue.number,<br>              owner: context.repo.owner,<br>              repo: context.repo.repo,<br>              body: msg<br>            });<br>      env:<br>        REPORT_URL: &quot;${{ steps.wandb-report.outputs.REPORT_URL }}&quot;</pre><blockquote>- <strong>Trigger (on)</strong>: The workflow is triggered by a comment on an issue (`on: issue_comment`).<br>- <strong>Permissions</strong>: Defines the permissions needed for the workflow, including read access to repository contents, and write access to issues and pull requests.<br>- <strong>Jobs</strong>: This workflow consists of a single job named `generate_model_report`.</blockquote><blockquote><strong>Job</strong>: generate_model_report<br>This job is executed when two conditions are met: a pull request is linked in the issue, and the comment contains the keyword `/wandb`. It runs on the latest Ubuntu runner provided by GitHub Actions.</blockquote><blockquote><strong>Steps</strong>:<br>1. Get repo contents: This step uses the `actions/checkout@v3` action to check out the repository code so it can be used in the workflow.</blockquote><blockquote>2. Install dependencies: Installs Python dependencies (`ghapi` for GitHub API interaction and `wandb` for Weights &amp; Biases, a machine learning experiment tracking tool).</blockquote><blockquote>3. Parse value from the command: <br> — This step looks for a specific pattern (`/wandb [run_id]`) in the comment.<br> — It uses a Python script to extract the `run_id` value.<br> — The result (`VAL_FOUND` and `RUN_ID`) is saved as output for use in later steps.</blockquote><blockquote>4. Generate the comparison report:<br> — This step runs if the `run_id` was successfully extracted.<br> — Executes a Python script (`model_comparison.py`) which likely uses the `run_id` to fetch data from Weights &amp; Biases and generate a model comparison report.<br> — Environment variables are set, including `WANDB_API_KEY` from GitHub secrets for secure authentication with Weights &amp; Biases.</blockquote><blockquote>5. Make a comment with the GitHub API:<br> — This step is executed if the previous step (report generation) is successful.<br> — Uses the `actions/github-script@v6` to run a JavaScript snippet.<br> — The script posts a comment on the issue with a link to the generated report.</blockquote><p><strong>Create WANDB secret key</strong>: This is where the WANDB API keys is stored and used as an environment variable by using the special variable secrets as seen in the YAML file WANDB_API_KEY: ${{secrets.WANDB_API_KEY}} in the step named Generate a comparison report. Assuming you have created a repository for this project on GitHub, proceed with the following actions.</p><ul><li>Go to settings, click on Secrets and variables</li><li>Choose Actions, select New repository secret,</li><li>In the Name * dialog box enter WANDB_API_KEY and in secret* paste your API keys in the dialog box and click Add secret.</li></ul><p><strong>Push changes to GH: </strong>Now that all the necessary setup has been completed with Python scripts, you can now commit the changes and push it to GitHub.</p><p><strong>Generate a report with GH comment: </strong>To proceed to generate a report with the GH you would first need to grab the model run ID, which can be gotten from the model overview by going to the Run path and choosing the last characters after the project names as seen in the red unlined path in the image below. This run ID would be used to generate the report by making a pull request with a commit with the comment /wand 77yoyd81, please ensure to replace run id &lt;77yoyd81&gt; with yours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*3Z-iYY8YOJLOuqwg56cZBg.png" /><figcaption>screenshot of run ID</figcaption></figure><p>After this, you should have a report showing like this bel</p><p>Congratulations on successfully implementing, your first CI/CD workflow, and you can proceed to enforce this to make this test mandatory. If you click on the report it will take you to the comparison dashboard as seen earlier in the notebook.</p><p>Due to the long nature of this article, we did not cover concepts like the GitHub API and special variables in GitHub. I would provide links below which you can read at your leisure to have a deeper understanding of how to use them in your different workflows.</p><h4>Reference</h4><ol><li>Bob R. ( Mabl, 2017); Mabl source: <a href="https://www.mabl.com/blog/unit-testing-development-phase-cicd-pipeline">https://www.mabl.com/blog/unit-testing-development-phase-cicd-pipeline</a></li><li>Advantages of CI-CD: Cisco source: <a href="https://www.cisco.com/c/en/us/solutions/data-center/data-center-networking/what-is-ci-cd.html#~benefits">https://www.cisco.com/c/en/us/solutions/data-center/data-center-networking/what-is-ci-cd.html#~benefits</a></li><li>Understanding GitHub Actions; GitHub source: <a href="https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions">https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions</a></li><li>GitHub Actions Documentation; Git hub, source: <a href="https://docs.github.com/en/actions">https://docs.github.com/en/actions</a></li><li>Github context and special variables; Github, source: <a href="https://docs.github.com/en/actions/learn-github-actions/contexts">https://docs.github.com/en/actions/learn-github-actions/contexts</a></li><li>GitOps operational framework; Source: <a href="https://about.gitlab.com/topics/gitops/">https://about.gitlab.com/topics/gitops/</a></li><li>Weights and Bias (2023): What is CI/CD for machine learning: <a href="https://wandb.ai/hamelsmu/model-registry/reports/What-is-CI-CD-for-Machine-Learning---VmlldzozNzk2NDg2">https://wandb.ai/hamelsmu/model-registry/reports/What-is-CI-CD-for-Machine-Learning---VmlldzozNzk2NDg2</a></li><li>Weights and Bias MLOPs CI/CD course; Source: <a href="https://www.wandb.courses/courses/take/ci-cd-for-machine-learning/lessons/42949182-learning-objectives">https://www.wandb.courses/courses/take/ci-cd-for-machine-learning/lessons/42949182-learning-objectives</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44341e4aaa41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A step-by-step approach to understanding the fundamentals of DBSCAN algorithm in under 4mins.]]></title>
            <link>https://medium.com/@amaboh/a-step-by-step-approach-to-understanding-the-fundamentals-of-dbscan-algorithm-in-under-4mins-11c18db808af?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/11c18db808af</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[dbscan]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Thu, 11 May 2023 12:02:51 GMT</pubDate>
            <atom:updated>2023-05-11T12:02:51.915Z</atom:updated>
            <content:encoded><![CDATA[<p>While in the real world is easy to perceive clusters of different shapes and sizes within different clusters but not so easy nor intuitive for computers and this is where a technique like DBSCAN comes in handy. In a nutshell that is what DBSCAN aims to achieve and if you’ve understood that, then there’s no need to read this article anymore, you can go chill, watch a movie or do whatever you wish to do. We covered DBSCAN in just 10 seconds, depending on how fast you read the previous sentence. Spoiler alert, I hate to break this to you, but if it was that easy they would not have been over a thousand articles on the internet seeking to explain DBSCAN. However, in trying to make the complex, easy, and elegant we need to abstract the maths and statistics so you don’t fall asleep before even trying to figure out this algorithm implements the maths behind it.</p><p>It’s important that before we try to define the concept of DBSCAN, let’s explore some use cases of this algorithm that you may have come across but somehow did not know you were actually interacting with DBSCAN or it was “monsieur” DBSCAN who was given you a great browsing experience when interacting with X or Y product on your mobile phone or web.</p><p><strong>Use Cases of DBSCAN algorithm.</strong></p><p>We would look some of the popular use cases of DBSCAN algorithm in which we interact on a daily basis with, though they several other uses cases which you can explore later. We later on proceed to have a guide of when to use DBSCAN algorithm, but for we would explore three popular use cases of DBSCAN by listing them below.</p><ul><li><strong><em>Marketing:</em></strong> Most marketing ads and campaigns which make use of customer analytics to target different customer segments for a product with different types such as consumer goods make use of DBSCAN to group customers in different groups or categories based on their different attributes of the customer and this is always linked to <strong>customer segmentation</strong> and differentiated targeting. So each time you see different Pepsi-soda or Colgate toothpaste ads, just know behind the scene DBSCAN properly played a role in identifying the different segments to make these ads catchy and appealing to the different personas you see in the ad.</li><li><strong><em>E-commerce recommendation: </em></strong>When we interact with e-commerce platforms and see products recommendation each time we open these platforms or like on the popular e-commerce giant Amazon when we see recommendations to buy together with other products suggested. This is most likely DBSCAN clustering products of similar types bought by customers likely in the same cluster like yourself based on client and product features.</li><li><strong><em>Fraud detection:</em></strong> At some point in our life or in our social circles we’ve encountered situations where you’ve been contacted by your bank or financial institution informing you about a theft attempt on your account or experiencing your account being blocked for suspicion of fraudulent activities. This is likely DBSCAN at play helping to keep your money safe from theft when it detects <strong>abnormal activities</strong> on your account.</li></ul><p>When we analyze the first two cases listed above in Marketing and e-commerce recommendation we observe that what both have in common is the difficulties to draw a straight line between different groups or clusters and in the third case we observe an abnormal effect from your previous transactions which lets to an outlier aka fraud detection. This is the “clairvoyance” power of the DBSCAN algorithm and its essence, in its ability to spot patterns of high density in space vectors against those of low density. If the previous statement sounds gibberish, just re-read it the second, pause and think for a second time and we would come back to it. So this was a long blah blah about DBSCAN, so let’s define DBSCAN now that you have some background context in mind already to you can piece together some of the building blocks from this previous paragraphs.</p><p><strong>What is DBSCAN then?</strong></p><p>DBSCAN stands for Density-Based Spatial Clustering Application with Noise which is an unsupervised machine learning algorithm that clusters features of high density from clusters with low density. The DBSCAN algorithm groups feature into different clusters based on 3 main points.</p><ul><li>Core point: This is a point that is used as the center of attention to determine a cluster and is determined by the algorithm which forms a cluster around this point in a circular manner. Thus it must contain a certain minimum number of points from a certain minimum number of points around its epislon radius.</li><li>Border point: This is not a core point and is the number of points within the radius of the core point and is user-defined.</li><li>Noise points: These are points that do fall within the core points and the border points and can be perceived as outliers because there are no means to cluster these points.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCuaBpO_1TjK4HxRpCOUKw.png" /><figcaption>Photo Credit: Shot by author</figcaption></figure><p>In the diagram above A is a core point and has 4 min points within its radius (including the point itself), this forms a cluster. Points within the radius are border points whereas points B and C are reachable but not by any core points and thus belong to no cluster. However, point N belongs to no cluster and is out of reachable by any core point, making it a Noise Point.</p><p><strong>How DBSCAN works:</strong></p><p>With the definition of various components that make up the DBSCAN algorithm, we can now explore how DBSCAN maps clusters taking into consideration the definitions from the previous paragraph.</p><p>Features are assigned clusters based on two hyper-parameters.</p><ul><li>Epsilon which is the radius from an nth nearest neighbor where n is the min points</li><li>Min points are the least amount of points around the core point, which serve as the basis of cluster formation.</li></ul><p>Thus looking at the example below, where we have company financial data for various companies we would use just two metrics, revenue, and market capitalization of different companies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qtvs56vSrvSOwzDyGtMGYA.png" /><figcaption>Photo Credit: Shot by author</figcaption></figure><p>It’s obvious to our naked eyes that we have two clusters as we can observe the difference between groups of companies in blue and those in red. As Earlier noted at the beginning of the articles nested clusters are easily perceived by human eyes on a 2 dimension space, but this is not the case for a computer, and if we used an algorithm like hierarchical clustering (to be converted in the next article, then we would end up with something like this below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YE243QK7eI4zN9wB9OWV4Q.png" /><figcaption>Photo Credit: Shot by author</figcaption></figure><p>Thus imagine if we need to add a third axis say cash flow from investment and even a fourth feature like Net profit, this becomes a daunting task for a computer and this is where DBSCAN comes in handy. It is very useful for clustering nested clusters within high-dimensional space we can have a figure like the one below with just clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCgjAb9lpSzSAmyjAkfyrw.png" /><figcaption>Photo Credit: Shot by author</figcaption></figure><p><strong>When should we use DBSCAN?</strong></p><p>DBSCAN should be used when we do not have a particular outcome in mind, but wish to identify patterns in our dataset and ideally, all features are numeric. Thus let&#39;s examine some of the positive characteristics of DBSCAN</p><p><strong>Positive use cases of DBSCAN</strong></p><ul><li>It has a strong ability to handle irregularly shaped and sized clusters in any shape.</li><li>It has a robust ability to spot multiple outliers that are entirely excluded.</li><li>Clusters are auto-determined thus reducing timing in tuning parameters especially when we have no intuition on the characteristic of the dataset.</li></ul><p><strong>Negative use cases of DBSCAN</strong></p><ul><li>It is difficult to incorporate categorical data given it works well with numerical data.</li><li>It is very sensitive to scale like many clustering algorithms, which means variables need to be rescaled if they are on a different scale.</li><li>It performs poorly with high-dimensional data, and as the number of features increases it tends to degrade in performance.</li></ul><p>With the following advantage and disadvantages of DBSCAN listed above, we can observe that DBSCAN would be ideal when we have a dataset we perceive has an irregular shape and outliers, and we wish to detect anomalies.</p><figure><img alt="1*tc8uf h0nqquflc8 0uinq" src="https://cdn-images-1.medium.com/proxy/1*tc8UF-h0nQqUfLC8-0uInQ.gif" /><figcaption><a href="https://www.digitalvidya.com/blog/the-top-5-clustering-algorithms-data-scientists-should-know/">DBSCAN in action</a></figcaption></figure><h3>How to interpret the results of DBSCAN?</h3><p>DBSCAN is a density-based clustering algorithm that identifies clusters as dense regions in the data space, separated by regions of lower density of points. The results of DBSCAN can be interpreted by analyzing the clusters it identifies. Each cluster is defined by a set of core points, which are points that have at least a minimum number of other points within a specified distance (eps). Points that are not core points but are within the specified distance of a core point are considered border points, and points that are not core points and are not within the specified distance of a core point are considered noise points. The number of clusters identified by DBSCAN is not predetermined, and the algorithm can identify clusters of arbitrary shapes. However, determining an appropriate distance of neighborhood (eps) is not easy and requires domain knowledge</p><p>To evaluate the quality of DBSCAN clustering results, there are different methods that can be used. One way is to use internal and external indices. Internal indices measure the quality of clustering results based on the data itself, while external indices measure the quality of clustering results based on external information, such as class labels. Some examples of internal indices include CDbw (Composing density between and within clusters), the Silhouette coefficient, and the Davies-Bouldin index. Another way to evaluate the quality of DBSCAN clustering results is to compare them with the results of other clustering algorithms, such as K-means. It is important to note that the evaluation of clustering results is not always straightforward, and the choice of evaluation method depends on the specific problem and data set</p><p>References:</p><ul><li>DBSCAN: Density-Based Clustering Essentials: <a href="https://www.datanovia.com/en/lessons/dbscan-density-based-clustering-essentials/">https://www.datanovia.com/en/lessons/dbscan-density-based-clustering-essentials/</a></li><li>Explaining DBSCAN clustering: <a href="https://towardsdatascience.com/explaining-dbscan-clustering-18eaf5c83b31">https://towardsdatascience.com/explaining-dbscan-clustering-18eaf5c83b31</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11c18db808af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The beauty of Principal Component Analyses, the ML technique of making complex things simple]]></title>
            <link>https://medium.com/@amaboh/the-beauty-of-principal-component-analyses-the-ml-technique-of-making-complex-things-simple-a6b082f0c7d8?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6b082f0c7d8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[quant-finance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pca-analysis]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 00:13:03 GMT</pubDate>
            <atom:updated>2023-02-20T00:13:03.989Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is aimed at making Principal Component Analyses mostly abbreviated as PCA easy to understand and have a mental model to know when to use it and how to use this beautiful technique. I feel there&#39;s a need to approach this from a top-down approach rather than a bottom-up approach which dives straight into defining PCA and then explaining its use before giving problems and use cases. Thus, I’ll start with the use cases of PCA in modern-day applications which surround us on a daily basis and use an analogy of a forest to drive the point home, sounds interesting! Hold on tight we’re in for a long ride.</p><p>If after reading the forest analogy to explain PCA and you’re able to grasp the core concept, then you can skip reading the rest of the article and go to the implementation part of PCA using a finance case to implement a stock portfolio that can beat the S&amp;P500 returns, but first let’s look at some instances in our life where we’ve encountered or used PCA.</p><h4>Use cases of PCA in real-life applications</h4><ol><li>Facial recognition: Gotha! Oh yes, each time you watch a movie with the FBI scene using CCTV camera’s to detect a criminal or hero-like character like the Professor in the popular Netflix show Casa the Papel, PCA was at play. Since PCA reduces the dimensions of data associated with facial features it enables easy recognition of faces in videos and buzz.</li><li>Network traffic visualization: Gotha the second time! We all use google maps and other navigation apps on our phones when we’re running late for work, school, or a date. Well, that’s PCA at play helping you to easily visualize the network traffic by reducing the dimensionality of network traffic and buzz.</li><li>Image compression: Gotha the third time! Do you remember the last time you had to upload your picture to a website requiring a maximum size, or in the early days of most messaging apps where you had to compress pictures to send to a friend? Well, that was PCA behind the scene making that magic happen, so you reduce the size of the picture and not lose quality. This is done by reducing the image dimensions from a realistic example of 4096 dimensions to 100 and buzz.</li></ol><p>Now that we have vivid illustrations of some of the day-to-day use cases in which we utilized PCA intentionally or unintentionally it would be good to test your analytical mindset to see if you notice a pattern that kept repeating in the three previous examples. Look closely at one theme which kept recurring throughout the 3 previous examples. Ok, I’ll give you a hint, with the word buzz!</p><p>Some of you guys spotted it and yes it is dimensionality reduction worded differently with buzz at the end of such phrases.</p><p><strong>So what is dimensionality reduction?</strong></p><p>This is at the heart of PCA and explains the why and what of PCA. If you’ve been around many Data scientists with a heavy math background you must have come across the buzz phrase “curse of dimensionality”, and it sounded like some other Data science jargon that you didn’t want to dig into. Well without trying to bore you with a heavy explanation of dimensionality and vector space, it comes down to the fact that having too many features in your dataset turns to produces a lot of noise by affecting the accuracy and training time of the machine learning model.</p><p>To drive the point home let’s use the forest analogy where we take a walk into a big forest and a chopper is used to fly over the forest and we’re told to separate the trees from the forest. Well, I know you’ve heard of this term term “separating the trees from the forest”. However, it was important to have this visual understanding so that as you think about this and realize how difficult it is for your frontal lobe to process this information and almost crash with a nap, this is the same logic that applies with a computer in trying to process too many features to determine the output variable. Thus trying to make sense of a complex situation not actually complex per se but with many attributes which make it complex, PCA comes in like our favorite superhero Thor to the rescue so we can have clarity and make sense of identifying the principal components and how principal components affect the target variable, thus separating the trees from the forest. If you read this far I believe we can now dive into some technical depths of what is PCA when to use it, and how to use it but before let&#39;s recap on the why of PCA.</p><p><strong>Why use PCA?</strong></p><ul><li>You are analyzing a data set with too many attributes, and you find it extremely difficult to visualize the data. Thus to eliminate the “curse of dimensionality” call our Thor to the rescue.</li><li>To improve the efficiency/performance of a model by reducing training time because a higher number of features in a data set has a negative effect on the accuracy and is positively correlated with the training time required to train the machine learning model.</li></ul><p><strong>What is PCA?</strong></p><p>Principal Component Analysis is an unsupervised pre-processing task for dimensionality reduction which extracts principal features using “orthogonal linear transformation” which is a fancy mathematical word used to say that this data is transformed from high dimensional space into low dimension space, enabling the transform data to retain some core properties of the original data. Thus using PCA “<em>we apply orthogonal transformation which makes correlated variables uncorrelated</em>”, keep this in mind as we go along. Let us try and go deeper for clarity by examining a two-dimensional dataset where each feature is represented by a column.</p><p>I’ll be using a pen and paper to illustrate this and to make things simple, though my handwriting may be bad I hope the illustrations can help you make sense of how PCA works.</p><p>Using our two-dimensional dataset. We can represent each feature in the following matrix with feature columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3WiaGd9ehsHitqbyMczZA.jpeg" /><figcaption>shot with iPhone- image credit to author</figcaption></figure><p>From the table above with our feature columns, we can plot the following hypothetical scatter slot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLShcIDpux3k6CyTZYDMfQ.jpeg" /><figcaption>shot with iPhone- image credit to author</figcaption></figure><p>Using PCA we’re able to derive such principal components from our dataset that describes the data points with a set of principal components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1n_e9HhhkvYZkQZjGvfRPg.jpeg" /><figcaption>shot with iPhone- image credit to author</figcaption></figure><p>Thus we can see that our principal components that which are not randomly chosen, but computed to explain the greatest amount of variance in our dataset. The first Principal component in red is computed such that it reflects the greatest amount of variance in the original features, while the second component is orthogonal (lies at 90 degrees to the first component) to the first, and explains the second greatest amount of variance to the first principal component.</p><p>I hope you are now able to connect some dots at this point, remember in the opening paragraph of this section when I said keep this in mind when I said to keep this in mind as we go along? Well if you did not then I’ll scroll back up and read that sentence again, bingo now you can connect the dots. This was the phrase “<em>we apply orthogonal transformation which makes correlated variables uncorrelated</em>”. In our first scatter plot, we see that there is clearly a correlation but after applying PCA we see that the two lines show no correlation. This is the simple mathematical force at play behind PCA using Eigen values and Eigen vectors to project high-dimensional data into lower dimensions. To get graphs of the maths behind you can revise your basic <a href="https://www.khanacademy.org/math/linear-algebra"><em>linear algebra</em></a><em> </em>by simply revising <a href="https://www.khanacademy.org/math/linear-algebra/vectors-and-spaces/vectors/v/vector-introduction-linear-algebra#:~:text=A%20vector%20is%20a%20quantity%20or%20phenomenon%20that%20has%20two,%2C%20electromagnetic%20fields%2C%20and%20weight."><em>vectors</em></a> and checking out<a href="https://www.mathsisfun.com/algebra/eigenvalue.html"> <em>Eigenvectors</em></a><em>.</em></p><p>What PCA enables us to do is represent the original data feature vectors, by representing the data as linear combinations of principal components. Thus, the principal component is the equivalent of the linear transformation of data from feature1 x feature2 axis to PCA1 x PCA2 axis.</p><p>You may be wondering why go through all this, well in our little example above we have just 2 features and it’s just a 2-dimensional space so it’s obviously a waste of time, and yes my friend you are right. However, in a very large dataset in which we have like 80 to 100 different features, you can imagine the complexity of interpreting this spaghetti-like dataset. Thus principal components remove the noise by reducing a large number of features to just a couple of principal components like a mechanic disassembling a car into the principal components. In a nutshell, Principal components are orthogonal projections of data onto lower dimensional space.</p><p><strong>When to use PCA?</strong></p><ul><li>When we observe covariance between variables and multicollinearity between features.</li><li>When we have a lot of input variables or features and wish to de-noise our data.</li><li>To visualize multidimensional data by reducing the number of dimensions.</li></ul><p><strong>How do we calculate PCA?</strong></p><p>While this section aims to walk you through a set-by-set calculation to aid your understanding when implementing PCA in your machine learning model, it is important to note that in the real life or on the job you would most likely be using a library such as Skilearn in Python. If you already have an intuition of how this is done you can skip this section can jump straight to the implementation phase where I use Jupyter notebook as my IDE on a financial dataset.</p><ol><li><strong>Standardizing features: </strong>We standardize features to have a common unit of measure between features for example a financial dataset having variables with some units of 1000 (thousands) and another variable in 10⁹ (billions) this would result in the larger variable having a more dominating effect on the model. Thus we standardize to have uniform and consistent data with lesser effects of extraneous/inconsistent data and ensure our machine learning algorithm is not sensitive to scale data. Using standardization we have a mean of 0 and a variance of 1.</li><li><strong>Calculate the covariance matrix:</strong> Recall that our dataset assumes multicollinearity which is a derivation of covariance divided by the square root of the standard deviation of the two features. The covariance matrix is a square matrix, of d x d dimensions, which represents the feature columns but we use d to another for dimensions. This illustrates the pairwise correlation between features.</li><li><strong>Compute the Eigenvectors and Eigenvalues from the covariance matrix: </strong>We calculate the Eigenvectors and their associated Eigenvalues of the covariance matrix. Due to the fact that we do not which to go into any mathematical calculations and try to abstract the mathematical equations we do go into the equation here since we want to keep things short but it would valuable to revise the basics of <a href="https://www.khanacademy.org/math/linear-algebra"><em>algebra</em></a>.</li><li><strong>Sort the Eigenvectors in descending order using Eigenvalues: </strong>At this stage, we use Eigenvectors to determine the principal components by simply putting the Eigenvector with the highest eigenvalue as the first principal component, followed by the next highest Eigenvector with the second highest Eigenvalue as the second principal component and so on and so forth till the last one. Thus eigenvalues are used to measure the amount of shared variance and the higher the eigenvalues the greater the amount of shared variance explained, the reason for the sorting in descending of explainability of shared variance.</li><li><strong>Select the number of principal components:</strong> Here we simply select the top number of components by choosing the Eigenvectors which would represent our Principal components.</li></ol><p><strong>Hands-on using PCA on a financial dataset.</strong></p><p>I have a preference for financial data because it is easy to get and my personal bias toward finance is because I have a background in finance. So, we would be aiming to construct a portfolio from the S&amp;P 500 index. The link to the code would be provided at the end of this article.</p><p>I’ll be using Jupyter notebook but you can just use google collab for a quick try</p><ul><li>The first portion of this code is uses the save_500_ticker function to scrape the S&amp;P 500 list from Wikipedia utilizing Beautiful Soup, and the prices are gotten from the Yahoo Finance library.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJM_I3hZvK85Cov9PnZ5sQ.png" /></figure><p>The daily returns are then calculated using logarithmic returns and plotted.</p><p>We then proceed to use PCA from SkLearn to calculate the first principal component of the daily returns. This is done after handling missing values with 0 because PCA doesn’t work with NaN values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9sDE0adkBVrvBt0Jbrw1Q.png" /><figcaption>screen shot- image credit to author</figcaption></figure><p>We then proceed to construct a portfolio based on the weightings from the first principal component by extracting the weights of the stocks in the portfolio by using the absolute value of the first Principal component, normalizing the values, and dividing by the sum of absolute values. We then proceed to construct our portfolio by taking the weighted average of daily returns of stocks, and the normalized absolute value of the first principal component act as our weightings. Recall the first principal component explains the greatest amount of variance followed by the second.</p><p>We proceed to plot the cumulative returns of the constructed PCA portfolio which is compared to the S&amp;P 500 cumulative returns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZlArO4h-kSXDS8hLgTykA.png" /><figcaption>screen shot- image credit to author</figcaption></figure><p>We proceed to plot the stocks with the highest and lowest weights in the first principal component, compared to the cumulative returns of the S&amp;P500 index for the top 10 stocks in the first principal component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xK2rPoVKx5VuvPx7DgGEwQ.png" /><figcaption>screen shot- image credit to author</figcaption></figure><p>Although <strong>PCA offers multiple benefits</strong> such as easy computation (because it is based on linear algebra), acceleration for other ML algorithms because ML algorithms are faster when trained on Principal components than huge datasets, and PCA counteracts the problem of high-dimensional data which is overfitting (when data does well on training data but poorly on testing data). <strong>The flaws and disadvantages</strong> of PCA are the low interpretability of principal components and the trade-off between information loss and dimensionality reduction.</p><p><strong><em>Bonus(for self-declared financial nerds like myself).</em></strong></p><p>We can then proceed to do some fundamental analyses of the top stocks from the PCA portfolio by utilizing their financial statements. We can do so using my favorite financial research terminal OpenBB terminal, which is an alternative open-source and free financial research software. You can download it <a href="https://openbb.co/products/terminal"><em>here</em></a> if you wish to try this for yourself and follow along or explore.</p><p>If you are on Mac after installing OpenBB</p><ul><li>Press cmd + space and type OpenBB</li><li>Type “stock” in the terminal</li><li>Type “ca” in the terminal</li><li>Type “set CZR,NCLH,CCL,RCL,LNC,APA,TRGP,MGM,UAL,DXC” in the terminal [list of stocks from top10 PCA portfolio after using print(pc1.nsmallest(10)].</li><li>Type “cashflow” to see the cashflow statement or “income” for income statement</li><li>Happy Exploration!</li></ul><p>If you are using the OpenBB terminal to follow along then you should have something similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lC8H4h4TCI_Cszt9cQU7Tw.png" /><figcaption>screen shot- image credit to author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVY2Gp1gsNT7sWkunaZvyA.png" /><figcaption>screen shot- image credit to author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddj0kpPdsSZtSZSiyYojQg.png" /><figcaption>screen shot- image credit to author</figcaption></figure><p><em>Disclaimer: This article is for educational purposes only and should not be used as financial advice or strategy. Investing in the stock market is very risky and it is advised to seek advice from a financial advisor or accredited individuals before making any investment or following a particular strategy.</em></p><p><a href="https://github.com/amaboh/Machine_learning_in_finance"><em>Link to Github code base.</em></a></p><p><em>Get in touch with me on</em><strong><em> </em></strong><a href="https://www.linkedin.com/in/amaboh-achu-ngu-23333a9a/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6b082f0c7d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Hadoop with Homebrew on Mac M1 and M2 when Java already exists locally.]]></title>
            <link>https://medium.com/@amaboh/installing-hadoop-with-homebrew-on-mac-m1-and-m2-when-java-already-exists-locally-878ec5bfd414?source=rss-84831e473140------2</link>
            <guid isPermaLink="false">https://medium.com/p/878ec5bfd414</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[AMA]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 23:14:34 GMT</pubDate>
            <atom:updated>2023-01-31T16:15:55.007Z</atom:updated>
            <content:encoded><![CDATA[<p>Installing Hadoop may seem straightforward with many tutorials already covering this technology. So why write about this, well as the title says “WHEN JAVA ALREADY EXISTS!”, thus this is what this article is all about because it shows and explains a step-by-step approach to getting Hadoop working on your system.</p><p>You may be asking yourself don’t you need Java to use Hadoop, yes that’s right. However, this is where the problem arises because when you use the command %brew install Hadoop in the terminal, one of the dependencies installed by Hadoop is the Java OpenJDK (Java Development Kit), and this would lead to conflicts between the Java you had installed in your system and the OpenJDK dependency of Homebrew and this leads to conflicts between different versions of Java in your system.</p><p>When I was writing this article my presumption was many people who faced this problem have some background knowledge about the terminal and have Homebrew installed. However, when I was working with a couple of friends to have their system set up for Hadoop one day after I started writing this article, I realized none of them had Homebrew. So to keep things simple, this article would be divided into two parts, the first part focus on prerequisites. However, if you came here because you faced the challenge mentioned in the heading, then please go to the core problem part of this article.</p><h4><strong>Prerequisite</strong></h4><ol><li>Install Homebrew, but you may be asking what is Homebrew and why you need it. Well, Homebrew is a package manager and as mentioned on Homebrew’s website “Homebrew installs <a href="https://formulae.brew.sh/formula/"><strong>the stuff you need</strong></a> that Apple (or your Linux system) didn’t.” I’ll advise you to open their website and read <a href="https://brew.sh/">more</a>, but to get it on your system, run the following command on your terminal.</li></ol><pre>$ /bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><p>Use these commands to add homebrew on your bash_profile</p><pre>$ echo &#39;eval &quot;$(/opt/homebrew/bin/brew shellenv)&quot;&#39; &gt;&gt; /Users/&lt;username&gt;/.bash_profile<br><br>$ eval &quot;$(/opt/homebrew/bin/brew shellenv)&quot;</pre><p>2. Install SSH key, you would be using this to authenticate to Hadoop and sign in. It’s a security protocol for creating new authentication key pairs for SSH.</p><pre>$ ssh-keygen -t rsa -P&#39;&#39; -f ~/.ssh/id_rsa</pre><pre>$ cat ~/.ssh/id_rsa.pub &gt;&gt; ~/.ssh/authorized_keys</pre><p>Before we go to the core problem run the following commands on the terminal to verify which packages and applications we have on our system.</p><pre>$ java -version<br>$ hadoop version</pre><p>If you realized you have Java installed then you would have to reconsider uninstalling it and if you have Hadoop that’s also good. However, if you don’t have Hadoop then proceed with the commands below and continue to code with Ajun&#39;s medium article where he does a great job explaining how to install Hadoop.</p><p>3. Install Hadoop. To Hadoop and run it on your system run the following commands.</p><pre>$ brew install hadoop</pre><p>Please continue the configuration by following the steps in this Medium article with code with<a href="https://codewitharjun.medium.com/install-hadoop-on-macos-efe7c860c3ed"> <em>Ajun</em></a><em>, </em>as mentioned earlier I believe he does a great job explaining the configuration from scratch, so you can continue from step 2 onwards.</p><p>However, let&#39;s proceed to the heart of the problem which can be identified on the screen below which is the reason you decided to read this article.</p><p><strong>Problem Statement:</strong> If you proceed to install Hadoop with brew install Hadoop as explained above, it would download OpenJDK which is one of the dependencies of Hadoop. This is where the problem arises because they would be a conflict between the Java installed on your machine and that downloaded by Hadoop or OpenJDK. Thus if you read a couple of web blogs on the web on how to set up Hadoop Mac like that of code with <a href="https://codewitharjun.medium.com/install-hadoop-on-macos-efe7c860c3ed"><em>Ajun</em></a><em> </em>and you are wondering why you’re seeing this error message in red from the screen below. My dear friend you’ve come to the right place, so let&#39;s proceed to debug this core problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PShcg9e5MRVI4A6ICuFI9w.png" /></figure><p>We would proceed to solve this problem in the following sequence.</p><h4><strong>Debug Core Problem:</strong></h4><ol><li>Uninstall Java first. However, you may not know the JDK version on your system you can check this by typing the following command.</li></ol><pre>$ /usr/libexec/java_home </pre><p>It would produce a path for your java home and you would be able to see the JDK version appended like this “JDK@8.x.y”.</p><p>Run the following commands to uninstall Java and take note of the first line with the JDK version from the previous command so you can adjust per your JDK version.</p><pre>sudo rm -rvf /Library/Java/JavaVirtualMachines/jdk&lt;version&gt;.jdk<br>sudo rm -rvf /Library/PreferencePanes/JavaControlPanel.prefPane<br>sudo rm -rvf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin<br>sudo rm -rvf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist<br>sudo rm -rvf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper<br>sudo rm -rvf /Library/LaunchDaemons/com.oracle.java.JavaUpdateHelper.plist<br>sudo rm -rvf /Library/Preferences/com.oracle.java.Helper-Tool.plist</pre><p>2. Create a symlink for Java. Because you already have OpenJDK which is a dependency of Hadoop, but your system is ignorant of that aware of that because it&#39;s default path is /Library/Java/JavaVirtualMachines/openJDK&lt;version&gt;. Thus you need to kind of inform your machine of the path by creating a symlink that helps your machine locate Java considering you uninstalled it. To know more about symlinks you can read more at <a href="https://www.howtogeek.com/297721/how-to-create-and-use-symbolic-links-aka-symlinks-on-a-mac/"><em>HowToGeek. </em></a>Use the following command to create a symlink and please take note of your OpenJDK version.</p><pre>$ sudo ln -sfn $(brew --prefix)/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk</pre><p>3. Update your JAVA HOME path in your Hadoop-env.sh folder using VS code or editor of choice.</p><pre> cd /opt/homebrew/Cellar/hadoop/3.3.4/libexec/etc/hadoop<br>$ code hadoop-env.sh</pre><p>If you do not have VS code download it from this <a href="https://code.visualstudio.com/download"><em>link</em></a><em>.</em> Once you have it installed then use CTRL + SHIFT + P and type code to activate the code command to open VS code from the terminal and retype the code command above.</p><p>Once in the Hadoop-env.sh file change the path to the export JAVA_HOME to the path of your Hadoop file.</p><p>check your hadoop file by typing this</p><pre>$ /usr/libexec/java_home  </pre><p>Proceed by copying this to update your path and it should look like the path below</p><pre>export JAVA_HOME=/opt/homebrew/Cellar/openjdk@11/11.0.18/libexec/openjdk.jdk/Contents/Home</pre><p>Don’t forget to press CTRL + S to save and like me still go to file and click save lol. Let’s proceed to check if this is working.</p><p>Back in the terminal type the following</p><pre>$ echo JAVA_HOME</pre><p>If you get the same path, congratulations your good to go and can proceed by stopping all nodes, formatting name nodes and starting all nodes. Ok let’s just do it</p><p>Run the following commands one after the other</p><pre>stop-all.sh<br>jps #checks running nodes<br>hdfs namenode -format<br>start-all.sh<br>hadoop fs -mkdir /hadoop-test-files<br></pre><p>To check if all is good and running use this link to access the Hadoop UI at <a href="http://localhost:9870/">http://localhost:9870</a>, and click on the top right-hand Utilities drop-down arrow and choose “browse the file system”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FiqvSxpCQKRbdUJsHP07yw.png" /></figure><p>Youpi you can now see the file hadoop-test-files and it’s all green, congratulations you’re now on your way to becoming a Hadoop badass BigData Ninja. I hope this was helpful and if you need any clarification reach out to me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZ1n1y3XCwyAFWZukzVEFw.png" /></figure><p>I’ll also do a follow-up article on how to write a Hadoop and MapReduce application in IntelliJ.</p><p>Until next time happy keystroking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=878ec5bfd414" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>