<?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 Philipp Brunenberg on Medium]]></title>
        <description><![CDATA[Stories by Philipp Brunenberg on Medium]]></description>
        <link>https://medium.com/@philipp.brunenberg?source=rss-6edbaee01d5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sL78jne2kugaH_OTIvdEaA.jpeg</url>
            <title>Stories by Philipp Brunenberg on Medium</title>
            <link>https://medium.com/@philipp.brunenberg?source=rss-6edbaee01d5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:56:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@philipp.brunenberg/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[HashGNN: Deep-dive into Neo4j GDS’s new node embedding algorithm]]></title>
            <link>https://medium.com/data-science/hashgnn-deep-dive-into-neo4j-gdss-new-node-embedding-algorithm-5ce9c3029a5c?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ce9c3029a5c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[graph-data-science]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 18:48:24 GMT</pubDate>
            <atom:updated>2023-08-10T18:48:24.556Z</atom:updated>
            <content:encoded><![CDATA[<h3>HashGNN: Deep Dive into Neo4j GDS’s New Node Embedding Algorithm</h3><h4>In this article, we will explore alongside a small example how HashGNN hashes graph nodes into an embedding space.</h4><p>If you prefer watching a video on this, you can do so <a href="https://youtu.be/fccFuyjNEcM">here</a>.</p><p>HashGG (#GNN) is a node embedding technique, which employs concepts of Message Passing Neural Networks (MPNN) to capture high-order proximity and node properties. It significantly speeds-up calculation in comparison to traditional Neural Networks by utilizing an approximation technique called MinHashing. Therefore, it is a hash-based approach and introduces a trade-off between efficiency and accuracy. In this article, we will understand what all of that means and will explore along a small example how the algorithms works.</p><h3>Node Embeddings: Nodes with similar contexts should be close in the embedding space</h3><p>Many graph machine learning use-cases like link prediction and node classification require the calculation of similarities of nodes. In a graph context, these similarities are most expressive when they capture (i) the neighborhood (i.e. the graph structure) and (ii) the properties of the node to be embedded. Node embedding algorithms project nodes into a low-dimensional embedding space — i.e. they assign each node a numerical vector. These vectors — the embeddings — can be used for further numerical predictive analysis (e.g. machine learning algorithms). Embedding algorithms optimize for the metric: Nodes with a similar graph context (neighborhood) and/or properties should be mapped close in the embedding space. Graph embedding algorithms usually employ two fundamental steps: (i) Define a mechanism to sample the context of nodes (Random walk in node2vec, k-fold transition matrix in FastRP), and (ii) subsequently reduce the dimensionality while preserving pairwise distances (SGD in node2vec, random projections in FastRP).</p><h3>HashGNN: Circumvent training a Neural Network</h3><p>The clue about HashGNN is that it does not require us to train a Neural Network based on a loss function, as we would have to in a traditional Message Passing Neural Network. As node embedding algorithms optimize for “similar nodes should be close in the embedding space”, the evaluation of the loss involves calculating the true similarity of a node pair. This is then used as feedback to the training, how accurate the predictions are, and to adjust the weights accordingly. Often, the cosine similarity is used as similarity measure.</p><p>HashGNN circumvents the model training and actually does not employ a Neural Network altogether. Instead of training weight matrices and defining a loss function, it uses a randomized hashing scheme, which hashes node vectors to the same signature with the probability of their similarity, meaning that we can embed nodes without the necessity of comparing nodes directly against each other (i.e. no need to calculate a cosine similarity). This hashing technique is known as MinHashing and was originally defined to approximate the similarity of two sets without comparing them. As sets are encoded as binary vectors, HashGNN requires a binary node representation. In order to understand how this can be used to embed nodes of a general graph, several techniques are required. Let’s have a look.</p><h3>MinHashing</h3><p>First of all, let’s talk about MinHashing. MinHashing is a locality-sensitive hashing technique to approximate the Jaccard similarity of two sets. The Jaccard similarity measures the overlap (intersection) of two sets by dividing the intersection size by the number of the unique elements present (union) in the two sets. It is defined on sets, which are encoded as binary vectors: Each element in the universe (the set of all elements) is assigned a unique row index. If a particular set contains an element, this is represented as value 1 in the respective row of the set’s vector. The MinHashing algorithm hashes each set’s binary vector independently and uses K hash functions to generate a K-dimensional signature for it. The intuitive explanation of MinHashing is to randomly select a non-zero element K times, by choosing the one with the smallest hash value. This will yield the signature vector for the input set. The interesting part is, that if we do this for two sets without comparing them, they will hash to the same signature with the probability of their Jaccard similarity (if K is large enough). In other words: The probability converges against the Jaccard similarity.</p><figure><img alt="The Jaccard similarity measures the similarity of two sets. Generally, sets can also be encoded as binary vectors. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*6BCavX5pY8b159BV.png" /><figcaption>The Jaccard similarity measures the similarity of two sets. Generally, sets can also be encoded as binary vectors. Image by author.</figcaption></figure><p>In the illustration: Example sets s1 and s2 are represented as binary vectors. We can easily compute the Jaccard similarity by comparing the two and counting the rows where both vectors have a 1. These are quite simple operations, but the complexity resides in the pair-wise comparison of vectors if we have many vectors.</p><figure><img alt="The MinHashing algorithm generates k permutations of the set features and selects the feature with the smallest hashing value to create the minHash signature vector. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*IKkebFmF3wIwnWVV.png" /><figcaption>The MinHashing algorithm generates k permutations of the set features and selects the feature with the smallest hashing value to create the minHash signature vector. Image by author.</figcaption></figure><p>Our universe U has size 6 and we choose K (the number of hash functions) to be 3. We can easily generate new hash functions by using a simple formula and boundaries for a, b and c. Now, what we actually do is to hash the indices of our vectors (1-6), each relating to a single element in our universe, with each of our hash functions. This will give us 3 random permutations of the indices and therefore elements in our universe. Subsequently, we can take our set vectors s1 and s2 and use them as masks on our permuted features. For each permutation and set vector, we select the index of the smallest hash value, which is present in the set. This will yield two 3-dimensional vectors, one for each set, which is called the MinHash signature of the set.</p><p>MinHashing simply selects random features from the input sets, and we need the hash functions only as a means to reproduce this randomness equally on all input sets. We have to use the same set of hash functions on all vectors, so that the signature values of two input sets collide if both have the selected element present. The signature values will collide with the probability of the sets’ Jaccard similarities.</p><h3>WLKNN (Weisfeiler-Lehman Kernel Neural Network)</h3><p>HashGNN uses a message passing scheme as defined in Weisfeiler-Lehman Kernel Neural Networks (WLKNN) to capture high-order graph structure and node properties. It defines the context sampling strategy as mentioned earlier for HashGNN. The WLK runs in T iterations. In each iteration, it generates a new node vector for each node by combining the node&#39;s current vector with the vectors of all directly connected neighbors. Therefore, it is considered to pass messages (node vectors) along the edges to neighboring nodes.</p><figure><img alt="The WLK runs in T iterations. In each iteration it passes node information along the edges to the neighboring nodes. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*DnWGUrXPBbQQF33g.png" /><figcaption>The WLK runs in T iterations. In each iteration it passes node information along the edges to the neighboring nodes. Image by author.</figcaption></figure><p>After T iterations, each node contains information of nodes at T hops distance (high-order). The calculation of the new node vector in iteration t essentially aggregates all neighbor messages (from iteration t-1) into a single neighbor message and then combines it with the node vector of the previous iteration. Additionally, the WLKNN employs three neural networks (weight matrices and activation function); (i) for the aggregated neighbor vector, (ii) for the node vector and (iii) for the combination of the two. It is a notable feature of the WLK that the calculation in iteration t is only dependent on the result of iteration t-1. Therefore, it can be considered a Markov chain.</p><figure><img alt="WLK: In each iteration each node vector gets updated with information from neighboring nodes. Therefore, after t iterations, each node contains information from nodes with t-hop distance. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*ctr57TgC33PWFAAb.png" /><figcaption>WLK: In each iteration each node vector gets updated with information from neighboring nodes. Therefore, after t iterations, each node contains information from nodes with t-hop distance. Image by author.</figcaption></figure><h3>HashGNN by example</h3><p>Let’s explore how HashGNN combines the two approaches to embed graph vectors efficiently to embedding vectors. Just like the WLKNN, the HashGNN algorithm runs in T iterations, calculating a new node vector for every node by aggregating the neighbor vectors and its own node vector from the previous iteration. However, instead of training three weight matrices, it uses three hashing schemes for locality-sensitive hashing. Each of the hashing schemes consists of K randomly constructed hashing functions to draw K random features from a binary vector.</p><figure><img alt="The HashGNN Algorithm: We initialize the node vectors with their binary feature vectors. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*qv2j5oZ36-oiHIEG.png" /><figcaption>The HashGNN Algorithm: We initialize the node vectors with their binary feature vectors. Image by author.</figcaption></figure><p>In each iteration we perform the following steps:</p><p><strong>Step 1: Calculate the node’s signature vector:</strong> Min-hash (randomly select K features) the node vector from the previous iteration using hashing scheme 3. In the first iteration the nodes are initialized with their binary feature vectors (we&#39;ll talk about how to binarize nodes later). The resulting signature (or message) vector is the one which is passed along the edges to all neighbors. Therefore, we have to do this for all nodes first in every iteration.</p><figure><img alt="HashGNN Step 1: in each iteration is to calculate the message vector for each node by using hashing scheme 3. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*32SnZjbSYOoFFtes.png" /><figcaption>HashGNN Step 1: in each iteration is to calculate the message vector for each node by using hashing scheme 3. Image by author.</figcaption></figure><p><strong>Step 2: Construct the neighbor vector:</strong> In each node, we’ll receive the signature vectors from all directly connected neighbors and aggregate them into a single binary vector. Subsequently, we use hashing scheme 2 to select K random features from the aggregated neighbor vector and call the result the neighbor vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zlTnVklWwhgJwD94.png" /><figcaption>HashGNN Step 2: We collect the message vectors from all neighbors and aggregate them. Image by author.</figcaption></figure><p><strong>Step 3: Combine node and neighbor vector into new node vector:</strong> Finally, we use hashing scheme 1 to randomly select K features from the node vector of the previous iteration and combine the result with the neighbor vector. The resulting vector is the new node vector which is the starting point for the next iteration. Note, that this is not the same as in step 1: There, we apply hashing scheme 3 on the node vector to construct the message/signature vector.</p><figure><img alt="HashGNN Step 3: We combine the min-hashed node vector with the aggregated neighbor vector to arrive at the resulting node vector for this iteration. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*EmGpbcI7J9EswRV5.png" /><figcaption>HashGNN Step 3: We combine the min-hashed node vector with the aggregated neighbor vector to arrive at the resulting node vector for this iteration. Image by author.</figcaption></figure><p>As we can see, the resulting (new) node vector has influence of its own node features (3 &amp; 5), as well as its neighbors’ features (2 &amp; 5). After iteration 1 the node vector will capture information from neighbors with 1 hop distance. However, as we use this as input for iteration 2, it will already be influenced by features 2 hops away.</p><figure><img alt="After the first iteration, the new node vector has influence from its own features and the neighboring node’s features. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*72osF_GgUzgsH13z.png" /><figcaption>After the first iteration, the new node vector has influence from its own features and the neighboring node’s features. Image by author.</figcaption></figure><h3>Neo4j GDS generalizations</h3><p>HashGNN was implemented by the Neo4j GDS (Graph Data Science Library) and adds some useful generalizations to the algorithm.</p><p>One important auxiliary step in the GDS is feature binarization. MinHashing and therefore HashGNN requires binary vectors as input. Neo4j offers an additional preparation step to transform real-valued node vectors into binary feature vectors. They utilize a technique called hyperplane rounding. The algorithm works as follows:</p><p><strong>Step 1: Define node features:</strong> Define the (real-valued) node properties to be used as node features. This is done using the parameter featureProperties. We will call this the node input vector f.</p><p><strong>Step 2: Construct random binary classifiers:</strong> Define one hyperplane for each target dimension. The number of resulting dimensions is controlled by the parameter dimensions. A hyperplane is a high-dimensional plane and, as long as it resides in the origin, can be described solely by its normal vector n. The n vector is orthogonal to the plane&#39;s surface and therefore describes its orientation. In our case the n vector needs to be of the same dimensionality as the node input vectors (dim(f) = dim(n)). To construct a hyperplane, we simply draw dim(f) times from a Gaussian distribution.</p><figure><img alt="Binarization of features: We use hyperplane rounding to construct binary features from real-valued input vectors. We use one random Gaussian classifier for each target dimension. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*gQHtM2C_Gpagtz2i.png" /><figcaption>Binarization of features: We use hyperplane rounding to construct binary features from real-valued input vectors. We use one random Gaussian classifier for each target dimension. Image by author.</figcaption></figure><p><strong>Step 3: Classify node vectors:</strong> Calculate the dot-product of the node input vector and each hyperplane vector, which yields the angle between the hyperplane and the input vector. Using a threshold parameter, we can decide whether the input vector is above (1) or below (0) the hyperplane and assign the respective value to the resulting binary feature vector. This is exactly what also happens in a binary classification — with the only difference that we do not iteratively optimize our hyperplane, but rather use random Gaussian classifiers.</p><figure><img alt="Using n hyperplanes leads to n-dimensional binary node signatures. Image by author." src="https://cdn-images-1.medium.com/max/1024/0*b8X6ff22gpRpQBN5.png" /><figcaption>Using n hyperplanes leads to n-dimensional binary node signatures. Image by author.</figcaption></figure><p>In essence, we draw one random Gaussian classifier for each target dimension and set a threshold parameter. Then, we classify our input vectors for each target dimension and obtain a d-dimensional binary vector which we use as input for HashGNN.</p><h3>Conclusion</h3><p>HashGNN uses locality-sensitive hashing to embed node vectors into an embedding space. By using this technique, it circumvents the computationally intensive, iterative training of a Neural Network (or other optimization), as well as direct node comparisons. The authors of the paper report a 2–4 orders of magnitude faster runtime than learning based algorithms like SEAL and P-GNN, while still producing highly comparable (in some cases even better) accuracy.</p><figure><img alt="HashGNN is 2–4 orders of magnitudes faster than learning-based algorithms, while delivering comparable results. Image taken from: https://arxiv.org/abs/2105.14280." src="https://cdn-images-1.medium.com/max/1024/0*ENSXVpx5WFrcFDj4.png" /><figcaption>HashGNN is 2–4 orders of magnitudes faster than learning-based algorithms, while delivering comparable results. Image taken from: <a href="https://arxiv.org/abs/2105.14280.">https://arxiv.org/abs/2105.14280.</a></figcaption></figure><p>HashGNN is implemented in the Neo4j GDS (Graph Data Science Library) and can therefore be used out-of-the-box on your Neo4j graph. In the next post, I will go into practical details about how to use it, and what to keep in mind.</p><p>Thanks for stopping by and see you next time. 🚀</p><h3>References</h3><ul><li><a href="https://doi.org/10.48550/arXiv.2105.14280">Original Paper: Hashing-Accelerated Graph Neural Networks for Link Prediction</a></li><li><a href="https://neo4j.com/docs/graph-data-science/current/machine-learning/node-embeddings/hashgnn/">Neo4j GDS Documentation: HashGNN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ce9c3029a5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/hashgnn-deep-dive-into-neo4j-gdss-new-node-embedding-algorithm-5ce9c3029a5c">HashGNN: Deep-dive into Neo4j GDS’s new node embedding algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Neo4j GDS Link Predictions (with Demonstration)]]></title>
            <link>https://medium.com/data-science/understanding-neo4j-gds-link-predictions-with-demonstration-9b96eec89efb?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b96eec89efb</guid>
            <category><![CDATA[graph-data-science]]></category>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[link-prediction]]></category>
            <category><![CDATA[neo4j]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 08:13:39 GMT</pubDate>
            <atom:updated>2022-10-18T18:22:43.676Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Neo4j GDS Link Predictions (with Code-Demo)</h3><h4>A hands-on tutorial of a common Graph Machine Learning task</h4><h3>Introduction</h3><p>The Neo4j GDS Machine Learning pipelines are a convenient way to execute complex machine learning workflows directly in the Neo4j infrastructure. Therefore, they can save a lot of effort for managing external infrastructure or dependencies. In this post we will explore a common Graph Machine Learning task: Link Predictions. You can easily reproduce the steps using a popular open data set (<a href="https://www.aminer.cn/oag-2-1">Open Academic Graph</a>) to prepare the input data and configure a pipeline step-by-step. I will elaborate on the main concepts and pitfalls of working with such a pipeline, so that we understand what is happening under the hood. Finally, I’ll give some thoughts on current limitations.</p><p><a href="https://youtu.be/kq_b0QmxFCI">Here’s a link to my YouTube video on the topic.</a></p><h3>Motivation</h3><p>Link prediction is a common task in the graph context. It is used to predict missing links in the data — either to enrich the data (recommendations) or to compensate missing data.</p><p>The link prediction problem can be interpreted as a binary classification problem: For each pair of nodes in the graph we ask: Should there exist a relationship between them or not? This problem statement is indeed quite verbose — we need to classify each node in the graph with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zg9DyP516_e19vDh.png" /><figcaption>Graph Link Predictions can be interpreted as a binary classification problem. (Image by author)</figcaption></figure><h3>The domain</h3><p>As domain example to follow along, I will use a well-known and commonly used data set for link prediction: The Open Academic Graph. You can <a href="https://www.aminer.cn/oag-2-1">download</a> the dataset and reproduce the steps described here. I have filtered the data to contain only a handful of publications and loaded it into a Neo4j graph. The resulting graph schema looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*mGoKrueT0k2GqXU4.png" /><figcaption>Image: Citation-Graph schema consisting of Authors, Articles, Venues and relationships PUBLISHED, REFERENCES, PUBLISHED_IN. (Image by author)</figcaption></figure><p>Furthermore, I have transformed the data into a homogeneous co-author graph. A co-authorship edge between two authors indicates that they have collaborated on a publication previously. The number of collaborations becomes an edge property. We transform the bipartite graph consisting of authors and articles into a homogeneous graph consisting of nodes Author and edges CO_AUTHORED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*to2VXH4yuQ8lk1Gh.png" /><figcaption>Image: Co-Author Graph. From a bipartite graph of Authors and Articles we arrive at a homogeneous graph of Authors. (Image by author)</figcaption></figure><p>We will work with the co-authorship graph to predict whether two authors are likely to collaborate in the future given their previous collaborations. In other words: We want to predict new CO_AUTHORED-edges.</p><h3>General pipeline overview</h3><p>We will use a Neo4j GDS Link Prediction Pipeline to accomplish this task (and, more importantly, to understand how to use them 😇). Let’s walk through the required steps of the pipeline. You can find the official documentation <a href="https://neo4j.com/docs/graph-data-science/current/machine-learning/linkprediction-pipelines/link-prediction/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*lIkCaoi_JGyHk7Qx.png" /><figcaption>Image: Pipeline overview (Image by author)</figcaption></figure><p><strong>Projecting a subgraph</strong> The first step is to create an in-memory subgraph from our general graph. We use the projected graph only in the final steps of the pipeline, however, it may be easier to understand if we create it first. A projection can be created by filtering node labels and relationship types or even by custom Cypher queries. One important note for working with link prediction pipelines is that they work on undirected edges only. Therefore, we need to project our directed edges to undirected ones.</p><p><strong>Creating the pipeline</strong> Creating the pipeline is pretty straight forward. We only need to provide a name to refer to.</p><p><strong>Add node properties</strong> One of the most essential steps for the quality of the predictions is to use expressive features which allow the model to make the right decisions. The add-node-property step allows executing GDS graph algorithms (e.g. node embeddings) within the pipeline to generate new node features. The limitation for the algorithms (currently) is that they need to generate features for the nodes — as opposed to edges (we will discuss this later).</p><p><strong>Add link features</strong> The feature vector step is one of the major differences to traditional ML tasks. Rather than classifying a single datapoint, we want to classify a pair of nodes. To generate a link feature vector for each pair of nodes, we use the feature vectors of both nodes and combine them into a single vector. The link-feature-vector step defines how to generate a link vector for a node pair from the individual node features. First, we need to specify which node features to use. Secondly, we have the choice of three combiner functions:</p><ul><li>Hadamard = Element-wise product,</li><li>Cosine = Cosine Similarity (angle between vectors),</li><li>L2 = Squared Distance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*vwvKnvHwSiqEbi3n.png" /><figcaption>Image: The link feature step: The node vectors are combined into a link vector using one of three combiner functions. (Image by author)</figcaption></figure><p><strong>Data splitting</strong> … looks like a trivial point in this pipeline. However, it is an essential part to understand whether you final model is useful or not. As we are classifying pairs of nodes rather than individual nodes, we end up with many combinations (|V| - 1) for each data point in the graph. Unless we are dealing with a close to fully-connected graph, there are naturally many combinations (|V| - 1 - degree(n)) without an edge for each node. These would end up being negative samples to our model and therefore a model which predicts NO-EDGE would yield high accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*7XieYHjjKNaQxSwP.png" /><figcaption>Image: Negative samples in the sample graph (Image by author)</figcaption></figure><p>To circumvent this, we do the following:</p><ul><li>Take all existing edges which constitute the positive samples in the graph (POS)</li><li>Split the positive samples into three distinct sets (POS = POS_TEST + POS_TRAIN + POS_FEATURE)</li><li>For each of the three sets, sample negative examples from the graph (e.g. TEST = POS_TEST + NEG_TEST).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*fnXGmE1i-o-rJHI7.png" /><figcaption>Image: Splitting the data into balanced datasets. The positive samples are split into three distinct sets: TEST, TRAIN, FEATURE. (Image by author)</figcaption></figure><p>The FEATURE set is used to calculate the node features configured earlier. This is an important distinction and prevents data leakage into the train and test sets. We will discuss this a little in the Common Pitfalls section.</p><p>Notes on negative sampling: Usually we want to find one negative sample for each positive. The approach to finding good negative samples is a research topic in itself, and many approaches exist. The Neo4j GDS only supports random sampling.</p><p><strong>Model configuration &amp; training</strong> Currently, there exist two classification approaches in the Neo4j GDS: Logistic Regression and Random Forests. We can add multiple model candidates with various parameter spaces to the pipeline. During training, each model candidate is subject to a k-fold cross validation to find the best model configuration. Another important parameter for the training is the evaluation metric to use. The GDS offers one metric for Logistic Regression so far: AUCPR (area under curve precision-recall). The winning model is stored under the provided model identifier for later usage.</p><p><strong>Prediction</strong> The prediction step applies the winning model to predict missing edges between all pairs of node in the graph, which do not have an edge. As this leads to a very large number of node pairs to evaluate the model for, the process can take up quite a long time. As usual, we have the choice how to consume the results: Stream or mutate. The mutate option will create the predicted relationships in the graph projection.</p><h3>Common pitfalls</h3><p>The most common pitfall which produces biased results, is to leak test data into the model training. This is not so much of an issue for traditional machine learning tasks as the data points have directly associated features. However, in a graph context, we often want to generate features which take into account connections in the graph. Therefore, these algorithms analyze the surroundings of nodes. In other words: The algorithms explore relationships and other data points to determine the role, connectedness, significance or embedding of a node in the larger context. The generated features then capture this knowledge about the network structure of data.</p><p>When training a model to decide whether an edge should exist between two data points, we want to hide some data from the training step, so that we can test the model performance reliably. The model should be trained without knowing the test edges. Rather, we want to obtain a model which is capable of making a good decision based on features which are independent of such an edge. Therefore, we need to pay additional attention when generating our features: No training or test data should go into the feature generation step.</p><p>The approach to enforce encapsulation and prevent data leakage is to split the input data into the three aforementioned sets: Train, test, feature. We use the feature set to calculate node properties used in the pipeline. As the three sets are distinct, we can be certain none of the edges used for training or evaluation have influenced our feature generation.</p><p>However, at this time, the only way to accomplish this strict encapsulation is by generating the features only within the pipeline. Feature generation outside the pipeline has no information about the data splits and is therefore likely to capture graph structures which the model is trying to predict.</p><h3>The implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63807bfec10f57608504df91c236d097/href">https://medium.com/media/63807bfec10f57608504df91c236d097/href</a></iframe><h3>Considerations</h3><p>The GDS pipeline encapsulates a lot of complexity in a handful lines of code. It makes large efforts to automate such workflows and prevent the engineer from tapping into one of the many pitfalls along the way. It remains indispensable to understand the concepts and error sources in link prediction to obtain useful results.</p><p>The strong encapsulation imply reduced flexibility and customization. The following szenario is not possible with the automated workflows at the moment:</p><p><strong>It is not possible to add a node-pair feature to the feature vector. Only node properties.</strong></p><p>Let’s consider the following example for a moment: We want to make predictions for a pair of authors (a1, a2). In addition to consider the node properties of a1 and a2, which we would combine into a single vector, we would like to consider features on the pair itself. For example, it might be valuable information to the model whether the two authors (a1, a2) have cited the same paper before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*gfBNde_MwQyfY7hk.png" /><figcaption>Image: A node pair feature: Two authors cite two papers in common. (Image by author)</figcaption></figure><p>This would be a feature on the author pair, rather than on each author individually; Each author has a multiple values — one for each other author. Obviously, this feature would best be represented as an edge in the graph; It is a pair feature. In turn, if we added this feature to our pair feature vector, we wouldn’t need to use a combiner as with the node features.</p><p>The major challenge with this is obviously that we needed to calculate such a feature on the various data splits to prevent data leakage. Therefore, the feature calculation either needs to happen within the pipeline (where the data splits are accessible). Or we needed to have access to the splits used for feature training, train and test.</p><p>This leads us to the second limitation with the pipelines currently:</p><p><strong>It is not possible to configure custom splits (feature, train, test).</strong></p><p>The pipeline allows configuration of ratios of positive samples and samples negative samples randomly. However, we cannot split our data by a custom logic — for example a timestamp. We may want data before a certain timestamp end up in the train set, whereas data after that timestamp should go to the test set. In order to accomplish this, we would need to mark our data accordingly and tell the pipeline how to use the markers in its flow. As discussed above, this custom splitting would be necessary to prevent data leakage in custom features as well.</p><h3>Conclusion</h3><p>The GDS Link Prediction Pipelines are a wonderful tool for setting up complex machine learning workflows directly in the Neo4j infrastructure. It reduces overhead required for external tools and resources by enabling workflows within the framework boundaries. The pipelines are simple to use and prevent many pitfalls which would require quite some thought otherwise. The API, currently, has its limitations with regard to flexibility over a custom-built solution. However, it is currently in beta version, and the GDS team may improve it in future releases.</p><h3>References &amp; Resources</h3><ul><li>Open Academic Graph Dataset, <a href="https://www.aminer.cn/oag-2-1">https://www.aminer.cn/oag-2-1</a>, License: ODC-BY</li><li>Jie Tang, Jing Zhang, Limin Yao, Juanzi Li, Li Zhang, and Zhong Su. ArnetMiner: Extraction and Mining of Academic Social Networks. In <a href="http://www.sigkdd.org/kdd2008/"><em>Proceedings of the Fourteenth ACM SIGKDD International Conference on Knowledge Discovery and Data Mining</em></a> (<a href="http://www.sigkdd.org/kdd2008/">SIGKDD’2008</a>). pp.990–998. [<a href="http://keg.cs.tsinghua.edu.cn/jietang/publications/KDD08-Tang-et-al-ArnetMiner.pdf">PDF</a>] [<a href="http://keg.cs.tsinghua.edu.cn/jietang/publications/KDD08-Tang-et-al-Arnetminer.ppt">Slides</a>] [<a href="http://aminer.org/">System</a>] [<a href="http://aminer.org/RESTful_service">API</a>]</li><li>Arnab Sinha, Zhihong Shen, Yang Song, Hao Ma, Darrin Eide, Bo-June (Paul) Hsu, and Kuansan Wang. 2015. An Overview of Microsoft Academic Service (MAS) and Applications. In Proceedings of the 24th International Conference on World Wide Web (WWW ’15 Companion). ACM, New York, NY, USA, 243–246.</li><li>Fanjin Zhang, Xiao Liu, Jie Tang, Yuxiao Dong, Peiran Yao, Jie Zhang, Xiaotao Gu, Yan Wang, Bin Shao, Rui Li, and Kuansan Wang. OAG: Toward Linking Large-scale Heterogeneous Entity Graphs. In <a href="http://kdd.org/kdd2019/"><em>Proceedings of the Twenty-Fifth ACM SIGKDD International Conference on Knowledge Discovery and Data Mining</em></a> (<a href="http://kdd.org/kdd2019/">KDD’19</a>).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b96eec89efb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understanding-neo4j-gds-link-predictions-with-demonstration-9b96eec89efb">Understanding Neo4j GDS Link Predictions (with Demonstration)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a simple recommendation engine in Neo4j]]></title>
            <link>https://medium.com/data-science/building-a-simple-recommendation-engine-in-neo4j-45770d8747eb?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/45770d8747eb</guid>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[graph-database]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 14:15:27 GMT</pubDate>
            <atom:updated>2022-04-08T15:11:00.773Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s build a simple recommendation engine with plain Cypher</h4><p>Graph databases like Neo4j are an excellent tool for creating recommendation engines. They allow us to examine a large context of a data point potentially comprising various data sources. Their powerful storage model is very well suited for applications where we want to analyze the direct surrounding of a node. If you would like understand what makes graphs so powerful in comparison with relational models, read <a href="https://towardsdatascience.com/at-its-core-hows-a-graph-database-different-from-a-relational-8297ca99cb8f">here</a>.</p><p>In this article, I describe how we implemented a simple recommendation engine directly in Neo4j using only Cypher. The approach bases on basic NLP and simple conditional probabilities to find the most likely matching item. The implementation can be done in a handful of cypher lines in a single query. We run the query in real-time as the user interacts with the app. This simple approach yields very satisfying results and is a wonderful first version. It saves us a lot of hassle to provision and maintain additional external systems, which we needed for more complex approaches. Even though it works well, there are some limitations to this solution as well.</p><h3>The domain: DayCaptain, tasks, events, areas and project</h3><p>DayCaptain is a personal time planning app which allows users to create day plans consisting of tasks and events. The primary property of tasks and events is their title, which is a short string specifying it. One way to organize these objects is by assigning them to (life) areas and projects. An area is a larger and persistent theme, whereas a project is timely bound. Projects themselves can be assigned to an area, in which case they inherit the area. Instead of writing “tasks and events” for the rest of this article, let’s focus only on tasks for now.</p><p>Now, the goal is to detect the area assignment for a new task as the user starts typing in the frontend. For example: The user creates a task and starts to write “Deploy ETL pipeline” in DayCaptain. As he types, we want to detect the most likely area for the words the writes by analyzing other tasks using these words.</p><h3>Tokenization and stemming — the preparation</h3><p>For the moment, we only consider the title property of a task. In order to turn it into workable features, we need to extract its tokens and stem them. We use the <a href="https://nlp.stanford.edu/software/">StanfordNLP</a> framework to process each input string as the user creates new tasks and events, and store their token usages as relations in the graph.</p><figure><img alt="Graph data model: Tasks and tokens" src="https://cdn-images-1.medium.com/max/800/0*6ZHdn7CNQtW1b6yy.png" /><figcaption>The data model: A task’s primary property is the title. It links to stemmed tokens and is assigned to an area. (Image by author)</figcaption></figure><h3>Sets, areas and conditional probabilities</h3><p>Our objective is to find the most likely area assignment for a set of words which the user is currently typing. Therefore, we want to find the area where the probability P(A|T) is largest. In other words: Given a token T, we want to find the area A which has the largest probability of containing this word.</p><p>Let’s start with a simple example:</p><figure><img alt="Graph data model: Tasks and tokens" src="https://cdn-images-1.medium.com/max/800/0*oKd9MtED8PhuSeeY.png" /><figcaption>Tasks have relationships to tokens and areas — the sit in between. (Image by author)</figcaption></figure><p>Now, as we can see, the tasks (or events) sit in between areas and token, and basically form the assignments of them. As we create new tasks and events consisting of tokens, and relating them with areas, we get more such indirect relations between areas and token. These indirect relations are exactly, what we want to analyze to find the recommendations.</p><figure><img alt="Example: Indirect relations between token and areas" src="https://cdn-images-1.medium.com/max/800/0*KcqFBsCBv_uifi_r.png" /><figcaption>As tasks sit in between areas and token, they form indirect relations between them. (Image by author)</figcaption></figure><p>Now, form the picture above, we can also construct an assignment matrix between areas and token.</p><figure><img alt="Assignment matrix of areas and token" src="https://cdn-images-1.medium.com/max/800/0*nMw2j2zmj0ttDDHL.png" /><figcaption>Using the indirect relations, we can construct a frequency matrix of areas and token. (Image by author)</figcaption></figure><p>Having all these numbers at hand, we can easily calculate our conditional probability for P(A|T) = P(A &amp; T) / P(T). Here are some examples:</p><figure><img alt="Calculation: Conditional probability of an Area give a token" src="https://cdn-images-1.medium.com/max/800/0*rpNX-CJBsIbfvHnh.png" /><figcaption>Using our frequency matrix, we can easily calculate conditional probabilities for seeing an area given a token. (Image by author)</figcaption></figure><p>A very intuitive way to illustrate such probabilities is to view them as areas.</p><figure><img alt="Illustration of probabilities as areas" src="https://cdn-images-1.medium.com/max/800/0*id3rCoJnhCBZtTJS.png" /><figcaption>The frequencies can also be depicted as areas. (Image by author)</figcaption></figure><p>Our recommendation query is straightforward. However, this example is only works for a single token. The question is: How do we combine multiple words into such a probability calculation?</p><h3>Finding recommendations for multiple words</h3><p>Each task and event can, and probably would consist of multiple tokens. To extend our model to such cases, the illustration as areas is particularly helpful.</p><p>Example: Let’s say, we wanted to find the area assignment for the task “Prepare Neo4j workshop”. Then, we want to find the probability P(A|”Neo4j” &amp; “workshop”). From calculus, we can infer, that we need to find P(A &amp; “Neo4j” &amp; “workshop”) and P(“Neo4j” &amp; “workshop”). If we view our area illustration (or our matrix) we can derive what these probabilities are. Here’s the calculation:</p><figure><img alt="Calculation of the conditional probability for two token." src="https://cdn-images-1.medium.com/max/800/1*DijVTJB5CK2mHQfeF5NLRg.png" /><figcaption>Calculation of the conditional probability for two token. (Image by author)</figcaption></figure><p>As we can already see from the examples, we do not need the global count of assignments, because it always cancels out. Therefore, our recommendation query is as simple as fining the counts of assignments within each area. Here’s the query:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e48943125e3048e2edc1bf1dafe37f52/href">https://medium.com/media/e48943125e3048e2edc1bf1dafe37f52/href</a></iframe><p><strong>Some notes to the query:</strong> In real DayCaptain, there are also projects which are modeled in between areas and tasks. The Information label is a superclass of tasks and events (or basically everything, which has a title property). Also, the query is simplified in such a way, that it does not consider users. In our production case, we actually limit this query to a specific user.</p><h3>That’s so simple — but how well does it work?</h3><figure><img alt="Gif showing area recommendation as a title is typed for a task." src="https://cdn-images-1.medium.com/max/800/0*Qybl6dtHbH5D137n.gif" /><figcaption>Area detections in action 🚀 (Image by author)</figcaption></figure><p>We have conducted a quantitative assessment of the recommendation engine and have even compared it to a deep neural network model on the same data. The results are more than satisfying. In both cases, we split our data set into a train and test set. Even though there is no training phase in our simple approach, we wanted to test whether the recommendation engine works well on data points it hasn’t seen before.</p><p>We have a large body of data from myself, as I have been using DayCaptain for more than 4 years now. For both approaches, we measured how many times they predicted the correct result for a known task or event. Both approaches predicted the correct area in around 95% of the time.</p><h3>Man, that’s cool — but what does it mean?</h3><p>Let’s have a short discussion about this: Our simple statistic (or probabilistic) recommendation approach uses very simple maths, and a lot of intuition to produce very useful results. It is very easy and straightforward to implement in plain Cypher, and runs directly in our Neo4j backend. There’s no overhead for adding external systems, there are no training cycles or models, which we need to manage, and there’s low overhead in maintaining the code. We are actually able to query results in real-time (multiple times while the user is typing) without the need of any preparation of results. Compared to more sophisticated approaches like a deep NN model with a word2vec embedding, it yields equally good results.</p><p>However, the mayor downside of this approach is: It is limited to a simple feature set. Once we would like to consider more features in our recommendation, we had to model them explicitly into our query. It could become very complex and hard to understand, or even impossible to maintain. Not to speak of the complicated development process of finding the right way to combine multiple features into a reasonable result.</p><h3>Let’s round this one up.</h3><p>Neo4j’s powerful querying model allows us to build powerful recommendations right into the database. We created a very simple, yet very powerful prediction query to provide the best experience to our users. Our approach was really 80/20, and we reached some very good results. For us, the mayor advantage is the implementation directly in our graph database as it saves us from a lot of work for provisioning, training and monitoring additional systems. However, the application of such approaches is limited to a small set of features as the query may become rather complex and would require large effort to maintain and extend. The approach described here, definitely serves as a good starting point to build an initial working solution.</p><h3>Let’s team up — let me hear from you.</h3><p>I hope you have enjoyed reading this article and that you could take away something out of it. If you have any questions or a different opinion, I warm-heartedly welcome you to leave a comment or contact me directly. Hit the subscribe button to read more like this. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45770d8747eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-a-simple-recommendation-engine-in-neo4j-45770d8747eb">Building a simple recommendation engine in Neo4j</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graph Embeddings: How nodes get mapped to vectors.]]></title>
            <link>https://medium.com/data-science/graph-embeddings-how-nodes-get-mapped-to-vectors-2e12549457ed?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e12549457ed</guid>
            <category><![CDATA[graph-embedding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 13:19:47 GMT</pubDate>
            <atom:updated>2022-02-22T16:39:27.521Z</atom:updated>
            <content:encoded><![CDATA[<h3>Graph Embeddings: How nodes get mapped to vectors</h3><ul><li>Most traditional Machine Learning Algorithms work on numeric vector data</li><li>Graph embeddings unlock the powerful toolbox by learning a mapping from graph structured data to vector representations</li><li>Their fundamental optimization is: Map nodes with similar contexts close in the embedding space</li><li>The context of a node in a graph can be defined using one of two orthogonal approaches — Homophily and Structural Equivalence — or a combination of them</li><li>Once the metrics are defined, the maths are concisely formulated — let’s explore.</li></ul><h3>Graph databases and machine learning</h3><p>Graph databases enjoy wide enthusiasm and adoption for big data applications of interrelated data from various sources. They are based on a powerful storage concept which enables a concise query language to analyze complex relationship patterns in the data (<a href="https://towardsdatascience.com/at-its-core-hows-a-graph-database-different-from-a-relational-8297ca99cb8f">more here</a>).Therefore, algorithms like PageRank, centrality detection, link prediction and pattern recognition can be stated in a simple and intuitive way.</p><p>However, most of the well-developed, traditional machine learning algorithms, like linear &amp; logistic regression, neural networks and their alike, work on numeric vector representations. To unlock this powerful toolbox to work on graph structures, we need a way to represent our network of data in a vector form. Graph embeddings are a form of learning exactly this mapping from the data in the graph.</p><h3>The objective of a graph embedding</h3><figure><img alt="A simple graph structure with vector mappings" src="https://cdn-images-1.medium.com/max/800/1*lWaDMOc0RVcrEvYLiapNKA.png" /><figcaption>Image by author</figcaption></figure><p>Our goal is to find a vector representation for each node in the graph. Rather than taking into account the associated features of a node, the mapping should represent the network structure of the node. Put differently, the embedding vector of a node should be based on its relationships and neighboring nodes. Nodes which are similar in the graph, should be mapped close in the vector space. The vector space, which we map the node into is called an embedding space.</p><p>Now, if we look at the above statement, two questions come to mind, that require additional thought:</p><ul><li>What makes two nodes <em>similar</em> in the graph?</li><li>What does <em>close</em> in the embedding space mean?</li></ul><h3>Similar nodes in a network</h3><p>To elaborate on similarity in a graph, let’s consider a sentence for a moment:</p><figure><img alt="An example sentence to demonstrate word contexts" src="https://cdn-images-1.medium.com/max/800/1*al05xRc4VQsG5xzXYnSTxw.png" /><figcaption>Image by author</figcaption></figure><p>A sentence is a sequence of words with each word having a definite position. Therefore, a word in a sentence has exactly one ancestor and one successor. To define the context of a word in a sentence, we could use the words surrounding it. For example, the distance-one context of the word ‘capital’ are the words ‘the’ and ‘of’. The distance-two context would be the words ‘is’, ‘the’, ‘of’, ‘Germany’. This is called the n-gram model and is used by a popular approach for finding word embeddings called word2vec.</p><p>Similar to n-gram, we can define a context of a node in a graph. Though, we have more choices in a graph structure than in a sequence of words. In general graphs, each node potentially connects to more than two other nodes — whereas in a sentence a word only has one direct ancestor and successor.</p><p>Therefore, a sentence is a vector, and a word’s context can be explored by moving along the index axis. A graph, however is described as a two-dimensional adjacency matrix, and the direct ancestors of a node is a vector. To explore the context of a node, we have multiple choices at every distance level, and we have to decide how to traverse them.</p><p>Generally, there are two orthogonal approaches for exploring a network context:</p><figure><img alt="Differences between breadth-first and depth-first explained with an example graph" src="https://cdn-images-1.medium.com/max/800/1*gmrxwE_JAog7kNxhZpkzeA.png" /><figcaption>Image by author</figcaption></figure><ol><li>Breadth-first: We elaborate on the direct neighbours of our source node first, before we (potentially) move on to the nodes of distance two. This is also called Homophily and is derived from a sociological concept, stating that people generally tend to interact closely with similar others. Therefore, it is based on the assumption that similar nodes in the graph have close relationships.</li><li>Depth-first: We explore one chain of connections by following a path starting from the source node into its depth first, before we move on to the next. In contrast to Homophily, this metric captures the role of a node in a network from a wider perspective. Rather than looking at close relationships, we seek to find the structural role of a node: e.g. how it is embedded into a larger context of communities. This metric is called Structural Equivalence.</li></ol><p>We can use these two approaches to find the context of a node — potentially, by combining them. Having a set of nodes describing the context of each node, we can use these sets to compare each pair of nodes with respect to context similarity. We could apply a Jaccard similarity, for example, to measure how much two contexts overlap. This would give us a way to find nodes with a similar network structure in our graph.</p><figure><img alt="Calculation of the Jaccard Similarity of two sets" src="https://cdn-images-1.medium.com/max/800/1*RHP4eHVXQAcveRS_-JUFdA.png" /><figcaption>Image by author</figcaption></figure><h3>Sampling a context</h3><p>However, we cannot sample the entire context of any given node as it would eventually lead to capturing the entire graph for any node. Therefore, we employ an approximation which is called a sampling strategy. The idea is to start a fixed amount of random walks in the source vertex to explore its context to generate a random sample. The sampling strategy defined by node2vec combines Homophily and Structural Equivalence. It implements a parameter to decide in each step of the walk whether it should stay close to the source node (Homophily) or should explore another distance level (structural equivalence).</p><figure><img alt="An example graph with the sampling strategy for a source node" src="https://cdn-images-1.medium.com/max/800/1*IXkxDKcaqwEi5_etUY5ihQ.png" /><figcaption>Image by author</figcaption></figure><p>Instead of using the Jaccard similarity described earlier, in node2vec, we try to find a numerical vector for each node. We use the sampled contexts of nodes in the graph, to optimize the mapping function to map nodes with similar contexts close together.</p><h3>The Maths of node2vec</h3><p>Let’s explore how node2vec works in detail by considering the following example:</p><pre>V: all nodes in graph<br>N_S(u): neighborhood of u determined by sample strategy S<br>f(u): mapping function of node u onto a vector</pre><p>Our goal is to find embeddings for all nodes u in V, such that the vector representations of nodes with similar contexts are close in the embedding space. We already know what similar contexts in the graph means, but we still need to define, what closeness in the embedding space means.</p><figure><img alt="The mapping function maps a node from the graph to a d-dimensional numerical vector" src="https://cdn-images-1.medium.com/max/800/1*5qApx3thPxIB_fZlOldHLQ.png" /><figcaption>Image by author</figcaption></figure><p>Let’s consider only two nodes in the graph for now:</p><pre>u: source node<br>v: node in context of u</pre><p>To get our maths started, we simply choose two random vectors f(u), f(v) for the two nodes. To measure similarity in the embedding space, we use the dot-product of the two vectors, which is the angle between them.</p><figure><img alt="The dot-product of two vectors is the angle between them" src="https://cdn-images-1.medium.com/max/800/1*hqYXn1Q1_cPZdQnLsmBJeQ.png" /><figcaption>Image by author</figcaption></figure><p>As node v is in the neighborhood of u, the idea is now to incrementally optimize the mapping function f, such that their similarity gets maximized.</p><p>To turn our similarity into a probability, we apply a softmax to it. The softmax normalizes the similarity score dot(f(u), f(v)) with the sum of all similarities of u with all other vectors v in V. The dot-product therefore gets transformed into a number between [0,1] and all similarities add up to a sum of one. The result is the probability of seeing node v in the context of node u from their vector representations. Now, we can incrementally optimize this probability by updating our vector f(u) using Stochastic Gradient Descent.</p><figure><img alt="An equation stating that applying the softmax to the dot-product leads to a probability" src="https://cdn-images-1.medium.com/max/800/1*cqR_LlJ5XZ9NWLV1Sc2mfw.png" /><figcaption>Image by author</figcaption></figure><p>The next step is to generalize this concept to do the optimization not only for one node v in N_S(u), but rather for all nodes in the context of u. We want to optimize the probability of seeing the entire sampled context if we are given node u. If we assume independence of samples, we can simplify this formula into a product of simple probabilities.</p><figure><img alt="The resulting equation of applying the probability to all nodes in the context of the source node." src="https://cdn-images-1.medium.com/max/800/1*ZI-8iKsl0qzIbMaxF5GY_w.png" /><figcaption>Image by author</figcaption></figure><p>Finally, we want to learn a mapping for each source node u in the graph. Therefore, we apply the formula to all nodes of the graph simultaneously. We optimize the sum using SGD by making adjustments to our mapping f so that the probability increases. We incrementally improve until we reach a maximum number of iterations or find a fixed point in our optimization problem.</p><figure><img alt="The final equation of the node2vec algorithm" src="https://cdn-images-1.medium.com/max/800/1*7u4TKCfXN28p4FlyvL9kmg.png" /><figcaption>Image by author</figcaption></figure><h3>Further notes</h3><p>There is one major challenge when implementing this solution and running it on a large dataset: When we calculate the softmax to determine the probability P(f(v) | f(u)), there is a normalization term in the denominator, which is pretty ugly to calculate. This normalization term is the sum of all similarities of u and all other nodes in the graph. It stays fixed for the entire iteration of the optimization, and therefore also fixed for all iterations of the sum for source node u. The first optimization is to move that factor out of the sum.</p><p>The second challenge is that it is very expensive to calculate such a factor over all vectors. In every iteration, we would have to determine the dot-product for every source node u with all other vectors in the graph to find the normalization factor. To overcome this, a technique called negative sampling is used to approximate this factor.</p><h3>Edge embeddings</h3><p>The approach described above can also be applied to a different foundational assumption: Instead of finding a mapping of nodes with similar contexts, we could also set a different objective of mapping edges into the embedding space such that these are close, who share same nodes. Combining node and edge embeddings in node2vec, we derive at the more general term <em>graph embeddings</em>, which is capable of mapping interrelated data to vector representations.</p><h3>Conclusion</h3><p>We have explored how we can find a mapping f(u) to map nodes of a graph into a vector space, such that similar nodes a close. There are various ways to define similarity of nodes in a graph context: Homophily and Structural Equivalence. Both have orthogonal approaches and node2vec defines a strategy to combine the two into a parameterized sampling strategy. The sampling strategy is a means to find the context of nodes, which is in turn used to derive our embedding. Similarity in the embedding space in turn, is defined as the dot product between the two mapped vectors. The embedding itself is an iterative optimization using Stochastic Gradient Descent. It adjusts the vectors for all nodes in each iteration to maximize the probability of seeing nodes from the same context together. The implementation and application to very large datasets requires some statistical approximation to speed up the calculation.</p><p>node2vec is an important key to unlock the powerful tool box of conventional machine learning algorithms to work on graph-structured data.</p><p>Me personally, I’m once again taken away by the simplicity and conciseness of the definition of the algorithm to solve the problem at hand. I find it astonishing how well these approaches work if they are applied to the right problem, with the right amount of data.</p><h4>References</h4><ul><li><a href="http://arxiv.org/abs/1607.00653">node2vec: Scalable Feature Learning for Networks</a>. A. Grover, J. Leskovec. <em>ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD)</em>, 2016.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e12549457ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/graph-embeddings-how-nodes-get-mapped-to-vectors-2e12549457ed">Graph Embeddings: How nodes get mapped to vectors.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Beat Procrastination To Unlock Our Full Potential — 4 Simple Steps]]></title>
            <link>https://medium.com/@philipp.brunenberg/realized-potential-full-potential-self-doubt-3eae652eec89?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eae652eec89</guid>
            <category><![CDATA[procrastination]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[goals]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[limiting-beliefs]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 15:11:14 GMT</pubDate>
            <atom:updated>2022-02-20T13:47:52.758Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A hand writing goals into a journal." src="https://cdn-images-1.medium.com/max/1024/0*zM75rCsCR3Ict_NZ.png" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/s/photos/hand-writing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>4 Simple Steps to Beat Procrastination and to Accomplish Our Goals</h3><h4>Beat the inner critic with four simple steps to accomplish goals</h4><p>All too often it’s just us, standing in our own ways. We compromise our own progress for nebulous feelings of doubt and confusion. Here is a simple approach to self-worth, peace of mind and accomplishment.</p><h3>Who am I to write this post?</h3><p>I’ve had 0 EUR income for the past six month. But I haven’t failed — I’ve found dozens of ways that do not work.</p><p>Early in this year, we set out to create a company called <a href="https://daycaptain.com/">DayCaptain</a>. It’s a personal time planning tool which we have created for ourselves. We have been using DayCaptain daily for four years now — and we thought it might be of value for others as well. It’s entirely bootstrapped — so there’s not a single external force pulling us in any direction. We knew it wouldn’t be an easy ride — and it wasn’t and isn’t. It’s like getting up every single morning — day after day, week after week, month after month — trying to figure out what we should be doing differently.</p><p>Hundreds of emails that went unanswered. Dozens of calls with potential users that only resulted in being told that it’s cool — but not for them. It’s a dry journey. By now, we were only three times in the position to celebrate a new paying customer. Three times in six months — it requires some endurance and belief.</p><p>Time and again I came across the challenge of running such a project. And ironically, it illustrates the very foundation of reaching goals itself.</p><h3>What are valuable goals?</h3><p>If we think about a valuable goal for us to pursue, we usually come up with something that challenges us. I believe we have a natural intrinsic drive to improve ourselves, or our situation. If this wasn’t true — what’s the point of setting a goal? So, in conclusion, the goals we pick are slightly out of reach and that’s why we want them in the first place.</p><p>Having such a goal inspires us and lets us focus in one direction — but they are also hard to pursue.</p><h3>Why are valuable goals hard to pursue?</h3><ol><li><strong>We are the only ones to hold us accountable.</strong> We take full responsibility for the results. It is up to us to make progress. If we don’t, no one does. There are usually no external forces like a paycheck or an investor to hold us accountable. We own the results and we own the work.</li><li><strong>There are no immediate rewards.</strong> Most valuable and worthwhile goals take time to grow and manifest themselves. No instant gratification — only work. They require persistent action over a long period of time. In the beginning, there will be little to no rewarding results to keep us motivated.</li><li><strong>It’s easy to lose trust in the value, and confidence in the approach.</strong> The lack of early results could easily lead to doubts about the usefulness of our endeavour, or the effectiveness of our approach. It is not clear to see if we are doing anything of value or if we are only wasting our time. A decent amount of such trust and confidence is necessary to pursue our goal for an extended period of time — especially in the absence of results.</li></ol><h3>Procrastination is an inability to act.</h3><p>The aforementioned traits of our goal form fertile ground for procrastination. Procrastination is an inability to act single-mindedly and focused on a task which we know we should be doing. We fear failure — because it’s challenging. We are uncertain about our approach — because we cannot know better. And we are unsure about the value — because no one cares.</p><p>So, what happens is: We fall into a kind of paralyzed state of inaction, questioning anything and everything. We might default to obviously far-off activities like cleaning the kitchen, watering the plants, or scrolling social media. Or to more seemingly productive, but familiar things like reading a paper, listening to a podcast on the topic, or working on low-priority issues.</p><p>In any case, we don’t do, what we should be doing. Or put differently, we waste time, which could have gotten us closer to the desired results, and therefore to the reinforcing reward we need the most.</p><p>Procrastination has another malicious effect: It facilitates the manifestation of limiting beliefs, and therefore damages the image we are carrying about ourselves. Just like we are forming a picture of someone else by watching his actions — we form a picture about ourselves. We observe our actions (or not-action) to form our self-belief. This even amplifies the fears and doubts that led to our inaction in the first place, and we experience a self-reinforcing effect.</p><p>At some point when motivation strikes us for some nebulous, non-reproducible reason, we finally break through our feelings and get into the work. Sometimes after weeks, sometimes at night, or after watching an inspiring video. Then, we realize that it was fun to work on the task and that we are actually capable of doing it.</p><p>The question usually following our emotional high of accomplishment is: How much could we have accomplished more if we hadn’t procrastinated so much over the past week? Over the past month? Over the past year? Over the past 5 years?</p><h3>How can we overcome this paralyzed state?</h3><h4>Rule 1: Split planning and execution time</h4><p>During the planning time, we make decisions about what to work on next — we don’t have to execute. As we don’t have to act immediately, we can leave our feelings of unworthiness, or fear of failure aside, and have a clear vision about our situation.</p><p>If we ask ourselves today fearlessly what we should be doing tomorrow, we probably know exactly what to answer. Chances are, we can formulate an entire sequence of steps that lead exactly to where we want to end up. It might not be the global optimum — like if we knew everything about the world. Rather, it’s a local optimum: A decision based on where we stand and what we know right now. As we take action and progress, we may learn from experience that it wasn’t the best thing we could have done, and we start to understand why. But that’s because we’ve learned a lesson — and we won’t get to that point of learning until we act out the plan we currently have.</p><p>During planning, we simply trust our intuition and ask fearlessly what we should be doing. But we have to make decisions for the days ahead.</p><p>I personally have two types of routines to do my planning. Of course, I use <a href="https://daycaptain.com/">DayCaptain</a>, but a sheet of paper is also fine.</p><p><strong>1. Week planning</strong>: On Sundays, I take an hour to review my goals and decide what tasks I want to complete to accomplish them. I create tasks that are derived from my goals. They are vaguely defined week goals, rather than small, actionable tasks. I also review my calendar to see where I have time to work and go through my todo lists to not miss out on anything.</p><figure><img alt="A list of week goals in DayCaptain." src="https://cdn-images-1.medium.com/max/600/0*d6wUxjxKf7r2k-Ei.png" /><figcaption>A task list for a week in <a href="https://daycaptain.com/">DayCaptain</a>. Image by author.</figcaption></figure><p><strong>2. End-of-day routine</strong>: I take five minutes each day, right before I leave work, to do my planning for tomorrow. The tasks I schedule are derived from my week goals. Based on the current progress, I create a new actionable, small, next step for tomorrow. Ideally, I also assign a time budget to the tasks to indicate how much time I plan to spend on them. I also review my calendar and todos to stay on top of things.</p><figure><img alt="A day plan in DayCaptain, containing prioritized tasks and events for the day." src="https://cdn-images-1.medium.com/max/800/0*T3g2pDWcQOxKyNlf.png" /><figcaption>A day plan in <a href="https://daycaptain.com/">DayCaptain</a>. Image by author.</figcaption></figure><p><strong>Note: Don’t be scared of becoming supernatural.</strong></p><p>A “plan” often gets confused with a schedule. When I tell others that I plan each of my days, some say things like: “Man, you gotta work like a robot! 🤖” However, for me, a plan is a “statement of deliberate intention”. It’s merely a statement of my deliberately made decisions what I want to accomplish today and an assessment of the time I have. But as this definition is so unwieldy, I continue to call it “plan”.</p><h4>Rule 2: During execution time we don’t make decisions.</h4><p>Once planning time is over, we execute without second-guessing. We will have doubts and resistance against the tasks in our plan. The feelings of fear will inevitably come. It’s all too tempting to do something different — anything is good enough. There are no limits to the ways our brains will try to trick us, to get us out of this very life-threatening situation.</p><p>When I sat down to start this post, I recall that mine came up with: “Should I maybe walk to a coffee shop, because I’m more creative there?”</p><p>The single most important rule is: We do not change our plan ad-hoc. We have to trust our plan and intuition even — and especially — in the face of our rawest feelings. We thought it was a good idea yesterday and the day before — probably for quite some time. Right now is exactly the wrong moment to challenge our decision.</p><h4>Rule 3: Start with the tiny-most, first step.</h4><p>Once starting with a task, don’t sit down and say: “I’m gonna finish this huge, ugly task — that scares me, and I don’t feel good enough to accomplish — right now.” It won’t work. Rather, we ask ourselves: “What is the smallest possible first step that I can accomplish in 25 minutes?” Emphasis is on <strong>smallest possible</strong> and <strong>first</strong>. If we don’t know, the first step is to write down all steps required. Too often we start with trying to get the task done, while exploring simultaneously what we need to do. To be honest, for me, it is often the 3rd or 4th step to start with the actual work.</p><p>For example, when I started to write this post I sat down and brainstormed for 25 minutes what I would like to write about. The second step is to group the content, the third to create a storyline, the fourth to start writing.</p><h4>Rule 4: Set a timer for 25 minutes and don’t allow yourself to do anything else.</h4><p>Having our task broken down into tiny steps we start to work on the first one. I do it in 25-minute increments before I take a 5-minute break. During this time, I won’t allow myself to do anything else. Phone is off, social media is closed — it’s only me and the task.</p><p>Writing a blog post (for me) can be challenging. Writing one about something I can only vaguely articulate, is tough. Thinking about it feels much like looking at a tightly-knit nest of interconnected experiences and beliefs — maybe let’s not do it.</p><p>Brainstorming about the content for 25 minutes is easy — I can do it. After 25 minutes, when the timer rings, it already feels much clearer. It was fun. I’d like to continue. Usually, the fear is already gone, and I start to feel some excitement in anticipation of the results, instead of fear of failure.</p><p>25 minutes into working on this post that I have been putting off for days, I have an entire sheet sketched with the things I want to put into it. What do you think I’d have felt if I had gone out to visit a coffee shop? After 25 minutes? I’d probably only arrived. What do you think my brain would have learned about myself, watching me do this? Is that the picture I would like to have about myself?</p><h3>How can we make it stick?</h3><p>If you find this helpful and like to try, please, don’t make the mistake of thinking that it will all magically change. Even though we created an entire tool and company around this — sometimes, like these days, I fall off that habit. There was a two-hour call with my co-founder and best friend Basti to get me back onto my track.</p><p>We are talking about establishing a new routine which we do every day — actually multiple routines. It’s natural to fall-off from time to time when things start to get busy — so don’t be too hard on yourself. However, I strongly believe that we can make such habits stick by having some reliable anchors throughout our day, and by making our habit easy and fun to do. Both are the reasons why we created <a href="https://daycaptain.com/">DayCaptain</a> as our daily guide.</p><h3>The end</h3><p>It may be true, that the company is not going as expected — yet. I don’t make money at that point in my life, and it’s been tough to reduce myself to what is left in absence of any external rewards. However, pursuing it provided me with great opportunity to learn much about myself. It has led to undisguised and forthright thoughts about my life. I experienced more than ever before what it takes to pursue our goals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eae652eec89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[At its core: How’s a graph database different from a relational?]]></title>
            <link>https://medium.com/data-science/at-its-core-hows-a-graph-database-different-from-a-relational-8297ca99cb8f?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8297ca99cb8f</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[tigergraph]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 11:19:23 GMT</pubDate>
            <atom:updated>2021-11-19T17:51:41.435Z</atom:updated>
            <content:encoded><![CDATA[<h3>At Its Core: How Is a Graph Database Different from a Relational One?</h3><h4>It’s easy to come up with some answers by simply Googling the topic, however, as I found, most answers list benefits mostly superficially</h4><p>In today’s never resting world new data is constantly created and is the fundamental asset of most businesses. Systems are available 24/7 and generate data every second of the day. Additionally, complex compositions of data generating and processing systems collaborate to provide services to the user. One question that I came across many times recently which — and which I’ve given careful thought as a result — is: What’s the deal about graph databases and how are they different? It’s easy to come up with some answers by simply Googling the topic, however, as I found, most answers list benefits mostly superficially. In this post I’d like to give a brief description about my understanding of their true value — independent of marketing slides from large companies and tech influencers.</p><h3>Databases maintain and persist a materialized state of all previously processed events coming into our system.</h3><p>An event is a self-contained and immutable message coming into our system. When we set up a database to process and store such events, we have to make various design decisions:</p><ul><li>What data would we like to store?</li><li>How is it represented?</li><li>At what layer of abstraction do we store data?</li><li>Which events we would like to process and how to apply them to our data?</li></ul><p>For example: We could store raw events as they come into our systems, or apply them as they come in to update our data.</p><h3>A database has a purpose and reason for storing data in a particular way.</h3><p>E.g. if the database serves as the persistence layer of a user-facing application to serve user requests in real-time, it should incorporate a representation that holds the data quickly accessible for that particular set of requests. For answering statistical business questions, in contrast, that take into account large amounts of historical data, this might not be the best approach.</p><p>Now, what’s the difference between graph databases and relational databases? As graph databases gain more and more attention from many companies, and most companies also have traditional relational databases in place, I’d like to focus on these two here.</p><figure><img alt="How relational databases model relationships with index" src="https://cdn-images-1.medium.com/max/800/1*1I2v0bQujmLZxlYkixQ5Dw.png" /><figcaption>Image by author</figcaption></figure><h3>Relational databases are entity-first.</h3><p>Let’s start with the relational model. Relational databases store data in tables. A table represents an entity. I’d call them entity-first. The approach is to define a schema for a table and then store only objects of that particular type within that table. Therefore, similarly structured data is stored close together.</p><h3>Relational models store relationships as data in the user domain.</h3><p>There exists no concept of a relationship between data in a relational model. Meaning, you cannot define a relationship between tables. In order to link data in a relational model, you have to explicitly model the relationship into your data. You cannot distinguish between the actual data, and the data only kept to represent the relationship. The only way to model a relationship is to model it as a foreign key into your table — either as an attribute of your entity (one-to-one, many-to-one) or with an additional table (one-to-many, many-to-many). One could consider that mapping table as a relationship table and therefore the relationship as an entity. However, it doesn’t come implicit from the technology to support relationships — rather we are creating new data. This leads to one fundamental implication: Relational databases store foreign keys as user data — i.a. references to another entry in an entity table. As the reference is data in the user domain the database cannot have an automatic mechanism to manage them — they are subject to user logic.</p><figure><img alt="How graph databases model relationships with pointer" src="https://cdn-images-1.medium.com/max/800/1*tLO1hR-n3qHpZtmxYeURSg.png" /><figcaption>Image by author</figcaption></figure><h3>Graph databases are relationship-first.</h3><p>A graph model, in contrast, has an explicit concept for entities (nodes) and relationships (edges) — which makes it different. As we can define relationships between entities directly we do not need to care how to model them explicitly in our schema. We do not need to know about foreign keys and neither do we have to write logic about how to store them. We define a schema of entities and relationships and the system will take care of it. This has a huge benefit if we want to model highly connected data: The implementation can take care of references efficiently. Instead of storing additional data (the reference) in our data tables as attributes explicitly, the graph database system can store true memory pointers to the next related entity. Most graph database systems store data in a structure similar to linked lists. They store direct links to data which is connected, rather than similar objects. I’d say they are relationship-first.</p><h3>The aforementioned differences in the two approaches lead to some implications about the use-cases each can serve well.</h3><h3>Graph databases store data like object-oriented languages.</h3><p>As relational databases don’t incorporate a concept of a relationship, we need to model them explicitly as data into our schema. This leads to a discrepancy from the object-oriented modeling that we use in most programming languages. Each object can maintain a collection of other objects it is related to. These references are usually pointers to objects in-memory, and we do not have to store them explicitly. Nor do we have to find the object in memory with some foreign key attribute. Therefore, quite some overhead is required to do the so-called object-relational mapping.</p><p>Graph databases store data like object-oriented languages — we have direct pointers to related objects. Therefore, the object-relational mapping is more straightforward.</p><h3>The traversal of a single relationship can be done at constant time.</h3><p>As graph databases can jump from one entity to a related one just by following a memory pointer, we call this index-free adjacency. We do not have to find a foreign key in a different table (using an index) or — even worse — find a key in a mapping table, and the resulting foreign key in a third table to follow a relationship. Therefore, the traversal of a single relationship can be done at constant time. Meaning, it is independent of the size of the data stored in the graph database. Whereas we have to scan one — potentially multiple — indices in a relational one, which is growing with the data size.</p><h3>It just feels wrong to write multi-hop queries in SQL.</h3><p>While it is indeed possible to model connected data and relationships in relational models, once we try to follow paths with multiple hops using SQL query language, we might get the feeling what we are writing down is not quite the thing that we want to accomplish. We have to join tables on some condition that we have to specify manually to find neighbouring data — potentially multiple times and therefore write ugly nested queries. It feels bulky and like a lot of overhead is occurring. If something like this happens, it’s usually a strong indicator that we are using a technology not quite the way it was designed for. We don’t want to join entire tables — we want to look up one particular data point.</p><p>In graph databases this looks different. As they were designed to query related data based on the structure of connection, they offer a concise and intuitive syntax to do so. We can specify exactly what paths we want to find. No join conditions or complex nested queries, no mapping tables — just the simplest description of what we want to find.</p><h3>Conclusion</h3><p>Graph and relational databases differ in one fundamental design principle: Graphs do have a concept of a relationship and relational don’t. That’s why a graph database can manage interconnected data much more efficiently. Still, both have their reasons for existence: Graphs perform better and are more intuitive to use when analyzing an entire context close to a single data point — potentially with multiple hops. However, if the exploration of highly joined and densely connected data is not a requirement, a relational model may serve the needs similarly well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8297ca99cb8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/at-its-core-hows-a-graph-database-different-from-a-relational-8297ca99cb8f">At its core: How’s a graph database different from a relational?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Apache Spark Hash-Shuffle]]></title>
            <link>https://medium.com/@philipp.brunenberg/understanding-apache-spark-hash-shuffle-b9aed2d587b0?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9aed2d587b0</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 18:56:20 GMT</pubDate>
            <atom:updated>2021-11-11T18:56:20.712Z</atom:updated>
            <content:encoded><![CDATA[<p>As described in <a href="https://www.philipp-brunenberg.de/entries/understanding-spark-shuffle">Understanding Spark Shuffle</a> there are currently three shuffle implementations in Spark. Each of these implements the interface ShuffleWriter. The goal of a shuffle writer is to take an iterator of records and write them to a partitioned file on disk — the so called map output file. The map output file is to be partitioned so that subsequent stages can fetch data merely for a specific partition.</p><p>Several approaches exist to accomplish this — each with specific pros and cons and therefore beneficial in different situations. The ShuffleManager attempts to select the most appropriate one based on your configuration and your application. In this post we will deep dive into the so called BypassMergeSortShuffleWriter, which is also referred to as hash-shuffle. We will understand how it works and elaborate on its up- and downsides to understand in which situations it might be a good choice to use.</p><h3>How does the BypassMergeSortShuffleWriter work?</h3><p>The hash-shuffle is based on a naive approach of partitioning the map output: it maintains a file for each partition. The name BypassMergeSortShuffle originates from the fact that its intermediate files do not need to be merged when creating the output file — therefore it bypasses the merge sort. As we shall see in later posts, the other implementations write multiple intermediate files each containing records from many partitions. These files need to be merged in the end to create a partitioned output file. The hash-shuffle in contrast, inserts the records of a partition only into a single file. Thus, no merging of files is needed. The writer opens a BufferedOutputStream for each file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_TEYqdWKh1A32GzA.png" /><figcaption>Image by author</figcaption></figure><p>Once all records were written to the respective output stream, all the partition files are combined into one partitioned output file. This is done by reading each file using a FileInputStream and copying it using the Utils.copyStream method. This function copies all data from a FileInputStream to a FileOutputStream. Finally, an index file is created to enable readers to load data for a specific partition from the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/0*31SxRtJxXm0JoI6e.png" /><figcaption>Image by author</figcaption></figure><p>When looking at the hash-shuffle from a performance perspective it is valuable to know one implementation detail about it: The Utils.copyStream method implements two ways of copying a stream: either it uses the java.nio library, or it uses the FileOutputStream directly. The former approach utilizes the implementation of the java.nio.channels.FileChannel.transferTo method. This method copies bytes from the source location on the disk to the target location (eventually) without loading them into memory. Dependent on the actual implementation this may be achieved by using direct memory access (DMA). DMA offloads the work for loading and writing bytes from the CPU to a DMA controller which handles the transfer of bytes directly. In this case, the CPU only needs to initiate the transfer by programming the DMA controller. In the documentation of the transferTo method it says: “This method is <strong>potentially</strong> much more efficient than a simple loop […]. <strong>Many</strong> operating systems can transfer bytes directly […]“. This emphasizes the fact that it is highly dependent on the implementation of the transferTo method — and therefore on the OS — whether it is more efficient or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*Qps59g8w0mAnhrkc.png" /><figcaption>Image by author</figcaption></figure><p>If the transferTo is not used (default case) all bytes are loaded to memory from the input stream and are copied to the output stream. This approach certainly places much more work on the CPU and increases memory utilization.</p><h3>What are the pros and cons?</h3><p>The major drawback of the BypassMergeSortShuffle is that it consumes a large overhead of resources for each partition. It opens a file and maintains a BufferedOutputStream for every partition, each requiring a memory buffer of the size of spark.shuffle.file.buffer (default 32k). Resulting in R FileStreams and memory allocated for buffers of the size R * bufferSize — where R is the number of reduce tasks (equivalent to the number of partitions after the shuffle). Consequently, on an executor with C cores there exist C * R open BufferedOutputStreams at a time. Furthermore, after writing the R files, we must re-access and read them (eventually into memory) to create an integrated output file.</p><p>The major advantage (over other approaches) is the bypassing of the merge sort. As all intermediate files only contain records from a single partition, these files can be combined to form a partitioned output. Within each partition, however, the records are unordered.</p><h3>What are the preconditions?</h3><p>Considering these properties of the BypassShuffleMergeSort, it is beneficial to use only in certain situations: There is no point in opening a separate output file for each partition if a map-side combiner and aggregation is specified for the shuffle. In this case only one record would be written to each file. More importantly, it is reasonable to use the BypassMergeSort only for shuffling a <em>small</em> (whatever that means) number of partitions as we have a large overhead for each partition.</p><p>That brings us straight to the pre-conditions that need to be met in order for the hash-shuffle to be chosen by the ShuffleManager:</p><ol><li><strong>No map-side combine &amp; aggregation</strong></li><li><strong>Small number of partitions:</strong> The number of output partitions of a shuffle is less or equal than the configuration parameter spark.shuffle.sort.bypassMergeThreshold.</li></ol><h3>What can we configure?</h3><p>There are some configuration parameters that can be adjusted to influence the behavior of the hash-shuffle:</p><ol><li><strong>spark.shuffle.sort.bypassMergeThreshold (default: 200):</strong> Only if the number of output partitions is smaller that the specified threshold, BypassMergeSortShuffleWriter will be used for the shuffle.</li><li><strong>spark.shuffle.file.buffer (default: 32k):</strong> This configuration specifies the memory buffer allocated by every output stream. A buffer of this size will be allocated for every partition.</li><li><strong>spark.file.transferTo (default: false):</strong> Whether the java.nio.channels.transferTo method should be used. This method — dependent on its implementation — enables to copy data between files using direct memory access (DMA).</li></ol><h3>Conclusion</h3><p>The goal of a shuffle writer implementation is to create a partitioned map output file so that the subsequent stage can fetch relevant data. The BypassMergeSortShuffleWriter is one of three implementations and — as the name suggests — bypasses the merge sort that is performed by the alternative shuffle strategies. It is based on a very simple approach of opening a file for every output partition and commits records respectively. This approach certainly has its limitations and is beneficial to use merely in a limited set of use cases. The main drawback is that a buffer of a fixed size is allocated in memory for every output partition which makes it unfeasible to be used with many partitions. For a small number of partitions it might, however, be a good choice as it removes work for sorting records from the CPU and potentially even the final copying of files. Therefore, the BypassMergeSortShuffleWriter can be seen as highly specialized optimization for a very specific shuffle use case — in contrast to its actual origin of being an early and naive implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9aed2d587b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Apache Spark Shuffle]]></title>
            <link>https://medium.com/@philipp.brunenberg/understanding-apache-spark-shuffle-85644d90c8c6?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/85644d90c8c6</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[technical-deep-dive]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 18:51:41 GMT</pubDate>
            <atom:updated>2021-11-11T18:51:41.530Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is dedicated to one of the most fundamental processes in Spark — the shuffle. To understand what a shuffle actually is and when it occurs, we will firstly look at the Spark execution model from a higher level. Next, we will go on a journey inside the Spark core and explore how the core components work together to execute shuffles. Finally, we will elaborate on why shuffles are crucial for the performance of a Spark application.</p><p>Currently, there are three different implementations of shuffles in Spark, each with its own advantages and drawbacks. Therefore, there will be three follow-up articles, one on each of the shuffles. These articles will deep-dive into each of the implementations to elaborate on their principles and what performance implications they inherit.</p><p>In order to be able to fully understand this article you should have a basic understanding of the Spark execution model and the basic concepts: MapReduce, logical plan, physical plan, RDD, partitions, narrow dependency, wide dependency, stages, tasks, ShuffleMapStage and ResultStage.</p><h3>Recab: What is a shuffle?</h3><p>To understand when a shuffle occurs, we need to look at how Spark actually schedules workloads on a cluster: generally speaking, a shuffle occurs between every two stages. When the DAGScheduler generates the physical execution plan from our logical plan it pipelines together all RDDs into one stage that are connected by a narrow dependency. Consequently, it cuts the logical plan between all RDDs with wide dependencies. The final stage which produces the result is called the ResultStage. All other stages that are required for computing the ResultStage are called ShuffleMapStages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GQXf0tZ0J6wELP6R.png" /><figcaption>Image by author</figcaption></figure><p>By the definition of a ShuffleMapStage (ending in a WideDependency) there must occur a redistribution of data before the subsequent stage can run. Hence, every stage has to end with a shuffle. Intuitively, we can think of the physical execution plan as a series of map steps (in the MapReduce paradigm) that exchange data according to some partitioning function.</p><h3>What happens during a stage?</h3><p>The physical plan that was generated by the DAGScheduler consists of stages, which in turn consist of tasks. The evaluation of a stage requires the evaluation of all partitions of the final RDD in that stage. Therefore, there will be one task for each of the partitions and, hence, the number of tasks of a stage is equal to the number of output partitions of the final RDD.</p><p>Once we start evaluating the physical plan, Spark scans backwards through the stages and recursively schedules missing stages which are required to calculate the final result. As every stage needs to provide data to subsequent ones, the result of a ShuffleMapStage is to create an output file. This output file is partitioned by the partitioning function and is used by downstream stages to fetch the required data. Therefore, the shuffle occurs as a implicit process which glues together the subsequent execution of tasks dependent stages.</p><p>When executing an action, the executors in our cluster do nothing different than executing tasks. This execution follows a general procedure for every tasks. Let’s go through the execution of a single ShuffleMapTask on an executor:</p><ol><li><strong>Fetch:</strong> Each executor will be scheduled a taks by the TaskScheduler. The task contains information about which partition to evaluate. So the executor will access the map output files of previous stages (potentially on other workers) to fetch the outputs for the respective partition. The whole process of fetching the data, i.e. resolving the locations of the map output files, its partitioning, is encapsulated in each executors block store.</li><li><strong>Compute:</strong> The executor calculates the map output result for the partition by applying the pipelined functions subsequently. Note that this still holds true for plans generated by SparkSQL’s WholeStageCodeGen because it simply produces one RDD (in the logical plan) consisting of one function for all merged functions during the optimization phase. Meaning that from an RDD point of view there is only one MappedRDD initially.</li><li><strong>Write:</strong> The ultimate goal of a task is to produce a partitioned file on disk and registers it with the BlockManager to provide it to subsequent stages. The output file needs to be partitined in order to enable subsequent stages to fetch only the data required for their tasks. Generally, the output files are also sorted by key within each partition. This is required as the subsequent task will fetch the records and applies the function iteratively. Therefore, same keys should occure consecutively.</li></ol><h3>How is a task executed?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WjIK-hGYe1Urarf3.png" /><figcaption>Image by author</figcaption></figure><p>The diagram shows the principal execution of a ShuffleMapTask and the most important components involved. By looking at the flow of execution the structure of a general task described above becomes very apparent: Within the runTask method the partition of the final RDD is evaluated by using its iterator over the records. This iterator internally uses the RDD’s compute method which specifies how to compute the partition. For a ShuffledRDD for example, it accesses the BlockShuffleReader to read the required data. The BlockShuffleReader in turn encapsulates the distributiveness of the records of the partition and is responsible for accessing local and remote block stores to provide the requested records. The BlockShuffleReader uses the ShuffleBlockFetcherIterator which iteratively fetches blocks form the BlockManagers while obeying memory and count limits. The resulting iterator is directly passed to the ShuffleWriter.</p><p>The ShuffleWriter is the component we are going to look at in detail throughout this series of blog posts. Currently, there are three implementations of a shuffle writer each with its own upsides and drawbacks. Which one will be selected is mostly dependent on what kind of operation we want to execute and the configuration. The selection of the respective strategy is done within the only implementation of the ShuffleManager at the moment: the SortShuffleManager.</p><h3>Shuffles and performance</h3><p>If we look at the execution of tasks from this perspective and realize that nothing else happens on executors than the three fundamental steps described above, it becomes obvious to see that these are the only three places where performance bottlenecks can occur. We also understand that basically all of these steps happen simultaneously on each executor and stress all of our resources:</p><ul><li><strong>CPU</strong>: Used for evaluation of functions, serialization, compression, encryption, read/write operations.</li><li><strong>Memory</strong>: Used by buffers for fetch and write, heap for execution, heap used for cache.</li><li><strong>Network</strong>: Used while reading data from other workers, providing data to other workers.</li><li><strong>Disk</strong>: Writing intermediate results to disk, loading previous map output files that are red by other workers.</li></ul><p>However, it has been found that the main bottleneck in modern clusters is the CPU. This is because many tasks are CPU-bound and disks and networks in today’s clusters provide decent throughput. Therefore, large efforts have been put into ‘bringing Spark closer to bare metal’ through project tungsten. One of the efforts made resulted in a shuffle strategy (an implementation of ShuffleWriter) called ‘tungsten-sort’. Meaning, that performance and resource consumption of shuffles in general could differ significantly, dependent on what shuffle implementation is used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85644d90c8c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the right data model]]></title>
            <link>https://medium.com/@philipp.brunenberg/choosing-the-right-data-model-7fa01f87ac79?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa01f87ac79</guid>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 18:49:08 GMT</pubDate>
            <atom:updated>2021-11-11T18:49:08.423Z</atom:updated>
            <content:encoded><![CDATA[<p>One essential choice to make when building data-driven applications is the technology of the underlying data persistence layer. As the database landscape becomes more and more densely populated, it is essential to understand the fundamental concepts and their implications to choose the appropriate technology for a specific use-case. A very comprehensive overview on a conceptual level can be found in Martin Kleppmann’s big data bible “Designing Data-Intensive Applications”. Kleppmann writes: “… every data model embodies assumptions about how it is going to be used. Some kinds of usage are easy and some are not supported; some operations are fast and some perform badly; some data transformations feel natural and some are awkward.” He compares currently existing data models by considering various criteria. Here, I will use these criteria to provide an overview of existing concepts and to elaborate on their advantages and shortcomings.</p><p>The properties I find most useful to distinguish different data models and to compare them against each other are the following:</p><ul><li>Schema flexibility: Whether a schema is required and when it is enforced. Two major categories exist: schema-on-write and schema-on-read. The former one ensures that only data compatible to the schema can end up in the data store. The latter one allows data of all format in the database and offloads compatibility issues entirely to the consuming process.</li><li>Data storage locality: Whether related data is stored closely located (nested data) or in multiple places (various tables). Referencing data can be achieved using foreign keys (meta data stored along the referenced data) or pointers using addresses (non-exposed meta data managed by the database).</li><li>Join support: Whether a database system supports the resolution of references using joins.</li><li>Impedance mismatch: The degree of divergence between the application model and the database model (e.g. object-oriented vs. relational model). The larger the impedance mismatch the higher the effort required from the translation layer (e.g. object-relational mapping).</li><li>Update granularity: The smallest granularity level of updates. The larger the granularity, the more overhead occurs for fine-grained updates (e.g. updating one field in a document requires to re-write the entire document).</li></ul><p>These are sufficient to describe and outweigh advantages and disadvantages of currently existing data models for storing and retrieving data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/0*Mr7cDYgH3vjMa2bW.png" /><figcaption>Image by author</figcaption></figure><p>On a higher level, data models are commonly distinguished by the schema flexibility. Two major groups evolved, which are basically separated by this property: SQL and NoSQL. The relational data model (SQL) enforces the schema on write. Meaning that data that is inserted into a table necessarily needs to match a static schema. Otherwise the insert fails. This is similar to compile-time type checking as it fails early before the execution. NoSQL models on the other hand support so called dynamic schemata, also referred to as schema-on-read. This means that any kind of data can be inserted into the database without the need to match a schema. Rather the reading process is assumed to handle whatever data is read from the data store. This adds flexibility to the schema of an application as there is no need for migration routines and forward/backward compatibility are much easier to accomplish. This property is especially valuable in times of quick iteration cycles of development teams and zero-downtime deployment requirements.</p><p>The second level distinction is along the data locality axis and further divides the NoSQL technologies into two sets: document models and graph models. Document models store related data close to each other in documents. Related data is nested within documents rather than using references to other entities (foreign keys) like in relational databases. The data model does not consist of entities and relationships but rather of documents with nested entities. This makes it easy to model one-to-many relationships without joins. However, many-to-one relationships are complex to realize as data would either be duplicated in all documents or needed to be referenced. Joins, however, are in general not supported by document models so that the application layer would need to implement the logic of resolving many-to-many and many-to-one relationships. Document databases have the advantage of being very close to the object-oriented model by supporting nested objects. This reduces the impedance mismatch and therefore the complexity in the translation layer.</p><p>A third group are graph databases which provide schema flexibility but in contrast to document models place emphasis on the relations of entities rather then keeping them nested. Graph models like relational models consist of nodes (entities) and edges (relationships). They do not store related data close to each other but provide directly traversable pointers. The data is kept in various places on disk, though, unless in relational models, it is not required to perform joins on ids to resolve relationships. This makes it especially performant to perform recursive queries by simply traversing edges (pointers) of the desired type. Therefore, graph models are very well suited for highly interconnected data with lots of many-to-many relationships. Graph models require indices on properties to enable direct access to nodes.</p><p>The boarders between these categories blur as one adopts concepts from another, trying to compensate shortcomings of particular use-cases. Several implementations of SQL for example provide a keyword for performing recursive joins. However, what can easily be done in graph models requires large effort in relational models even if there exists a convenient way of writing it down. Moreover, it is generally possible to model one data model as representation of another. However, this naturally results in generally overly complex and awkward side effects and certainly vanishes performance advantages of the implementing technology.</p><p>It is valuable to know the underlying concepts of various efforts to store and retrieve data. From these concepts arise implications for the performance of certain operations we might perform on the database system. Having understood these concepts enables us to validate our choice of the data model against our expected access patterns. It might occur the situation, however, where we need to outweigh contradicting use-cases that cannot be served by one single technology. In this case it may be reasonable to choose a database implementation that makes efforts to compensate for the weaknesses of it’s own approach. As requirements change and that particular use-case becomes more important for the application it is crucial to keep in mind the divergence of use-case and model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fa01f87ac79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The bigger picture: How SparkSQL relates to Spark core (RDD API)]]></title>
            <link>https://medium.com/data-science/the-bigger-picture-how-sparksql-relates-to-spark-core-rdd-api-56b85791c44c?source=rss-6edbaee01d5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/56b85791c44c</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[notes-from-industry]]></category>
            <dc:creator><![CDATA[Philipp Brunenberg]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 18:35:52 GMT</pubDate>
            <atom:updated>2021-11-16T21:20:02.615Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/notes-from-industry">Notes from Industry</a></h4><h4>Often times it is said that Spark’s high-level API SparkSQL “builds up on top” of Spark core. However, it’s not so self-evident how. I took a dive.</h4><p>Apache Spark’s high-level API SparkSQL offers a concise and very expressive API to execute structured queries on distributed data. Even though it builds on top of the Spark core API it’s often not clear how the two are related. In this post I will try to draw the bigger picture and illustrate how these things are related.</p><p>The most fundamental concept that the Spark core is based on is the MapReduce. MapReduce is a mixture of declarative and procedural approaches. On the one hand it requires the user to specify two functions — namely, map and reduce — to be executed concurrently on distributed data. This is the declarative part — we only tell MR what to do, not every step of how to accomplish it. On the other hand, the logic within the two functions is of procedural nature. Meaning that we write code which is executed step-by-step on each piece of data. The logic itself — the semantics of the function — is opaque to the framework. The only thing it knows about it are the input and output types of these functions. Thus, automatic optimization is merely possible on the level of map and reduce functions.</p><p>As elaborated in my talk at Spark &amp; AI Summit Europe 2018, Spark core basically adds a new layer of abstraction on top of the MapReduce paradigm. It does nothing different than specifying higher-level transformations which are translated into an optimized chain of map and reduce functions. Optimizations, however, only can happen on the level of map/reduce functions. Consequently, Spark core’s optimization strategy is limited to pipeline <strong>narrow transformations</strong> into stages (<a href="https://www.youtube.com/watch?v=KfrmJTQ_AfA&amp;t=801s">watch this</a> for a deeper understanding of Spark core).</p><p>SparkSQL in contrast provides a way to specify entirely declarative queries on distributed data. In order to do so, however, the structure of the data needs to be known to the framework by providing an explicit schema (i.e. structured data). The API then allows the user to specify queries on the data providing many predefined operators (very similar to SQL). A structured query is therefore a combination of operators — also known as expression. The API provides two ways to specify user queries: using functions defined in Dataset-API, or by writing SQL queries directly. Both ways simply provide a way to tell Spark how the resulting Dataset can derived from the input Dataset, using predefined operators. In some cases, however, if no suitable operator exists in Spark, we see ourselves urged to write so called user-defined functions. These functions are simply a way to execute procedural code on each record.</p><p>The query (or expression) that the user specified to produce the desired result builds up an abstract syntax tree (AST). The tree is composed of expressions and operators, which take expressions themselves. In contrast to Spark core where we assemble a chain of opaque functions being executed, we now have a chain of logical operands that we use to produce the final result. As we can distinguish these operators we can now apply optimization rules on the level of these operations. The Spark optimizer, called catalyst, specifies many generally applicable rules of optimizing such trees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IOtmKz2-Uv9BMGS7.png" /><figcaption>Image by author</figcaption></figure><p>In the first step it transforms an AST into another AST by resolving column and table names using an internally maintained catalog. The resolved logical plan is then transformed into an optimized logical plan by recursively applying optimization rules until a fixed point is reached. Many optimization rules are implemented by the catalyst. However, the catalyst is designed to be easily extendable with custom rules. Note that optimization on an operator level becomes inherently possible as we use logical operators provided by the framework to specify our queries in a declarative way. We could also write user-defined functions for all of the functionality available by SparkSQL. However, we would end up with exactly the same degree of optimization as if we used Spark core: namely, an optimization on stage-level, as stage-internals are opaque to the catalyst.</p><p>Now, the interesting question is: how do we bridge the gap between an AST, representing our query, and the Spark core, which SparkSQL “is build up upon”? There is another major step in the query execution process: physical planning. This step transforms a logical plan into a physical plan by replacing logical operators with physical ones. It does so by applying two sets of optimizations: rule-based and cost-based.</p><p>The rule-based optimization, similarly to the logical optimization, applies a set of rules to transform a subtree into a logically equivalent one. Even though the result stays the same, the rule influences the way the result is produced (e.g. pipelining, predicate pushdown). This step is similar to the transformation step that transforms a logical plan into a physical plan in the Spark core, which pipelines together narrow dependencies into stages. The cost-based optimization, in contrast, replaces operators that have various execution strategies, like joins. Each of the execution strategies may have different implications for the performance. The cost model is utilized to make assumptions about the most efficient strategy.</p><p>Finally, each expression of the optimized AST is transformed into an AST of scala code that evaluates the expression. At runtime, this code is compiled to Java bytecode, which will be shipped to the executors. Pipelining operators and compiling them into a single function reduces the overhead of having to parse the expression AST every single time it needs to be evaluated and reduces virtual function calls. Parsing and compilation refactor theses steps to an only-once task. The generated functions basically implement an iterator that applies the expression to each entry of a partition.</p><p>After the code was generated for pipelined expressions, we build up a logical plan of RDDs. We end up with one RDD for each generated code function and an RDD for every join selected by physical planning. Spark core transforms this logical plan into a physical execution plan consisting of stages and tasks. The physical plan can be executed by the cluster simply by scheduling tasks to the executors.</p><p>We have seen that the benefits of using higher-level APIs like SparkSQL originate from the fact that we write declarative queries using operators provided by Spark. Spark understands the semantics of a query and can optimize on a operator-level by replacing patterns in the query with more efficient ones. Consequently, if we write user-defined functions to express our logic, we prohibit the catalyst form logically optimizing our query, as the code written within the function is opaque to the optimizer. The optimized query is transformed into a physical plan of map/reduce (map/shuffle in Spark terminology) steps during physical planning (by pipelining), which directly relates to the Spark core execution model. The functions executed by each stage are compiled at runtime into Java bytecode and sent to the executors. This reduces overhead for parsing the expression tree again for every record.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56b85791c44c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-bigger-picture-how-sparksql-relates-to-spark-core-rdd-api-56b85791c44c">The bigger picture: How SparkSQL relates to Spark core (RDD API)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>