<?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 Tanmay Thakur on Medium]]></title>
        <description><![CDATA[Stories by Tanmay Thakur on Medium]]></description>
        <link>https://medium.com/@tanmaythakurbrn2rule?source=rss-46b642aa7f12------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iR53kGtILLkKV5aP.jpg</url>
            <title>Stories by Tanmay Thakur on Medium</title>
            <link>https://medium.com/@tanmaythakurbrn2rule?source=rss-46b642aa7f12------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:44:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanmaythakurbrn2rule/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[Our metrics ran on the order of how we inserted them]]></title>
            <link>https://medium.com/@tanmaythakurbrn2rule/our-metrics-ran-on-the-order-of-how-we-inserted-them-833e522e170e?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/833e522e170e</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[esg]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 06:10:18 GMT</pubDate>
            <atom:updated>2026-11-05T06:10:18.649Z</atom:updated>
            <content:encoded><![CDATA[<p>How a dependency graph, a loop that runs until nothing changes, and one integer per row fixed a formula engine we had outgrown.</p><p>If you’ve ever built a spreadsheet that got out of hand, you know the moment. One tab feeds another, someone adds a column that refers back to an earlier one, and Excel pops up a warning about a circular reference. It’s annoying, but Excel is doing you two favours at once. It works out which cells depend on which and calculates them in that order, and it tells you when something loops back on itself.</p><p>Our data pipeline did neither. For a long time, nobody noticed.</p><p>I work on the data infrastructure side at Sustainable Labs. We collect environmental, social and governance (ESG) data on about 5,300 listed companies in Japan and turn it into one consistent dataset that people can compare and analyse: emissions, energy and water use, workforce diversity, board composition, and hundreds of other indicators. More and more decisions lean on numbers like these, from how investors weigh a company to how companies benchmark themselves against their peers. A carbon figure that is quietly wrong is worse than one that is missing, because nobody thinks to question it.</p><p>A lot of what people want isn’t disclosed directly. Nobody publishes “CO₂ per employee”. Companies publish their emissions and their headcount, and we divide. So next to the raw data we keep a table of formulas, 126 of them, that derive one indicator from others. In other words, at the heart of our pipeline sits something very much like a giant spreadsheet.</p><p>The pipeline reruns every week. It merges the latest disclosures, estimates what’s still missing, and recalculates, producing millions of rows for each financial year, with history going back to 2011.</p><p>A few months ago we found out that some of those numbers depended on something that had nothing to do with the companies: the order in which our engine happened to run the formulas. This is how we found it, how we fixed it, what the fix cost us, and what we’d tell anyone with a growing pile of derived metrics.</p><h3>A formula table is a graph</h3><p>Our formulas grew one at a time. Someone needed an indicator, wrote a formula, moved on. Many indicators ended up with more than one formula, because companies disclose different things. If a company reports its scope 3 emissions, we can divide by sales to get its scope 3 intensity. If it reports the intensity, we can multiply back to get the emissions. Both formulas are sensible. Side by side, they form a loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Sr5JQHlHiPr6WkQzABE9w.png" /><figcaption>Two reasonable formulas that together make a loop.</figcaption></figure><p>Treat every indicator as a node and every formula as arrows from its inputs to its output, and the formula table becomes a directed graph. Ours had 108 calculated indicators. When we finally drew it, it contained four loops covering 17 indicators. The largest tied together nine greenhouse gas indicators: start at any one of them, follow the formulas, and you can reach all the others.</p><h3>Why the old engine couldn’t cope</h3><p>The engine was built for throughput. It applies each formula to all 5,300 companies at once, so the simplest and cheapest design is a single pass through the formulas in a fixed sequence. Ours ran two passes, set by hand, and within each pass a fixed sequence that had nothing to do with which formula needed which. Each formula ran exactly once.</p><p>With a handful of formulas that was fine. At 126, with loops, it caused three kinds of trouble:</p><ul><li><strong>Inputs read before they existed.</strong> 28 formulas ran before one of their inputs had been calculated. “CO₂ per assets” came before “total CO₂” in the sequence, so it divided by nothing and stayed blank.</li><li><strong>Numbers calculated from themselves.</strong> Say a company reports scope 3 emissions of 1,000 tonnes and sales of 50,000. The engine calculates the intensity, 0.02. Later it reaches the emissions formula, multiplies 0.02 by 50,000, and writes 1,000 back over the reported figure. The number matches, but a disclosed value is now labelled as ours. Add rounding or a unit conversion and the number stops matching too.</li><li><strong>Results that depended on position.</strong> Adding or renaming a formula could move it in the sequence and change its output.</li></ul><p>None of this raised an error. Every value looked plausible. That is what made it dangerous.</p><h3>Step 1: Order by dependencies</h3><p>The tool for this is old and well understood. A <em>strongly connected component</em> is a group of nodes where every node can reach every other one; in our case, a loop or several overlapping loops. Collapse each component into a single node and the graph has no loops left, so it can be sorted. Each indicator’s step is one more than the latest step of anything it reads.</p><pre>import networkx as nx<br><br>g = nx.DiGraph()<br>for target, inputs in formulas:            # (&quot;co2_per_employee&quot;, [&quot;total_co2&quot;, &quot;employees&quot;])<br>    for i in inputs:<br>        if i in calculated:                # reported inputs don&#39;t need ordering<br>            g.add_edge(i, target)<br><br>loops = [c for c in nx.strongly_connected_components(g) if len(c) &gt; 1]<br>dag = nx.condensation(g)                   # every loop becomes one node<br>step = {}<br>for node in nx.topological_sort(dag):<br>    step[node] = 1 + max((step[p] for p in dag.predecessors(node)), default=-1)</pre><p>We wrote our own small version of Tarjan’s algorithm to avoid a new dependency, but the idea is the same. Our 108 indicators fell into four steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G489nGOe-uDzwF-YhLgjXg.png" /></figure><p>Before writing any of the fix, we turned the graph into an interactive page and walked our data quality team through it. People who know the data well spotted problem areas in minutes. If you only take one thing from this article, take that: draw the map and show it to the people who know the domain. That knowledge trumps all.</p><h3>Step 2: Inside a loop, repeat until nothing changes</h3><p>No order works inside a loop, by definition. So the engine runs the loop’s formulas, then runs them again, filling only values that are still blank, until a round adds nothing new. The number of rounds is bounded by the size of the loop, and in practice it stops after one or two. In one of our loops, a company’s number of women managers can only be calculated after its percentage of women managers has been worked out from another formula. A single pass never got there. Two rounds do.</p><h3>Step 3: Never compute a value from itself</h3><p>Repeating formulas makes the self-derivation problem worse unless you stop it. Our rule: a value may never be calculated from something that was itself calculated from that value. To enforce it, every calculated value carries a record of which loop members it was derived from.</p><pre># bit[i] is a distinct power of two for each member of a loop<br>mask = 0<br>for i in inputs_in_same_loop(target):<br>    mask |= derived_from[i] | bit[i]<br><br>if mask &amp; bit[target]:<br>    skip(formula)                  # one of the inputs came from target<br>else:<br>    value = evaluate(formula)<br>    derived_from[target] = mask</pre><p>Only inputs from the same loop matter, because nothing outside a loop can lead back into it. That keeps the record to a single integer per row, and the check is a vectorised bitwise operation over the whole table. It costs almost nothing.</p><p><strong>Order by what a formula needs, not by where it happens to sit.</strong></p><h3>Step 4: Add guard rails</h3><p>We already kept theoretical limits for each indicator; a percentage should sit between 0 and 100, for example. Our final recalculation stage hadn’t been checking them. Now it rejects any result outside the limits instead of writing it. The first run rejected about 6,000 values a year, including water percentages with a median of 466% and an efficiency ratio with a median of minus 540. The formulas assumed a unit their inputs didn’t use. Those values had been published for years.</p><h3>Keeping it cheap</h3><p>The pipeline runs every week on the same AWS containers it always has, and we wanted the fix to fit inside them: no new infrastructure, no bigger machines, no extra storage. A few choices made that possible.</p><ul><li><strong>No new moving parts.</strong> Same container images, same schedule, same database. The graph code is about 150 lines of plain Python with no new libraries.</li><li><strong>The ordering is nearly free.</strong> It’s worked out once per run from 126 formulas and takes milliseconds.</li><li><strong>The provenance record never touches disk.</strong> It’s one integer per row, kept in memory during the run and dropped before saving. The stored dataset has exactly the same rows and columns as before.</li><li><strong>Only loops repeat.</strong> Extra rounds run just the formulas inside a loop, and only for values that are still blank.</li><li><strong>Each step reads only what it needs.</strong> In the recalculation stage, every step loads just the indicators its formulas use instead of copying the whole year.</li></ul><p>For a full financial year, the merge stage went from 275 to 295 seconds, and recalculation went from 54 to 21 seconds. Together that’s about 4% less compute per year than before, while doing more work.</p><h3>Testing a change that touches millions of numbers</h3><ul><li><strong>Run old and new side by side on identical inputs</strong>, and classify every row that differs: newly filled, emptied, changed, or note text only. Trace every category to a cause before you ship.</li><li><strong>Measure the noise first.</strong> Our estimation step moves about 1.2 million values a year by roughly 2.5% on every run, with or without code changes. A naive before-and-after diff is mostly noise. Comparing two runs of the old code gave us the baseline to compare against.</li><li><strong>Turn every real surprise into a test.</strong> Each odd company we found became a small hand-built case in the test suite.</li></ul><h3>New problems the fix created</h3><p>This approach is better, but it isn’t free, and some of what it changed surprised us. If you try something similar, plan for these:</p><ul><li><strong>Part of it is slower.</strong> Repeating loops costs time, and our merge stage got 1 to 7% slower. Overall compute still went down, but only because we also changed recalculation to read just the data each step needs. Without that, the fix would have cost us time.</li><li><strong>Formulas that never ran start running.</strong> Fixing the order woke up formulas that had silently done nothing. Some carried rules nobody had seen in action, such as “a calculated value overrides the reported one”. Values changed that weren’t wrong before, just untouched. Expect to review rules that have never been exercised.</li><li><strong>Correct can mean emptier.</strong> When the engine refuses a circular calculation, or a result outside the limits, the value stays blank. Some numbers users saw before are now missing, because they were never valid. That needs explaining to the people who use the data.</li><li><strong>Mid-run state gets more delicate.</strong> To make later steps see the values that will actually be saved, we put reported values back after each step. In one edge case the “reported value” was an empty reading that had already been rejected, and a later formula tripped over it. That crashed one financial year in production. Our comparisons had covered the first and last years of the range, and the failing case was in between.</li><li><strong>Loops still need a tie-break.</strong> Filling blanks round by round is deterministic, but when two formulas could both fill a value, the formula with more discolure rate wins. That’s a rule, not a truth, and it should be a decision we made on purpose.</li></ul><h3>What we got</h3><ul><li>About 36,000 values that used to be blank are now calculated across ten financial years, most of them CO₂ intensities.</li><li>Six greenhouse gas intensities that had never been calculated now are, about 6,500 values.</li><li>About 6,000 impossible values a year are no longer published.</li><li>The recalculation stage runs about 60% faster, from 54 to 21 seconds per financial year, and the pipeline as a whole uses about 4% less compute per year.</li><li>No extra storage and no new infrastructure: same AWS containers, same schedule, same table size.</li><li>No result depends on where a formula sits in the table, and new formulas are ordered automatically. If someone adds a formula that creates a new loop, the pipeline reports it at the start of every run.</li></ul><p>The bigger change is that we can explain our numbers. For any calculated value we can say which step produced it, which inputs it read, and why any formula was skipped. Total observability and explanability is what we pride ourselves on.</p><h3>What it did for our time series estimates</h3><p>Not every company reports every indicator every year, so after merging we estimate the gaps. For most indicators the first choice is the company’s own history: carry the previous year forward, extend the trend of the last few years, or interpolate between two reported years. When a company has no usable history, we fall back to the median of comparable companies in the same market, sector and region for that year. Estimates that come from formulas are checked against bounds that depend on company size.</p><p>Every one of those reference points (the company’s history, the peer medians, the size groups and the bounds) is built only from values that weren’t themselves estimated. Anything the merge stage produces counts as observed, including the values our formulas calculate. So the formula engine isn’t just one step in the pipeline. It decides what the estimator is allowed to treat as fact.</p><p>That is where the fix paid off a second time:</p><ul><li><strong>More real points to estimate from.</strong> Values that used to be blank are now calculated, so they enter the history and the peer reference as observations instead of being gaps that need guessing. For CO₂ intensities alone, the number of observed values across ten financial years went from about 8,500 to about 38,300.</li><li><strong>Fewer bad points spreading.</strong> A value calculated from itself, or one that depended on where a formula sat, used to enter the reference data as if a company had disclosed it. Through peer medians, one distorted company could move the estimates of every similar company.</li><li><strong>A history that only moves for real reasons.</strong> Trends are extended from a company’s past values. Now that results don’t depend on formula position, those past values change only when a disclosure or a source changes, not because the engine ran things in a different order.</li></ul><p>Estimation is also where we learned to respect noise. Re-estimating every week moves about 1.2 million estimated values a year by around 2.5%, simply because new disclosures shift the trends and medians they’re built on. That’s expected behaviour for a time series that keeps getting new data, and it’s why we compare every change against that baseline. What we haven’t done yet is measure how much more accurate the estimates became; that needs a set of held-out disclosures to test against, and it’s our next step.</p><p><strong>Formula tables age like code but rarely get reviewed like code. Drawing ours on one page was the most useful hour of the whole project.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833e522e170e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Elasticsearch : A short guide]]></title>
            <link>https://medium.com/goalist-blog/leveraging-elasticsearch-a-short-guide-17f6266e459d?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f6266e459d</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 11:18:11 GMT</pubDate>
            <atom:updated>2024-04-15T11:18:11.878Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leveraging Elasticsearch : A short guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*bWEFyNH_CQ6-SaXoYUG_TQ.png" /></figure><p>What is Elasticsearch?</p><p>It is a distributed, open-source search and analytics engine designed for handling large volumes of structured and unstructured data. It is a databse that provides a scalable solution for real-time search, analytics, and data visualization.</p><p>At its core, Elasticsearch is designed to index and search large datasets quickly and efficiently. It utilizes a distributed architecture that allows it to horizontally scale across multiple nodes, enabling it to handle petabytes of data and support high-throughput search and analytics workloads.</p><p>One of the key advantages of Elasticsearch is its ability to provide near real-time search results. As data is indexed into Elasticsearch, it becomes immediately searchable, allowing users to retrieve relevant information quickly, regardless of the size of the dataset.</p><p>Elasticsearch is widely used in various industries and applications, including e-commerce, content management systems, log analytics, cybersecurity, and business intelligence. Its flexibility and versatility make it suitable for a wide range of use cases, from powering search engines on websites to analyzing log data for system monitoring and troubleshooting.</p><p>Let’s now discuss in short how Elasticsearch is built up:</p><h3><strong>Nodes</strong></h3><p>Nodes are individual instances of Elasticsearch running on a server or virtual machine. Each node can perform various roles, such as data storage, data indexing, and query processing. Nodes can be categorized into different types based on their roles, such as master-eligible nodes, data nodes, and coordinating nodes.</p><h3><strong>Cluster</strong></h3><p>A cluster is a collection of one or more nodes that collectively store and manage data. Nodes within a cluster communicate with each other to share metadata, coordinate operations, and distribute data shards across the cluster. Clusters provide fault tolerance and high availability by automatically redistributing data and workload in case of node failures.</p><h3><strong>Index</strong></h3><p>An index is a logical namespace that maps to one or more physical data shards distributed across the nodes in a cluster. Each index represents a collection of documents with similar characteristics or belonging to the same data category. Documents within an index are stored, indexed, and searched independently of each other.</p><h3><strong>Shard</strong></h3><p>A shard is a subset of an index’s data that resides on a single node within a cluster. Elasticsearch divides each index into multiple primary and replica shards, distributing the data across nodes for parallel processing and fault tolerance. Sharding allows Elasticsearch to scale horizontally and handle large datasets efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKD13WHeO5yfvp9fYOD_HA.jpeg" /></figure><p>Now let’s talk a little about how Elasticsearch is able to serve up real time queries with structured or unstructured documents</p><h3><strong>Indexing</strong></h3><p>When a document is indexed, Elasticsearch performs the following steps:</p><ol><li><strong>Tokenization</strong>: The document’s text content is tokenized into individual terms or tokens, using techniques like standard, edge n-gram, or keyword tokenizers.</li><li><strong>Analysis</strong>: The tokens are analyzed and processed through a series of text analysis techniques, including stemming, stop word removal, lowercase conversion, and custom token filters.</li><li><strong>Inverted Indexing</strong>: The tokens are stored in an inverted index data structure, which maps each unique token to the documents that contain it. This allows for fast and efficient full-text search queries.</li><li><strong>Document Storage:</strong> The original document along with its metadata is stored in a data structure called a Lucene segment, which is optimized for fast retrieval and compression.</li></ol><p>So with us being armed with the knowledge of Elasticsearch’s setup and it’s advantages, I’d like to talk about a few of it’s unique features that have helped me in making complex queries</p><p>For an example, we will take two models, users and articles, a user can have multiple articles, these will be indexed into the elasticsearch database. I am using the python API for elasticsearch to create my application</p><pre>class Article(BaseModel):<br>    title: str<br>    content: str<br>    id: UUID = uuid4()<br>    metadata: dict = {}<br>    collection: str<br>    user_id: UUID<br><br>class User(BaseModel):<br>    username: str<br>    email: str<br>    password: str<br>    full_name: str<br>    id: UUID = uuid4()</pre><p>We will also create two indices that correspond to the above models</p><pre>index_mapping_articles = {<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;title&quot;: {&quot;type&quot;: &quot;text&quot;},<br>      &quot;content&quot;: {&quot;type&quot;: &quot;text&quot;},<br>      &quot;id&quot;: {&quot;type&quot;: &quot;keyword&quot;},<br>      &quot;metadata&quot;: {&quot;type&quot;: &quot;object&quot;},<br>      &quot;collection&quot;: {&quot;type&quot;: &quot;keyword&quot;}<br>    }<br>  }<br>}<br><br>index_mapping_users = {<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;username&quot;: {&quot;type&quot;: &quot;keyword&quot;},<br>      &quot;email&quot;: {&quot;type&quot;: &quot;keyword&quot;},<br>      &quot;password&quot;: {&quot;type&quot;: &quot;keyword&quot;},<br>      &quot;full_name&quot;: {&quot;type&quot;: &quot;text&quot;},<br>      &quot;id&quot;: {&quot;type&quot;: &quot;keyword&quot;}<br>    }<br>  }<br>}</pre><h3><strong>Object Search</strong></h3><p>In the realm of search and data retrieval, traditional keyword-based search may fall short when dealing with complex, nested data structures. this is where object search comes in, it refers to the capability of a search engine to efficiently query and retrieve information from within structured and nested objects or documents.</p><p>Nowadays there are many applications which require insertion capabilities that ignore schema, but can easily be retrieved with key value pair searches. Object search addresses this challenge by enabling search engines to understand and navigate through the hierarchical structure of documents or objects. By treating each document as a collection of nested fields and objects, object search allows users to search for specific attributes, values, or patterns within the document hierarchy.</p><p>Let’s say a user wants to insert an article with tags that can be searchable as well, he could insert an object into the metadata field for articles, for example :</p><pre>{&quot;tag&quot; : &quot;programming&quot;, &quot;database&quot; : &quot;elasticsearch&quot;}</pre><p>The same article could be searched with the following query:</p><pre>es.search(index=&quot;articles&quot;, body={<br>    &quot;query&quot;: {<br>      &quot;bool&quot;: {<br>        &quot;must&quot;: [<br>          {<br>            &quot;match&quot;: {<br>              &quot;user_id&quot;: id<br>            }<br>          },<br>          {<br>            &quot;bool&quot;: {<br>              &quot;should&quot;: [<br>                {<br>                  &quot;exists&quot;: {<br>                    &quot;field&quot;: f&quot;metadata.tag&quot;<br>                  }<br>                },<br>                {<br>                  &quot;query_string&quot;: {<br>                    &quot;query&quot;: &quot;programming&quot;,<br>                    &quot;fields&quot;: [&quot;metadata.*&quot;]<br>                  }<br>                }<br>              ]<br>            }<br>          }<br>        ]<br>      }<br>    }<br>  })</pre><p>The above query also utilizes a very powerful feature of elasticsearch:</p><h3><strong>Multi Search</strong></h3><p>Elasticsearch provides a powerful feature called multi search, which allows users to execute multiple search queries in a single request. This feature enhances performance, reduces network overhead, and simplifies application logic by enabling batch processing of search requests. We can enable it by using the ‘must’ keyword in the above request. We could search for multiple query conditions, a sort of AND condition from relational database queries.</p><h3><strong>Fuzzy Search</strong></h3><p>Fuzzy search is a powerful technique used in information retrieval systems to find results that are approximate or similar to a given query, even when the query contains misspellings, typos, or variations. Unlike exact match search, which requires the query term to match the indexed data exactly, fuzzy search employs algorithms to match similar terms based on their similarity or distance from the original query term. This is very useful for building out searches for documents that we forget about or remember a few shoddy details about. Fuzzy search algorithms analyze the similarity between the query term and the indexed terms in the dataset. We can enable fuzzy search very easily in Elasticsearch by adding the “fuzziness” in the base query:</p><pre>es.search(index=&quot;articles&quot;, body={<br>    &quot;query&quot;: {<br>      &quot;bool&quot;: {<br>        &quot;must&quot;: [<br>          {<br>            &quot;match&quot;: {<br>              &quot;user_id&quot;: id<br>            }<br>          },<br>          {<br>            &quot;multi_match&quot;: {<br>              &quot;query&quot;: &quot;actor&quot;,<br>              &quot;fields&quot;: [&quot;title&quot;, &quot;content&quot;],<br>              &quot;fuzziness&quot;: &quot;AUTO&quot;<br>            }<br>          }<br>        ]<br>      }<br>    }<br>  })</pre><p>This query would return all documents from storage that contain the following words in the title and content fields of the article that satisfy the following conditions:</p><ul><li>Removing a character (act<strong>or</strong> → act)</li><li>Inserting a character (actor → actor<strong>s</strong>)</li><li>Transposing two adjacent characters (<strong>ac</strong>t → <strong>ca</strong>t)</li><li>Changing a character (cat → <strong>f</strong>at)</li></ul><p>To find similar terms, the fuzziness query creates a set of all possible variations, or expansions, of the search term within a specified edit distance. The query then returns exact matches for each expansion. It works on the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein edit distance</a> parameter.</p><p>Other than the few features that I could tell you about, Elasticsearch comes with a host of other useful features such as autocompletion, relevancy tuning, analytics, aggregation, vizualisations and even geo-spatial searches. Users can even unlock valuable insights from the data stored within their Elasticsearch DB’s with machine learning integration offered as well.</p><p>While elucidating the above features for you, I hope that I have convinced enough of you to switch over your databases to Elasticsearch when building applications that may require complex text based queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f6266e459d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/leveraging-elasticsearch-a-short-guide-17f6266e459d">Leveraging Elasticsearch : A short guide</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sagas to solve Pizza - the Microservices style]]></title>
            <link>https://medium.com/goalist-blog/sagas-to-solve-pizza-the-microservices-style-00e95efb2408?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/00e95efb2408</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Sat, 11 Nov 2023 07:00:04 GMT</pubDate>
            <atom:updated>2023-11-11T07:00:04.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUsFHgqEAkDCSrnIVNJyNQ.png" /></figure><p>In the ever-evolving landscape of software architecture, microservices have emerged as a game-changer. The shift from monolithic to microservices architecture brings unprecedented flexibility, scalability, and agility. An architectural style that structures an application as a collection of loosely coupled, independently deployable services, have gained widespread adoption. This paradigm shift allows organizations to break down complex systems into manageable, autonomous components, fostering rapid development and deployment.</p><p>However, as we navigate the intricate web of distributed systems, a crucial element comes into play — sagas.</p><p>As microservices proliferate, the need for effective coordination between independently functioning services becomes paramount. Enter sagas — orchestrating the flow of transactions and maintaining consistency in a world where services operate independently yet collaboratively.</p><p>In a microservices architecture, traditional ACID transactions face challenges due to the distributed nature of services. Sagas provide a more resilient alternative by breaking down transactions into smaller, manageable steps, ensuring that the system remains consistent even in the face of failures. Sagas are also called long lived transactions (LLT) because of this nature as they break down a chain of calls into discrete steps. Saga is a design which can coordinate multiple changes in state, but avoids the need for locking resources for long periods of time.</p><p>Using sagas comes with the added benefit of forcing us to<br>explicitly model our business processes, which can have significant benefits.</p><p>In the context of EazyBake Corp, a pizza chain, let’s explore how a saga can be formed to manage a common process: the customer order fulfillment process.</p><p><strong>Step 1: Order Placement </strong><br>The saga begins when a customer places an order for a delicious EazyBake pizza through the online platform. At this stage, the system initiates a series of transactions that need to be coordinated to ensure a seamless order fulfillment process.</p><p><strong>Step 2: Payment Processing</strong><br> Once the order is placed, the first step in the saga involves processing the payment. The system communicates with the payment service to charge the customer for the pizza. If the payment is successful, the saga proceeds to the next step. If there’s an issue with the payment, a compensating transaction is triggered to handle the failure gracefully, such as notifying the customer and canceling the order.</p><p><strong>Step 3: Inventory Management </strong><br>With the payment confirmed, the saga moves on to the inventory management step. The system checks the availability of the pizza ingredients in the inventory. If there are sufficient ingredients, the order proceeds to the next step. If there’s a shortage, a compensating transaction is triggered to update the order status, notify the customer, and possibly suggest alternative menu options.</p><p><strong>Step 4: Order Preparation </strong><br>Assuming the inventory check is successful, the order moves to the preparation stage. The system communicates with the kitchen service to start preparing the pizza. If any issues arise during the preparation (e.g., oven malfunction), a compensating transaction ensures the order is appropriately updated, and the customer is notified.</p><p><strong>Step 5: Delivery Scheduling</strong><br>As the pizza is being prepared, the system coordinates with the delivery service to schedule the delivery. If the scheduling is successful, the order progresses. In case of a delivery scheduling failure (e.g., no available delivery drivers), a compensating transaction triggers actions such as updating the order status and providing the customer with revised delivery estimates.</p><p><strong>Step 6: Order Delivery</strong> <br>The final step in the saga involves delivering the pizza to the customer. The delivery service ensures the pizza reaches the customer within the scheduled time. If successful, the saga concludes with the order marked as delivered. If any issues occur during delivery (e.g., the wrong address), compensating transactions manage the order status and customer communication accordingly.</p><p><strong>Benefits of the Saga in EazyBake Corp:</strong></p><ol><li>Consistency: The saga ensures that at each step, the system is in a consistent state, and if an error occurs, compensating transactions bring the system back to a well-defined state.</li><li>Fault Tolerance: By breaking down the order fulfillment process into smaller, manageable steps, the saga enhances fault tolerance. If a specific step fails, it can be addressed without affecting the entire process.</li><li>Visibility and Traceability: The saga provides a clear and traceable flow of the order fulfillment process, making it easier to monitor and troubleshoot any issues that may arise.</li></ol><p>In this way, EazyBake Corp uses sagas to orchestrate the customer order fulfillment process, ensuring a delightful and consistent experience for pizza lovers.</p><p>Let’s explore different ways to implement sagas for our EazyBake corporation</p><p><strong>Choreography-Based Saga</strong>:<br>In choreography-based sagas, each service involved in the saga knows its responsibilities and communicates directly with other services to achieve the desired outcome.</p><p>In EazyBake Corp, when one wants to order a pizza, the customer initiates the order and the order service notifies the payment service. The payment service processes the payment and notifies the inventory service which in turn checks the updates the ingridient (stock) availability notifying the kitchen service. The kitchen service prepares the service and notifies the delivery service. The delivery service, finally schedules the pizza delivery and makes the order as delivered.</p><p><strong>Benefits:</strong></p><ol><li>Decentralized Communication: Services communicate directly, reducing centralization.</li><li>Flexibility: Easy to add or modify services without affecting the entire process.</li></ol><p><strong>Drawbacks</strong></p><ol><li>Increased Complexity: Understanding the entire flow may become challenging as the number of services increases.</li></ol><p><strong>Orchestration-Based Saga:</strong><br>In orchestration-based sagas, there is a central component (orchestrator) responsible for coordinating the interactions between services.</p><p>Discussing the same scenario here where one needs to order a pizza from EazyBake Corp. The orchestration service calls the order service and initiates the order, once the order has been successfully placed, the orchestration service gets the success response and then it calls the payment service to process the payment. This becomes a chain wherein when the orchestration service recieves a success response from the payment service it calls the inventory service then the kitchen service and lastly the delivery service.</p><p><strong>Benefits:</strong></p><ol><li>Centralized Control: The orchestrator maintains a clear view of the entire process, making it easier to manage and monitor.</li><li>Easy to Understand: The overall flow is defined in one place, enhancing readability.</li></ol><p><strong>Drawbacks:</strong></p><ol><li>Single Point of Failure: The orchestrator becomes a critical component, and failure can impact the entire saga.</li><li>Potential Bottleneck: As the system scales, the orchestrator may become a performance bottleneck.</li></ol><p><strong>Hybrid Approach:</strong><br>A hybrid approach combines choreography and orchestration, allowing certain parts of the saga to be orchestrated while others follow a choreography-based pattern.</p><p>An example would be the central orchestration service initiating the order and controlling the payment and inventory service. The payment service then processes the payment but communicates directly with the kitchen and delivery services, so does the inventory service communicate directly with the kitchen service. The kitchen service then prepares the pizza and delivery service schedules the delivery after that and marks the order as delivered.</p><p><strong>Benefits:</strong></p><ol><li>Flexibility: Allows for a mix of centralized control and decentralized communication.</li><li>Scalability: Certain services can operate independently, enhancing scalability.</li></ol><p><strong>Drawbacks:</strong></p><ol><li>Increased Complexity: Requires careful design and documentation to maintain clarity.</li><li>Coordination Challenges: Ensuring seamless communication between orchestrated and choreographed services may be challenging.</li></ol><p>When deciding implementations, EazyBake’s tireless engineers can choose any of these approaches and decide what works best for them. In their world they would have to weigh up flexibility, scalability, complexity and coordination to find the right balance for thier microservices. Implementing sagas for a pizza delivery chain as big as EazyBake would be a complex process for sure but the benefits of breaking it down into steps which are manageable and traceable, which can be made fault tolerant and consistent is better in the long term.</p><p>Let’s hope other companies learn from EazyBake!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00e95efb2408" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/sagas-to-solve-pizza-the-microservices-style-00e95efb2408">Sagas to solve Pizza - the Microservices style</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A domain driven delivery]]></title>
            <link>https://medium.com/goalist-blog/a-domain-driven-delivery-fc15bada7833?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc15bada7833</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 12:36:47 GMT</pubDate>
            <atom:updated>2023-10-04T16:35:35.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4PircLuqSIyn9XQTkK8yw.png" /></figure><p>Microservices are fast becoming a mainstay of developing applications (<a href="https://thenewstack.io/return-of-the-monolith-amazon-dumps-microservices-for-video-monitoring/">except when Prime Video had to move back to monoliths due to too many serverless functions</a>). Smaller teams that can work on things without blocks, the lessening of coupling programatically which makes it easier to build and test, they are independently deployable so we can make new things and experiment quickly and most importantly, they are flexible — can be coded in multiple languages where poeple of different expertises can all be of help. It comes with it’s own complexities, sure, but whenever a company thinks of scaling up they have to think about seperation of concerns and scaling is always better horizontally, not vertically. A growing codebase is something which is mutating all the time, growing parts, so to say and we don’t want it to grow into a monster.</p><p>In comes Domain Driven Development, or hereafter referred to as DDD for my fingers’ sake. The most important concern when making microservices from a monolith is the boundary where you split. Microservices make sure that there are no functional interdependencies. Service A will keep running even if Service B shuts down. This would happen even if Service A had API calls to Service B, so it’s important to focus on understanding and modeling the core business domains within an application.</p><p>We will be taking the example of a famous pizza chain, EazyBake Corp. and how it may be developing microservices using DDD to better serve their customers and of course, maximize profits!</p><p>Even before development begins we have to start thinking about <strong>bounded contexts</strong>, a bounded context is made by drawing a boundary where explicit and related responsibilities need to be carried out. A bit vague that explanation but let’s take the context of our EazyBake Corp., a pizza chain which has multiple branches around the world. Every branch recieves multiple orders every day and all these orders are assigned to appropriate personnel to be delivered. Everything that occurs in our corporation needs to be split up. Bounded contexts hide implementation details but what they do is expose contracts, a certain set of instructions that will happen when you call the domain’s service. For example, some bounded contexts that we can think of for our corporation are Orders, Inventory, Delivery and so on. A customer would place an order using the Orders’ exposed contracts, the Orders’ contract would then call Inventory and so on, in fulfilling one order, a saga(a topic for another post) would be created.</p><p>Another thing to keep in mind is when deciding domains there should be <strong>ubiquitous language </strong>between domain experts and the developers, meanings should be clear, for example in EazyBake Corp. terms like “order,” “pizza size,” and “delivery address” should have a clear and common meaning for both the development team and the pizza shop staff who are going to be taking orders and interacting with the interfaces daily.</p><p>Now what we need to do is represent loose collections of our domain’s concept as an object. An <strong>aggregate</strong> is a cluster of related entities and value objects treated as a single unit. For example, in our pizza chain, an order might be an aggregate that includes customer information, pizza selections, and delivery details. These items individually have no meaning except maybe to the customer as our domains are split, but put them together you begin to get an idea of what all is actually happening in the real world when an order is placed.</p><p>You must be thinking, there’s a lot that has been introduced and sure, it has helped you understand what DDD is, but why DDD? Well let’s get into the advantages:</p><h3>Clear and Shared Understanding</h3><p>By adopting a ubiquitous language, everyone involved in the project, from developers to business analysts and domain experts, shares a common understanding of EazyBake’s domain. This clarity helps in reducing miscommunication and ensures that the software accurately reflects the business requirements.</p><h3>Improved Maintainability</h3><p>Breaking down the system into bounded contexts and aggregates allows for easier maintenance and updates. Developers can work on specific parts of the application without affecting other areas, making it simpler to scale and evolve the system over time.</p><h3>Flexibility and Adaptability</h3><p>In a competitive market like pizza delivery , the ability to adapt to changing customer preferences and market trends is crucial. DDD’s focus on modeling the core domain means that changes can be made more quickly and efficiently, allowing the pizza delivery service to stay competitive.</p><h3>Quality Assurance</h3><p>With a clear understanding of the domain and well-defined models, it becomes easier to write comprehensive tests that cover the critical aspects of the application. This results in higher software quality and more robust applications.</p><h3>Better Collaboration</h3><p>DDD encourages collaboration between developers and domain experts throughout the development process. This collaborative approach ensures that the software aligns closely with the business needs and goals.</p><h3>Enhanced User Experience</h3><p>A well-modeled domain leads to a more intuitive and user-friendly application. Customers using EazyBake’s application will appreciate the ease of placing orders and tracking deliveries, ultimately leading to higher customer satisfaction.</p><p>May all these points lead you into splitting your next big business across domains so that you too can make it big, just like EazyBake!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc15bada7833" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/a-domain-driven-delivery-fc15bada7833">A domain driven delivery</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenTelemetry: Looking into the black box]]></title>
            <link>https://medium.com/goalist-blog/opentelemetry-looking-into-the-black-box-3140654e5978?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/3140654e5978</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 04:43:42 GMT</pubDate>
            <atom:updated>2023-08-09T13:02:09.295Z</atom:updated>
            <content:encoded><![CDATA[<p>As a DevOps engineer, there is one thing you dread the most: a 3AM call from your manager saying the all important service has gone down and no one knows the cause. What’s more, this is your biggest account and your company’s existence depends upon this one service being up. Doomsday scenario to say the least. Of course you ask for logs, maybe for any alert flags that were raised or traces. Maybe metrics of the system could help explain the outage behavior. All of these would help you gain access to critical knowledge that would help you debug. But none of these are present, you are completely in the dark about this outage and even the system behavior. Hopefully, this is the moment you wake up and breathe a sigh of relief because you have already added tools into place that give you observability.</p><p>Observability has become a cornerstone of modern software development, helping developers tackle the challenges posed by distributed and microservices-based architectures. Unlike traditional debugging, observability focuses on providing real-time insights into an application’s internal state, allowing developers to identify bottlenecks, troubleshoot issues, and optimize performance. With applications becoming more intricate and spread across multiple services, observability is no longer a luxury but a necessity.</p><p><a href="https://opentelemetry.io/">OpenTelemetry</a>, a revolutionary open-source project, has emerged as a powerful tool to enable observability and streamline the monitoring of modern software systems. Born from the merger of two existing projects, OpenTracing and OpenCensus, OpenTelemetry brings together the best of both worlds to create a unified and extensible framework for observability. By offering a common set of APIs, libraries, agents, and instrumentation, OpenTelemetry simplifies the process of integrating observability into applications.</p><p>In this article, we will focus on three outputs from an application: logs, traces, and metrics. We will learn how to instrument, generate, collect, and export telemetry data so that you will never find yourself in a situation where you do not have insight into the runtime behavior of your application. We will use OpenTelemetry SDKs to instrument a Go client and server so that the application will emit telemetry to the OpenTelemetry Collector service. The OpenTelemetry Collector service will transform and export that telemetry data to backend systems to enable visualization, analysis, and alerting.</p><p>OpenTelemetry includes the following components:</p><ul><li>Libraries for instrumenting widely used programming languages, offering both automated and manual instrumentation options.</li><li>A unified collector binary capable of being deployed through various methods.</li><li>Pipelines designed for the collection, conversion, and export of telemetry data.</li><li>A collection of open standards designed to prevent dependency on a single vendor.</li></ul><p><strong>OpenTelemetry Collector</strong></p><p>A conceptual reference architecture diagram for OpenTelemetry (OTel):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OI60PHovboqL5K6NTbwU2g.png" /><figcaption>Image courtesy: <a href="https://opentelemetry.io/docs/">https://opentelemetry.io/docs/</a></figcaption></figure><p>The OTel Collector is a vendor-agnostic proxy that can receive telemetry data in multiple formats, transform and process it, and export it in multiple formats to be consumed by multiple backends (such as Jaeger, Prometheus, other open source backends, and many proprietary backends). As you can see in our architecture diagram, the OTel collector is central to our observability system. The OTel Collector is composed of the following:</p><ul><li>Receivers: Push- or pull-based processors for collecting data</li><li>Processors: Responsible for transforming and filtering data</li><li>Exporters: Push- or pull-based processors for exporting data</li></ul><p>Each of the preceding components is enabled through pipelines described in YAML configurations.</p><p><strong>The correlation of telemetry</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*j5cj01uKisQNTutxv0sDXQ.png" /><figcaption>Image courtesy: <a href="https://opentelemetry.io/docs/specs/otel/logs/">https://opentelemetry.io/docs/specs/otel/logs/</a></figcaption></figure><p>In complex distributed systems, understanding the relationships between different components and their interactions is essential to identify bottlenecks and troubleshoot issues. Correlation, in the context of telemetry, refers to the ability to link related events or data points across various services and components of an application.</p><p>OpenTelemetry facilitates correlation through the concept of context propagation. A context, often referred to as a trace context, is a container for storing metadata and contextual information about a request or transaction. This context is carried across different services and components as requests flow through the system. By attaching the same context to logs, traces, and metrics generated by different services, we can easily follow the path of a request and gain insights into its journey through the application’s architecture.</p><p>Correlation is particularly crucial in diagnosing performance issues or errors that span multiple services. Without proper correlation, tracking down the root cause of an issue can be like searching for a needle in a haystack. OpenTelemetry’s ability to maintain consistent trace contexts across various services simplifies the process of linking logs, traces, and metrics related to a particular transaction or request.</p><p><strong>Traces and Spans</strong></p><p>We have talked a lot about traces and their key role in making a system observable. But what exactly is a trace?</p><p>Think of a trace as a journey map for a single action or request that goes through different parts of a computer system. Imagine you’re ordering a pizza online. The trace would be like a timeline that shows every step your pizza order takes, from the moment you click “Order” to when the pizza arrives at your door. It includes all the different stops or places your order goes through, like the order processing, baking, packaging, and delivery. This trace helps you see the entire path your pizza takes and how long each part of the process takes.</p><p>A span is like a small part of the journey described in the trace. Going back to the pizza example, a span would be like focusing on just one specific step in the process, such as when the pizza is being baked in the oven. It gives you detailed information about what happened during that particular step — like how hot the oven was, how long the pizza was inside, and if there were any special instructions followed. Spans help you understand the details of each individual step that makes up the entire journey.</p><p>In a computer system, traces and spans work similarly. Traces show you the entire path of a request or action as it moves through different parts of the system, while spans break down each step into smaller, more detailed pieces of information. This helps developers and system operators understand how things are working, where there might be slowdowns or issues, and how to improve the overall performance of their applications.Traces that can propagate across components in a system are called distributed traces. Distributed tracing and correlation of activities is a powerful tool for determining causality within a complex system.Each<br>trace and span can be uniquely identified, and each span contains a context consisting of Request, Error, and Duration metrics. A trace contains a tree of spans with a single root span.</p><p>To serve as an example. I will use a project that I made, which has been heavily inspired (basically trial and error many times to learn) by the demo example in the <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/examples/demo">OpenTelemetry repo</a>.</p><p>I will use this project to show usage of OpenTelemetry. There is a client and a server communicating to one endpoint /hello , the client is continuously sending requests with random wait times while the server responds after waiting for a random amount of time. The OpenTelemetry Collector is being run using a docker-compose with Jaeger to visualize the traces and spans and Prometheus to visualize the metrics.</p><pre>func main() {<br> // create a handler wrapped in OpenTelemetry instrumentation<br> handler := handleRequestWithRandomSleep()<br> wrappedHandler := otelhttp.NewHandler(handler, &quot;/hello&quot;)<br><br> // serve up the wrapped handler<br> http.Handle(&quot;/hello&quot;, wrappedHandler)<br> http.ListenAndServe(&quot;:7080&quot;, nil)<br>}<br><br>// handleRequestWithRandomSleep registers a request handler that will record request counts and randomly sleep to induce<br>// artificial request latency.<br>func handleRequestWithRandomSleep() http.HandlerFunc {<br> var (<br>  commonLabels = []attribute.KeyValue{<br>   attribute.String(&quot;server-attribute&quot;, &quot;foo&quot;),<br>  }<br> )<br><br> return func(w http.ResponseWriter, req *http.Request) {<br>  //  random sleep to simulate latency<br>  var sleep int64<br>  switch modulus := time.Now().Unix() % 5; modulus {<br>  case 0:<br>   sleep = rng.Int63n(2000)<br>  case 1:<br>   sleep = rng.Int63n(15)<br>  case 2:<br>   sleep = rng.Int63n(917)<br>  case 3:<br>   sleep = rng.Int63n(87)<br>  case 4:<br>   sleep = rng.Int63n(1173)<br>  }<br>  time.Sleep(time.Duration(sleep) * time.Millisecond)<br>  ctx := req.Context()<br>  span := trace.SpanFromContext(ctx)<br>  span.SetAttributes(commonLabels...)<br>  w.Write([]byte(&quot;Hello World&quot;))<br> }<br>}</pre><p>I am recording the latency of the request and response and request count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phP2yJ_0oVioVKCDeDjKrw.png" /></figure><p>Above is a trace visualized by Jaeger and a span that has been expanded, we can see every information that has been tagged by our server. Any logs associated with this trace would also be shown here.</p><p><strong>Metrics</strong></p><p>In the context of OpenTelemetry, a metric is like a specific measurement or number that helps you understand how well a certain part of a process is performing. It’s like having a way to quantify how things are going. Just like how you might use the time it takes for your pizza to be delivered as a measurement of the delivery process.</p><p>Now, let’s apply this concept to the pizza-ordering process:</p><p>Imagine you’re curious about how fast the pizza delivery is, and you want to measure it using a metric. The metric can help you gain insights into how the whole process is working out, the time taken to deliver the pizza, fuel consumption, etc. Aggregated metrics over time can help you gain insights into peak delivery times, delivery boys who are loitering and locations where your pizza is especially popular.</p><p>In terms of OpenTelemetry, Metrics are measurements at a given moment of a particular aspect of an application during runtime. An individual capture is called a metric event and consists of a timestamp, a measurement, and associated metadata. The OpenTelemetry API does not allow for custom aggregations but does provide some common aggregations, such as sum, count, last value, and histograms, which are<br>supported by backend visualization and analysis software such as Prometheus.<br>To give a better idea of when metrics are useful, here are some example scenarios:</p><ul><li>Providing the aggregate total number of bits read or written in a process</li><li>Providing CPU or memory utilization</li><li>Providing the number of requests over a period of time</li><li>Providing the number of errors over a period of time</li><li>Providing the duration of requests to form a statistical distribution of the request processing time</li></ul><p>OpenTelemetry offers three types of metrics:</p><ul><li>counter: To count a value over time, such as the number of requests</li><li>measure: To sum or otherwise aggregate a value over a period of time, such as how many bytes are read per minute</li><li>observer: To periodically capture a value, such as memory utilization<br>every minute</li></ul><p>We will alter the two functions mentioned above in the code block, adding metric recording functions into the handler</p><pre>func handleRequestWithRandomSleep() http.HandlerFunc {<br> var (<br>  meter        = global.Meter(&quot;demo-server-meter&quot;)<br>  instruments  = NewServerInstruments(meter)<br>  commonLabels = []attribute.KeyValue{<br>   attribute.String(&quot;server-attribute&quot;, &quot;foo&quot;),<br>  }<br> )<br><br> return func(w http.ResponseWriter, req *http.Request) {<br>  //  random sleep to simulate latency<br>  var sleep int64<br>  switch modulus := time.Now().Unix() % 5; modulus {<br>  case 0:<br>   sleep = rng.Int63n(2000)<br>  case 1:<br>   sleep = rng.Int63n(15)<br>  case 2:<br>   sleep = rng.Int63n(917)<br>  case 3:<br>   sleep = rng.Int63n(87)<br>  case 4:<br>   sleep = rng.Int63n(1173)<br>  }<br>  time.Sleep(time.Duration(sleep) * time.Millisecond)<br>  ctx := req.Context()<br>// record metrics<br>  meter.RecordBatch(<br>   ctx,<br>   commonLabels,<br>   instruments.RequestCount.Measurement(1),<br>  )<br>  span := trace.SpanFromContext(ctx)<br>  span.SetAttributes(commonLabels...)<br>  w.Write([]byte(&quot;Hello World&quot;))<br> }<br>}</pre><p>Adding one request count every time a request is made and adding it to the metric is what we are doing here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMA0LuYKaqdejtud96Kolw.png" /></figure><p>Here is a Prometheus visualization of the metric of request count. We can see the average requests per second for the server application. At the bottom of the screenshot, we will see the common labels and other associated metadata that was added in the server main.go. Prometheus<br>provides a powerful query language to analyze and alert on metrics.</p><p><strong>Alerts</strong></p><p>One last advantage of OpenTelemetry is the addition of configuring an Alert Manager which can help us pre empt any anomalous event to prevent the dreaded scenario which we thankfully woke up from in the start of this piece. Alertmanager configuration consists mainly of routes and receivers. A route describes where to send an alert based on it either being default or by some criteria. We can send alerts via webhooks to custom endpoints or to 3rd party services like Chatwork or Slack.</p><p>We have to define rules to set up alerts. Below, we can see a single group named demo-server specifying a single rule named HighRequestLatency. The rule specifies an expression, which is a Prometheus query. The query triggers when the mean request latency is exceeding 200,000 microseconds, or 0.2 seconds. The alert is triggered with a severity label of page and an<br>annotation summary of High request latency.</p><pre>groups:<br>  - name: demo-server<br>  rules:<br>    - alert: HighRequestLatency<br>    expr: | histogram_quantile(0.5, rate(http_server_duration_<br>    bucket{exported_job=&quot;demo-server&quot;}[5m])) &gt; 200000<br>    labels:<br>      severity: page<br>    annotations:<br>      summary: High request latency</pre><p>IaaS such as AWS, Azure and GCP all have products which offer the ability to add OpenTelemetry into your multi service stack to ease suffering when debugging within their respective ecosystems.</p><p>Amazon Web Services (AWS):</p><ol><li>AWS X-Ray: AWS provides a service called X-Ray, which helps developers analyze and debug distributed applications, including those built on AWS services. X-Ray integrates well with OpenTelemetry, allowing you to send trace data from OpenTelemetry-enabled applications to X-Ray for analysis.</li><li>AWS CloudWatch: AWS CloudWatch offers monitoring and observability services. You can use OpenTelemetry to send trace data to CloudWatch using the CloudWatch Agent or custom instrumentation. This enables you to gain insights into application performance and troubleshoot issues.</li></ol><p>Google Cloud Platform (GCP):</p><ol><li>Google Cloud Trace: Google Cloud Trace is GCP’s distributed tracing service that allows you to monitor application performance. It integrates smoothly with OpenTelemetry, enabling you to send trace data to Cloud Trace for analysis.</li><li>Google Cloud Monitoring: GCP provides a monitoring solution called Google Cloud Monitoring (formerly known as Stackdriver). It supports OpenTelemetry-based instrumentation to gather and analyze trace data, helping you gain insights into application behavior.</li></ol><p>Microsoft Azure:</p><ol><li>Azure Application Insights: Azure Application Insights is a monitoring and observability service offered by Azure. It supports OpenTelemetry, allowing you to collect and analyze trace data from your applications, providing insights into performance and issues.</li><li>Azure Monitor: Azure Monitor is a comprehensive monitoring solution for Azure services and applications. It supports OpenTelemetry, enabling you to instrument your applications and gather trace data for analysis within Azure Monitor.</li></ol><p>In the world of software and technology, complexity often resembles a deliciously topped pizza — layers upon layers of intricacies, processes, and interactions that come together to create a seamless experience. Just as OpenTelemetry serves as the chef’s secret recipe for perfecting the art of pizza-making, it also plays a pivotal role in the digital realm.</p><p>As we savor the last bite of our pizza analogy, it’s clear that OpenTelemetry serves as a bridge, connecting the various components of a system into a harmonious symphony. Just as every ingredient in a pizza contributes to its flavor and appeal, each piece of data captured by OpenTelemetry contributes to a holistic understanding of software performance.</p><p>So the next time you indulge in your favorite pizza, remember that behind the scenes, OpenTelemetry is also at work — ensuring that your order is seamlessly processed, your pizza is baked to perfection, and your delivery arrives right on time. In this digital age, just as a pizza’s taste is paramount, the smooth operation of software systems is crucial, and OpenTelemetry stands as the conduit through which this excellence is achieved.</p><p>As technology continues to evolve and software systems become even more intricate, OpenTelemetry remains a trusted companion, tirelessly gathering data, measuring metrics, and orchestrating the performance of these systems. So, whether you’re enjoying a slice of your favorite pizza or witnessing the prowess of a well-functioning software ecosystem, remember that the secret ingredient to success lies in harmonious orchestration — something both the culinary and digital worlds can wholeheartedly agree upon.</p><p>I hope in the preceding few words, I have been able to convince you to start plugging in OpenTelemetry into your multi-service applications. Hopefully, the days of scratching out our hair when errors occur and constantly logging at breakpoints are behind us as we move onto clear vision.</p><p>PS: The full code used in this article is present <a href="https://github.com/lordtt13/golang-products/tree/master/OpenTelemetry">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3140654e5978" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/opentelemetry-looking-into-the-black-box-3140654e5978">OpenTelemetry: Looking into the black box</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use your text data effectively!]]></title>
            <link>https://medium.com/in-pursuit-of-artificial-intelligence/how-to-use-your-text-data-effectively-a9dbe8c5621?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9dbe8c5621</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Mon, 20 Jun 2022 02:42:26 GMT</pubDate>
            <atom:updated>2022-06-20T02:42:26.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*sZwGsHkxVnXgJB7r-tEIfg.jpeg" /></figure><p>Data is fast becoming the currency of the information age, the saying: “You’re not more important than the data you produce”, might be a little too extreme but it conveys the truth to a significant extent. A lot of the data produced and stored in the many mediums present today is raw, unparsed, untagged and would take too long for people to sit down and make machine learnable.</p><p>We, at <a href="https://goalist.co.jp/en/company/">Goalist</a>, face this problem on a daily basis, we crunch a lot of crawled and submitted data. Data that includes feedbacks, suggestions, submission information, descriptions and a lot of correspondence information that mostly is kept for recording purposes. About 10% of the data we collect is fed into recommendation engines that we have running as this portion is carefully put into a cycle of parsing, training and feedback. The data we consume and store is a great help to the AI teams that we have working constantly to automate many of the tedious tasks that require a great amount of man hours.</p><p>Many of the natural language downstream tasks that we perform include summarization, translation and classification. A lot of these tasks are in very specific domains, in Japanese, which narrows down the transfer learning techniques that can be applied in this case. We could go ahead and choose generic Japanese Language Models but these do not work well in our specific use cases. Transformers are the standard for solving NLP tasks in this day and age and we are not going to reinvent the wheel.</p><p>In this article, I am going to show you how to domain adapt a generic Japanese Language Model, after which you can attach model heads to them and try to accomplish one of the downstream tasks mentioned earlier. A lot of what I mention here are the same techniques we use at <a href="https://goalist.co.jp/en/company/">Goalist</a> when domain adapting our data. This article is an unwrapping of the first phase of our NLP MLOps pipeline.</p><p>Here is a brief of things we are going to cover:<br>1. Domain Adaptation: The technique in detail and why its use is effective.<br>2. Framework of Choice: What to use when going into practice.<br>3. Preprocessing: Making raw data machine learnable.<br>4. Modeling: Strategy to utilize when domain adapting.</p><p><strong>Domain Adaptation</strong></p><p>Domain adaptation, it’s when we fine-tune a pre-trained model on a new dataset, and it gives predictions that are more adapted to that dataset.</p><p>Domain adapting models written specifically for the Japanese language is a very good place for us to start fast prototyping the ideas that we have in mind at <a href="https://goalist.co.jp/en/company/">Goalist</a>. This gives us a freedom to try out various ideas on incoming data which is, as mentioned earlier, coming in as a stream and so much of it is new, even to us. So time becomes a very important factor when trying to fit data to a task.</p><p><strong>Framework of Choice</strong></p><p>We, at <a href="https://goalist.co.jp/en/company/">Goalist</a>, use huggingface for most of our NLP MLOps needs, it is really a useful framework for training, tokenizing, storage, inference and is really easy to maintain! But the most important advantage that huggingface gives us and is our tool of trade is because of its ability to deal with unstructured data.</p><p>Another great benefit is that a person lacking domain specific or linguistic knowledge of the target corpus can still train the model without worries, if the tokenizer chosen has the knowledge to encode the context of the corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hddbwSURJM8bG7O5vyggIg.png" /><figcaption>An example of unstructured data that comes in for ingestion</figcaption></figure><p>As can be seen from the above image, the data that comes in for ingestion is very unstructured, it is mostly in a comma delimited or JSON format and does not have consistent tags as documents from different departments and usecases are merged together just before parsing.</p><p><strong>Preprocessing</strong></p><p>The best practice to adopt is to use the Datasets library, also by huggingface, which has a handy function to stream data directly from archived files, which is used by us a lot.</p><pre>dataset_dict = { &quot;text&quot;: raw_datas }<br>dataset = Dataset.from_dict(dataset_dict)</pre><p>Here I parse texts after a little cleaning and put it into a datasets class. Now I can save it to cache for easy and fast loading! Raw data can be as simple as a list of strings that the model needs to be trained on.</p><p>The model of course cannot process these raw strings, so we need to tokenize the strings to ids and attention masks. The model and tokenizer that we will use for this task are this one:</p><p><a href="https://huggingface.co/nlp-waseda/roberta-base-japanese">nlp-waseda/roberta-base-japanese · Hugging Face</a></p><p>I chose this as a starting point for a generic Japanese model because it had a decent vocabulary size and has been trained on all of Japanese Wikipedia and the Japanese part of the CC-100 dataset. We also needed to select a model that has been trained for Language Modeling as this model’s base can encode the context of the corpus on which it has been trained on. These are the pre training objectives which help the model learn better language representations of its training corpus.</p><p>Now, we need to retrain the tokenizer on the new texts so that any missed tokens from this corpus are now included in the new tokenizer, like so:</p><pre>tokenizer = transformers.AutoTokenizer.from_pretrained(&quot;nlp-waseda/roberta-base-japanese&quot;)<br>org_len = len(tokenizer)<br>new_tokenizer = tokenizer.train_new_from_iterator(raw_datas, org_len + 1000)</pre><p>I choose to increase the vocabulary size by a thousand because I checked against the raw training corpus and counted the number of unknown tokens and their frequency. Fair warning though, training a new tokenizer from an old one is only possible for FastTokenizers class of huggingface. For tokenizers that aren’t fast we need to train a new tokenizer from scratch, here is a tutorial on how to do so:</p><p><a href="https://github.com/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb">notebooks/tokenizer_training.ipynb at main · huggingface/notebooks</a></p><p>Now that the tokenizer has been expanded, we need to resize the embedding layer so as to accommodate the new tokens of the augmented vocabulary.</p><pre>model = transformers.AutoModelForMaskedLM.from_pretrained(&quot;nlp-waseda/roberta-base-japanese&quot;).to(&#39;cuda&#39;)<br>model.resize_token_embeddings(len(new_tokenizer))</pre><p>At this juncture, we have our model ready for training, our tokenizer is ready to deal with any new context that it sees in the training corpus and the number of unknown tokens is reduced. We already have our dataset as list of strings ready for tokenization, which remains the only step before the fun part, i.e. training!</p><p>This is where the strength of the datasets class comes into play, it has many methods which make it very easy for the user to take archived unstructured data stored locally to batch encoded streams ready for training. One of the cooler aspects of the datasets class is its ability to keep indexes like traditional databases, the most important being semantic similarity indexes like FAISS using very little memory. To read more about it you can go to huggingface documentation:</p><p><a href="https://huggingface.co/docs/datasets/index">Datasets</a></p><p>One of its awesome methods is map, which is very similar to mapReduce functions used in big data DB’s where data comes in a stream and these functions act as transformers in an ETL pipeline. Dataset.map() works in exactly the same way. Some of the more powerful applications of Datasets come from using map. The primary purpose of map is to speed up processing functions. It allows you to apply a processing function to each example in a dataset, independently or in batches.</p><p>We will first tokenize, drop the text column because we do not need it anymore and utilize the rest of the ids for training. Then we will group texts in a batch together to remove some of the sparsity created by padding, and removes the loss of information caused by truncation, chunking texts together is a good strategy to follow when going for a language modeling task because you want to encode as much information possible into the model without it learning any trivial representations. The last thing we do is split the dataset into train and test groups for training and validation. An added note, if you use batching in your map functions you must ensure that your mapping function can handle an array of examples compared to vanilla map where the function should take care of a single example, I have used both below for further reference.</p><pre>new_tokenizer.pad_token = new_tokenizer.eos_token</pre><pre>def tokenize(example):<br>    return new_tokenizer(example[&#39;text&#39;])</pre><pre>def group_texts(examples):<br>    concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}<br>    total_length = len(concatenated_examples[list(examples.keys())[0]])<br>    total_length = (total_length // block_size) * block_size<br>    result = {<br>        k: [t[i : i + block_size] for i in range(0, total_length, block_size)]<br>        for k, t in concatenated_examples.items()<br>    }<br>    result[&quot;labels&quot;] = result[&quot;input_ids&quot;].copy()<br>    return result</pre><pre>dataset = dataset.map(tokenize)<br>dataset = dataset.remove_columns(&#39;text&#39;)<br>dataset = dataset.map(group_texts, batched=True)<br>dataset = dataset.train_test_split(test_size=0.1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uErMvKkz8f23CllQDcrGQ.png" /><figcaption>Grouping texts in a batch</figcaption></figure><p><strong>Modeling</strong></p><p>Now, for a Language Modeling pre training objective we must define a data collator, which will help us prepare texts for the model in a batched fashion. We will go for Causal Language Modeling as our pre training objective. Under Causal Language Model, the idea here is again to predict the masked token in a given sentence. The model is allowed to just consider words that occur to its left for doing the same. For more knowledge on the various language modeling pre training objectives, you can look at this article:</p><p><a href="https://towardsdatascience.com/understanding-masked-language-models-mlm-and-causal-language-models-clm-in-nlp-194c15f56a5">Understanding Masked Language Models (MLM) and Causal Language Models (CLM) in NLP</a></p><p>Data Collators are a huge help also when training, because they apply dynamic padding when preparing batches for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRRz3wIx6_Y0_TK2yAyq8Q.png" /><figcaption>Dynamic Padding at a glance</figcaption></figure><p>As we can see dynamic padding reduces the sparsity of the dataset after padding and goes into the whole theme of reduction of information loss. Training speed also increases because length of batch fed into the model is reduced. More on dynamic padding can be found here:</p><p>Now the easy part, we define training arguments and just call one method to train, here we see the power of the huggingface framework, which abstracts away setting up a training loop, an optimizer, checkpointing and many more things!</p><pre>data_collator = transformers.DataCollatorForLanguageModeling(tokenizer=new_tokenizer, mlm=False)</pre><pre>training_args = transformers.TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    evaluation_strategy=&quot;epoch&quot;,<br>    learning_rate=2e-5,<br>    weight_decay=0.01,<br>    num_train_epochs=1)</pre><pre>trainer = transformers.Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=dataset[&quot;train&quot;],<br>    eval_dataset=dataset[&quot;test&quot;],<br>    data_collator=data_collator,<br>)</pre><pre>trainer.train()</pre><p>That’s all, just attach any downstream task specific head to do NER, classification, summarization, translation, text generation, question answering and more! Fine tuning for those tasks with very few to no examples (zero shot learning) can be done very easily now that our upstream model has domain adapted and learned the language representations.</p><p>At <a href="https://goalist.co.jp/en/company/">Goalist</a>, we have multiple downstream models performing various tasks, inheriting from a single huge upstream model very much like the one which we trained now. Upstream models in our organisation get updated weekly as data comes on in a stream!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9dbe8c5621" width="1" height="1" alt=""><hr><p><a href="https://medium.com/in-pursuit-of-artificial-intelligence/how-to-use-your-text-data-effectively-a9dbe8c5621">How to use your text data effectively!</a> was originally published in <a href="https://medium.com/in-pursuit-of-artificial-intelligence">The HumAIn Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Verify — Part 1]]></title>
            <link>https://medium.datadriveninvestor.com/face-verify-part-1-6e4a50afc430?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e4a50afc430</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tflite]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Fri, 22 May 2020 00:01:01 GMT</pubDate>
            <atom:updated>2020-05-22T00:01:01.008Z</atom:updated>
            <content:encoded><![CDATA[<h3>Face Verify — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*xnLFwjSLyMcmordk.jpeg" /></figure><p>Facial recognition is a term we hear thrown around about 10 times a day in a technology dominated era, but did you know it’s actually split into three subtasks?</p><p>Facial detection, recognition and verification are actually three seperate tasks contributing to the same goal, using your facial signature as a virtual key to anything you don’t want to secure using the term “password”.</p><p>Facial detection involves detecting if a face is present in an image, it can’t do anything else, although this is a fairly cheap computational process, requiring only landmark filters, like the haarCascade face landmarks filter. Look here for a detailed explanation : <a href="http://www.willberger.org/cascade-haar-explained/">http://www.willberger.org/cascade-haar-explained/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*BoOw_ubgZE9pbjSv.jpeg" /></figure><p>Facial recogniton and verification may sound similar but unlike facial recognition which performs a 1:n match against a database of known faces, facial authentication is 1:1. The user is authenticating using their face as their credential to secure access to their online account. To authenticate, the user simply takes a selfie (which is converted into a 3D face map) that is then compared, one-to-one, with the stored biometric template. A proper match, based on an accuracy score, completes the secure authentication process in the background.</p><p>In this tutorial I will endevour to explain the algorithms used by my friend <a href="https://medium.com/u/23aeacd38998?source=post_page-----bd1ff4a9f45e----------------------">SphericalKat</a> in his app <a href="https://github.com/ATechnoHazard/faceverify-lib/">https://github.com/ATechnoHazard/faceverify-lib/</a> , which aims to provide a simple API for cropping faces from a bitmap and comparing two faces to verify that they’re from the same person. He has done so using the TFLite Models of MTCNN and MobileFaceNet, which we’ll delve deeper into moving forwards.</p><p>FaceNet is a face recognition system developed in 2015 by researchers at Google that achieved then state-of-the-art results on a range of face recognition benchmark datasets. The FaceNet system can be used broadly thanks to multiple third-party open source implementations of the model and the availability of pre-trained models.</p><p>The FaceNet system can be used to extract high-quality features from faces, called face embeddings, that can then be used to train a face identification system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i6zUG3AGmV6thzEL.jpeg" /></figure><p>A demo from the app, the test subject being <a href="https://medium.com/u/23aeacd38998?source=post_page-----bd1ff4a9f45e----------------------">SphericalKat</a></p><p>FaceNet is a face recognition system that was described by <a href="http://www.florian-schroff.de/">Florian Schroff</a>, et al. at Google in their 2015 paper titled “ <a href="https://arxiv.org/abs/1503.03832">FaceNet: A Unified Embedding for Face Recognition and Clustering</a>.”</p><p>It is a system that, given a picture of a face, will extract high-quality features from the face and predict a 128 element vector representation these features, called a face embedding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*9ObBj1AwBvzQoMKl.png" /></figure><p>The model is a deep convolutional neural network trained via a triplet loss function that encourages vectors for the same identity to become more similar (smaller distance), whereas vectors for different identities are expected to become less similar (larger distance). The focus on training a model to create embeddings directly (rather than extracting them from an intermediate layer of a model) was an important innovation in this work.</p><blockquote><em>Our method uses a deep convolutional network trained to directly optimize the embedding itself, rather than an intermediate bottleneck layer as in previous deep learning approaches.</em></blockquote><p>- <a href="https://arxiv.org/abs/1503.03832">FaceNet: A Unified Embedding for Face Recognition and Clustering</a>, 2015.</p><p>These face embeddings were then used as the basis for training classifier systems on standard face recognition benchmark datasets, achieving then-state-of-the-art results.</p><p>The paper also explores other uses of the embeddings, such as clustering to group like-faces based on their extracted features.</p><p>It is a robust and effective face recognition system, and the general nature of the extracted face embeddings lends the approach to a range of applications.</p><p>Before we can perform face recognition, we need to detect faces.</p><p>We will use the Multi-Task Cascaded Convolutional Neural Network, or MTCNN, for face detection, e.g. finding and extracting faces from photos. This is a state-of-the-art deep learning model for face detection, described in the 2016 paper titled “ <a href="https://arxiv.org/abs/1604.02878">Joint Face Detection and Alignment Using Multitask Cascaded Convolutional Networks</a>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XVDZLFkqGzHKnHTl.png" /></figure><p>Face detection and alignment in an unconstrained environment is challenging due to various poses, illuminations and occlusions. Recent studies show that deep learning approaches can achieve impressive performance on these two tasks. In this paper, the authors proposed a deep cascaded multi-task framework which exploits the inherent correlation between detection and alignment to boost up their performance. In particular, the framework leverages a cascaded architecture with three stages of carefully designed deep convolutional networks to predict face and landmark location in a coarse-to-fine manner. In addition, an online hard sample mining strategy that further improves the performance in practice was proposed. The method achieves superior accuracy over the state-of-the-art techniques on the challenging FDDB and WIDER FACE benchmarks for face detection, and AFLW benchmark for face alignment, while keeping up real time performance.</p><p>We can use the mtcnn library to create a face detector and extract faces for our use with the FaceNet face detector models in subsequent sections.</p><p>The first step is to load an image. We will also convert the image to RGB, just in case the image has an alpha channel or is black and white.</p><p>Next, we can create an MTCNN face detector class and use it to detect all faces in the loaded photograph.</p><p>The result is a list of bounding boxes, where each bounding box defines a lower-left-corner of the bounding box, as well as the width and height.</p><p>If we assume there is only one face in the photo for our experiments, we can determine the pixel coordinates of the bounding box . Sometimes the library will return a negative pixel index, and I think this is a bug. We can fix this by taking the absolute value of the coordinates.</p><p>We can then use the preprocessing functions to resize this small image of the face to the required size; specifically, the model expects square input faces.</p><p>We can use this function to extract faces as needed in the next section that can be provided as input to the FaceNet model.</p><p>We here use the mobile version of Facenet, MobileFaceNets, which uses less than 1 million parameters and is specifically tailored for high-accuracy real-time face verification on mobile and embedded devices. There was first an analysis on the weakness of common mobile networks for face verification. The weakness has been well overcome by the above mentioned MobileFaceNets. Under the same experimental conditions, MobileFaceNets achieve significantly superior accuracy as well as more than 2 times actual speedup over MobileNetV2. After trained by ArcFace loss on the refined MS-Celeb-1M dataset , single MobileFaceNet of 4.0MB size achieves 99.55% accuracy on LFW and 92.59% TAR@FAR1e-6 on MegaFace, which is even comparable to state-of-the-art big CNN models of hundreds MB size. The fastest one of MobileFaceNets has an actual inference time of 18 milliseconds on a mobile phone. For face verification, MobileFaceNets achieve significantly improved efficiency over previous state-of-the-art mobile CNNs.</p><p>We will now create a face embedding.</p><p>A face embedding is a vector that represents the features extracted from the face. This can then be compared with the vectors generated for other faces. For example, another vector that is close (by some measure) may be the same person, whereas another vector that is far (by some measure) may be a different person. The FaceNet model will generate this embedding for a given image of a face.</p><p>The FaceNet model will pre-process a face to create a face embedding that can be stored and used as mapping to authenticate against although in our implementation we save on memory by not storing embeddings but just generating them on every image and comparing then.</p><p>With that we are done with the theoretical stage, my friend and co-worker at Smoketrees (<a href="https://smoketrees.dev/">https://smoketrees.dev/</a>), <a href="https://medium.com/u/23aeacd38998?source=post_page-----bd1ff4a9f45e----------------------">SphericalKat</a> will take over for Part 2 where you’ll learn how to use the TFLite versions of these models to use in an android application, where you use these both for face verification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e4a50afc430" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/face-verify-part-1-6e4a50afc430">Face Verify — Part 1</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Verify — Part 1]]></title>
            <link>https://medium.com/dataseries/face-verify-part-1-c9443bb2b8e2?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9443bb2b8e2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[tflite]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Wed, 20 May 2020 15:29:10 GMT</pubDate>
            <atom:updated>2020-05-20T15:29:10.233Z</atom:updated>
            <content:encoded><![CDATA[<h3>Face Verify — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*xnLFwjSLyMcmordk.jpeg" /></figure><p>Facial recognition is a term we hear thrown around about 10 times a day in a technology-dominated era, but did you know it’s actually split into three subtasks?</p><p>Facial detection, recognition and verification are actually three seperate tasks contributing to the same goal, using your facial signature as a virtual key to anything you don’t want to secure using the term “password”.</p><p>Facial detection involves detecting if a face is present in an image, it can’t do anything else, although this is a fairly cheap computational process, requiring only landmark filters, like the haarCascade face landmarks filter. Look here for a detailed explanation : <a href="http://www.willberger.org/cascade-haar-explained/">http://www.willberger.org/cascade-haar-explained/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*BoOw_ubgZE9pbjSv.jpeg" /></figure><p>Facial recogniton and verification may sound similar but unlike facial recognition which performs a 1:n match against a database of known faces, facial authentication is 1:1. The user is authenticating using their face as their credential to secure access to their online account. To authenticate, the user simply takes a selfie (which is converted into a 3D face map) that is then compared, one-to-one, with the stored biometric template. A proper match, based on an accuracy score, completes the secure authentication process in the background.</p><p>In this tutorial I will endevour to explain the algorithms used by my friend <a href="https://medium.com/u/23aeacd38998?source=post_page-----bd1ff4a9f45e----------------------">SphericalKat</a> in his app <a href="https://github.com/ATechnoHazard/faceverify-lib/">https://github.com/ATechnoHazard/faceverify-lib/</a> , which aims to provide a simple API for cropping faces from a bitmap and comparing two faces to verify that they’re from the same person. He has done so using the TFLite Models of MTCNN and MobileFaceNet, which we’ll delve deeper into moving forwards.</p><p>FaceNet is a face recognition system developed in 2015 by researchers at Google that achieved then state-of-the-art results on a range of face recognition benchmark datasets. The FaceNet system can be used broadly thanks to multiple third-party open source implementations of the model and the availability of pre-trained models.</p><p>The FaceNet system can be used to extract high-quality features from faces, called face embeddings, that can then be used to train a face identification system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i6zUG3AGmV6thzEL.jpeg" /></figure><p>A demo from the app, the test subject being <a href="https://medium.com/u/23aeacd38998?source=post_page-----bd1ff4a9f45e----------------------">SphericalKat</a></p><p>FaceNet is a face recognition system that was described by <a href="http://www.florian-schroff.de/">Florian Schroff</a>, et al. at Google in their 2015 paper titled “ <a href="https://arxiv.org/abs/1503.03832">FaceNet: A Unified Embedding for Face Recognition and Clustering</a>.”</p><p>It is a system that, given a picture of a face, will extract high-quality features from the face and predict a 128 element vector representation these features, called a face embedding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*9ObBj1AwBvzQoMKl.png" /></figure><p>The model is a deep convolutional neural network trained via a triplet loss function that encourages vectors for the same identity to become more similar (smaller distance), whereas vectors for different identities are expected to become less similar (larger distance). The focus on training a model to create embeddings directly (rather than extracting them from an intermediate layer of a model) was an important innovation in this work.</p><blockquote><em>Our method uses a deep convolutional network trained to directly optimize the embedding itself, rather than an intermediate bottleneck layer as in previous deep learning approaches.</em></blockquote><p>- <a href="https://arxiv.org/abs/1503.03832">FaceNet: A Unified Embedding for Face Recognition and Clustering</a>, 2015.</p><p>These face embeddings were then used as the basis for training classifier systems on standard face recognition benchmark datasets, achieving then-state-of-the-art results.</p><p>The paper also explores other uses of the embeddings, such as clustering to group like-faces based on their extracted features.</p><p>It is a robust and effective face recognition system, and the general nature of the extracted face embeddings lends the approach to a range of applications.</p><p>Before we can perform face recognition, we need to detect faces.</p><p>We will use the Multi-Task Cascaded Convolutional Neural Network, or MTCNN, for face detection, e.g. finding and extracting faces from photos. This is a state-of-the-art deep learning model for face detection, described in the 2016 paper titled “ <a href="https://arxiv.org/abs/1604.02878">Joint Face Detection and Alignment Using Multitask Cascaded Convolutional Networks</a>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XVDZLFkqGzHKnHTl.png" /></figure><p>Face detection and alignment in an unconstrained environment is challenging due to various poses, illuminations and occlusions. Recent studies show that deep learning approaches can achieve impressive performance on these two tasks. In this paper, the authors proposed a deep cascaded multi-task framework which exploits the inherent correlation between detection and alignment to boost up their performance. In particular, the framework leverages a cascaded architecture with three stages of carefully designed deep convolutional networks to predict face and landmark location in a coarse-to-fine manner. In addition, an online hard sample mining strategy that further improves the performance in practice was proposed. The method achieves superior accuracy over the state-of-the-art techniques on the challenging FDDB and WIDER FACE benchmarks for face detection, and AFLW benchmark for face alignment, while keeping up real time performance.</p><p>We can use the mtcnn library to create a face detector and extract faces for our use with the FaceNet face detector models in subsequent sections.</p><p>The first step is to load an image. We will also convert the image to RGB, just in case the image has an alpha channel or is black and white.</p><p>Next, we can create an MTCNN face detector class and use it to detect all faces in the loaded photograph.</p><p>The result is a list of bounding boxes, where each bounding box defines a lower-left-corner of the bounding box, as well as the width and height.</p><p>If we assume there is only one face in the photo for our experiments, we can determine the pixel coordinates of the bounding box . Sometimes the library will return a negative pixel index, and I think this is a bug. We can fix this by taking the absolute value of the coordinates.</p><p>We can then use the preprocessing functions to resize this small image of the face to the required size; specifically, the model expects square input faces.</p><p>We can use this function to extract faces as needed in the next section that can be provided as input to the FaceNet model.</p><p>We here use the mobile version of Facenet, MobileFaceNets, which uses less than 1 million parameters and is specifically tailored for high-accuracy real-time face verification on mobile and embedded devices. There was first an analysis on the weakness of common mobile networks for face verification. The weakness has been well overcome by the above mentioned MobileFaceNets. Under the same experimental conditions, MobileFaceNets achieve significantly superior accuracy as well as more than 2 times actual speedup over MobileNetV2. After trained by ArcFace loss on the refined MS-Celeb-1M dataset , single MobileFaceNet of 4.0MB size achieves 99.55% accuracy on LFW and 92.59% TAR@FAR1e-6 on MegaFace, which is even comparable to state-of-the-art big CNN models of hundreds MB size. The fastest one of MobileFaceNets has an actual inference time of 18 milliseconds on a mobile phone. For face verification, MobileFaceNets achieve significantly improved efficiency over previous state-of-the-art mobile CNNs.</p><p>We will now create a face embedding.</p><p>A face embedding is a vector that represents the features extracted from the face. This can then be compared with the vectors generated for other faces. For example, another vector that is close (by some measure) may be the same person, whereas another vector that is far (by some measure) may be a different person. The FaceNet model will generate this embedding for a given image of a face.</p><p>The FaceNet model will pre-process a face to create a face embedding that can be stored and used as mapping to authenticate against although in our implementation we save on memory by not storing embeddings but just generating them on every image and comparing then.</p><p>With that we are done with the theoretical stage, my friend and co-worker at Smoketrees (<a href="https://smoketrees.dev/">https://smoketrees.dev/</a>), <a href="https://medium.com/u/23aeacd38998?source=post_page-----bd1ff4a9f45e----------------------">SphericalKat</a> will take over for Part 2 where you’ll learn how to use the TFLite versions of these models to use in an android application, where you use these both for face verification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9443bb2b8e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataseries/face-verify-part-1-c9443bb2b8e2">Face Verify — Part 1</a> was originally published in <a href="https://medium.com/dataseries">DataSeries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensorflow 2.0 — from preprocessing to serving (Part 4)]]></title>
            <link>https://medium.com/dataseries/tensorflow-2-0-from-preprocessing-to-serving-part-4-975ceb1d4035?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/975ceb1d4035</guid>
            <category><![CDATA[tensorflow2]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Wed, 20 May 2020 11:15:15 GMT</pubDate>
            <atom:updated>2020-05-20T11:15:15.991Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tensorflow 2.0 — from preprocessing to serving (Part 4)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*jH_fVUGTZ6z-XGdXMHe4lg.png" /></figure><p>Welcome to this the fourth and last part of a tutorial into tensorflow and it’s keras API. We’ll be discussing everything deep learning — starting from how to preprocess input data, then modelling your neural net to encode your data and process an output, optimize training and serve the model as a REST API.</p><p>As you can see from the title, we’ve already had 3 stories on this topic already, in this one we’ll go through all those steps quickly, and use the model created to serve requests.</p><p>Before you start reading this article and it’s predecessors, you should be aware of the basics of the following subjects so that you don’t feel flustered while reading them:<br>1.Calculus<br>2.Linear Algebra<br>3.Neural Networks<br>4.Numpy, Pandas</p><p>And as you might have inferred from the topic this is a programming article so it might help having some pre-existing experience in python.</p><p>As this article involves serving models, it’s better to do this on Google Colab -Colaboratory is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud.</p><p>With Colaboratory you can write and execute code, save and share your analyses, and access powerful computing resources, all for free from your browser.</p><p>The dataset we’ll be using here is the Fashion-MNIST. Fashion-MNIST is a dataset of <a href="https://jobs.zalando.com/tech/">Zalando</a>&#39;s article images-consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes. We intend Fashion-MNIST to serve as a direct drop-in replacement for the original <a href="http://yann.lecun.com/exdb/mnist/">MNIST dataset</a> for benchmarking machine learning algorithms. It shares the same image size and structure of training and testing splits.</p><p>An exemplar of the dataset is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*OvuEcP3S79Mfxoip.png" /></figure><p>Sample from the Fashion MNIST Dataset (each class takes three-rows)</p><p>You guys might have prior experience with MNIST’s handwritten digits dataset but we won’t use that here because of two very elegant reasons:<br>1.Network design for MNIST is too easy, you can get a 98% accuracy even though you use Dense Networks.<br>2.It’s overused, we want to learn something new, not regurgitate old material.</p><p>But first we should get to know what an API is, An application program interface (API) is a set of routines, protocols, and tools for building software applications. Basically, an APIspecifies how software components should interact.</p><p>We’ll look at a small example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*DAsZ7LkpfO4T6nLv.png" /></figure><p>Our Tensorflow model server is going to be the same, except it returns the predictions from a ML model</p><p>Now let us load in and normalize the data just like in the first part of the tutorial</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*byScSWR3BGHsbOBA.png" /></figure><p>We’ll then expand dimensions, reshape and get the number of unique classes. Now we go ahead and build out our convolutional model, just like in our second tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*YMJdRE9TFRLRrMz9.png" /></figure><p>Now we go ahead and train:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*OZvXTmzvk9q-zzId.png" /></figure><p>Now that we’ve trained the model, we need to save the it in a temporary file so that it is ready to be served, if there’s already a saved model, we remove it from the system. A SavedModel is a directory containing serialized signatures and the state needed to run them, including variable values and vocabularies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*M6um03ngrHf2e5MW.png" /></figure><p>Note the use of versions, that’ll be of note later.</p><p>The saved_model.pb file stores the actual TensorFlow program, or model, and a set of named signatures, each identifying a function that accepts tensor inputs and produces tensor outputs.</p><p>SavedModels may contain multiple variants of the model (multiple v1.MetaGraphDefs, identified with the --tag_set flag to saved_model_cli).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*aPoy1WBRmbKqxGsY.png" /></figure><p>The saved_model_cli contains more class information in it’s output, it’d be really great if you could look at the full output of this command.</p><p>Now go ahead and install the tensorflow-model-server package on your colab terminal using the “!”(bang) symbol. (Instructions to set up the package locally are also included in the whole code)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-nr6C2Pb2YWi7iPG.png" /></figure><p>Now we’ll go ahead and start serving the model as a service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*lP-g4QSeCIj6vOaI.png" /></figure><p>This is where we start running TensorFlow Serving and load our model. After it loads we can start making inference requests using REST. There are some important parameters:</p><ul><li>rest_api_port: The port that we&#39;ll use for REST requests.</li><li>model_name: We&#39;ll use this in the URL of REST requests. It can be anything.</li><li>model_base_path: This is the path to the directory where we&#39;ve saved our model.</li></ul><p>The nohup parameter is required so the service runs uninterrupted. Let’s just check our logs so as to see that everything went without a hitch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*tdKOgdR5fPyZDKKH.png" /></figure><p>If no errors are logged, it means that our model has started serving and we can send requests to it to get predictions.</p><p>Now, let’s look at a random example from our dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*yvAuy1A0PXR94s-9.png" /></figure><p>Now we’ll create a request, to be passed in a JSON format, it should contain the inputs, properly formatted, exactly like we passed the data for training, because our model is trained to recognize only preprocessed data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*XLWiRNWyyb87bzA5.png" /></figure><p>As you can clearly see, we’re passing in 3 instances to get inferences for.</p><p>Now, we package this in a request and send it to out model for predictions, we get a ping back, predictions namely, in the same JSON format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*lfoLF4COlF04GkQr.png" /></figure><p>The predictions are in softmax format, a probabilty corresponding to every class an instance belongs to. So what we can do is find the index each instance belongs to by taking argmax of each prediction and mapping them back to string labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*EQsFaZTGqUjrv9F4.png" /></figure><p>Now let’s see how they matched up with actual predicitions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*c0fYADgdiYp_4oNm.png" /></figure><p>Pretty good results!</p><p>Now, we look into versioning our models, let’s see how to make and select models by version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/0*q8T5B-kxIJwzRrBH.png" /></figure><p>Pay ectra attention to the last couple parts of the url to which we’re making a post request, specifically versions/1:predict, by default if there’s only one model, that’s v1 and that’s the only one being served.</p><p>We’ll now go ahead and make another version of our model, compile and fit it on our dataset again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*YNSmMkUBxYxWqV8H.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*seSFYD0EnPLfj2i3.png" /></figure><p>Now save the second version of our model appropriately</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*3BNLG1atWfCPtJkV.png" /></figure><p>The coolest thing is, you don’t need to restart the server for the model to recognize the second version, it has already been saved as an asset and is ready to be served. We again make a post request, but this time to the second version of the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/0*_j8-XGdkcaLRWaIc.png" /></figure><p>See? The url now has changed to 2:predict. Versioning is easy with tensorflow-server.</p><p>But a valid question to ask at this point is what if we use a version number that does not exist? Well, let’s test it out shall we?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*Nlzk3Vz2wwgT9zXy.png" /></figure><p>We encounter an error, which we expected.</p><p>And with that we are done, from preprocessing to serving.</p><p>To look at the code in whole please check this out:</p><p><a href="https://github.com/lordtt13/Medium-Articles">https://github.com/lordtt13/Medium-Articles</a></p><p>Stay tuned for my next series.</p><p>Till then, Cheerio!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=975ceb1d4035" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dataseries/tensorflow-2-0-from-preprocessing-to-serving-part-4-975ceb1d4035">Tensorflow 2.0 — from preprocessing to serving (Part 4)</a> was originally published in <a href="https://medium.com/dataseries">DataSeries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensorflow 2.0 — from preprocessing to serving (Part 4)]]></title>
            <link>https://medium.com/@tanmaythakurbrn2rule/tensorflow-2-0-from-preprocessing-to-serving-part-4-3272a2183edb?source=rss-46b642aa7f12------2</link>
            <guid isPermaLink="false">https://medium.com/p/3272a2183edb</guid>
            <category><![CDATA[tensorflow2]]></category>
            <dc:creator><![CDATA[Tanmay Thakur]]></dc:creator>
            <pubDate>Tue, 19 May 2020 20:07:51 GMT</pubDate>
            <atom:updated>2020-05-19T20:07:51.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tensorflow 2.0 — from preprocessing to serving (Part 4)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*jH_fVUGTZ6z-XGdXMHe4lg.png" /></figure><p>Welcome to this the fourth and last part of a tutorial into tensorflow and it’s keras API. We’ll be discussing everything deep learning — starting from how to preprocess input data, then modelling your neural net to encode your data and process an output, optimize training and serve the model as a REST API.</p><p>As you can see from the title, we’ve already had 3 stories on this topic already, in this one we’ll go through all those steps quickly, and use the model created to serve requests.</p><p>Before you start reading this article and it’s predecessors, you should be aware of the basics of the following subjects so that you don’t feel flustered while reading them:<br>1.Calculus<br>2.Linear Algebra<br>3.Neural Networks<br>4.Numpy, Pandas</p><p>And as you might have inferred from the topic this is a programming article so it might help having some pre-existing experience in python.</p><p>As this article involves serving models, it’s better to do this on Google Colab -Colaboratory is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud.</p><p>With Colaboratory you can write and execute code, save and share your analyses, and access powerful computing resources, all for free from your browser.</p><p>The dataset we’ll be using here is the Fashion-MNIST. Fashion-MNIST is a dataset of <a href="https://jobs.zalando.com/tech/">Zalando</a>&#39;s article images—consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes. We intend Fashion-MNIST to serve as a direct drop-in replacement for the original <a href="http://yann.lecun.com/exdb/mnist/">MNIST dataset</a> for benchmarking machine learning algorithms. It shares the same image size and structure of training and testing splits.</p><p>An exemplar of the dataset is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*Te-W-us1HgRKV1Ag.png" /></figure><p>Sample from the Fashion MNIST Dataset (each class takes three-rows)</p><p>You guys might have prior experience with MNIST’s handwritten digits dataset but we won’t use that here because of two very elegant reasons:<br>1.Network design for MNIST is too easy, you can get a 98% accuracy even though you use Dense Networks.<br>2.It’s overused, we want to learn something new, not regurgitate old material.</p><p>But first we should get to know what an API is, An application program interface (API) is a set of routines, protocols, and tools for building software applications. Basically, an APIspecifies how software components should interact.</p><p>We’ll look at a small example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*QQDqAUYsgYvmm32TvXkZLA.png" /></figure><p>Our Tensorflow model server is going to be the same, except it returns the predictions from a ML model</p><p>Now let us load in and normalize the data just like in the first part</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1OgLRvmekLSYIWwBer6wQ.png" /></figure><p>We’ll then expand dimensions, reshape and get the number of unique classes. Now we go ahead and build out our convolutional model, just like in our second tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*xHYXrUrWj7kiRxm4jMmCSA.png" /></figure><p>Now we go ahead and train:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*2OzYxXjnugcN8oHecoJzsw.png" /></figure><p>Now that we’ve trained the model, we need to save the it in a temporary file so that it is ready to be served, if there’s already a saved model, we remove it from the system. A SavedModel is a directory containing serialized signatures and the state needed to run them, including variable values and vocabularies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*F-aCw-j_kbzMyVC9Z94aEQ.png" /></figure><p>Note the use of versions, that’ll be of note later.</p><p>The saved_model.pb file stores the actual TensorFlow program, or model, and a set of named signatures, each identifying a function that accepts tensor inputs and produces tensor outputs.</p><p>SavedModels may contain multiple variants of the model (multiple v1.MetaGraphDefs, identified with the --tag_set flag to saved_model_cli).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*xsOhZHN0KALG2nGcl-yMjQ.png" /></figure><p>The saved_model_cli contains more class information in it’s output, it’d be really great if you could look at the full output of this command.</p><p>Now go ahead and install the tensorflow-model-server package on your colab terminal using the “!”(bang) symbol. (Instructions to set up the package locally are also included in the whole code)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ztzaHpHky6Hs6v3WrqP1Q.png" /></figure><p>Now we’ll go ahead and start serving the model as a service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*-eQDhd77ltA7XhtFkg2OiQ.png" /></figure><p>This is where we start running TensorFlow Serving and load our model. After it loads we can start making inference requests using REST. There are some important parameters:</p><ul><li>rest_api_port: The port that we&#39;ll use for REST requests.</li><li>model_name: We&#39;ll use this in the URL of REST requests. It can be anything.</li><li>model_base_path: This is the path to the directory where we&#39;ve saved our model.</li></ul><p>The nohup parameter is required so the service runs uninterrupted. Let’s just check our logs so as to see that everything went without a hitch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*qM2c5LK_58mcKgr8Q3QQ-g.png" /></figure><p>If no errors are logged, it means that our model has started serving and we can send requests to it to get predictions.</p><p>Now, let’s look at a random example from our dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*qaR-16pHpaIKJjhEjO_PeQ.png" /></figure><p>Now we’ll create a request, to be passed in a JSON format, it should contain the inputs, properly formatted, exactly like we passed the data for training, because our model is trained to recognize only preprocessed data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*WP704UlAZD8FUQ1uzZW1Ow.png" /></figure><p>As you can clearly see, we’re passing in 3 instances to get inferences for.</p><p>Now, we package this in a request and send it to out model for predictions, we get a ping back, predictions namely, in the same JSON format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*IGPOgb0vfSCECYIcA2w-8g.png" /></figure><p>The predictions are in softmax format, a probabilty corresponding to every class an instance belongs to. So what we can do is find the index each instance belongs to by taking argmax of each prediction and mapping them back to string labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*yhWD1XTUFV7zLOks_owFwA.png" /></figure><p>Now let’s see how they matched up with actual predicitions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*DUXW-ufm5pVzd6Lng1G38A.png" /></figure><p>Pretty good results!</p><p>Now, we look into versioning our models, let’s see how to make and select models by version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*ZaeO5pxUw08fqRvjfWU56w.png" /></figure><p>Pay ectra attention to the last couple parts of the url to which we’re making a post request, specifically versions/1:predict, by default if there’s only one model, that’s v1 and that’s the only one being served.</p><p>We’ll now go ahead and make another version of our model, compile and fit it on our dataset again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*FbfTqLpPIzt-eTreJN_wow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*WLmRMlipi1P6BuZKObmRCQ.png" /></figure><p>Now save the second version of our model appropriately</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*ZqbtmLVV2dRPYiTRKrenrA.png" /></figure><p>The coolest thing is, you don’t need to restart the server for the model to recognize the second version, it has already been saved as an asset and is ready to be served. We again make a post request, but this time to the second version of the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*dyUOzP935E8nUMFtg0Ms1w.png" /></figure><p>See? The url now has changed to 2:predict. Versioning is easy with tensorflow-server.</p><p>But a valid question to ask at this point is what if we use a version number that does not exist? Well, let’s test it out shall we?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*5mobV5p6DOTYtcpI64eBmw.png" /></figure><p>We encounter an error, which we expected.</p><p>And with that we are done, from preprocessing to serving.</p><p>To look at the code in whole please check this out:</p><p><a href="https://github.com/lordtt13/Medium-Articles">lordtt13/Medium-Articles</a></p><p>Stay tuned for my next series.</p><p>Till then, Cheerio!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3272a2183edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>