<?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 Simón Cerda on Medium]]></title>
        <description><![CDATA[Stories by Simón Cerda on Medium]]></description>
        <link>https://medium.com/@simsagues?source=rss-4bf783c564d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Simón Cerda on Medium</title>
            <link>https://medium.com/@simsagues?source=rss-4bf783c564d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:30:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simsagues/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[Prompt Engineering: From beginner to prompt wizard]]></title>
            <link>https://medium.com/@simsagues/prompt-engineering-from-beginner-to-prompt-wizard-c43d3e09b152?source=rss-4bf783c564d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c43d3e09b152</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Simón Cerda]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 16:53:23 GMT</pubDate>
            <atom:updated>2025-01-26T16:53:23.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m2PUgRuOS3AyghWl" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Large language models (LLMs) like GPT-4 and Llama are changing the game. From writing stories to answering questions, these AI systems are doing things we couldn’t have imagined a few years ago. But here’s the thing — getting the best out of them isn’t just about typing in a question or a command. The secret sauce behind great results is something called <strong>prompt engineering</strong>.</p><p>Imagine talking to someone who knows a little about everything, but how you ask your question determines whether they give you a goldmine of useful information or something totally off the mark. That’s what working with an LLM is like! The way you phrase or structure your prompt can completely change the quality of the response.</p><p>In this post, we’re going to break down how you can become a master at prompt engineering. Whether you’re just starting out or have been experimenting with LLMs for a while, I’ll walk you through practical tips and real-world examples to help you get the most out of these powerful tools. Ready to level up your AI game? Let’s dive in!</p><h3>What is Prompt Engineering?</h3><p>Imagine you’re in a conversation with a genius — someone who has read every book, every article, and remembers almost everything. Now, this genius can answer just about any question, but there’s a catch: they don’t always know <em>how</em> you want the question answered unless you ask it in the right way. That’s where <strong>prompt engineering</strong> comes in.</p><p><strong>Prompt engineering</strong> is basically the art (and a bit of science) of asking the right questions to get the exact answer you want from an LLM, like GPT-4. These models are trained on massive amounts of data, which means they know a lot, but how you talk to them — or more specifically, how you <strong>craft your prompts</strong> — will determine whether you get a brilliant response or something vague and off-topic.</p><h4>The Power of a Well-Crafted Prompt</h4><p>Let’s take a simple example. Imagine you ask an LLM:<br><em>“Tell me about the moon.”</em></p><p>You’ll likely get a basic response, something like:<br><em>“The moon is Earth’s only natural satellite and has been studied for centuries.”</em></p><p>Sure, it’s a good answer, but what if you needed more specific information? What if you were writing a research paper and needed to know about the <strong>moon’s surface composition</strong>? The original question doesn’t guide the model well enough.</p><p>Now, let’s tweak that prompt a bit:<br><em>“Describe the moon’s surface composition, focusing on the elements found in lunar rocks.”</em></p><p>Bam! Suddenly, you get a much more targeted and detailed response because the LLM now knows exactly what you’re looking for. This is the magic of prompt engineering — giving just enough detail in your query to guide the model toward the answer you need.</p><h4>How LLMs Work Under the Hood</h4><p>Technically speaking, LLMs like GPT-4 are trained on billions of sentences and phrases from books, websites, and other sources. They use this information to predict what comes next in a sentence based on patterns they’ve learned. When you give them a prompt (or a question), they don’t “think” like humans do — they generate responses by figuring out what words are likely to follow based on what you asked.</p><p>Here’s where it gets interesting: since LLMs don’t <em>actually</em> understand context the way humans do, your prompts need to include enough context for them to “fill in the gaps.” So, when you’re vague or too broad in your question, the model might miss the mark because it’s working with incomplete information.</p><p>This is why specific and well-structured prompts are crucial. The more you refine your prompt, the better the model can generate a useful answer.</p><h3>Key Techniques for Effective Prompt Engineering</h3><p>So, now that we know <em>what</em> prompt engineering is, let’s dive into some key techniques that can turn you from a beginner into a prompt wizard! These methods will help you craft prompts that get the best possible responses from large language models (LLMs). Think of them as your toolkit for guiding the model in the right direction.</p><h4>1. Be Specific with Your Prompts</h4><p>Imagine you’re asking someone to help you plan a vacation. If you just say, <em>“Tell me about vacations,”</em> they could talk about anything — ski trips, beach getaways, safaris — you name it. But what if you <em>really</em> wanted advice on planning a beach vacation in Mexico?</p><p>When you’re working with LLMs, it’s the same story. If your prompts are vague, the model doesn’t know exactly what you want. The more specific you are, the better your results will be.</p><p>For example, instead of saying:<br><em>“Write about technology,”</em><br>you could say:<br><em>“Write a 300-word article on how AI is changing the healthcare industry, focusing on patient care.”</em></p><p>By narrowing down the topic, you’ll get a response that’s much more useful. The model can zero in on exactly what you want it to talk about, avoiding random or unrelated information.</p><h4>2. Use Constraints to Guide the Model</h4><p>Sometimes, less is more. Imagine you’re asking a friend for movie recommendations, and they give you a list of 50 films. Overwhelming, right? But if you say, <em>“I only have time to watch one movie tonight, and I like comedies,”</em> suddenly, your friend’s suggestion is much more targeted.</p><p>Similarly, when prompting an LLM, setting <strong>constraints</strong> like word count, tone, or even style can help it give you a much more focused response. Let’s look at an example:</p><ul><li>Instead of saying:<br><em>“Summarize this article,”</em><br>try this:<br><em>“Summarize this article in 100 words, focusing only on the main points and avoiding technical jargon.”</em></li></ul><p>By giving the model clear instructions, you’re setting boundaries, which helps it give you exactly what you’re looking for, without too much fluff or unnecessary details.</p><h4>3. Leverage Zero-shot, One-shot, and Few-shot Prompting</h4><p>Now, let’s get into a fun technique — using <strong>zero-shot, one-shot, and few-shot prompting</strong>. These terms might sound a little technical, but they’re actually pretty simple once you get the hang of them.</p><ul><li><strong>Zero-shot prompting</strong> is like asking the model to do something without giving it any examples. You just throw the task at it and see how it responds. For instance, you might say:<br><em>“Write a haiku about the ocean.”</em><br>The model will try to generate a haiku based purely on what it knows about the structure of a haiku (3 lines, syllable pattern of 5–7–5) and the ocean.</li><li><strong>One-shot prompting</strong> is when you give the model <em>one example</em> to follow. This is useful when you want to show the model the type of response you’re looking for. For example:<br><em>“Here’s an example haiku:<br>‘The ocean is calm,<br>waves whisper soft on the shore,<br>a quiet embrace.’<br>Now write another haiku about the stars.”</em></li><li><strong>Few-shot prompting</strong> works the same way, but instead of giving one example, you provide <strong>a few examples</strong> to really help guide the model. This is great for tasks where there are multiple right answers or styles you want to convey.<br>For example:<br><em>“Here are three examples of motivational quotes. Now, generate a new quote based on these examples.”</em></li></ul><p>Why does this work? LLMs are trained by learning from patterns. By showing them one or more examples, you’re teaching the model what type of response you’re expecting, and it will try to mimic that pattern.</p><h4>4. Iterate and Refine</h4><p>Prompt engineering is like cooking a dish — you rarely get it perfect on the first try. Sometimes you need to tweak the ingredients (or in this case, the wording of your prompt) to get the result you want. It’s completely normal to have to <strong>iterate</strong> on your prompts, refining them little by little until you strike gold.</p><p>Let’s say you start with:<br><em>“Explain how a car engine works.”</em><br>The model gives you a decent answer, but maybe it’s too technical for your needs.</p><p>So, you tweak it to:<br><em>“Explain how a car engine works in simple terms, so a 12-year-old could understand.”</em></p><p>Now, the response might be more digestible, but maybe it’s still a bit wordy. You refine it one more time:<br><em>“In 5 sentences, explain how a car engine works in simple terms, so a 12-year-old could understand.”</em></p><p>By making these small adjustments, you’re teaching the model to align more closely with what you really want</p><h3>Advanced Techniques for Prompt Optimization</h3><p>As you dive deeper into prompt engineering, you’ll start to notice that some tasks require a more sophisticated approach. In this section, we’ll explore advanced techniques that can help you fine-tune your prompts even further. These strategies are useful when working with complex models or when you need to ensure precise, high-quality outputs. You’ll also learn why some models work better with specific templates and how to leverage those for optimal results.</p><h4>1. Role-Based Prompts for Contextual Precision</h4><p>Sometimes, it’s not just <em>what</em> you ask but <em>how</em> you ask it. By assigning a role or persona to the model, you provide it with additional context that helps shape its response in a way that fits your needs.</p><p>For example, let’s say you need the LLM to generate legal advice. Instead of asking: <br><em>“Explain copyright law,”</em><br>you could guide the model like this: <br><em>“You are a copyright lawyer. Explain copyright law in the context of digital content creation.”</em></p><p>This framing gives the model a specific role to act from, helping it generate more authoritative, tailored responses. By simulating different personas, such as teachers, experts, or technical advisors, you give the model a more focused path to follow, which is especially useful for detailed tasks.</p><h4>2. Formatting Prompts with Templates for Structured Responses</h4><p>When you need highly structured output,<strong> prompt templates</strong> are your best friend. Templates guide the model by setting a clear framework for how the response should look, which is especially valuable when working with LLMs for technical tasks or multi-step processes.</p><p>For example, instead of a vague request like: <br><em>“How do I set up a cloud database?”</em><br>you could use a template that specifies the sections you need: <br><em>“Explain how to set up a cloud-based database. Break it down into the following sections: <br>1. Required tools <br>2. Setup steps <br>3. Security considerations <br>4. Common mistakes to avoid.”</em></p><p>This kind of structured template ensures the model hits all the important points you need, preventing irrelevant or scattered information from creeping into the response.</p><h4>3. Prompt Template Formatting: A Deep Dive</h4><p>Some large language models (LLMs), like <strong>Llama 3</strong> , use <strong>special tokens </strong>and formats that help define the structure of a conversation or task. Understanding and using these tokens can make a big difference in how the model interprets your input and generates responses. Let’s take a look at Llama 3 prompt template formatting as an example.</p><p>In Llama’s system, specific tokens like <em>‘&lt;|begin_of_text|&gt;’</em>, <em>‘&lt;|end_of_text|&gt;’</em>, and <em>‘&lt;|eot_id|&gt;’</em> (End of Turn) are used to signal the start and end of a message, or when a response has been fully generated. These tokens provide critical cues to the model for understanding how to handle multi-step interactions, tools, or even conversations between different parties, like a user and the assistant.</p><p>Here’s a breakdown of some common tokens and their roles:</p><ul><li><strong>&lt;|begin_of_text|&gt;</strong>: Marks the start of the prompt.</li><li><strong>&lt;|end_of_text|&gt;</strong>: Signals the end of the prompt or response.</li><li><strong>&lt;|start_header_id|&gt;…&lt;|end_header_id|&gt;</strong>: These tokens define who is “speaking” in the conversation. For instance, you might use ‘&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;’ to indicate a user message, followed by ‘&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;’ for the AI’s reply.</li><li><strong>&lt;|eot_id|&gt;</strong>: This token indicates that the model has finished responding and is awaiting further instructions or input from the user.</li></ul><p>By using this format, you can help the model keep track of multiple messages in a conversation, ensuring a more organized and meaningful interaction. This is particularly useful for <strong>multi-turn conversations</strong>, where the model needs to remember the roles and context across several exchanges. For instance:</p><p>```<br>&lt;|begin_of_text|&gt;&lt;|start_header_id|&gt;system&lt;|end_header_id|&gt;<br>You are a helpful assistant.&lt;|eot_id|&gt;&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;<br>What is the capital of France?&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;<br>The capital of France is Paris.&lt;|eot_id|&gt;<br>```</p><pre>&lt;|begin_of_text|&gt;&lt;|start_header_id|&gt;system&lt;|end_header_id|&gt;<br>You are a helpful assistant.&lt;|eot_id|&gt;&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;<br>What is the capital of France?&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;<br>The capital of France is Paris.&lt;|eot_id|&gt;</pre><p>In this case, the tokens ‘&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;’ and ‘&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;’ indicate who is speaking and when the conversation moves from user input to assistant output. The model is therefore better able to maintain a smooth, logical flow in the dialogue.</p><h4>4. Leveraging System Prompts for Task Instructions</h4><p>Another powerful technique involves <strong>system prompts</strong>, which set up the context or “rules” for how the model should behave throughout the interaction. For example, in Llama’s system, you can use a system prompt to tell the model how to respond before the user even asks a question:</p><pre>&lt;|start_header_id|&gt;system&lt;|end_header_id|&gt;<br>You are a knowledgeable assistant who helps users understand complex data science concepts in simple terms.&lt;|eot_id|&gt;</pre><p>This type of setup ensures that every response the model generates is in line with the behavior defined at the beginning. System prompts are a great way to control the tone, complexity, and level of detail in the model’s answers.</p><h4>5. Conditional Prompts for Multi-Step Interactions</h4><p>Sometimes, you need the model to perform a series of tasks or make decisions based on user input. In these cases, <strong>conditional prompts</strong> come in handy. You can instruct the model to choose its response based on different scenarios:</p><p><em>“If the user asks about coding, provide examples of Python code. If the user asks about debugging, focus on common errors and troubleshooting tips.”</em></p><p>This lets you create a more dynamic interaction where the model adjusts its responses depending on the input it receives, making it more versatile and interactive.</p><p>These advanced techniques not only give you more control but also help you create highly optimized prompts that suit different models and tasks. Understanding prompt templates, tokens, and the nuances of how LLMs interpret input allows you to unlock their full potential, delivering accurate and structured responses every time.</p><h3>Conclusion</h3><p>Mastering prompt engineering is like learning a new language — a language that lets you communicate with AI in a way that brings out its best. By understanding the art of crafting simple yet powerful prompts, you can turn complex tasks into a breeze, whether you’re generating text, solving technical problems, or even creating tools. As we’ve explored, starting with key techniques such as clarity, context, and step-by-step instructions is crucial, but unlocking the true potential of large language models comes when you dive into advanced strategies.</p><p>From role-based prompts to structured templates, and even prompt formats using special tokens like those in Llama 3.x, there’s a world of possibilities waiting to be explored. These advanced techniques not only enhance the quality of responses but also allow you to control the direction and complexity of the AI’s output, making it adaptable to any challenge you throw its way.</p><p>Whether you’re a beginner or already experienced, refining your prompt engineering skills will make working with LLMs smoother, more efficient, and incredibly rewarding. As AI continues to evolve, mastering this art will ensure you’re ahead of the curve, unlocking even more innovative ways to use these models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c43d3e09b152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Less Is More: Designing Data Visualizations That Inform, Not Overwhelm]]></title>
            <link>https://medium.com/@simsagues/less-is-more-designing-data-visualizations-that-inform-not-overwhelm-60824311e0bf?source=rss-4bf783c564d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/60824311e0bf</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-presentation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Simón Cerda]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 14:02:08 GMT</pubDate>
            <atom:updated>2024-11-25T14:02:08.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YOj4W7zFofhwNj7w" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In an age where data flows endlessly across dashboards, reports, and presentations, the ability to distill complex information into clear, impactful visuals is more important than ever. Data visualizations are powerful tools, capable of turning raw numbers into stories that inform decisions, inspire action, and communicate insights. Yet, the effectiveness of these visuals often hinges on a simple principle: less is more.</p><p>When faced with a wealth of information, it’s tempting to cram every possible detail into a single chart or graph. But complexity can quickly lead to confusion, obscuring the message the data is meant to convey. Overwhelming visuals risk losing their audience entirely, turning what could have been a clear narrative into a puzzle too frustrating to solve.</p><p>I’m Simón, a data enthusiast with over five years of experience working with data in various capacities, from creating reports in PowerPoint to developing cutting-edge Generative AI tools. My journey has always been driven by a deep passion for transforming raw data into meaningful insights that drive decisions and spark understanding. Over the years, I’ve immersed myself in the world of data visualization, exploring how to effectively showcase data in ways that resonate with an audience and tell compelling stories.</p><p>Currently, as I pursue a Master’s in Data Science, I’ve become increasingly aware of the widespread misunderstandings and overlooked principles in how data is presented. Many newcomers to data exploration feel overwhelmed by the sheer variety of techniques and tools available for visualization. This inspired me to write this article — to help simplify the process for those starting their journey and to emphasize the importance of clarity and purpose in designing visualizations.</p><p>I also want to acknowledge one of my biggest inspirations, Cole Nussbaumer, whose incredible book on storytelling with data has been a game-changer in teaching how to craft impactful visual narratives. Her work has been instrumental in shaping my perspective, and I hope to pass on some of that inspiration through this article.</p><h3>Exploratory vs Explanatory</h3><p>When it comes to data visualization, it’s crucial to distinguish between exploratory and explanatory analysis. Exploratory analysis is like panning for gold — you sift through heaps of sediment to uncover a few valuable nuggets. However, when communicating your findings, the focus should shift to explanatory analysis: presenting a polished story around those golden insights. Too often, people fall into the trap of showing their audience the entire pan of dirt, overwhelming them with unnecessary details. Instead, embrace the “less is more” philosophy — highlight only the gold, the key insights your audience truly needs, to ensure clarity and impact.</p><h3>Storyboard</h3><p>Storyboarding is a powerful way to ensure your communication stays clear and focused, embodying the “less is more” principle. By sketching a simple, flexible outline of your content upfront — using tools like whiteboards, paper, or Post-it notes — you create a structure that aligns with your audience’s needs and prevents wasted effort. Starting low-tech avoids the trap of prematurely overcommitting to slides or visuals, which can lead to bloated, unfocused presentations. Instead, storyboarding allows you to experiment with different narrative flows and focus on the core insights, ensuring a concise and impactful delivery.</p><h3>Choosing your data visualization</h3><p>Now, let’s get practical: what visualizations should you use? Cole noted that after creating over 150 visuals for workshops and consulting projects, only about a dozen types of charts were used repeatedly. Building on this insight, I’ll break down the most effective visualizations based on the type of data you want to present, helping you choose the right tool to clearly and effectively communicate your message.</p><h4>Just a Number</h4><p>When sharing just one or two numbers, simple text can be an effective way to communicate. Focus on making the numbers prominent, supported by a few words, rather than using a table or graph that may dilute their impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*61ZK4PJ3p70EgxjHMVfYFg.png" /></figure><p>Having numbers doesn’t always mean you need a graph. For example, stating “25% of people used public transportation in 2020, compared to 30% in 2000” is much clearer than using a graph for just two numbers, which might confuse the viewer. In such cases, a simple text statement is often more effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-gF9ZASwRz--R-RwX-MrA.png" /></figure><h4>Relationship Between Two Things</h4><p>When you want to explore the relationship between two continuous variables, a scatterplot is an excellent choice. A scatterplot allows you to plot individual data points on a two-dimensional axis, revealing trends, patterns, or correlations. For example, if you were to examine the relationship between income and education level, each point on the scatterplot would represent an individual’s income versus their years of education. By visualizing this, you can easily identify if a positive or negative correlation exists between the variables or if there’s any significant clustering of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*y-HbrEQ2Bh1GzFjz1vwvgg.png" /></figure><h4>Continuous Data</h4><p>For displaying trends or changes in continuous data over time, line charts are highly effective. Line charts show how a variable evolves, allowing you to track fluctuations and identify patterns over a period. For instance, if you were analyzing the average temperature over several months, a line chart would clearly highlight rising or falling trends, providing valuable insight into seasonality or unusual variations. Unlike bar charts, line charts are ideal when the data is continuous and you want to emphasize the connection between points, making them perfect for showing trends in time series data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*FIgXugRAODZbcjmpKhoMIw.png" /></figure><h4>Exploring Categorical Variables</h4><p>Bar charts are a powerful tool for displaying categorical variables because they provide a clear, easy-to-interpret visualization. The simplicity of a bar chart allows the audience to immediately compare categories based on the length or height of the bars, making it easy to identify which category is the largest, smallest, or has the greatest difference between them. Because of the human ability to quickly assess the length of bars, this type of chart minimizes cognitive load, allowing viewers to focus on the message the data conveys. Additionally, bar charts ensure that comparisons are made from a baseline of zero, which avoids misleading impressions that can occur if the baseline is skewed or absent. This straightforward approach is why bar charts remain one of the most effective and widely used chart types in data visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*7JJmikxHMx0yl41Yxzkw0g.png" /></figure><p>I personally don’t favor pie charts for data visualization. While they can occasionally be useful for showing proportions, they have significant limitations that make them less effective for representing complex categorical data. The human eye has difficulty accurately judging the size of pie slices, particularly when the segments are close in size, making it hard to discern small differences or compare categories effectively. This can lead to confusion and obscure the key message. Pie charts are typically best suited for datasets with only a few categories, where the proportions are clearly distinguishable. However, even with data labels, pie charts often take up more space than necessary for relatively simple data. In contrast, I always prefer bar charts. They offer greater clarity, are easier to read, and provide a more straightforward way to compare categories, making them a far superior choice for most categorical data visualizations.</p><h3>Don’t Overcomplicate Your Visuals</h3><p>When it comes to data visualization, simplicity is often more impactful than complexity. While charts like heat maps or correlation matrices might seem visually impressive, they can quickly become unnecessary distractions if they don’t provide valuable insights. Overloading your audience with complex visuals that aren’t directly relevant to the key message only serves to confuse rather than clarify. It’s important to remember that not every dataset requires an intricate chart; sometimes, a straightforward bar chart or line graph is all you need to convey your point effectively. Keep in mind that the goal of any visualization is to enhance understanding, not to showcase every advanced tool available. Focus on using the simplest and most effective chart that highlights the essential information.</p><h3>Reducing Cognitive Load: Keep It Simple</h3><p>Have you ever looked at a slide packed with text, graphs, and random images, only to feel overwhelmed and unsure where to focus? That’s a prime example of cognitive load at work. Every element on a slide or page demands mental effort from your audience to process, and if there’s too much going on, it becomes difficult for them to extract the core message. For example, imagine a presentation with a complicated chart full of data points, labels, and colors that distract from the main takeaway. Even if the chart could provide valuable insight, the audience may struggle to make sense of it, and as a result, the message is lost.</p><p>The goal should always be to minimize unnecessary elements and focus on what truly adds value. Instead of overwhelming your audience with a complex heatmap that requires deep analysis, consider a simple bar chart with clear labels that directly communicates the key information. This allows your audience to focus their mental energy on understanding the message, rather than deciphering confusing visuals. By reducing cognitive load and keeping things simple, you ensure that your audience grasps the essential points without unnecessary distractions.</p><h3>Conclusion</h3><p>In data visualization, less truly is more. While it’s tempting to use complex charts or add unnecessary elements to showcase your skills, the most effective visuals are often the simplest. By focusing on clarity and reducing cognitive load, you can ensure that your audience grasps the essential message without feeling overwhelmed. Whether you’re choosing between bar charts or line graphs, understanding the core idea behind your data will guide you toward the right choice. Remember, the goal is to inform, not to dazzle with unnecessary visuals.</p><p>For anyone looking to dive deeper into the art of storytelling with data, I highly recommend Cole Nussbaumer Knaflic’s book <em>Storytelling with Data</em>. It provides a clear, practical approach to making your data-driven insights not only understandable but also impactful. Her insights have been invaluable in shaping how we should think about designing visuals that communicate effectively. Keep it simple, keep it focused, and your visuals will speak for themselves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60824311e0bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Data Analysis: Unleashing the Power of Chatbots]]></title>
            <link>https://medium.com/@simsagues/revolutionizing-data-analysis-unleashing-the-power-of-chatbots-6c2cae23ec04?source=rss-4bf783c564d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c2cae23ec04</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Simón Cerda]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 14:03:12 GMT</pubDate>
            <atom:updated>2023-09-08T14:03:12.225Z</atom:updated>
            <content:encoded><![CDATA[<p>Using OpenAI to build Data Analysis Chatbots. Query and retrieve data insights directly from structured database using natural language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AgISNNCRMor-RnJL" /><figcaption>Photo by Cytonn Photography on Unsplash</figcaption></figure><p>In today’s data-driven world, organizations are constantly striving to extract meaningful insights from their vast troves of information. Traditionally, this process has involved coding, complex queries, and time-consuming data extraction. However, with the advance on AI and chatbots those problems sounds far from being a real problem anymore. These intelligent conversational agents are revolutionizing all kind of fields, including data analysis, enabling users to query a structured database, retrieve relevant information, and receive natural language insights, all without the need for coding or manual data extraction. In this article, we will explore how OpenAI’s API is empowering developers to build data analysis chatbots that streamline the analysis process and unlock the power of data like never before.</p><p>The versatility of the OpenAI API extends to a wide range of tasks involving natural language understanding, code interpretation, and image processing. It provides a diverse collection of models, each tailored to specific tasks and varying in their computational capabilities. Additionally, the API allows users to fine-tune and customize models according to their unique requirements. With these capabilities, the API facilitates tasks such as content generation, semantic search, and classification, empowering users with a comprehensive toolkit for various applications.</p><p>Let’s delve straight into the process of creating the Data Analytics Chatbot using OpenAI. In this case, we will leverage the powerful ‘text-davinci-003’ model, which excels at handling various language tasks with exceptional quality and can seamlessly process lengthy prompts. Below is an illustrative example showcasing how the OpenAI API can be utilized for this purpose.</p><pre>openai.Completion.create(<br>  model=&quot;text-davinci-003&quot;,<br>  prompt=&quot;I need the name and city information from the <br>          top 5 employees by amount of sales in the East Region&quot;<br>)</pre><p>While the concept may appear straightforward at first glance, the reality is a bit more intricate. The Model requires a set of foundational assumptions to produce coherent results. Thus, prior to making any inquiries to the API, we must furnish the model with essential information about the Database and clearly define the type of task we intend to accomplish</p><p>Let’s assume we have a simple database with three tables, Employees, Stores and Sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*RB8E11maGa4LvbHo6pD9tA.png" /></figure><p>To enable the model to comprehend the database structure, we will supply the schema alongside sample values from the tables. By utilizing the metadata and performing some pre-processing, we can construct both the schema and a data sample dictionary for the database. This preparatory phase can be achieved either through an automated script or manually, as a necessary pre-processing step.</p><pre>schema_db = {<br>&#39;Employee&#39;: [&#39;id&#39;, &#39;name&#39;, &#39;age&#39;, &#39;store_id&#39;, &#39;role&#39;], <br>&#39;Store&#39;: [&#39;id&#39;, &#39;address&#39;, &#39;city&#39;, &#39;region&#39;],<br>&#39;Sales&#39;: [&#39;id&#39;, &#39;date&#39;, &#39;amount&#39;, &#39;currency&#39;, &#39;employee_id&#39;]<br>}<br>sample_db = {<br>&#39;Employee&#39;: [1, &#39;John&#39;, 37, 11, &#39;Manager&#39;], <br>&#39;Store&#39;: [11, &#39;5th Avenue&#39;, &#39;New York&#39;, &#39;East&#39;],<br>&#39;Sales&#39;: [&#39;1182&#39;, &#39;11/12/2022&#39;,720, &#39;$ dollar&#39;,11]<br>}<br></pre><p>With the contextual information and the foundation laid by the schema and data samples, the query becomes much more informed, enhancing the accuracy and relevance of the results produced by the model. By specifying the target database and the desired outcome, we enable the model to generate SQL queries tailored to our specific requirements, facilitating a more effective and customized data analytics experience.</p><pre>User_Query = &quot;I need the name and city information from the <br>          top 5 employees by amount of sales in the East Region&quot;<br><br>openai.Completion.create(<br>  model=&quot;text-davinci-003&quot;,<br>  prompt=f&quot;### Postgres SQL tables, with their properties:{schema_db}<br>              and samples: {sample_db}<br>            ### Write A SQL query for the following query {User_Query}&quot;<br>)</pre><p>Having refined and enriched the initial query, we have achieved a higher level of precision and completeness. While there may still be room for further enhancements, upon executing the query provided below, the API responds with the following SQL statement.</p><pre>SELECT e.name, s.city<br>FROM Employee e<br>INNER JOIN Store s ON e.store_id = s.id<br>INNER JOIN Sales sa ON e.id = sa.employee_id<br>WHERE s.region = &#39;East&#39;<br>GROUP BY e.name, s.city<br>ORDER BY SUM(sa.amount) DESC<br>LIMIT 5</pre><p>If we go through the SQL, we can se it’s pretty accurate, it retrieves the name and city from the top 5 employees located in the stores at the East Region. The only flaw it’s that the SQL is grouping by employees name and city when it should be by employee id, considering that it could be more than one employee with the same name and city.</p><p>Given the API’s capability to comprehend multiple instructions, we have the option to incorporate additional rules into the prompt. However, it’s essential to acknowledge that this approach might not embody the ideal “Smart-each” aspect. Nonetheless, we can delve into this aspect further and discuss its implications later on.</p><pre>User_Query = &quot;I need the name and city information from the <br>          top 5 employees by amount of sales in the East Region&quot;<br><br>openai.Completion.create(<br>  model=&quot;text-davinci-003&quot;,<br>  prompt=f&quot;### Postgres SQL tables, with their properties:{schema_db}              and samples: {sample_db}<br>           ### Write A SQL query for the following query {User_Query}<br>           ### if grouping is necessary do it by id&quot;<br></pre><p>After querying, the API will return the following SQL statement.</p><pre>)<br>SELECT e.name, s.city<br>FROM Employee e<br>INNER JOIN Store s ON e.store_id = s.id<br>INNER JOIN Sales sa ON e.id = sa.employee_id<br>WHERE s.region = &#39;East&#39;<br>GROUP BY e.id<br>ORDER BY SUM(sa.amount) DESC<br>LIMIT 5</pre><p>Now the SQL statement it’s exactly what we need to retrieve the data we ask for in the beginning. If we run the query using any SQL package to an existing database, the results will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*-9vKGcgtKRzdI32IUykl-g.png" /></figure><p>But how can this be transform into a more natural language type of answer? What if we send back this results to the API asking this time, for a more natural language answer using the results from the SQL query and the question from the beginning as context.</p><pre>tabular_data = list(df.to_dict(&#39;index&#39;).values())<br>col_names = df.columns.to_list()<br><br>sql_response = openai.Completion.create(<br>  model=&quot;text-davinci-003&quot;,<br>  prompt=f&quot;&quot;&quot;Can you answer the following question using natural lenguage: &#39; {User_Query}&#39;<br>  the next table have all the information required to answer the previous question,\n<br>  Table: column names : {col_names}\n<br>  row values:{tabular_data}&quot;&quot;&quot;<br>)</pre><pre>The Top 5 employees in the East Region are John from New York,<br>Peter from Miami,Steve from Washington DC, Maria from Atlanta<br>and Rachel from New York.</pre><p>So now we have a chatbot prototype where a user can ask a specific question like</p><p><strong>“I need the name and city information from the top 5 employees by amount of sales in the East Region”</strong></p><p>and as return the chatbot will answer</p><p><strong>“The Top 5 employees in the East Region are John from New York, Peter from Miami, Steve from Washington DC, Maria from Atlanta and Rachel from New York.</strong></p><h4>Further Steps &amp; Conclusion</h4><p>As mentioned earlier, relying on explicit statements like “if grouping is necessary, do it by id” is essentially contrary to the principles of machine learning. In such scenarios, the most effective approach would involve constructing a Fine-Tuned model tailored precisely to your database schema, utilizing typical data analytics questions as training data.</p><p>By adopting this method, the model gains a profound understanding of the inherent relationships within your dataset and how to handle specific tasks, such as grouping data by the “id” field. This fine-tuning process empowers the model to provide more contextually relevant and accurate responses, aligning it better with the requirements of your data analytics endeavors.</p><p>In this particular situation, I have opted to keep the algorithm in its current state since I lack the resources to train a Large Language Model (LLM). Alternatively, you might consider exploring the possibility of creating this chatbot using other pre-trained LLMs. The LLama models, in particular, appear to hold significant promise in this context.</p><p>Moreover, an additional progressive step to enhance the project would involve developing a user interface (UI) to demonstrate the chatbot’s capabilities effectively. Such a UI would serve as a platform to showcase the demo, making it more accessible and user-friendly for potential users to interact with the chatbot seamlessly. This advancement could amplify the value and utility of the application, making it more appealing to a broader audience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c2cae23ec04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classify Bank Complaints using Customized Transformer Model]]></title>
            <link>https://medium.com/@simsagues/classify-bank-complaints-using-customized-transformer-model-4ada90f8e565?source=rss-4bf783c564d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ada90f8e565</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[complaints]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[banking]]></category>
            <dc:creator><![CDATA[Simón Cerda]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 14:24:57 GMT</pubDate>
            <atom:updated>2023-03-21T14:24:57.476Z</atom:updated>
            <content:encoded><![CDATA[<h4>Text Classification: How BERT Models Outperform Traditional Methods in Natural Language Processing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DESTubaZXo98tNfMWJUxzA.png" /><figcaption>Photo by Unseen Studio on Unsplash</figcaption></figure><h3>Introduction</h3><p>The task of classifying text is perhaps one of the most frequently seen tasks when talking about Natural Language Processing. The ability to automatically classify and understand text can provide great value to many industries.</p><p>Over this post, I will show how to create a state-of-the-art text classifier model, using a Transformers architecture, which has shown incredible results in different NLP tasks and challenges. I adjust a pre-trained BERT model, to use it on a collection of bank complaints, to be able to predict some labels on the dataset like the Product &amp; Issue of the complaint.</p><p>Being able to automatically classify complaints or client messages can be a great time and effort saver for the company as they can route the request to the dedicated team without the need to review them one by one.</p><p>There are already different articles working on this same problem, the idea of this post is to show that Transformers and Bert Models exceed in performance and how we can use some of the pre-trained model available in HuggingFace to achieve top results.</p><h3>Getting the Data</h3><p>For Training, I used a consumer complaint database, provided by <a href="https://www.consumerfinance.gov/data-research/consumer-complaints/">consumerfinance.gov</a>. This collection of complaints has a narrative description of the problem written by the consumer and some categories to group these complaints into, for example, Product, showing the product that is the target of the complaint; And Issue, another variable that categorizes what type of problem is mentioned in the complaint. All complaint data is freely available for anyone to use, analyze, and build on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*AhvekPIdZ9j7ab4Pp5FKCA.png" /></figure><h3>Pre-Processing</h3><p>Before start training the model, I did some exploration and pre-processing of the data.</p><p>For this project I’m going to concentrate only on the columns “Product”, “Issue” and “Consumer complaint narrative”, being this last one the column with the consumer narrative that I’m going to process and the other two, the ones I seek to predict.</p><p>The whole database has a total of 3 million records and 18 columns, to clean the data I decided to delete all the records that were empty for the columns we are going to work with, which were 200k total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*PVCiVrmOwVJ4Qw3NqIwovA.png" /><figcaption>Product Categories</figcaption></figure><p>If we check the category Product, there are 18 different unique values, with some unbalanced categories like “<em>Credit reporting, credit repair services or other personal consumer reports</em>”.</p><p>There are also a few redundant variables that can be grouped together, for example, there’s one category called “Credit card or prepaid card” and other one called “Credit Card”, considering that the second one fit in the first one, they can be merged into just one category. After using the same logic for other product and issue values, we end up with 10 different products, and 18 different issues.</p><p>To work with the unbalanced classes in Product and Issue we use the function <strong>RandomUnderSampler</strong> from the library <strong>imblearn</strong>, this function perform Under-sample to the majority classes by randomly picking samples to balance them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*IKCBd8YJcaOy_abuaiatvQ.png" /><figcaption>output of RandomUnderSampler</figcaption></figure><p>By using this process the data is reduced significantly, but considering the large volume of data I had, it’s not bad to work with a more clean and precise sample.</p><h3><strong>Training</strong></h3><h4>Model</h4><p><strong>DistilBERT </strong>is a small, fast, cheap and light Transformer model trained by distilling BERT base. It has 40% less parameters than <em>bert-base-uncased</em>, and runs 60% faster while preserving over 95% of BERT’s performances as measured on the GLUE language understanding benchmark.</p><p><a href="https://huggingface.co/docs/transformers/model_doc/distilbert">DistilBERT</a></p><p>In this project, we took the <a href="https://huggingface.co/docs/transformers/model_doc/distilbert#transformers.DistilBertForSequenceClassification">DistilbertForSequenceClassification</a> class and adapted it to fit our problem. This Class uses a classification/regression head on the Distilbert output. In our adaptation we added an additional head next to the first one so that the model would be able to predict two labels (Product &amp; Issue).</p><p>I will not go into detail on how to build the model or the Distilbert components, since it is not relevant for this post.</p><h4><strong>Results</strong></h4><p>To visualize the results, I run the same training and test data with a different model, a simpler one to compare with, a TF-IDF model.</p><p>TF-IDF (term frequency-inverse document frequency) is a statistical measure that evaluates how relevant a word is to a document in a collection of documents. This is done by multiplying two metrics: how many times a word appears in a document, and the inverse document frequency of the word across a set of documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Pzv8olzHen9poTlfPzxbgg.png" /></figure><p>The results were not what I was expecting, comparing with the simpler model such as the TF-IDF, I can say AdaptDistilbert is better, but only around 1–2 %, for example, on the Product Label, there is a 84.5% accuracy on the TF-IDF and a 86% on the Adapted Distilbert Model, only 1.5 % of improvement.</p><h4><strong>Conclusion and Further Steps</strong></h4><p>Now, the question to conclude my post would be<em> It’s worth to use the Transformer Model?</em></p><p>As I already show, my model only got 1.5% more than a traditional model, considering the time and computation required to run the Transformer model, it would not be advisable for this use case, at least for now. But it will always depend on the business need and capabilities.</p><p>Perhaps, some more exploration should be done to see if there is more information that can be added to the model. Do further fine-tuning to check the best training parameters. We could also try others robust Transformers models and compare.</p><p>Transformers continue to prove why are they considered state-of-the-art, but depending on the case, it may not be the best solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ada90f8e565" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Document Information Extraction using OCR and NLP]]></title>
            <link>https://medium.com/@simsagues/document-information-extraction-using-ocr-and-nlp-2c3caa5a7720?source=rss-4bf783c564d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c3caa5a7720</guid>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[information-extraction]]></category>
            <category><![CDATA[layoutlm]]></category>
            <dc:creator><![CDATA[Simón Cerda]]></dc:creator>
            <pubDate>Mon, 13 Dec 2021 19:17:58 GMT</pubDate>
            <atom:updated>2021-12-13T23:39:19.238Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article only consider one of the approaches that my team and I work to resolve a business problem. It’s not designed to be a very technical post, so I won’t go into specific coding details, but I will point to some useful references and libraries.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*leGeiv5g85K3Kp3q" /><figcaption>Photo by <a href="https://unsplash.com/@wesleyphotography?utm_source=medium&amp;utm_medium=referral">Wesley Tingey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a world where data processing is becoming an increasingly huge topic, being able to extract information quickly and efficiently can become a significant business advantage. One of the biggest challenges in information extraction is the diversity of sources and document formats.</p><p>For example, in the financial area, there are a lot of scanned documents, such as salary slips, statements banks, loans agreements, among other forms. These documents can present information without a consistent structure, so extracting important information can be time consuming.</p><p>For this reason, we leveraged different solutions involving computer vision and NLP techniques to develop an approach that is capable of identifying information in a Q<strong>uestion : Answer</strong> format and automatically extracting it. So for example if there is a document field with the name of an employee as “Name: Juan” our model needs to be able to extract that information as {Q<em>uestion: “Name”, Answer: “Juan”}</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*G6j25ywmkBe3kwPUWMfBFw.png" /></figure><p>Within this article I want to show the different steps we performed to implement our model:</p><ul><li><strong>Building the dataset</strong></li><li><strong>Fine-tunning a pre-trained Text and Layout Model</strong></li><li><strong>Defining the <em>question: answer</em> relationship algorithm</strong></li></ul><h3><strong>Building the dataset</strong></h3><p>In order to test our approach, we compiled a set of 32 salary slips images downloaded from internet. A salary slip is a document that contains a detailed list of elements on a salary and details of a particular employment. They have values like Employee Name, Date and Pays Amount. The model was trained with 32 different salary slips documents (jpg format) that where found on internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*UHjymy-OZmuHOa0TwIlj5A.png" /><figcaption>salary slips images</figcaption></figure><h4>OCR</h4><p>The first step to build the model is to be able to extract the content of each salary slip in a format that a computer can understand. To do this we use OCR (Optical Character Recognition). OCR software allows to capture data from scanned documents or pictures into text. There are many OCR tools. For this project we used Cloud Vision API. This tool receives an image and returns a list of text elements with their relative coordinates from the image (usually known as ‘bounding boxes’).</p><h4>Label-Studio</h4><p>Once all the fields and bounding boxes were extracted, it was necessary to label each field, for which we used an annotation-tool called Label-Studio, you can check the documentation and website <a href="https://labelstud.io/">here</a>, Each box returned by the OCR was manually classified into the following options: Header, Question, Answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJRGyLwWqGCHMeToRYp-MQ.png" /><figcaption>Label-Studio annotations</figcaption></figure><h3>Fine-Tunned LayoutLM model</h3><p>BERT-like model have been proved been the state-of-the-art techniques on all kind of NLP task, and they don’t lag behind when trying to extract text information using the document layout and visual information.</p><p>LayoutLM It’s a simple but effective pre-training method of text and layout for document image understanding and information extraction tasks. You can check more information here:</p><p><a href="https://arxiv.org/abs/1912.13318">LayoutLM: Pre-training of Text and Layout for Document Image Understanding</a></p><p>Our model will be a fine-tunned version of this model using the dataset that we already describe, you can find the pre-trained model on the hugginface.co repository.</p><p><a href="https://huggingface.co/microsoft/layoutlmv2-base-uncased">microsoft/layoutlmv2-base-uncased · Hugging Face</a></p><p>The input of the models are:</p><ul><li><strong>token id:</strong> text detected by the OCR tool and embedded by the model tokenizer</li><li><strong>Box:</strong> list containing the relative coordinates of the text item on a box shape (x0,y0,width, height)</li><li><strong>Label: </strong>(‘Header’, ‘Question’, ‘Answer’)</li></ul><h4>Results</h4><p>After training the model, we got the following scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*HfkluEQFYnK-7oBHXcNcxg.png" /></figure><p>We got an overall f1 score of 83%, it could be better, but considering the size of our training dataset, the results are not bad, we can see a low performance on the header label, this may be caused for having poor annotations or just a lack of regular headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lGUst6nYwZbDeWbbyMw2g.png" /><figcaption>LayoutLM model classifications</figcaption></figure><h4>Defining the <em>question: answer</em> relationship algorithm</h4><p>Once the classes of each box were defined, the next task was to associate each question with its respective answer, for example, on the picture from above, there is a question: “EMPLOYEE NO.” and an answer: “12345”, but the model does not yet have something that connect these two items.</p><p>To connect these items, we followed an iterative approach, going through the answers and then, based on a combination of distance between boxes and their vertical/horizontal alignment, we ranked all the potential relations between questions and answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*hCM9TVW9ec7X5kOGYHRaZQ.png" /></figure><p>After running the algorithm to find key-value items, we got the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*847DhIckXsKOYde9LTHTwA.png" /></figure><h3>Conclusion</h3><p>We were able to pull the text from the scanned documents using OCR then label them with our LayoutLM model and transform it on a structured format. Overall the results were acceptable, the performance could have been better if we had worked with a bigger training set, the quality of the document and the performance of the OCR tool will also impact en the final result.</p><h4>What to try next</h4><ul><li>Get a bigger dataset</li><li>Try different OCR tools</li><li>Improve the key-value algorithms.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c3caa5a7720" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>