<?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 Kristof Slechten on Medium]]></title>
        <description><![CDATA[Stories by Kristof Slechten on Medium]]></description>
        <link>https://medium.com/@kristofsl?source=rss-5111ef8b72f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*N1GurVqze_2BiZNw.jpg</url>
            <title>Stories by Kristof Slechten on Medium</title>
            <link>https://medium.com/@kristofsl?source=rss-5111ef8b72f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:30:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kristofsl/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[Conformal predictions]]></title>
            <link>https://kristofsl.medium.com/conformal-predictions-94506997429c?source=rss-5111ef8b72f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/94506997429c</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[uncertainty]]></category>
            <category><![CDATA[conformal-prediction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Kristof Slechten]]></dc:creator>
            <pubDate>Wed, 24 May 2023 20:57:20 GMT</pubDate>
            <atom:updated>2025-03-05T14:56:36.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>This article is a small summary of my notes regarding conformal predictions. Conformal predictions is the new kid on the block in the “measuring uncertainty field” in machine learning.</p><p>Conformal prediction is a framework in machine learning and statistical inference that provides a way to quantify and control the confidence or reliability of predictions made by a model. It aims to address the <strong>limitations of traditional point predictions</strong>, which only provide a single prediction without any measure of uncertainty.</p><h3>Motivation</h3><p>Usually we expect past performance to be a good indicator for future performance. We build a training set, and evaluate our algorithm on a test set and we hope that this represents the context of future predictions.</p><p>We estimate how it will work on future data by testing it on data that we know today, so basically we expect past performance to estimate future performance.</p><p>For instance… The model has a AUC score of 0.9 on the test set and we expect an AUC score of 0.9 on unseen future data.</p><p>But how good are these estimates? Do we have any guarantees? We have a score that is actually telling us something on average (for instance a 90% accuracy on the test test). We really care about how good a prediction is on a single new point and how confident can we be about this new prediction?</p><h3>A practical example regarding uncertainty</h3><p>Let’s take a simple example where you have a neural network that examines an MRI to detect a tumor in the brain. Let’s say our neural network is learned to classify an image into 3 categories / labels :</p><ul><li>Normal</li><li>Tumor detected</li><li>Concussion</li></ul><p>A neural network can have a cross-entropy loss function that will give back a number between 0 and 1 and this number will represents a concept of confidence. For highly critical decision making this is a problem since we have no assurance that our model is well-calibrated in terms of their predicted probabilities. This means that a score 0.8 does not necessarily correspond to an 80% confidence level in the true label.</p><p>There are several ways to address this problem like bayesian networks, model calibration, etc but in this article we will look at conformal predictions.</p><p>Conformal predictions don’t give you a confidence number for a single prediction, but give you a <strong>set of predictions for which we are X percent certain that the true label is in that set.</strong></p><p>For our case let’s examine both and see which is more useful for a doctor.</p><p><em>Traditional prediction:</em></p><ul><li>Normal 0.9</li><li>Tumor detected 0.05</li><li>Concussion 0.05</li></ul><p><em>Conformal prediction:</em></p><p>We are ≥ 90% sure that this patient has one of the options of this set:</p><p>[ Normal, Tumor, Concussion ]</p><p>In the below case you will be more tempted to accept that you are not certain enough to assume that there is no tumor and further analysis is required.</p><h3>What is so special about conformal predictions?</h3><p>The big difference with other approaches is that you don’t need to analyse your model and don’t need to (re)train the model multiple times (model calibration, ensemble methods, etc) and the model itself doesn’t need to have robust uncertainty incorporated (bayesian networks). The model is a black box in this approach.</p><h3>Concepts in the context of classification</h3><p>We have a classification of images and for conformal predictions we need the following:</p><ul><li>A calibration set of size n (where n is a finite small portion of the data set). This calibration set is never seen by the model.</li><li>A model which estimates the probability distribution for each potential classification label (we have k labels in the example below).</li><li>A new image Xₙ₊₁ that we will use for a conformal prediction</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYzVjEl6uXwVEesZSV1lcA.jpeg" /></figure><p>We now have a function T that takes in a new image and predicts a set which contains a subset of all the possible classes.</p><p>This function T uses the model and the calibration set and the predicted set contains the true class for the new image with high probability.</p><p>The probability can be controlled by x which is a parameter, so if we take x to be 0.1, then we have 90% probability that our image has a classification class which is present in the set that is given by the function T.</p><p>Let’s see an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rp6nlFSzWLIyMJKQhrah-g.png" /></figure><p><em>Image 1:</em> We are sure that it’s a squirrel and the prediction set also contains only one image</p><p><em>Image 2:</em> We are less sure than in image 1 and our prediction set grows to 4 classes</p><p><em>Image 3:</em> We are not certain at all and our prediction set contains 6 classes.</p><h3>Basic simple algorithm</h3><p>Let’s see how we can construct that function T that appears to do all the magic.</p><p><strong>Step 1:</strong></p><p>We need to identify the score of a correct class. Let’s say we have a classification problem with 9 classes, then we will get a classification score between 0 and 1 for each of the classes when using a softmax output for a neural network.</p><p>Only one of them is correct in our single label classification example below. We call the value for the correct label Eᵢ</p><p>When we do this for each sample in the calibration set, then we have a collection of E values of size n (size of our calibration set).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgPtfC5E5FmAkR9-OdXDug.jpeg" /></figure><p><strong>Step 2:</strong></p><p>We have a bag of E values of size n and let’s sort them and take the 10% quantile of the n E values. n is not infinite but if it was, then there’s a 90% chance that a new E value would have a value bigger then our 10th quantile.</p><p>n is off course finite so we take a small finite sample correction into account for the fact that n is not infinite. This is why we don’t take the exact 10th quantile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPX-CPr_HdJxxf_AIEqkGw.jpeg" /></figure><p><strong>Step 3:</strong></p><p>You can take a new prediction where each class has a score and only keep the scores that are above your 10% quantile value and form a set.</p><p><strong>Summary :</strong></p><p>These 3 steps are the idea behind conformal predictions and this is a very intuitive and powerful concept.</p><p>We want our prediction set to have the following qualities:</p><ul><li>The set size should adapt to the difficulty of the prediction (bigger sets for more uncertain predictions)</li><li>The set size should not be too big when not needed</li></ul><p>And conformal predictions give use that statistical guarantee and this is true for any algorithm, and dataset, any alpha parameter and any calibration set size if we look at below statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98fyyRFjMdTWIvKd2m6KPQ.png" /></figure><p>(the above should also be 1-alpha on the right side)</p><p>The size of your calibration set will have an impact, but you can choose this impact yourself. You can fill in the size of n in de above formule. When our alpha is 0.1 and our n = 100, then we are the chance that our actual value is in the set is between 90% and 91%. If you want to narrow down this interval, then you need to use a bigger calibration set.</p><p><strong>This means that using a calibration set of size 100 gives you back enormous statistical guarantees in many situations (distribution free for any dataset / algorithm) and this is impressive.</strong></p><h3>General framework</h3><p>We can generalise the above concepts:</p><ol><li>Define a notion of uncertainty (for instance the outcome of your softmax function in a neural network) in your prediction</li><li>Define a score function that uses this notion of uncertainty and gives back a number (in the above example we used the soft max output for the true label).</li><li>Compute q̂ in a way that we correct that we have a finite sample (in the below example we use a calibration set size of 50 and we want 90% confidence (0.1 alpha)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCJJUMFn_hhyqVxlsPF-WA.jpeg" /></figure><p>4. Deploy to the prediction set when our score function result for the new datapoint is above q̂</p><h3>Regression</h3><p>We discussed a simple classification example, but what about regression problems where you don’t have a notion of uncertainty in the prediction.</p><p>We can use quantile regression to solve this problem where we train 2 models that each have small changes to the loss function and where one model predicts the upper limit and the other predicts the lower limit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_qbAAXB74MaZg8DLQODXw.jpeg" /></figure><p>These 2 models estimate quantiles but again we have the same problem. They are an estimate …</p><p>But we can use them as our notion of uncertainty.</p><p>Step 1:</p><p>Our score function is the distance between our boundary line and the actual label. If we have label that is outside the limit, then we have a positive number, if it’s inside the boundary line, then we use a negative number to reflect the distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rUk6sNt125zGsABSFf-nw.jpeg" /></figure><p>Step 2 and 3:</p><p>And now it’s simple. We use the value from the score function and apply the same methodology that we discussed in this article (calculate q̂ and use that to correct the upper/lower limits).</p><p>This is a very basic intro in a fascinating field and hopefully you enjoyed this introduction</p><p>Sources :</p><ul><li><a href="https://www.youtube.com/watch?v=0MsGri8nmJQ">https://www.youtube.com/watch?v=0MsGri8nmJQ</a></li><li><a href="https://youtu.be/nql000Lu_iE">https://www.youtube.com/watch?v=YzTzN3RyFrk</a></li><li><a href="https://youtu.be/YzTzN3RyFrk">https://www.youtube.com/watch?v=nql000Lu_iE</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94506997429c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From spring boot to ZIO]]></title>
            <link>https://kristofsl.medium.com/from-spring-boot-to-zio-d70f0f8d28e1?source=rss-5111ef8b72f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d70f0f8d28e1</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[zio]]></category>
            <dc:creator><![CDATA[Kristof Slechten]]></dc:creator>
            <pubDate>Sun, 21 May 2023 19:28:55 GMT</pubDate>
            <atom:updated>2023-10-24T19:46:09.302Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a small summary of the personal journey that took me from spring boot to ZIO for some of my development cases. This is not a technical discussion regarding spring boot or ZIO, but a story why I use ZIO as my preferred stack for some of my projects.</p><p>I’ve been a java developer when I finished my master computer science many years ago and I switched to become a data scientist before the AI hype.</p><p>Although I mainly like data science and applied math, I’m still a software engineer at heart and I believe that a data scientist can also be a good software engineer. I have developed in many languages like java, python, c++, typescript, … but object oriented development was the dominant paradigm. I also believe that you should use the right tool for the job and learning new languages / frameworks have always been an option when I am tackling new types of problems. People evolve / change and languages evolve …</p><p>I worked with the first versions of spring, hibernate, etc. and when spring boot came to live, I was amazed … You could setup up a SOAP project in a few hours … The ecosystem, the documentation, the convention over configuration principle, etc were amazing at that time.</p><p>The J2EE stack was no longer the default for many customers and Spring (Boot) became the standard for Java development in that period.</p><p>As I moved away from Java development, I became a data scientist and I embraced the python ecosystem. The customer for which I’m a data scientist for 5 years now had a Java / Spring / JVM stack for all their web applications and the core of their ERP architecture is an old AS400 system which is still used today and they are slowly transitioning from an on premise data center to GCP.</p><p>They don’t have big budgets and occasionally I still get my hands dirty for “non data science” work like Kafka streams, GCP cloud functions, etc. and the customer and my java colleagues prefer one stack and Spring (boot/cloud/etc) is still the way to go for them.</p><p>After the rise of Java 8 I wanted to learn a new language and Java 8 learned many things from Scala, so I began reading books on Scala as a hobby, while working in python for my professional data science projects. For some data engineering projects I used Scala / Spark.</p><p>I got more intrigued by the benefits of functional style programming after Java 8 and I decided to use functional style scala for some hobby projects and the learning curve was steep but doable. When touching subjects like monad transformers, I felt beauty but I also knew that it was a robust solution for a problem that I didn’t have in my professional context.</p><p>Spring and other frameworks dropped support for Scala and integrating java annotations in a scala project was a hell so Scala remained a hobby language except for the Spark use cases.</p><p>And then I learned about ZIO and saw some talks from John De Goes and the way you could compose functions, schedule them, retry them, etc. struck my curiosity.</p><p>I started to use ZIO for some hobby projects. It gave me that same feeling I had when I first used Spring Boot, but first versions still had some rough edges (lack of documentation, no build in logging, dependency injection was complicated, poor ecosystem, etc) but the good parts were dominating my feeling and I decided to give it a try in a small hobby project and the integration with Java libraries felt more convenient (although I dumped annotation heavy libraries like optaplanner for OR tools to make the integration less painful).</p><p>Scala 3 was under development and I saw some preview talks where the “implicit dragons” were tamed with a new better syntax and I liked the evolution of the language (and the python indentation style which is controversial).</p><p>In the meanwhile ZIO 1.0 came out and the ecosystem started to grow. ZIO Kafka was a perfect match for some of the small Kafka consumer projects that I needed and I decided to give it a go.</p><p>I became more fluent with ZIO and started to expand the use case of ZIO in small projects where concurrency and parallelism matters. The GCP capabilities expanded a lot over time and Cloud Functions are not always the best / only tool for a problem. We are using cloud run, cloud batch, cloud scheduler, cloud workflows, etc and basically the container approach gives freedom and I managed to move away from python / spring boot and use ZIO 2 / Scala 3 for some of the small projects that I personally maintain at our customer and even Java developers in our team are starting to appreciate many aspects like the easy unit testing, the readable functional style, the powerful dependency injection mechanism, etc.</p><p>This does not mean that they will ditch spring boot any time soon, but where the spring boot army knife is no longer the best option, I am using ZIO/Scala when working close together with the java team.</p><p>I’ve been using ZIO for some time now and even when making a simple REST API service I can honestly say that I personally would also choose ZIO/Scala over Spring Boot since the Scala 3 tooling is finally becoming stable and I prefer the developer experience of ZIO.</p><p>ZIO / Scala 3 is not my dominant tool as a data scientist in the python ecosystem but when possible I would always consider ZIO/Scala as an option.</p><p>I hope this explains the twitter response that I gave on John his blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d70f0f8d28e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A deep dive into transformers]]></title>
            <link>https://kristofsl.medium.com/a-deep-dive-into-transformers-45687c374749?source=rss-5111ef8b72f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/45687c374749</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Kristof Slechten]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 00:00:20 GMT</pubDate>
            <atom:updated>2023-10-17T13:26:40.601Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)">transformer</a> architecture is taking over the deep learning world at the moment and it’s concepts are behind models like <a href="https://en.wikipedia.org/wiki/ChatGPT">ChatGPT</a> which are currently the new hype and the below blog intro is of course written by ChatGPT itself …</p><p><em>ChatGPT :</em></p><blockquote>The architecture of transformers has revolutionised the field of natural language processing (NLP) in recent years. As a result, NLP models have achieved remarkable accuracy in a wide range of tasks, including language translation, text classification, and question answering. The transformer architecture has been so successful because of its ability to handle long-range dependencies, its parallel processing capability, and its ability to efficiently process sequences of inputs.</blockquote><blockquote>One of the most famous NLP models that have adopted the transformer architecture is OpenAI’s GPT-3, or Generative Pretrained Transformer 3. It has been trained on a massive corpus of text data and has demonstrated remarkable performance in various NLP tasks, such as language generation, question answering, and text completion.</blockquote><blockquote>In this blog post, we will explore the architecture of transformers and why it’s so important for NLP models like GPT-3. We will delve into the details of how transformers work, including the key components of self-attention mechanisms and feed-forward networks. We will also discuss the advantages of the transformer architecture, such as its ability to handle large amounts of data and its parallel processing capabilities.</blockquote><p>If you are curious about what is actually happening behind the scenes, then strap your seatbelt and get ready for the rollercoaster ride where I try to explain the complete architecture step by step …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*EMXvyZ4L7sqTjuBG.jpg" /></figure><h3>1. Introduction and some history</h3><p>In the AI world we have seen many neural network architectures / principles. Up until 2018 the most common influential architectural patterns were :</p><ul><li><a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">Convolutional neural networks (CNN)</a> : This architecture has been dominating the computer vision space to many years.</li><li><a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">Recurrent neural networks (RNN)</a> : This architecture and it’s variants (GRU / LSTM) were dominating the sequence learning space, including the natural language processing (NLP) space.</li></ul><p>Each of the architectures had specific strengths and weaknesses and non of the architectures seemed to generalise extremely well for all types of problems. They all had strong and weak characteristics.</p><p>The transformer architecture looks like the first architecture that can take over the leading innovation role in all problem domains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*76sI0jUzhgS9KNVN.jpg" /></figure><p>It’s architectural foundations are the basis for large language models like <a href="https://en.wikipedia.org/wiki/GPT-3">GPT-3</a> and its variant <a href="https://en.wikipedia.org/wiki/ChatGPT">ChatGPT</a> and 2 milestones from Google have launched this architecture:</p><ul><li>The <a href="https://en.wikipedia.org/wiki/Attention_(machine_learning)">Attention mechanism</a> paper : The paper “attention is all you need” is one of the most influential paper in the deep learning world today and it describes the attention mechanism which is at the core of the transformer architecture.</li><li><a href="https://en.wikipedia.org/wiki/BERT_(language_model)">BERT</a> : BERT was the first language model based on the transformers architecture and it’s performance and scaling possibilities were exceeding other architectures from that period.</li></ul><p>But what’s the fuzz all about? Neural networks have been around for a long time. <strong>What makes transformer based neural networks so special?</strong></p><ol><li><em>Stable differentiable architecture</em></li></ol><p>Neural networks have specific connections between neurons with weights that need to be learned by the network. The network needs to be expressed as matrix multiplications and in the learning phase we need differentiable equations. This means that for any small change in a parameter, we need to be able to calculate the corresponding change in the model error or <a href="https://en.wikipedia.org/wiki/Loss_function">loss function</a>. <strong>The gradients that are calculated need to be smooth and well conditioned.</strong></p><p>As the network is learning you don’t want the slope to change very quickly as the weights are adjusted in the network when you make small steps in any direction for a learnable parameter / weight.</p><p>They also behave much better when the gradient is well conditioned, that is, it’s not radically larger in one direction than another.</p><p>Neural networks is creating differentiable building blocks and the art of them is stacking the pieces in such a way that the gradients don’t change too quickly and are roughly of the same magnitude in every direction.</p><p>Transformers have this characteristic and this makes them easy to train.</p><p>2. <em>Attention window</em></p><p>The attention mechanism was first introduced to solve some of the core problems of <em>recurrent neural networks </em>in the sequence learning /sequence to sequence domain.</p><p><em>Recurrent neural networks</em> suffer from short term memory (vanishing gradients). Simply put those networks have a hard time capturing relationships between entities like words in the sentence that are not close to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*e2tX8OD9nfCyKID1CTdIOw.png" /></figure><p>Transformers tackle this problem with an unlimited reference window if you use enough compute resources and this is done through the attention mechanism. The network can learn relationships between words that are not close to each other as if they are close positioned to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZIX-qRrQos1NNHK4Z1K8w.png" /></figure><p>3. <em>Scaling</em></p><p>An architecture needs to scale well if we want to handle huge amounts of data and compute power. You need to be able to run computations in parallel. Recurrent neural (RNN) networks do not scale very well because of the sequential nature of the architecture.</p><p>As an example in sequence to sequence language translation. The key problem with RNN models was that they ingested the input sentence one word at a time in natural language problems. This makes them very hard to scale because you need the output from the previous word / token / unit to proceed the calculations for the next word.</p><p>The output of the final word in a translated sentence depended on the previous computations. In the below figure you can see a basic encoder / decoder architecture. We can implement this with RNN principles. This means that the word “student” can’t be calculated without having the results for the calculations for “je suis étudiant” and having the results for the calculations for “I am a”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*EilLw_md4uN1TXeai3n7Rg.png" /></figure><p>The transformer network allows you to run some computations in parallel and this is an incredible advantage and this is a huge advantage of the attention mechanism. You could never train a large language model like GPT-3 if your architecture doesn’t scale.</p><p>You can compare it in some way with a convolutional neural network (which scale well) where you take in several pixels and build a representation of an area of pixels. We will explain this in detail in this article.</p><p><em>4. Generalisation</em></p><p>Transformers architectures seem to work well in many domains and generalise better then previous architectures. We see them popping up in research in NLP, vision, time-series, etc.</p><p><strong>In general it should be noted that as brilliant our architecture may be, in the end our network is a next word prediction machine and many of the NLP architectures are trained on simple tasks like predicting a blanked out word in a sentence and the learned network can do tasks like language translation or question answering after fine tuning the base model.</strong></p><h3>2. Overall architecture</h3><p>In the below picture you can see the conceptual architectural drawing of a transformer from the original paper. We will talk you through each of the components in this article and give intuitions where / how the magic happens. We will explain each of the components below and their relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*D_vvYZ1hJHAx8UnK.png" /></figure><h3>3. Embeddings</h3><p>A neural network needs words to be represented as vectors. In a one-hot representation of a language, there is one vector element for each word. For a vocabulary of size <em>N</em> that vector is an <em>N</em>-dimensional space. Each word represents a point in that space, one unit away from the origin along one of the many axes (as you can see in the picture below on the left).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*YIVUrXkMVfmYOVhR.png" /></figure><p>We want to map each of the words in the picture above in a low dimensional space (as you can see in the picture on the right). Each word (and, battery, check, down, etc) can be represented as 2 numbers in the 2 dimensional space on the right and each word is one dot in the representation on the right.</p><p>In a nutshell … Word points are all taken and rearranged (projected, in linear algebra terminology) into a lower-dimensional space. The picture above shows what they might look like in a 2-dimensional space for example. Now, instead of needing <em>N</em> numbers to specify a word, we only need 2. These are the (<em>x</em>, <em>y</em>) coordinates of each point in the new space. Here’s what a 2-dimensional embedding might look like for our toy example, together with the coordinates of a few of the words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*xCdXBEYj64AjaQkI.png" /></figure><p>A good embedding groups words with similar meanings together. A model that works with an embedding learns patterns in the embedded space.</p><p>That means that whatever it learns to do with one word automatically gets applied to all the words right next to it. This has the added benefit of reducing the amount of training data needed. Each example gives a little bit of learning that gets applied across a whole neighbourhood of words.</p><p>An embedding reduces the number of parameters needed by a tremendous amount. However, the fewer the dimensions in the embedded space, the more information about the original words gets discarded. The richness of a language still requires quite a bit of space to lay out all the important concepts so that they don’t step on each other’s toes. By choosing the size of the embedded space, we get to trade off computational load for model accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/0*ylvDjTgpNWQyCBue.png" /></figure><p>It will probably not surprise you to learn that projecting words from their one-hot representation to an embedded space involves a matrix multiplication. Projection is what matrices do best. Starting with a one-hot matrix that has one row and <em>N</em> columns, and moving to an embedded space of two dimensions, the projection matrix will have <em>N</em> rows and two columns, as shown in the above figure.</p><p>The above example shows how a one-hot vector, representing for example <em>battery</em>, pulls out the row associated with it, which contains the coordinates of the word in the embedded space. In order to make the relationship clearer, the zeros in the one-hot vector are hidden, as are all the other rows that don’t get pulled out of the projection matrix. The full projection matrix is dense, each row containing the coordinates of the word it’s associated with.</p><p>These embeddings are used as input and output as you can see in the below overall architectural picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*tNcYGcU2gKQ_2ZvCdKJU2A.png" /></figure><h3>4. Attention</h3><p>Attention is a mechanism that humans use when operating on language. We have the ability to capture relationships between words and how important that relationship is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KhAngmzMg-dmc_ri.png" /></figure><p>In the above example we can clearly see that <em>green</em> has a high attention relationship with <em>apple</em> and <em>apple</em> has a high attention relationship with <em>eating</em>. This attention information is crucial for understanding this sentence and transformers implement this mechanism in a very efficient way in a neural network architecture. This is explained in the next section.</p><h3>5. Self-attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*2MrUirudUUxGx1pkf8Espg.png" /></figure><p>Let’s look at the below sentence: “<em>Kris is funny</em>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OtfyLu2fOar50lgSQCEcKw.png" /></figure><p>We have 3 words (and 3 corresponding input vectors in blue) and for each word we want to create a vector representation that is attention based. That calculation is parameterised by q, K and V</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Sv_MP0hhzvJlLqpiGI30Q.png" /></figure><p>When we calculate A <strong><em>for each word in the sentence</em></strong>, then we can use the below formula which will become clear after reading this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*oh8j4PzER_JWJhxQ.png" /></figure><p>But for our intuition we will see how we will calculate the <strong><em>Attention value A</em></strong> for <strong>one input word and just remember that we will do this calculation for each word separately.</strong></p><p>So let’s focus on the word “<em>funny”</em> and the below explanation is done for each word separately. We will calculate the attention value A3 for the word funny and this value is influenced by the word funny and all the other words in the sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fx7cWSsUM0yA_Rky1sVMwA.png" /></figure><p>To build the attention based vector representation A3 of that word “funny” we will take into account the words <em>kris</em>, <em>is</em> and <em>funny </em>and each word in the sentence is associated with 3 vectors (q, K and V). We will look at all the other words in the sentence and mechanism does this by <strong>calculating q, K and V vectors for each word.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjelZ0rE1AWBtpOaaT5BlQ.png" /></figure><p>And how do we get those vectors (q, K, V) for each word (embedding vector)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1ZqDVBY-oLUW3XPHm2diA.png" /></figure><p>Q, K and V are vectors and they are created by multiplying the embedding by three matrices that we trained during the training process (WQ, WK, WV)</p><p>Multiplying x1 by the WQ weight matrix produces q1, the “query” vector associated with that word. We end up creating a “query”, a “key”, and a “value” projection of each word in the input sentence.</p><p>So what are the Q, K and V vectors supposed to do? How will we use them if we have them for each word?</p><p>Let’s take a step back and give some intuition…</p><p>We know that word embeddings are vectors that represent the semantic meaning of a word. Words with similar meanings may have similar embeddings. <strong>However, in a sentence, the individual meanings of the words do not represent their meanings in the sentence.</strong></p><p>Let’s say V1, V2, V3 and V4 are the word embeddings of words in a sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*DvaIidKcbCLVWTdRk8akzA.png" /></figure><p>In this example, we will give self-attention to v3, and compare it with v1, v2, v3, and v4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*BkmOYRYJAJrTYJ92UGBBXg.png" /></figure><p>S31, S32, S33, S34 are not vectors but values (dot product). The dot product is done for comparing the similarity of vectors and word representations in our example. (bigger dot product value equals more similarity)</p><p>The alignment scores, S31, S32, S33, and S34, will tell us how similar the semantic meanings of v3 and each of the four compared words. The higher the alignment score, the more similar the semantic meanings of the words, and the more attention v3 will have to pay attention to the other word in the pair.</p><p>Our 4 values need to be normalised (their sum must be 1) and a <a href="https://en.wikipedia.org/wiki/Softmax_function">softmax</a> function does exactly that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*f9FOvWJ7hsCUUiJ8xHN-Qg.png" /></figure><p>We get 4 new values (W31, W32, W33, W34). These are the attention weights (and we are <strong>not</strong> talking about learnable weights in the network) for each word in relation with the third word.</p><p>In order to determine the total amount of attention the word(v3) should pay to the other words, we multiply the attention weights with their respective original word embeddings and then add all of these values together to get the final word embedding Y3 for the word being compared (v3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*0Y7Ddj_RHQJ3Jqq7V1Wa2Q.png" /></figure><p>This is great but what is actually learned here? There are no learnable weights in the above intuition that can be altered via <a href="https://en.wikipedia.org/wiki/Backpropagation">backpropagation</a> ? When there are no weights to learn, the self-attention weights will essentially be pre-determined and the model won’t be able to learn any deeper connections between two words. This is why we will introduce weights in the self-attention block.</p><p>There are some weights added in the above calculations that can be learned (Mk, Mq, Mv).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1gz7260Nyr1VviHSkqIzA.png" /></figure><p>Mk, Mq, and Mv are simply the key, query, and value matrices/weights that the model will learn.</p><p>Remember that in the calculations above, we only did the self-attention operation for one word, v3. In reality, this will happen to all of the words simultaneously.</p><p>In the below animation we can see the process again for one attention value calculation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J87PWHwnBR5QCVJF.gif" /></figure><p>Let’s translate our intuition into a concrete example with numbers. In our example we have 3 inputs (word vectors) for a self-attention block.</p><p><strong><em>Step 1 : Prepare the inputs</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MGqE9M0qn0uD8XbP.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T92VCcToVeUXZl5_2lxzXw.png" /></figure><p><strong><em>Step 2 : Initialise the weights</em></strong></p><p>Every input must have three representations. These representations are called <strong>key </strong>(orange), <strong>query </strong>(red), and <strong>value </strong>(purple). For this example, let’s take that we want these representations to have a dimension of 3. Because every input has a dimension of 4, each set of the weights must have a shape of 4×3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8WwL1eijwo4XV32n.gif" /></figure><p>To obtain these representations, every input (green) is multiplied with a set of weights for <strong>keys</strong>, a set of weights for <strong>queries</strong>, and a set of weights for <strong>values</strong>. In our example, we initialise the three sets of weights as follows (artificial non realistic values)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISYK4-GVxI8OYyQ-qEgW_w.png" /></figure><p><strong><em>Step 3 : Derive key, query and value for each input</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMeqc15RwyRwE4GmUc03xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXsET_Ki09qpa3S92NvdHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gx0fVXtC7BKCMYiF1TCs9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrzOf8MtJ3o-jhUE9tYyJw.png" /></figure><p><strong><em>Step 4 : Calculate attention score for input 1</em></strong></p><p>We take the query vector from input 1 and do a dot product with all of the key vectors (also the key vector for input 1) and each dot product gives back a score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bizaPcCvbYlFzDFy.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8e0WVKp3xISXlsCVvj-wGw.png" /></figure><p>Our scores vector [2,4,4] needs to be normalised in the next step (the sum of the 3 components should be 1).</p><p><strong><em>Step 5 : Calculate softmax</em></strong></p><p>Take the <a href="https://en.wikipedia.org/wiki/Softmax_function">softmax</a> across these attention scores (blue).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lIXVFeLJAvmGkMPP.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2bgRBlLX1zuAqveRk4zPw.png" /></figure><p><strong><em>Step 6 : Multiply scores with values</em></strong></p><p>The softmax attention scores for each input (blue) is multiplied by its corresponding <strong>value </strong>(purple). This results in 3 <em>vectors</em> (yellow).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R7R4INWL_7LQwKQ4.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rp3iyWfn5HlzWERMYVpcA.png" /></figure><p><strong><em>Step 7 : Sum weighted values to get Output 1</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0VBBMbs-_TAUpPA5.gif" /></figure><p>Take all the <strong>weighted</strong> <strong>values </strong>(yellow) and sum them element-wise:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jpf0_nSnWcIzHZTnlLaQg.png" /></figure><p>The resulting vector [2.0, 7.0, 1.5] (dark green) is Output 1, which is based on the <strong>query representation from Input 1</strong> interacting with all other keys, including itself.</p><p><strong><em>Step 8 : Repeat for input 2 and input 3</em></strong></p><p>We have explained how to get output #1. We need to do the same for output #2 and output #3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*81Y0YqjIkqM1-jIh.gif" /></figure><p>So far so good… This whole self attention mechanism implementation is also called scaled dot-product attention and is schematically visualised below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*fpDpwdR81h9uqCdt.png" /></figure><p>And if we want to map our example to the formula in the paper then it’s time to start thinking in matrices instead of separate vectors so we put our input vectors in one matrix. X1 and X2 are getting stacked when we shift our multiple vector examples into 1 big input matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1ZqDVBY-oLUW3XPHm2diA.png" /></figure><p>Our above example with separate vectors becomes which is a stacked version of X1 and X2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*E-TXTRSvURjPkJ1hwjXTuQ.png" /></figure><p>In our first step we calculated the keys, queries and values separately, but now we will do it with the input matrix X</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*BjttLs2LIZIWEI4V.png" /></figure><p>Every row in the X matrix corresponds to a word in the input sentence and we have a row in each Q, K, V matrix for each input.</p><p>Our scores (Q x K transpose) are also stored in a score matrix like below where we get the attention score for a word (Q) to word (K) combination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*uVPlVMaBBVHR2h8Q8brLuQ.png" /></figure><p><strong>Finally</strong>, since we’re dealing with matrices, we can condense the other steps in one formula to calculate the outputs of the self-attention layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHkoy-9Fy2oYk-bYe-EVJQ.png" /></figure><p>Our scores matrix (Q x KT) is divided by the dimension of the keys to have more stable gradients when doing <a href="https://en.wikipedia.org/wiki/Backpropagation">backpropagation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNYBFay8TtOWQ5f2ZrBDLw.png" /></figure><p>And now we can clearly see that every part of the paper formula is explained in this section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*oh8j4PzER_JWJhxQ.png" /></figure><p>Let’s move on to the next concept in the architecture which is called multi-head attention.</p><h3>6. Multi-head attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*2MrUirudUUxGx1pkf8Espg.png" /></figure><p>In this section we will cover the second type of attention. Roughly speaking we can look at multi-head attention as a big for loop over self-attention. We call one attention calculation a <strong><em>head</em></strong> and multi-head calculation is doing it multiple times.</p><p>The only thing that is different, are our <strong>WQ, WK, WV</strong> matrices and these are separate matrices for each head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*o1ZqDVBY-oLUW3XPHm2diA.png" /></figure><p>The paper further refined the self-attention layer by adding a mechanism called “multi-headed” attention. If we have 2 “heads” then we get the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7i2pwO8YyIFPFJcBPfukg.png" /></figure><p><strong>We can calculate these heads separately / in parallel</strong> because they have separate learned WQ, WK and WV matrices. Each of those were initialised randomly and give different results with the <a href="https://en.wikipedia.org/wiki/Backpropagation">backpropagation</a> optimisation.</p><p>This is al great but one head in the attention model did the following:</p><p>We had in input vector of size 4 (4 dimensions) for each input word. If we have 2 words in our sentence, then our input is a 2x4 matrix :</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*E-TXTRSvURjPkJ1hwjXTuQ.png" /></figure><p>After one attention head we had an output vector with the size of number of words / input for each input vector and this gets stacked (Z — &gt; 2 x 3 matrix)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EfSOLPR096HR6nlZ96wFw.png" /></figure><p>So if we have input vectors of size 4 and if we have 2 words/input vectors in our sentences, then we get back a 2x3 attention head matrix for each attention head (8 2x3 matrices in the picture above).</p><p>This leaves us with a bit of a challenge. The next layer (feed-forward layer) is expecting a single matrix (each word has a single vector representation).</p><p>The solution is simple…</p><ol><li>We concatenate all the attention heads</li><li>We multiply it with a new learnable weight matrix W</li><li>Our result of the multiplication is Z (which has the same dimensions as our input)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5u6Gam504PbtQsjUdqwLrw.png" /></figure><p>So if we put it all together in one overview with a simple input sentence of 2 words (“thinking machines”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Kiu_mMwjDGzjHMc9EU4OA.png" /></figure><p>And again we can see that output Z has the same dimensions as X and this is great if we want to stack multiple similar encoding blocks on top of each other.</p><h3>7. From Self-Attention to an MLP in an encoder block</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*2MrUirudUUxGx1pkf8Espg.png" /></figure><p>In our previous section we saw that we got back a Z vector for each input X. Those Z vectors are then passed through a fully connector forward layer as you can see in the below graphical representation. This is a simplified representation and we will discuss the details at a later stage in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CojY-Jso8p_CHfhQ.png" /></figure><p>Since our dimensions are stable when going through an encoder block, we can easily stack them on top of each other. The output of the previous encoder block is the input for the next encoder block.</p><p>It’s worth to mention that the feed forward network is the exact same network for each vector flowing through it separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OoPVMGtyNfbTf7Ow.png" /></figure><h3>8. The encoder and decoder interactions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*q3OpFcgx1IAeut7zSS9nIw.png" /></figure><p>We have only been talking about encoder blocks that can stack on top of each other. How do they communicate with the decoding part of the architecture at inference time?</p><p>Let’s go through a simple flow with a simple sentence, but let’s also add tokens that represent the start (sos) and the end of a sentence (eos).</p><p>The sentence “Kris is funny” is represented below with both additional tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5Rpkp0k05mzFNqv8wV-bA.png" /></figure><p>We will input this sentence into the encoder section. We calculate Q, K, V based on the learned matrix and the input embeddings and this is passed to a multi-head attention block and it’s output is passed to a feed forward neural network and that output is fed again into an encoder block. And the same procedure happens N times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jM_-s2uE08eoQ_vBQWSrCA.png" /></figure><p>But how does this relate to the decoder? We have 1 output from those stacked encoders.</p><p>We have some output for our stacked encoders, but for the decoder section we start with the fact that our decoding sentence should start with the token &lt;sos&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXlycnslvBsxOy4BfVGeNQ.png" /></figure><p>And the first thing we do, is input that token (&lt;sos&gt;) into the decoder (and ignore the output of the encoder).</p><p>So we input whatever that is already generated or what we already know (of the generated sequence) and now we have not generated anything yet.</p><p>We use that &lt;sos&gt; token to compute Q, K and V for the multi head attention component in the decoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7T9n-X88p5cqHbWj40WYg.png" /></figure><p>And our output from the first multi-headed block in the decoder is used to compute Q for the next multi-headed block in the decoder.</p><p>And then we use the ouput from the encoder to compute K and V. And that combined information is the input for the next multi-headed block in the decoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUFmyMpVWMlhEiKWRwOh8w.png" /></figure><p>Our output from the attention block is then fed to a feed forward neural network (just like we did in de encoder).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mkdM9899T_3DjCyeyH0vA.png" /></figure><p>And this decoder process is also repeated N times and to be clear… <strong>We will input the encoder output in each step again.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I96hKpQo8FHlzhk8wJwZLg.png" /></figure><p>And after those N repeats our decoder outputs the next word in the sentence. In our case we expect it to output “Kris”.</p><p>And then our decoding steps gets repeated again but know we know that our input is “&lt;sos&gt; Kris” which alters our Q value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhso-cFmUYcxekpzsXYHWg.png" /></figure><p>And the above steps are repeated until we get a &lt;eos&gt; token.</p><p>The above mechanism is autoregressive. It takes the previous outputs from the decoder next to the outputs from the encoder as input for each step.</p><p>Schematically our decoder gets the attention / encoder representation of each input word and the previous output from the decoder for each generation step.</p><p>This is all great but why are we stacking encoders and decoders?</p><p>The optimisation through backpropagation (stochastic gradient descent) relies on luck. Most weights are initialized in a random fashion and when there is only one path to the optimal solution, then you need a lot of luck. If you have a lot of paths to the optimal solution, then you are changes are getting bigger …</p><p>Having a single attention layer (just one multi-head attention block and one feed forward block) only allows for one path to a good set of transformer parameters. Every element of every matrix needs to find its way to the right value to make things work well. It is fragile and brittle, likely to get stuck in a far-from-ideal solution unless the initial guesses for the parameters are very very lucky.</p><p>The way transformers sidestep this problem is by having multiple attention layers, each using the output of the previous one as its input.</p><p>The use of skip connections make the overal pipeline robust to individual attention blocks failing or giving wonky results.</p><p>Having multiples means that there are others waiting to take up the slack. If one should go off the rails, or in any way fail to live up to its potential, there will be another downstream that has another chance to close the gap or fix the error. The paper showed that more layers resulted in better performance, although the improvement became marginal after 6.</p><p>Another way to think about multiple layers is as a conveyor belt assembly line. Each attention block and feedforward block has the chance to pull inputs off the line, calculate useful attention matrices and make next word predictions. Whatever results they produce, useful or not, get added back onto the conveyer, and passed to the next layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*scqgCNSlnM3DOkgz.png" /></figure><h3>9. The encoder in detail</h3><p>Up until now we have ignored some details in the encoder block. It’s time to explain those in detail in this section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*0-Z8_Pjcl7x_9m9Pt05cKg.png" /></figure><h4>9.1 Input embedding positional encoding</h4><p>One thing that’s missing from the model as we have described it so far is a way to account for the order of the words in the input sequence. Recurrent neural networks don’t need positional encoding since you input each word sequentially. Transformers (which scale very well) don’t have this sequential way of working, so they need a solution to capture order.</p><p>And order is an important crucial concept. Below you can see an example where order is fundamental.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-DpyB8Kx-2A1FyRhqRzFg.png" /></figure><p>The order representation is the following symbol in the transformer architectural drawing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*iS_v0JjCAhz5wGycN74vIw.png" /></figure><p>To address this, the transformer adds a vector to each input embedding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkCzPgCZbPv5jeXoItkC6g.png" /></figure><p>These vectors follow a specific pattern that the model learns, which helps it determine the position of each word, or the distance between different words in the sequence.</p><p>The intuition here is that adding these values to the embeddings provides meaningful distances between the embedding vectors once they’re projected into Q/K/V vectors and during dot-product attention.</p><p>Let’s look at possible attempts and see why they are not sufficient. How do we choose</p><p><em>Attempt 1:</em> Just add the position in each dimension?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yhom3_WXPosMX7cWP2Asfw.png" /></figure><p>This will not work because we will shift our embedding matrices to much if our position is very large. These shifts will dominate our semantic meanings in the vector space and our original information will get lost.</p><p><em>Attempt 2 :</em> What if we added fractions so that our p vectors will never have very big values?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZCo1UbqSv1cn8yiyL4R2A.png" /></figure><p>We will now never have values bigger then 1 in our positional vectors. But this gives another problem if our sentences have different lengths. Below you can see that the positional vectors for position 1 in sentence 1 and sentence 2 are not the same. This will be confusing for our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8N2GfSKDxMc1nTcJLqpTw.png" /></figure><p>The authors of the paper came up with a clever solution that involves the sine and cosine functions.</p><p>Below we can see the embedding of the word “battery” before and we added the positional encoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*m3jzELY233nTVKNR.png" /></figure><p>The position of the word “battery” in the embedding space acts as the center of a circle. A perturbation is added to it, depending on where it falls in the order of the sequence of words.</p><p>For each position, the word is moved the same distance but at a different angle, resulting in a circular pattern as you move through the sequence. Words that are close to each other in the sequence have similar perturbations, but words that are far apart are perturbed in different directions.</p><p>Let’s take a deep dive and give intuitions regarding the below formulas in the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*l1YA3NOmrIhTp-ab.png" /></figure><p>Let’s say our base transformer uses word embeddings of 512 dimensions (elements). Therefore, the positional encoding also has 512 elements, so we can sum a word embedding vector and a positional encoding vector by element-wise addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ZKQJXY06rM3eYor8" /></figure><p>But why element-wise addition?</p><p>Why do we mix two different concepts into the same multi-dimensional space? How can a model distinguish between word embeddings and positional encodings?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zVwlJFrsWeY6wvYv" /></figure><p>The truth is that this efficient idea works in a magical way when putting both types of information in the same dimensional space.</p><p>Let’s dive deeper …</p><p>Basically we are computing a positional encoding matrix. For each position we want to calculate a value for each dimension of the embedding (d)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nl4AEWYsSCu9-yxz.png" /></figure><p>The notations in our formula are pretty straight forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*qkMtLeH0oS0uJdDniU7m8Q.png" /></figure><p>We have a sequence of length L and let’s say we want to know the positional encoding for position k.</p><p>k : This is our position and it’s always a value between 0 and L-1</p><p>d : The dimension of the output embedding space</p><p>i : This is used for alternating between the cosine and sine functions.</p><p>(i= 0 -&gt; 2i = 0 and 2i + 1 = 1, i = 1 -&gt; 2i = 2, 2i + 1 = 3, etc)</p><p>n : A scalar, set by 10000 by the authors of the attention paper.</p><p>P(k, j) : The position function for mapping position k in the input sequence to index (k,j) in the position encoding matrix.</p><p>To understand the above expression, let’s take an example of the phrase “I am a robot,” with n=100 and d=4. The following table shows the positional encoding matrix for this phrase. In fact, the positional encoding matrix would be the same for any four-letter phrase with n=100 and d=4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2Xsw0d1Dac4lgo5Q46cYg.png" /></figure><p>We can clearly see that the positional encoding for the first word (I) is [0,1,0,1] Our word embedding for the first word is altered in dimension 1 and 3 (if dimension count starts from 0) if we add our positional encoding to the word embedding vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnNnTLBZT3tqM8Hkf8R6XQ.png" /></figure><p>For the second position our word embedding gets pushed in all dimensions [0.84, 0.54, 0.10, 1.0].</p><p>For the third position our word embedding our word embedding again is pushed to all directions [0.91, -0.42, 0.20, 0.98]</p><p>What is the pattern here?</p><p>Let’s take a small recap of our sine function (and this also applies for the cosine function).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOIKs-2kgRgkFirz8J7n7A.png" /></figure><p>If we alter x, then we get a wave-like function with a higher frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pis0KihhjUpmk_iKUwBoqg.png" /></figure><p>And if we alter it again, we get an even higher frequency…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pf8iyaKtdqBmQ1Ikri9Ig.png" /></figure><p>This makes the sine function a good candidate for our problem.</p><p><strong>We want our positional encodings to be small since we don’t want them to become dominant over the semantic distances in the embedding space and we want them to always fall in a specific interval [-1,1] even if our input is very large (for instance many positions in a sentence).</strong></p><p>But there’s a problem… We can get back the same value for multiple inputs and this is a problem is since we want our position encoding matrix to have unique values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpSvrkTJtwGWxvJVCTbstg.png" /></figure><p>The solution is that we use sine and cosine functions with different frequencies. We alter between sine and cosine but we also alter the frequencies when working in multiple dimensions. The even dimensions would always use the sin function but each of those have a different frequency (like below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOaYld0qqWt--N0URUuppQ.png" /></figure><p>The odd dimensions would always use the cosine function but each of those also use a different frequency cosine functions.</p><p>Suppose we draw the positional encoding matrix for n=10,000, d=512, sequence length=100. We can see a nice pattern where every row (position) looks unique for every position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*QYy09VJr-5vGPYfb.png" /></figure><p>If we make our position indexes smaller and our encoding dimensions smaller the pattern is more visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*_jj9797JRvUjkJUp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*_ItBEhN0hF3UkvOGS52xlw.png" /></figure><p>The yellow / green vertical pattern from the picture above is clearly more present near the end off the encoding dimensions.</p><p>Let’s try to build up intuition why this works and how it tells us if words are close to each other …</p><p>As an example we take a word at position 0 with 5 dimensions, so pos = 0 and d = 5. The i in the formula represents the dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYn2uqKJ1cMOhgHHjIkX6A.png" /></figure><p>Now let’s plot a random frequency for the sin function and let’s see what happens if we move the position over the same frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQzFz6O5ywNmS6zj7WZKHA.png" /></figure><p>We can see that we get values within an interval (-1 / 1) and we can see that we have an overlap (p0 and p6 get the same value) as pointed out before.</p><p>So far so good. We said that using multiple frequencies is the solution and this is where the i parameter comes into play in the formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwLaUK3hIntGCdTk_p4Hsg.png" /></figure><p>And how do these different frequencies help? You can see below that on frequency i=4 there is no difference, but if the frequency gets higher we can clearly see the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIZojoYeHWm0QHJwFCCstg.png" /></figure><p>A great simplified analogy for this is thinking of a clock with multiple clock hands (hour, minutes, seconds, etc). The blue line below is the representation of one clock hand and it moves at a certain speed.</p><p>Each clock hand has different speeds and when we combine the information from all the clock hands, we get a unique time or position representation in our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*UD8EgiL9846BUMbx" /></figure><p>One last important note regarding the positional encodings. The encoder in the transformer takes input word embeddings containing positional encodings and applies further operations. If so, why doesn’t the model lose the word positions in the process?</p><p>The transformer circumvents this problem by residual connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qMcxc_PbdKX78Xc4" /></figure><h4>9.2 Skip connections</h4><p>In skip connections, a copy of the input is added to the output of a set of calculations. The inputs to the attention block are added back in to its output and the inputs to the element-wise feed forward block are added to its outputs.</p><p>This is done for 2 reasons:</p><ul><li>Skip connections are nothing new and they were crucial in the <a href="https://en.wikipedia.org/wiki/Residual_neural_network">ResNet</a> architectures. They help keeping the gradients smooth. Attention is a filter, which means that when it’s working correctly it will block most of what tries to pass through it. The result of this is that small changes in a lot of the inputs may not produce much change in the outputs if they happen to fall into channels that are blocked. This produces dead spots in the gradient where it is flat, but still nowhere near the bottom of a valley. These saddle points and ridges are a big tripping point for backpropagation. Skip connections help to smooth these out. In the case of attention, even if all of the weights were zero and all the inputs were blocked, a skip connection would add a copy of the inputs to the results and ensure that small changes in any of the inputs will still have noticeable changes in the result. This keeps gradient descent from getting stuck far away from a good solution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*PlQHevBWv9BQBf1a.png" /></figure><ul><li>The second purpose of skip connections is specific to transformers and is already mentioned. We want to make sure that the order informations is not lost when stacking multiple computations.</li></ul><h4>9.3 Layer normalisation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*WPqwisGvB0Pe1Qol_AMmIA.png" /></figure><p>In the above schema we can see a lot of “Add &amp; Norm” components. These are actually normalisation layers which is shown in detail below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfCKPthu1iKdcyxHuVK1Lg.png" /></figure><p>So what is their purpose? Why do we use them a lot in the architecture?</p><p>Normalisation is a step that pairs well with skip connections. There’s no reason they necessarily have to go together, but they both do their best work when placed after a group of calculations, like attention or a feed forward neural network.</p><p>The short version of layer normalisation is that the values of the matrix are shifted to have a mean of zero and scaled to have a standard deviation of one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*Q0dVb48RU8_s8Vmt.png" /></figure><p>The longer version is that in systems like transformers, where there are a lot of moving pieces and some of them are something other than matrix multiplications (such as softmax operators or rectified linear units), it matters how big values are and how they’re balanced between positive and negative.</p><p>If everything is linear, you can double all your inputs, and your outputs will be twice as big, and everything will work just fine. Not so with neural networks.</p><p>They are inherently nonlinear, which makes them very expressive but also sensitive to signals’ magnitudes and distributions. Normalization is a technique that has proven useful in maintaining a consistent distribution of signal values each step of the way throughout many-layered neural networks. It encourages convergence of parameter values and usually results in much better performance.</p><h3>10. Decoder attention</h3><p>The decoder is pretty much the same as the encoder when dealing with attention. The big difference is that the decoder is autoregressive like already mentioned (it gets the previous decoder output as input).</p><p>This has the consequence that it generates the sequence word by word, you need to prevent it from conditioning to future tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*kgTpA4jdjBftgSpL.png" /></figure><p>For example, when computing attention scores on the word “am”, you should not have access to the word “fine”, because that word is a future word that was generated after. The word “am” should only have access to itself and the words before it. This is true for all other words, where they can only attend to previous words.</p><p>We need a method to prevent computing attention scores for future words. This method is called <strong>masking</strong>. In a nutshell we are making sure that those attention scores are zero. The mask is added before calculating the softmax, and after scaling the scores</p><h3>11. Softmax</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*AnWcIDpKHVZo_voeUgIqGw.png" /></figure><p>We have talked about everything except for the output (sofmax and output probabilities).</p><p>The output of the final pointwise feedforward layer goes through a final linear layer, that acts as a classifier. The classifier is as big as the number of classes you have. For example, if you have 10,000 classes for 10,000 words, the output of that classier will be of size 10,000. The output of the classifier then gets fed into a softmax layer, which will produce probability scores between 0 and 1. We take the index of the highest probability score, and that equals our predicted next word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*bJYvzqTtAfWCKjrp.png" /></figure><p>The decoder then takes the output, add’s it to the list of decoder inputs, and continues decoding again until a “end of sentence” token is predicted.</p><p>The <a href="https://en.wikipedia.org/wiki/Softmax_function">softmax</a> is helpful here for three reasons. First, it converts our de-embedding results vector from an arbitrary set of values to a probability distribution.</p><p>As probabilities, it becomes easier to compare the likelihood of different words being selected and even to compare the likelihood of multi-word sequences if we want to look further into the future.</p><p>Second, it thins the field near the top. If one word scores clearly higher than the others, softmax will exaggerate that difference, making it look almost like an argmax, with the winning value close to one and all the others close to zero. However, if there are several words that all come out close to the top, it will preserve them all as highly probable, rather than artifically crushing close second place results.</p><p>Third, softmax is differentiable, meaning we can calculate how much each element of the results will change, given a small change in any of the input elements. This allows us to use it with backpropagation to train our transformer.</p><p>You made it through the end …</p><p>Thank you for reading this summary on transformers. I hope you enjoyed this blog post which itself is just a summary of the many great resources below on the topic … So all credits to the below resource authors.</p><p>Sources:</p><ul><li><a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></li><li><a href="https://kazemnejad.com/blog/transformer_architecture_positional_encoding/">https://kazemnejad.com/blog/transformer_architecture_positional_encoding/</a></li><li><a href="https://towardsdatascience.com/illustrated-guide-to-transformers-step-by-step-explanation-f74876522bc0">https://towardsdatascience.com/illustrated-guide-to-transformers-step-by-step-explanation-f74876522bc0</a></li><li><a href="https://alvinntnu.github.io/NTNU_ENC2045_LECTURES/nlp/dl-attention-transformer-intuition.html">https://alvinntnu.github.io/NTNU_ENC2045_LECTURES/nlp/dl-attention-transformer-intuition.html</a></li><li><a href="https://www.youtube.com/watch?v=dichIcUZfOw&amp;t=606s">https://www.youtube.com/watch?v=dichIcUZfOw&amp;t=606s</a></li><li><a href="https://www.youtube.com/watch?v=1biZfFLPRSY">https://www.youtube.com/watch?v=1biZfFLPRSY</a></li><li><a href="https://kikaben.com/transformers-positional-encoding/">https://kikaben.com/transformers-positional-encoding/</a></li><li><a href="https://towardsdatascience.com/illustrated-self-attention-2d627e33b20a">https://towardsdatascience.com/illustrated-self-attention-2d627e33b20a</a></li><li><a href="https://lih-verma.medium.com/query-key-and-value-in-attention-mechanism-3c3c6a2d4085">https://lih-verma.medium.com/query-key-and-value-in-attention-mechanism-3c3c6a2d4085</a></li><li><a href="https://alvinntnu.github.io/NTNU_ENC2045_LECTURES/nlp/dl-attention-transformer-intuition.html#self-attention">https://alvinntnu.github.io/NTNU_ENC2045_LECTURES/nlp/dl-attention-transformer-intuition.html#self-attention</a></li><li><a href="https://towardsdatascience.com/how-to-explain-transformer-self-attention-like-i-am-five-9020bf50b764">https://towardsdatascience.com/how-to-explain-transformer-self-attention-like-i-am-five-9020bf50b764</a></li><li><a href="https://e2eml.school/transformers.html">https://e2eml.school/transformers.html</a></li><li><a href="https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/">https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/</a></li><li><a href="http://jalammar.github.io/illustrated-transformer/">http://jalammar.github.io/illustrated-transformer/</a></li><li><a href="https://towardsdatascience.com/illustrated-guide-to-transformers-step-by-step-explanation-f74876522bc0">https://towardsdatascience.com/illustrated-guide-to-transformers-step-by-step-explanation-f74876522bc0</a></li><li><a href="https://blogs.nvidia.com/blog/2022/03/25/what-is-a-transformer-model/">https://blogs.nvidia.com/blog/2022/03/25/what-is-a-transformer-model/</a></li><li><a href="https://medium.com/inside-machine-learning/what-is-a-transformer-d07dd1fbec04">https://medium.com/inside-machine-learning/what-is-a-transformer-d07dd1fbec04</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45687c374749" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vehicle routing optimisation in ZIO 2 / Scala 3]]></title>
            <link>https://kristofsl.medium.com/vehicle-routing-optimisation-in-zio-2-scala-3-6eebaa87bff4?source=rss-5111ef8b72f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eebaa87bff4</guid>
            <category><![CDATA[vehicle-routing-problem]]></category>
            <category><![CDATA[scala-3]]></category>
            <category><![CDATA[zio]]></category>
            <category><![CDATA[google-or-tools]]></category>
            <dc:creator><![CDATA[Kristof Slechten]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 12:34:37 GMT</pubDate>
            <atom:updated>2023-03-11T15:16:08.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article describes a toy implementation of the capacitated vehicle routing problem in scala 3 / ZIO 2.0.</p><p>ZIO is a purely functional, type-safe, composable library for asynchronous, concurrent programming in Scala</p><h3>Vehicle routing problem</h3><p>The <strong>vehicle routing problem</strong> (<strong>VRP</strong>) is a problem which asks:</p><blockquote>“What is the optimal set of routes for a fleet of vehicles to traverse in order to deliver to a given set of customers?”</blockquote><p>It generalises the travelling salesman problem (TSP). Determining the optimal solution to VRP is NP-hard. Simply put, it will take an extremely long time to calculate the optimal solution if your problem context (routes / customers / constraints) becomes large. This is a typical exponential problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jk5WLrQ-3xJt7rmf.png" /></figure><p>We see examples of VRP every day:</p><ul><li>Meal prep companies delivering food from central kitchens to hungry homes</li><li>Delivery vans that bring you groceries from local stores</li><li>Couriers who deliver packages to your office</li></ul><p>Essentially, you have a fleet of vehicles and a collection of stops. You’re trying to figure out:</p><ol><li>Which vehicle should I assign to each stop?</li><li>What order should the vehicles visit those stops to minimize distance (while satisfying any other constraints you might have)</li></ol><p>The problem statement is easy to put together. It’s the solutions that are difficult to find. So.. It’s okay if you’ve been struggling to plan your routes efficiently.</p><p>Planning routes isn’t hard, which is why people have been able to do things manually for so long. The difficult part is planning <em>optimized</em> routes, and when you add constraints that are important for your business, planning optimized routes gets nearly impossible for a human to do without some help.</p><h3>Constraints</h3><p>In this example we are going to optimise the total distance and you can define the following constraints in our example:</p><p><em>General constraints:</em></p><ul><li>How long can our optimisation algorithm take in seconds?</li></ul><p><em>Customer specific constraints:</em></p><ul><li>What capacity in grams in needed for serving the customer that day?</li></ul><p><em>Vehicle specific constraints:</em></p><ul><li>What is the capacity of the vehicle in grams?</li></ul><p><em>Fleet constraints:</em></p><ul><li>What is the maximum kilometers a vehicle can drive on one day?</li><li>What is the maximum stop count for a vehicle on one day?</li></ul><h3>Architecture</h3><p>The code is written in the ZIO 2.0 ecosystem and consists of the following main components:</p><ul><li>ZIO HTTP : Webserver</li><li>ZIO-JSON : Parsing / generating JSON</li><li>Google OR-tools : Optimisation library</li><li>Radar Backend : To optimize we need distances between the depot and the customers. In this implementation we are using the Radar.com (<a href="https://radar.com/">https://radar.com/</a>) API for getting distance matrices. The free account is limited with 100,000 monthly calls and you can pass the key as an environment variable with the name GEO_KEY to the application / docker image.</li></ul><h3>Code</h3><p>All the code can be found on my github <a href="https://github.com/kristofsl/VRS">https://github.com/kristofsl/VRS</a> and inside the src/resources/instruction.txt you can find the detailed instructions for compiling / running the container</p><h3>Usage</h3><ul><li>clean : sbt clean</li><li>compile : sbt compile</li><li>assembly of fat jar : sbt assembly</li><li>creation docker container : docker buildx build — platform linux/amd64 -f ./project/dockerfile -t zio-vrs:1.0 .</li><li>run the container : docker run -d — name zio-vrs — restart unless-stopped -e “GEO_KEY=?” zio-vrs:1.0</li></ul><p>Remark : replace the ? with a free valid radar API key</p><h3>Example request / response</h3><p>In the below example you can find a sample request / response. All the fields are required.</p><h4>Request:</h4><pre>{<br>    &quot;locations&quot;: [<br>        {<br>            &quot;location&quot;: {<br>                &quot;latitude&quot;: 51.24601563591366,<br>                &quot;longitude&quot;: 4.416294928800372<br>            },<br>            &quot;name&quot;: &quot;customer_1&quot;,<br>            &quot;uid&quot;: &quot;c_1&quot;,<br>            &quot;weightInGramConstraint&quot;: 20000<br>        },<br>        {<br>            &quot;location&quot;: {<br>                &quot;latitude&quot;: 50.93021966123263,<br>                &quot;longitude&quot;: 5.36893267535137<br>            },<br>            &quot;name&quot;: &quot;customer_2&quot;,<br>            &quot;uid&quot;: &quot;c_2&quot;,<br>            &quot;weightInGramConstraint&quot;: 30000<br>        },<br>        {<br>            &quot;location&quot;: {<br>                &quot;latitude&quot;: 51.10163546963735,<br>                &quot;longitude&quot;: 5.789792511606002<br>            },<br>            &quot;name&quot;: &quot;customer_3&quot;,<br>            &quot;uid&quot;: &quot;c_3&quot;,<br>            &quot;weightInGramConstraint&quot;: 70000<br>        }<br>    ],<br>    &quot;depotLocation&quot;: {<br>        &quot;location&quot;: {<br>            &quot;latitude&quot;: 50.907600055332146,<br>            &quot;longitude&quot;: 5.345893584612312<br>        },<br>        &quot;name&quot;: &quot;depot&quot;,<br>        &quot;uid&quot;: &quot;d_1&quot;<br>    },<br>    &quot;vehicles&quot;: [<br>        {<br>            &quot;vehicleIdentifier&quot;: &quot;small_truck_0002&quot;,<br>            &quot;driverName&quot; : &quot;Pierre&quot;,<br>            &quot;capacityInGrams&quot;: 4000000<br>        },<br>        {<br>            &quot;vehicleIdentifier&quot;: &quot;small_car_0003&quot;,<br>            &quot;driverName&quot; : &quot;Jef&quot;,<br>            &quot;capacityInGrams&quot;: 200000<br>        }<br>    ],<br>    &quot;maxCustomerStops&quot;: 10,<br>    &quot;maxKm&quot;: 400,<br>    &quot;secondsOptimizationLimit&quot;: 60<br>}</pre><h4>Response:</h4><pre>{<br>    &quot;objectiveValue&quot;: 16945094,<br>    &quot;usedVehicleCount&quot;: 2,<br>    &quot;totalKm&quot;: 267.0,<br>    &quot;availableVehicleCount&quot;: 2,<br>    &quot;maxKmVehicle&quot;: 400,<br>    &quot;maxCustomerStopCount&quot;: 10,<br>    &quot;routes&quot;: [<br>        {<br>            &quot;vehicleId&quot;: 0,<br>            &quot;vehicleIdentifier&quot;: &quot;small_truck_0002&quot;,<br>            &quot;driverName&quot;: &quot;Pierre&quot;,<br>            &quot;distanceKm&quot;: 100.0,<br>            &quot;customerStopCount&quot;: 2,<br>            &quot;tour&quot;: [<br>                {<br>                    &quot;location&quot;: {<br>                        &quot;latitude&quot;: 50.9076,<br>                        &quot;longitude&quot;: 5.3458934<br>                    },<br>                    &quot;name&quot;: &quot;depot&quot;,<br>                    &quot;uid&quot;: &quot;d_1&quot;,<br>                    &quot;weightInGramConstraint&quot;: 0<br>                },<br>                {<br>                    &quot;location&quot;: {<br>                        &quot;latitude&quot;: 51.101635,<br>                        &quot;longitude&quot;: 5.7897925<br>                    },<br>                    &quot;name&quot;: &quot;customer_3&quot;,<br>                    &quot;uid&quot;: &quot;c_3&quot;,<br>                    &quot;weightInGramConstraint&quot;: 70000<br>                },<br>                {<br>                    &quot;location&quot;: {<br>                        &quot;latitude&quot;: 50.93022,<br>                        &quot;longitude&quot;: 5.3689327<br>                    },<br>                    &quot;name&quot;: &quot;customer_2&quot;,<br>                    &quot;uid&quot;: &quot;c_2&quot;,<br>                    &quot;weightInGramConstraint&quot;: 30000<br>                },<br>                {<br>                    &quot;location&quot;: {<br>                        &quot;latitude&quot;: 50.9076,<br>                        &quot;longitude&quot;: 5.3458934<br>                    },<br>                    &quot;name&quot;: &quot;depot&quot;,<br>                    &quot;uid&quot;: &quot;d_1&quot;,<br>                    &quot;weightInGramConstraint&quot;: 0<br>                }<br>            ],<br>            &quot;totalWeightInGrams&quot;: 100000,<br>            &quot;vehicleCapacityInGrams&quot;: 4000000<br>        },<br>        {<br>            &quot;vehicleId&quot;: 1,<br>            &quot;vehicleIdentifier&quot;: &quot;small_car_0003&quot;,<br>            &quot;driverName&quot;: &quot;Jef&quot;,<br>            &quot;distanceKm&quot;: 166.0,<br>            &quot;customerStopCount&quot;: 1,<br>            &quot;tour&quot;: [<br>                {<br>                    &quot;location&quot;: {<br>                        &quot;latitude&quot;: 50.9076,<br>                        &quot;longitude&quot;: 5.3458934<br>                    },<br>                    &quot;name&quot;: &quot;depot&quot;,<br>                    &quot;uid&quot;: &quot;d_1&quot;,<br>                    &quot;weightInGramConstraint&quot;: 0<br>                },<br>                {<br>                    &quot;location&quot;: {<br>                        &quot;latitude&quot;: 51.246017,<br>                        &quot;longitude&quot;: 4.416295<br>                    },<br>                    &quot;name&quot;: &quot;customer_1&quot;,<br>                    &quot;uid&quot;: &quot;c_1&quot;,<br>                    &quot;weightInGramConstraint&quot;: 20000<br>                },<br>                {<br>                    &quot;location&quot;: {<br>                        &quot;latitude&quot;: 50.9076,<br>                        &quot;longitude&quot;: 5.3458934<br>                    },<br>                    &quot;name&quot;: &quot;depot&quot;,<br>                    &quot;uid&quot;: &quot;d_1&quot;,<br>                    &quot;weightInGramConstraint&quot;: 0<br>                }<br>            ],<br>            &quot;totalWeightInGrams&quot;: 20000,<br>            &quot;vehicleCapacityInGrams&quot;: 200000<br>        }<br>    ],<br>    &quot;durationMinutes&quot;: 0<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eebaa87bff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anomaly / outlier detection using isolation forest in Scala]]></title>
            <link>https://kristofsl.medium.com/anomaly-outlier-detection-using-isolation-forest-in-scala-9f5f4d6edff9?source=rss-5111ef8b72f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f5f4d6edff9</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[zio]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[isolation-forests]]></category>
            <dc:creator><![CDATA[Kristof Slechten]]></dc:creator>
            <pubDate>Mon, 26 Apr 2021 21:43:19 GMT</pubDate>
            <atom:updated>2021-06-02T23:13:00.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article is describing the journey of implementing the unsupervised learning algorithm <a href="https://en.wikipedia.org/wiki/Isolation_forest">isolation forest</a> for anomaly / outlier detection from scratch.</p><p>Why?</p><ul><li>I could not find a Scala implementation library and implementing the complete algorithm from scratch gave me a good understanding of the algorithm including it’s good and bad parts …</li><li>I wrapped the implementation in a small project that can read actual data from a <a href="https://en.wikipedia.org/wiki/Apache_Kafka">Kafka</a> topic …</li><li>Everybody needs a hobby …</li></ul><h3>What’s the goal?</h3><blockquote>The algorithm is an unsupervised learning algorithm that can inspect numerical multidimensional data and can identify outliers / point anomalies.</blockquote><p>Let’s split up the above statement and explain it in detail.</p><ul><li>The algorithm works on numerical multidimensional data : This basically means that you have some entities that have numerical properties. An example would be a customer order which has the following numerical properties : a <em>price</em>, a <em>margin</em>, the <em>creation throughput minutes</em> , etc.</li><li>Outliers / point anomalies detection : The algorithm identifies abnormal rare items, events or observations which raise suspicions by differing significantly from the majority of the data.</li></ul><h3>That sounds simple?</h3><p>Identifying a point anomaly is an easy task in one dimension. If I were to give you the following order margins, then it would be easy to identify the abnormal margins in the below list :</p><p>[30%, 29%, 31%, 29%, 27%, 32%, 33%, 28%, <strong>4%</strong>, 29%]</p><p>The 4% margin stands …</p><p>But now let’s add the following complexity:</p><ul><li>From an automation perspective you don’t know the distribution of the margin. Maybe it’s a nice <a href="https://en.wikipedia.org/wiki/Normal_distribution">normal distribution</a>, and then you can check the deviation for the average to calculate if a point is an outlier but that’s an assumption which is not always true. The below distribution has anomalies that are close to the average (the middle red cross).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*0bi0yGGCOKj8Z6ZrPKBm8g.png" /></figure><ul><li>An order has a lot of properties and when we add multiple properties, then the problem becomes much harder (since each properties again has an unknown distribution). Let’s explain this in detail in the below section.</li></ul><h3>Multiple dimensions</h3><p>We will describe the problem with 2 dimensions because it’s easy to visualize in 2 dimensions, but in real cases the number of dimensions can be very large.</p><p>In the below picture we look at the margin and the total price of a collection of orders (each cross is an order). The red crosses are clearly anomalies and the black crosses are clearly normal cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*tVy0JRmgjupcZpp9VrpJLQ.png" /></figure><ul><li>If you would only look at the price, then the red crosses would appear normal.</li><li>If you would only look at the margin, then you have the same story.</li></ul><p>If you would have thousands of orders and you would have more then 2 dimensions, then it would be a hard job to manually detect the anomalous orders.</p><h3>Real-time detection</h3><p>The goal is to detect the anomalous entities in a real time fashion which means that we don’t want to collect the data in a CSV, a database or some other medium and do the anomaly detection the day after the data collection which is normal in a BI report/context.</p><p>I want to read a live stream of data and detect the anomalous entities on a live data stream. I have used a Kafka topic as an example, but it can be any streaming data medium.</p><p>I have chosen a tumbling window stream strategy based on the configurable record count. The below picture shows the flow that we want to implement in a continuous loop:</p><ol><li>Take the next 500 records in the stream of data</li><li>Perform anomaly detection on those 500 records and if there is an anomaly, perform some custom logic.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARq0iwF5IiKJsZimKGVYYA.png" /></figure><h3>Isolation forest algorithm</h3><p>This section focuses on the anomaly detection part of the solution. To understand our solution we first need to talk about the different types of anomaly detection. I already stated that the algorithm will identify point anomalies or outliers.</p><h4>Point anomaly detection?</h4><p>Point anomaly detection is a specific type of anomaly detection. As the term says, is an instance that could be considered as anomalous among other instances in the dataset. Point anomalies often represent some extreme value, irregularity or deviation that happens randomly and have no particular meaning. They are also called outliers. This type of anomaly detection is possible on 1 or multiple dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*bZpcr5fQKW-OsPxT.png" /></figure><p>When you add a time of an other contextual feature in the mix, then we talk about contextual anomalies and finding these anomalies is not our goal for this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*AoO3L9mjr_9chCXt" /></figure><h4>Isolation forests algorithm</h4><p>Anomaly detection usually happens in scenario’s where you don’t have a balanced dataset (= you have equal examples for each case of interest). Let’s consider insurance fraud. Suppose we have a dataset of transactions and we know that there is a lot of fraud.</p><p>It’s an expensive investigation and you better have a good argument when investigating a customer for fraude. When looking at a fraud detection dataset we may have 1% labeled fraud cases but there are probably around 10% fraude cases.</p><p>This put’s us in a tough spot. We don’t know the 9% fraud cases. They were never discovered. That makes it hard to build a dataset of normal cases. Most anomaly detection algorithms require a data set of normal cases (for example <a href="https://en.wikipedia.org/wiki/Autoencoder">auto encoders</a>).</p><p>The Isolation forests algorithm requires no <em>normal cases</em> labeling. It doesn’t expect to model the normal cases so that you can measure the deviation from the normal cases when trying to find the anomalies.</p><p>Isolation forests remove the labeling work and take a simple but effective approach with other advantages:</p><ul><li>It has a low linear time complexity and a small memory requirement</li><li>It is able to deal with high dimensional data with irrelevant attributes</li><li>It can be trained with or without anomalies in the training set</li></ul><p>Each point in the training set can be evaluated using the result from the training and you can evaluate new points on the generated isolation forest model. In our scenario we want to train the algorithm every single time when a new chunk of data is evaluated. This can only be done if your training process is fast so that you can use the evaluation in a real time fashion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*5a51yfdasMG__iOBhd1Tew.png" /></figure><p>If your training process is not fast enough, then it’s wise to train the model once every X stages and use that model for inference in the next stages until a new training is scheduled.</p><p>In this article we will focus on the strategy that is in the above picture. Every time we take a chunk of data, then we train a model on that data and use that model again on the training data to get the results for each entity in the training data.</p><h4>Intuition behind isolation forests ?</h4><p>Instead of trying to build a model of normal instances, it explicitly isolates anomalous points in the dataset. It does it via a very simple principle. Anomalous data points in a sample have the following properties:</p><ol><li>Few — they are the minority consisting of fewer instances and</li><li>Different — they have attribute-values that are very different from those of normal instances</li></ol><p>So how does it exploit this? Let’s look at this following simple one dimensional problem setting. We have some blue points that are spread in one dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*53JIMMXnufJMcSvNFpRW4w.png" /></figure><p>We choose a random split (black line below) somewhere between the first point and the last point. This gives us 2 parts for the one dimensional dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*8udBe1_tzzJcSgLNazZl5w.png" /></figure><p>For each part we do the same thing again. We choose a random split somewhere between the first point and the last point (red line below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*ioDy4BZz_WDcRVK9u7HBoA.png" /></figure><p>And this action keeps on going until we have one point in each subpart. Basically we keep represent this splitting mechanism as a <a href="https://en.wikipedia.org/wiki/Binary_tree">binary tree structure</a>.</p><p>This means that we have a binary tree structure and outliers are probably <em>higher</em> in the tree. In other words: <strong>the number of nodes you pass from the root to the node of a point is probably lower for outlier points.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EpV8KuLVldORCKsB.png" /></figure><p>This was a very simple example in one dimension. Let’s look at 2 dimensions and remember the explanation regarding multidimensional points in the beginning of the article…</p><p>The red point is clearly an anomaly …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*cKAC6S1X8DwVvK_TX8m1hQ.png" /></figure><p>But we don’t have to luxury to look in one dimension to search for anomalies. If I would only look along the orange axis, then the red point is not an anomaly. If I only look along the green axis, then the red point is also not an anomaly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*HA7GKSLpCxHbTGOCNEasUg.png" /></figure><p>Let’s see how the splitting strategy we discussed in on dimension might help. We choose one axis and split the data in 2 pieces (with a randomly chosen line in black)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*dxwSOeg18HjlZ_MUYFI33A.png" /></figure><p>For each piece we do the same action. We split each area with a line but this time we choose the other axis for our random line (green lines).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*vAAJnrmTb7H9XqKHkmk_ig.png" /></figure><p>We see that our red point is isolated more quickly then our blue points. This was just a toy example, but the isolation forest algorithm exploits this idea.</p><p>Great … So we have this splitting strategy where we are actually building a tree structure and our anomalies have a higher change of ending up high in the tree.</p><p>Since this splitting strategy has a random non deterministic character, it’s not really reliable for one specific tree. The random forest isolation algorithm solves this by building a lot of trees (hence the name :-))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*ou62actRfXOG3n4Al9C_fQ.png" /></figure><p>In the above picture you can see that we have build 4 trees in which our data point is located in different depths of the generated trees.</p><ul><li>tree left top : 4</li><li>tree right top : 3</li><li>tree left bottom : 3</li><li>tree right bottom : 2</li></ul><p><em>We simply take the average of the tree depths in our forest of trees which is our indication that our data point is an anomaly (avg = 3 in our case).</em></p><p>Some extra important things to note :</p><ul><li>Each tree is build with a relatively small subset of all the data (subsampling)</li><li>Every split will be done on a random dimension in our data.</li><li>Each tree will have a max depth. This means that you only split and at some point you just stop. This gives an “incomplete” tree but that’s fine. It will keep the memory print very low.</li></ul><p>The subsampling strategy helps for the following reasons:</p><ul><li><strong>Swamping</strong>: when normal instances are too close to anomalies, the number of partitions required to separate anomalies increases, a phenomenon known as <em>swamping</em>, which makes it more difficult for an algorithm to discriminate between anomalies and normal points. One of the main reasons for swamping is the presence of too many data for the purpose of anomaly detection, which implies one possible solution to the problem is sub-sampling. Since isolation forest responds very well to sub-sampling in terms of performance, the reduction of the number of points in the sample is also a good way to reduce the effect of swamping.</li><li><strong>Masking</strong>: when the number of anomalies is high it is possible that some of those aggregate in a dense and large cluster, making it more difficult to separate the single anomalies and, in turn, to detect such points as anomalous. Similarly to swamping, this phenomenon (known as “<em>masking</em>”) is also more likely when the number of points in the sample is big, and can be alleviated through sub-sampling.</li></ul><h3>Kafka ingestion</h3><p>Our code will provide a Kafka consumer implementation for the data ingestion part. Our consumer should perform anomaly detection on the data from 1 topic with JSON data.</p><p>A Kafka topic can have multiple partitions and each partition can be assigned to a specific consumer in a consumer group. Our anomaly detection algorithm should inspect the complete data from the topic (coming from multiple partitions). This means that our mechanism should be optimized (non blocking parallel processing where possible) and can’t be scaled / split over multiple consumers in a consumer group since we don’t want to store our data in some medium (a queue or database or … ) and perform the anomaly detection on that persistent medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*28dclr8rjNB_Gz6DtuJGew.png" /></figure><h3>Code</h3><p>Let’s go through the code step by step. Each section represents a particular portion of the code and all source code can be found on github <a href="https://github.com/kristofsl/ZioAnomalyCrawler">here</a>.</p><h4>Configuration</h4><p>Our code should inspect Kafka topics for anomalies. We provide an easy configuration file where you can specify the following:</p><ul><li>The Kafka topic that we want to inspect.</li><li>The Kafka consumer / group id settings</li><li>The bootstrap servers for your connection with Kafka</li><li>The JSON label that contains the unique ID of our record (we don’t assume that there is a Kafka key in the message)</li><li>The JSON label anomaly fields that contain our numeric data that we want to inspect</li></ul><p>Our sample configuration file looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*rkXY-02lWW5vW_f32Rf7mA.png" /></figure><h4>Building a tree</h4><p>Our tree will be a binary tree structure where you have internal nodes and external nodes.</p><ul><li>An external node is a leaf in the tree.</li><li>An internal node will be split into 2 nodes that can be either an internal node or an external node.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*QgPOH3DG0s0wjIgBd5zppQ.png" /></figure><p>Remember that each split is done by choosing a random variable/dimension in the data. We can represent our tree as a recursive algebraic data type structure. Our tree consists of <em>ITree</em> nodes which are either internal or external nodes and depending on the type we have some extra data members.</p><pre><em>/** ADT for the Isolation tree */<br></em><strong>sealed trait </strong>ITree[+A]</pre><pre><strong>case class </strong>ExternalNode[A](value: A, featureName: String, featureIndex: Int) <strong>extends </strong>ITree[A]</pre><pre><strong>case class </strong>InternalNode[A](splitValue:Double, featureName: String, featureIndex: Int, left: ITree[A], right: ITree[A]) <strong>extends </strong>ITree[A]</pre><p>In the below section we can find the pseudocode from the <a href="https://www.semanticscholar.org/paper/Isolation-Forest-Liu-Ting/00a1077d298f2917d764eb729ab1bc86af3bd241">paper</a> for our tree building recursive function. We need a function that receives some input data and a height limit for our output tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*COrT_CUJbQ76V6SB.png" /></figure><p>Since it’s a recursive function we have three parameters:</p><ul><li>The input (which is a subset of all the data)</li><li>The current tree height</li><li>The maximum depth of the tree</li></ul><p>First we need some helper functions:</p><ul><li>A function that can generate a random double between the min and max of a dimension in our data (generate random split)</li><li>A function that generates a random integer for selection a feature in our data</li><li>A function that can split our data (a list) in 2 lists based on the index of the feature.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46a2785ac8e8c1bf8c97e08988a573ab/href">https://medium.com/media/46a2785ac8e8c1bf8c97e08988a573ab/href</a></iframe><p>Every tree that we will build might not have external nodes for each element since we define a max tree depth or the data may contain duplicates at some point. In the below picture you can see that we reached the max depth limit of the tree. We will not split up the data in the red section into subtrees (which means that some nodes in the red section might have more data points)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ukfCLNtsK_SOEJkAQZeQpg.png" /></figure><p>If the data in our node only consists of duplicates for the selected split dimension, then we will also not split up that node (it’s useless since all values are the same in that randomly chosen dimension).</p><p>So let’s build our tree …</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98b4c4a44f9d21e7f5cba98a516307bc/href">https://medium.com/media/98b4c4a44f9d21e7f5cba98a516307bc/href</a></iframe><p>Great …</p><p>We have a way to build a tree with a subsample of our data and we use a random dimension for each split and our tree will not always have a single data record in each external node / leaf (because of duplicate values in a dimension or because of the tree depth).</p><h4>Checking the depth of a record in our tree structure</h4><p>We now need a way to check the tree depth, but this is a problem if our binary tree is not always complete (= not every external node only contains one element).</p><p>What to do with those “incomplete” tree leaf nodes? The paper proposes the following formula based on the fact that our tree is a <a href="https://en.wikipedia.org/wiki/Binary_search_tree">binary search tree</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*9yn5BslUx1vGDyd7uPJ-TQ.png" /></figure><p>Every time we hit a leaf with n elements (=incomplete), then we add the following to the already calculated depth and H(i) can be defined as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*51YjmvSMWfo7AqJsnUualg.png" /></figure><p>This formula uses gamma which is <a href="https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant">Euler’s constant</a> in the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*Fg1OEHI7FiMPbkTEKRug3A.png" /></figure><p>This gives us the following functions:</p><ul><li>Path length : Our function that calculates the depth of a record in our tree.</li><li>C : Our function that compensates if a leaf has multiple values</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cec73b9c48ff32c61e6b78cf453a86c/href">https://medium.com/media/6cec73b9c48ff32c61e6b78cf453a86c/href</a></iframe><h4>Building the forest</h4><p>Remember:</p><ul><li>We want to build a lot of trees based on a subsample of the data.</li><li>We want to use random dimensions for each split in a tree</li><li>We want to build small trees that are not necessarily completely split up.</li></ul><p>So let’s build a forest…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93bd65693f61926ee6481b6696a6e072/href">https://medium.com/media/93bd65693f61926ee6481b6696a6e072/href</a></iframe><h4>Calculating the anomaly score</h4><p>We have a forest of trees. We have a data point. We want to see if it’s an anomaly. The paper gives the following definition for the score that we can calculate:</p><ul><li>s(x,n): Anomaly score for point x given subsample size n.</li><li>E(h(x)): Average depth of element for all the trees in the forest.</li><li>c(n) : Again our compensation function C (see above code section) with our subsample size as input.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*MK2QwTe3YqeXY4RrjyOFwg.png" /></figure><p>This gives us the following code where we use 0.7 as our anomaly border value (you can play around with this value off course).</p><ul><li>Every data record with an anomaly result value ≥ 0.7 is an anomaly</li><li>Every data record with an anomaly result value &lt; 0.7 is a normal point</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ffbf80bf2446d7495d0d7a9a52a876e/href">https://medium.com/media/1ffbf80bf2446d7495d0d7a9a52a876e/href</a></iframe><h4>Reading a Kafka topic</h4><p>We want to have an efficient non blocking Kafka consumer that can take in batches of data and feed that information to our anomaly detection algorithm.</p><p>We use the ZIO effect system library to handle this in a very clean functional non blocking programming style. We only have 3 functions that are tied together for our main program loop.</p><ul><li>Kafka processing grouped within loop function: This is our main loop function that subscribes to a Kafka topic. It groups the records in batch sizes (and if it takes to long, then we just take what is present) that are passed to the process records function. After the processing we are committing the offset.</li><li>Process records function: The main function that is fed with data and should decide what to do with an anomaly. In our below code we just print the result.</li><li>Find json values function: We need to parse JSON in a fast way to retrieve the data that is needed for our algorithm</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c2ff6d13e1e867b5c41508f5f5beb80/href">https://medium.com/media/0c2ff6d13e1e867b5c41508f5f5beb80/href</a></iframe><h3>Conclusion</h3><p>The isolation forest algorithm is a useful lightweight (low linear time-complexity and small memory requirement) multidimensional point anomaly detection algorithm.</p><p>It’s an unsupervised algorithm that removed the “normal cases” labeling and this is a very powerful feature in my opinion.</p><h3>End note</h3><p>The article contains the main code snippets. You can find the full code in github <a href="https://github.com/kristofsl/ZioAnomalyCrawler">here</a>. We could have optimized the algorithm code with ZIO, but I wanted to separate ZIO from the algorithm code.</p><h3>References</h3><ul><li><a href="https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf?q=isolation-forest">Isolation forest paper for the pseudo-code</a> from Fei Tony Liu, Kai Ming Ting and Zhi-Hua Zhou</li><li><a href="https://en.wikipedia.org/wiki/Isolation_forest">https://en.wikipedia.org/wiki/Isolation_forest</a></li><li><a href="https://ziverge.com/blog/introduction-to-zio-kafka/">https://ziverge.com/blog/introduction-to-zio-kafka/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f5f4d6edff9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A gentle introduction to monads]]></title>
            <link>https://kristofsl.medium.com/a-gentle-introduction-to-monads-bc583d41d95?source=rss-5111ef8b72f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc583d41d95</guid>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[flatmap]]></category>
            <dc:creator><![CDATA[Kristof Slechten]]></dc:creator>
            <pubDate>Thu, 04 Feb 2021 00:27:16 GMT</pubDate>
            <atom:updated>2021-03-08T11:36:06.554Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monads?</h3><p>What the hell are monads you ask?</p><p>The formal wikipedia definition says : “<em>In </em><a href="https://en.wikipedia.org/wiki/Functional_programming"><em>functional programming</em></a><em>, a monad is an abstraction that allows structuring programs </em><a href="https://en.wikipedia.org/wiki/Generic_programming"><em>generically</em></a><em>. Supporting languages may use monads to abstract away </em><a href="https://en.wikipedia.org/wiki/Boilerplate_code"><em>boilerplate code</em></a><em> needed by the program logic. Monads achieve this by providing their own </em><a href="https://en.wikipedia.org/wiki/Data_type"><em>data type</em></a><em> (a particular type for each type of monad), which represents a specific form of </em><a href="https://en.wikipedia.org/wiki/Computation"><em>computation</em></a><em>, along with one </em><a href="https://en.wikipedia.org/wiki/Procedure_(computer_science)"><em>procedure</em></a><em> to wrap values of any basic type within the monad (yielding a monadic value) and another to </em><a href="https://en.wikipedia.org/wiki/Function_composition_(computer_science)"><em>compose functions</em></a><em> that output monadic values (called monadic functions).</em>”</p><p>Great …</p><p>It is said that there’s a curse with Monads. I’m not making this up and it’s called the “monad tutorial fallacy” and the legend says that when you finally understand them, you lose the ability to explain it to others. The curse is actually described in 4 steps:</p><ol><li>person X doesn’t understand monads</li><li>person X works long and hard, and groks monads</li><li>person X experiences amazing feeling of enlightenment, wonders why others are not similarly enlightened</li><li>person X gives horrible, incomplete, inaccurate, oversimplified, and confusing explanation of monads to others which probably makes them think that monads are stupid, dumb, worthless, overcomplicated, unnecessary, something incorrect, or a mental wank-ercise</li></ol><p>Great motivation …</p><p>So why write about this beast?</p><p>Monads are building blocks in the functional programming world and we see that functional programming is integrated to some extent in most modern object oriented programming languages.</p><p>Imagine you are an object oriented programmer in a Java 6 world. Our code is a representation of logic and how many times do you find below operations in your code:</p><ul><li>Operations that work on nullable/optional values</li><li>Operations that return a value or an error</li><li>Operations that perform operations on a List/Array</li><li>Operations that have an asynchronous nature.</li><li>Etc.</li></ul><p>Automatically you are responsible for coding below logic:</p><ul><li>Execute the rest of the code only if the value isn’t null</li><li>Execute the rest of the code only if there was no error</li><li>Execute the rest of the code once for each value in the list</li><li>Execute the rest of the code once the asynchronous code is finished</li><li>Etc.</li></ul><p>I see a repeating pattern emerging …</p><p>Wouldn’t it be nice if you could just focus on the core of your logic without worrying about generic logic like “executing the rest of the code once for each value in the list”.</p><p>Wait a second …</p><p>Java 8 is influenced by the functional programming world and introduced concepts like Streams on Lists and Optional. Those concepts seem to fit in the description above …</p><p>Lists / Options / Futures are monads and you’ve been using their Java equivalents without even knowing they were monads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*nSnDSELPgCQkYMDC" /></figure><p>Ok so you have this concept and why should I care about the internals of these concepts? I use some implementations, I like those implementations and I don’t have to understand them completely to take advantage of their power.</p><p>My challenge is twofold here:</p><ol><li>Break the curse and explain what the hell a monad is</li><li>Give insights why it’s a powerful concept that is so much more than the implementations most object oriented programmers are familiar with (Java Optional, etc)</li></ol><p>I learned the concept of monads and it gave me a very different perspective on concepts that I took for granted for many years. The new perspective influenced my code in many ways. (whether it was Java or Scala or Python)</p><p>Monads are everywhere but it doesn’t mean that we need to do anything special with them. You can use them, you can spot them, or completely ignore them and you will be fine.</p><p>But when dealing with large amounts of data or with complex data modelling, I immediately noticed the advantages of taking the monad perspective into consideration when deciding how to write code. Monads are not the answer to every problem but understanding them will give you a different perspective on subtle things and you will think about every “if-check” in your code in new ways.</p><p>This new way of thinking promotes code that is easier to test / more robust / more suitable for parallel / concurrent programming. Monads is a concept that is entangled with functional programming concepts like pure functions, higher order functions, immutability, etc and many of those concepts contribute to your code quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*PkPfhGg8fwslCUZ4" /></figure><h3>Scala?</h3><p>Almost all the code and the examples in this blogpost are written in Scala. Why Scala you ask?</p><ol><li>Today JavaScript is evolving to Java and Java is constantly taking over Scala features. So basically everybody wants to be Scala …</li><li>Scala is the preferred programming language for many data engineers.</li><li>Scala can make senior developers feel very junior. Old programmers like me like to feel young again.</li><li>Scala is sexy</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*4uMJn5fmhsLOU4ua" /></figure><p>I don’t want to hurt the feelings of Kotlin fanboys, but always remember that Kotlin is a better Java and Scala is a more powerful Java …</p><h3>Back to monads?</h3><p>Let’s get started and do a conceptual dive into these mysterious monads.</p><p><strong>Informally, a monad is anything with a constructor and a flatMap method and it’s a mechanism for sequencing computations …</strong></p><p>Well that’s it?</p><p>This is the core that you need to keep remembering and I will guide you step by step through the above statement.</p><p>But before we jump to monads, we have to talk about functors first. Functors? What is that?</p><p>Monads and Functors are both wrapper concepts that have roots in the same math theory (<a href="https://en.wikipedia.org/wiki/Category_theory">https://en.wikipedia.org/wiki/Category_theory</a>). We won’t go into the mathematical details, but think of both concepts as wrappers. The wrapper can be represented as a box around something. In the below image you can see a box that can contain an Integer value.</p><p>The wrapper concept is pretty useless if we are not allowed to do operations on the wrapper. In the below example you can see that we can put a value in the box and can apply a transformation on the value inside the box (if it exists).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*uh4tBSWjidlCTdhJ" /></figure><p>Functors and monads should both provide ways to put something inside the box. The difference between both is that you can call the map() function on the functor and you can call the flatmap() function on the monad. In the above image we have a box that may contain a value. In the Java world this is an Optional (Option in Scala).</p><p>Let that sink in …</p><ol><li>Yes, a Java Optional is a functor because it has a Map function and it’s a wrapper concept.</li><li>Yes, a Java Optional is a monad because it has a FlapMap function and it’s a wrapper concept.</li></ol><p>Ok, so our definition so far is pretty simple. A functor is a wrapper that has a map function and a monad is a wrapper with a flatmap function. Because flatmap is a special map function (= you “map” first and then you “flatten”), we can also conclude that every monad is also a functor.</p><p>Are we there yet? No keep hanging in there …</p><p>Because monads have mathematical roots, we need to understand the laws that apply to monads. Let’s formalise the box / map / flatmap principles :</p><ul><li>We need a Unit function. This function allows us to put a type A in a box F</li></ul><pre>def unit: A → F[A]</pre><ul><li>We need Map functionality, that allows us to apply A → B on the A type inside box F</li></ul><pre>def map: F[A] → (A → B) → F[B]</pre><ul><li>We need a Flatten functionality that allows us to unpack a type A inside 2 boxes F.</li></ul><pre>def flatten: F[F[A]] → F[A]</pre><p>With these three principles in mind we can start to write a formal Scala definition of these principles.</p><ol><li>We need a unit function that takes a parameter of type A and puts it inside the wrapper M.</li><li>Our M type has a trait (interface in JAVA) that says that we need a FlapMap function on our wrapper type. That FlapMap function takes a function as parameter and that function maps a type A to a type B (wrapped inside our wrapper/monad type).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*1ny8d-uMT7ribgIi" /></figure><p>Wait…</p><p>Why is there no Map in the above Scala code? Remember that every flatmap is a special case of a map function. This means that every Map operation can be rewritten as a FlapMap operation. So we don’t need to specify this for our monads in the Scala trait (=Java Interface).</p><p>So where’s the math in all of this?</p><p>Monads have mathematical laws that need to be obeyed by the unit function (=put something in the box) and the flatmap function. These laws are described below:</p><p><strong><em>left-identity law:</em></strong></p><pre>unit(x).flatMap(f) == f(x)</pre><p><strong><em>right-identity law:</em></strong></p><pre>m.flatMap(unit) == m</pre><p><strong><em>associativity law:</em></strong></p><pre>m.flatMap(f).flatMap(g) == m.flatMap(x ⇒ f(x).flatMap(g))</pre><p>We can see this in practice in the below Scala code which checks the monad laws for the Scala Option monad. Examine the code at your own pace …</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d278da00612eb8faa66cd869b78e2625/href">https://medium.com/media/d278da00612eb8faa66cd869b78e2625/href</a></iframe><p><em>This gives us the following output :</em></p><pre><em><br>Let&#39;s dive into the world of monads laws ...</em></pre><pre><em>left identity law -&gt; both below statement are equal</em></pre><pre><em>Some(10)</em></pre><pre><em>Some(10)</em></pre><pre><em>right identity law -&gt; both below statement are equal</em></pre><pre><em>Some(5)</em></pre><pre><em>Some(5)</em></pre><pre><em>associativity law -&gt; both below statement are equal</em></pre><pre><em>Some(16)</em></pre><pre><em>Some(16)</em></pre><p>I hear you thinking. This is all great, but I don’t see what’s the fuss all about…</p><p>In the functional programming world it’s all about functions. Writing the functions is usually not the hard part, but then we have to glue them together in a functional world. Remember our first statement: “a monad is anything with a constructor and a flatMap method and it’s a mechanism for sequencing computations”.</p><p>So let’s first do some sequencing. We will create a user service that retrieves a user object. That user object may have a child (recursive data). I want to see if our user has a grandchild …</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24ab852f53f97afff60b28d0c870ff10/href">https://medium.com/media/24ab852f53f97afff60b28d0c870ff10/href</a></iframe><p><em>This gives us the following output :</em></p><pre><em>Let&#39;s do some sequencing ...</em></pre><pre><em>Jan</em></pre><pre><em>Jan</em></pre><p>This is great as the flatmap operator allows us to chain operations together and to keep doing that for as long as we want. This shows the advantage of flatmap over a map function.</p><ol><li>Using the map operator would allow us to do one map operation and then we run into trouble …</li><li>Using the flatmap operator you can see that our flatmap function remains very clean.</li></ol><p>This is a principle that generalises very well. The above example is very simple but how does it help us in chaining different functions. Remember that we are in a functional programming world. We like to use pure functions that have no side effects. Below you can see 2 pure functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d25a901c00b7f2dac34351da003f4f94/href">https://medium.com/media/d25a901c00b7f2dac34351da003f4f94/href</a></iframe><p>I want to use them and combine them in useful logic. We are in luck. They have Option return types and that happens to be a Monad … This means that we have a flatmap function and this means that we can build sequences with these functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68baf48d4ec23c670612a2462b1bd97c/href">https://medium.com/media/68baf48d4ec23c670612a2462b1bd97c/href</a></iframe><p><em>This gives us the following output :</em></p><pre><em>the monad way ...</em></pre><pre><em>Some(2)</em></pre><pre><em>None</em></pre><pre><em>None</em></pre><p>The semantics of the stringDivideBy method:</p><ul><li>the first call to parseInt returns a None or a Some;</li><li>if it returns a Some, the flatMap method calls our function and passes us the integer aNum;</li><li>the second call to parseInt returns a None or a Some;</li><li>if it returns a Some, the flatMap method calls our function and passes us bNum;</li><li>the call to divide returns a None or a Some, which is our result.</li></ul><p>At each step, flatMap chooses whether to call our function, and our function generates the next computation in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uq1cTa_tBLXDzjT4" /></figure><p>In other words. It stops the chain when it becomes useless to continue. We are not interested in knowing where our chain failed. We are interested in whether our complete chain succeeded or not.</p><p>Ok, so we have a mechanism that allows us to chain clean pure simple functions which are readable and can be tested extremely well (no mocking required). We are able to sequence operations on our Option monad <strong>and</strong> on functions that return our Option monad.</p><p>This sounds very promising, but I already use the “standard” monads like Optional in Java 8. I don’t see the benefits yet in exploring the Monad world any further? Let’s write a monad ourselves for a real problem situation. Suppose you want to combine several functions and keep track of all the operations that are done (a log trail for profiling purposes for instance). Not a real hard problem and it can be solved in numerous ways but today we will choose a custom monad implementation.</p><p>We first create our Monad Class <em>Debuggable</em>. It’s a monad so what do we need?</p><ul><li>A constructor</li><li>A FlapMap function</li><li>An optional Map function</li></ul><p>In Scala you don’t need to specify that constructor and we create a case class that holds a value (the operational value) and a message (the log trail). What else do we need?</p><ol><li>We create our Map function and this just executes the provided parameter function on the value and wraps it inside a new Debuggable object.</li><li>We create our FlatMap function and remember that we will use this for sequencing a chain of operations. It’s identical to our map implementation but now we append the message instead of replacing it.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a3edb74c688e8a8488ea521a83b16a4/href">https://medium.com/media/9a3edb74c688e8a8488ea521a83b16a4/href</a></iframe><p>We seem to have a custom monad. Now let’s create some functions that use our monad (they are all pure functions that return our monad).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bfad35fcd572184789c13119247adc7/href">https://medium.com/media/9bfad35fcd572184789c13119247adc7/href</a></iframe><p>How do we glue the monad and the function together so that we can combine those 3 functions in any way we want and we will get a result and a log trail of our intermediate results.</p><p>Remember that we use the flatmap for sequencing and we use the map in the last step, because this is where the sequencing ends.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5f7aa0521c6c528c5507651b1f7611c/href">https://medium.com/media/b5f7aa0521c6c528c5507651b1f7611c/href</a></iframe><p><em>This gives us the following results:</em></p><ul><li>final result :</li></ul><pre>106</pre><ul><li>log message :</li></ul><pre><em>f: input: 100, result: 101</em></pre><pre><em>g: input: 101, result: 103</em></pre><pre><em>h: input: 103, result: 106</em></pre><p>This is a big step and you can let that sink in … You can create your own monads for your specific needs. The functions above didn’t care how they were combined and in what position they were executed. They just knew that they needed to return a Debuggable object.</p><p>Scala provides syntax that hides the ugly flatmap chaining constructions and you can write it more concise like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5009f6d09e413bf802cb529701cb91/href">https://medium.com/media/9d5009f6d09e413bf802cb529701cb91/href</a></iframe><p><em>This gives us the following output :</em></p><pre><em>final Scala for comprehension value: 106</em></pre><pre><em>final Scala for comprehension msg:</em></pre><pre><em>f: input: 100, result: 101</em></pre><pre><em>g: input: 101, result: 103</em></pre><pre><em>h: input: 103, result: 106</em></pre><p>In the monad world you just witnessed a writer monad (<a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)#Writer_monad">https://en.wikipedia.org/wiki/Monad_(functional_programming)#Writer_monad</a>). The code was not perfect and the code was also not very reusable (you have to return a Debuggable object in your pure functions) but it shows that you can write custom monads for your own needs.</p><p>The imperative solution to this problem is way simpler. Why prefer the monad?</p><p>Let’s say we start to profile code that is using multiple threads. Standard imperative logging technisch can result in interleaved messages from multiple threads. The writer monad doesn’t have this problem and using the monad version will actually simplify your solution. Remember that functional programming shines in the parallel / concurrent programming world.</p><p>This is just a very specific use case and there are many problem patterns that can be solved with Monads. Think of them as one of the gang of four patterns (<a href="https://www.gofpatterns.com/">https://www.gofpatterns.com/</a>) for the functional programming world. Absorb these best practices and decide if the monad implementation is the best fit for your use case.</p><p>A good monad can take in pure clean functions that are robust / easy to test / easy to read / etc. Those clean functions can be used in a monad implementation or in a non monad implementation. The monad should take away the boilerplate context for you. You can write code and use it in the Future Monad context and reuse it in another Monad context or even use it in a non Monad context.</p><p>I hope you now have a feeling of what Monads are and why they matter in certain software development contexts.</p><p>Sources:</p><ul><li><a href="https://alvinalexander.com/scala/functional-programming-simplified-book/">https://alvinalexander.com/scala/functional-programming-simplified-book/</a></li><li><a href="https://www.scalawithcats.com/dist/scala-with-cats.html">https://www.scalawithcats.com/dist/scala-with-cats.html</a></li><li><a href="https://jameswestby.net/tech/why-monads-are-useful.html">https://jameswestby.net/tech/why-monads-are-useful.html</a></li><li><a href="https://blog.rcard.in/object-oriented/functional/programming/2017/08/02/object-oriented-programming-strikes-back.html">https://blog.rcard.in/object-oriented/functional/programming/2017/08/02/object-oriented-programming-strikes-back.html</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc583d41d95" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>