<?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[Cmotions - Medium]]></title>
        <description><![CDATA[Cmotions specializes in creating fact based decisions, we do this by working on a relevant and aligned Data Strategy, putting that into practice with Data Governance, Business Intelligence and the thing we love most: Data Analytics, Data Science and A.I. - Medium]]></description>
        <link>https://medium.com/cmotions?source=rss----5d5661bf36c6---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Cmotions - Medium</title>
            <link>https://medium.com/cmotions?source=rss----5d5661bf36c6---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:02:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/cmotions" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The  AI Agents Course: A review]]></title>
            <link>https://medium.com/cmotions/the-ai-agents-course-a-review-b289f90799ea?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/b289f90799ea</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[courses-and-training]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Jurriaan Nagelkerke]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 12:20:39 GMT</pubDate>
            <atom:updated>2025-04-05T06:28:00.013Z</atom:updated>
            <content:encoded><![CDATA[<p><em>As a data scientist or LLM enthusiast, you hear and read about agents everywhere now. Unfortunately, not everyone has the same idea when they talk about agents… Put less mildly: </em><a href="https://techcrunch.com/2025/03/14/no-one-knows-what-the-hell-an-ai-agent-is/?utm_source=newsletter&amp;utm_medium=email&amp;utm_term=2025-03-18&amp;utm_campaign=Global+AI+Weekly+-+Issue+89">No one knows what the hell an AI agent is (TechCrunch</a>). <em>When concepts are unclear, building a deep understanding by taking a course is often the best thing to do — to deepen your own knowlegde and thoughts on the topic. Are you planning to take the </em><a href="https://huggingface.co/learn/agents-course/unit0/introduction">🤗 AI Agents course</a> <em>and wondering what to expect? Or did you take it and are you wondering what other participants got out of it? In that case I hope you enjoy this review of unit 1. Looking forward to your comments, experiences and reflections!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JfrD8OFq1dDDb4tO.jpg" /></figure><p>I ❤️🤗</p><p>As a data science &amp; AI practitioner, I love Huggingface for what they have contributed to the field over the past few years. Their role in the speed in which the community is able to learn and build on each others’ work cannot be overestimated. And they keep on adding!</p><p>Therefore, as a huge 🤗 fan, I also immediately joined the waiting list for the AI Agents Course the minute it was introduced. I’ve been building pipelines with LLMs for some time now, and i run into more and more examples where making things more ‘agentic’ is the logical next step. There are dozens of examples out there to build upon, but first gathering a strong knowledge base is in my experience always a good idea. By understanding the language and concepts, you can better communicate with peers and ask informed questions, to them or to copilot. Aside from that, I really enjoyed the ride of most of the Coursera (early days), Udemy and deeplearning.ai courses I took over the years. So bring it on!</p><p>In the next sections I will go through the contents of the unit 1, in which most important concepts around agents are introduced, and briefly discuss my key takeaways and experiences.</p><h4>What is an Agent?</h4><p>One of the main reasons for participating in this course is to get a firm conceptual understanding of what <em>defines</em> and Agent and what it is <em>not</em>. As the (gen)AI field is developing so fastly and so many people have joined the data science field in recent years, some common ground on concepts is essential to understand what pioneers and peers mean when they talk about AI agents. Everything is called AI nowadays and I (regretfully) sense the same is happening to Agents… I kept on asking myself: When does a solution or pipeline that includes an LLM become an actual agent? And when is it not that <em>agentic </em>so better not call it that? The <a href="https://huggingface.co/learn/agents-course/unit1/what-are-agents">first section of unit 1</a> helps to make a better distinction.</p><blockquote>An agent is an AI model capable of reasoning, planning, and interacting with its environment.</blockquote><p>This simple but complete definition tells the story on AI agents. The emphasis is on the so called <em>agency </em>of it: the ability of the agent to interact with the environment. The ability to interact is reflected in execution of <em>actions </em>the agent can perform, often via external tools. The analogy of <strong>The Brain </strong>— to think and plan — and <strong>The Body — </strong>to (inter)act — helps in understanding the essence of AI Agents. In short, Large Language Models (LLMs) are mainly used as the AI model that represents <em>the brain —</em> although alternatives like Vision Language Models (VLMs) are available. And depending on the tools we equip our agent with — <em>the body</em> —the sky is the limit in how our agent can interact with the environment.</p><blockquote>An Agent can perform any task we implement via Tools to complete Actions.</blockquote><p>For those who have been using LLMs for some time now, this is the essence of what agents bring to the table: Ability to interact with the environment via Tools. An isolated LLM can reason and can answer based on information in its training data, but it is limited to that knowledge and has no means to interact with the environment, not without an Agent (a body).</p><p>The next section of unit 1 is on <a href="https://huggingface.co/learn/agents-course/unit1/what-are-llms"><strong>what are LLMs</strong></a><strong>. </strong>It’s a nice, dense intro or refresher on LLMs — the encoder/decoder models, tokenization, the attention mechanism… Some clear visualisations and links to other 🤗 resources for more details. Towards building an agent, it is important to understand how llms are instructed via different types of messages, like system messages and user messages and how conversation history is treated.</p><p>Details on messages are covered in the next section of unit 1 on <a href="https://huggingface.co/learn/agents-course/unit1/messages-and-special-tokens"><strong>Messages and special tokens</strong></a><strong> </strong>that are used to help the LLM distinguish between text that comes from the user and text that contains generic instructions or history. The essence is that each time ‘the Brain’ is used (the LLM gets an input to complete), it should receive input that contains all the information needed to complete the text and respond: The brain has no memory! Put differently, the LLM doesn’t keep track of what it was asked before, the new input text to complete therefore has to contain all information needed to answer correctly. Special tokens and templates are crucial in helping the llm distinguish between the generic task it has, the conversation history to build upon and the user input provided.</p><p>And specifically for Agents, the information the LLM receives about the <strong>Tools </strong>that the agent has availabe to use, is crucial. This information needs to be presented to the LLM via the system message. How to do so is the topic of the next section of unit 1: <a href="https://huggingface.co/learn/agents-course/unit1/tools"><strong>What are Tools?</strong></a><strong> </strong>In short:</p><blockquote>A Tool is a function given to the LLM</blockquote><p>Tools come in many forms. Valuable tools do something that the LLM could not do on its own: it needs to <em>complement </em>the LLM — use information the LLM could not have been trained on (up-to-date data, internal sources) or performs tasks an LLM is not the best at (calculations, queries, generate images,…). It is vital that the LLM receives clear textual information about the tool: a generic description, something to call (like a function), arguments and typings of inputs and outputs. As the LLM can only generate text as output, the LLM needs to understand when to use which of the available tools, how to prepare the input for the tool and what to do with the output.</p><p>Although so far in the course there has been some example python code, the next part was for me the first piece of code I carefully inspected:</p><pre>@tool<br>def calculator(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Multiply two integers.&quot;&quot;&quot;<br>    return a * b<br><br>print(calculator.to_string())<br><br># Tool Name: calculator, Description: Multiply two integers., <br># Arguments: a: int, b: int, Outputs: int</pre><p>What are we looking at? With the @tool decorator a Tool is defined that the LLM can use. The .to_string() method shows what this decorator enables: translating a (well defined) function into a string that tells the LLM what the function does, how to call it and what to expect to come out of it. A more advanced way to achieve this — by defining a class Tool: is also discussed. It gives more flexibility but does the same.</p><h4><strong>Thought: ReAct vs Thought- Action-Observation</strong></h4><p>Now that we know how to instruct the Agent (LLM) to use external Tools, the next section of unit 1 elaborates on the continuous<a href="https://huggingface.co/learn/agents-course/unit1/agent-steps-and-structure"> <strong>Thought-Action-Observation cycle</strong></a><strong> </strong>agents operate in. <strong>Thought </strong>is about deciding on the next steps, <strong>Action </strong>concerns the Tool actions to perform and <strong>Observation </strong>regards processing the output of the model.</p><p>What was somewhat confusing to me at first, was the introduction of the <strong>ReAct </strong>(Reasoning-Acting) approach in the discussion of the Thought-Action-Observation cycle: So first we look at the agent operating in Think-Act-Observe cycles, now <em>within that </em>a Reasoning-Acting approach was introduced. I’m probably not the only one who got a bit confused by the apparent similarities (in terms Though-Action-Observation &lt;&gt; Reasoning-Acting). As second glance it becomes clearer: the ReAct approach is relevant <em>within </em>the Thought step. It encourages the Brain (LLM) not to jump to conclusions but think carefully, if possible break down the task in steps. This approach helps overcome the problem of ‘greedy’ LLMs that jump to conclusions too fast, by creating time for the LLM to think more carefully. As such, <em>ReAct</em> boosts the <em>Thought</em> step to come up with a better plan to turn into <em>Actions </em>and <em>Observations</em>. Most recent models like deepseek and openai’s o1 model have similar reasoning strategies incorporated in the model to boost performance.</p><h4><strong>Actions and three (or two?) types of Agents</strong></h4><p>The next cycle step concerns the essence of agents - Actions:</p><blockquote>Actions are the concrete steps an AI agent takes to interact with its environment.</blockquote><p>Immediately a distinction is made between different types of agent (action)s — JSON agents, code agents and function-calling agents— which makes things a bit more complex. It’s debatable whether this distinction really helps — conceptually its suffices to conclude there are numerous ways agents can interact with the environment and dependent on how they are set up, actions are triggered by providing tools with formatted JSON input, by generating code by the LLM that needs to be executed or with function input generated by the LLM.</p><p>If this distinction is not immediately clear to you: It also wasn’t for me… In the rest of the section it became a bit clearer: More generally speaking, there are two types of agents: those that generate <em>input </em>for an exernal tool (JSON formatted or otherwise suitable for the receiving function) or those that generate ‘<em>an executable code block — typically in a high-level language like Python.</em>’ The latter type is referred to as <strong>Code Agents</strong>, the former <strong>JSON Agents </strong>/ <strong>Function calling Agents.</strong> In short: ‘<em>Actions bridge an agent’s internal reasoning and its real-world interactions by executing clear, structured tasks — whether through JSON, code, or function calls.</em>’</p><h4><strong>Observations — as actions have consequences</strong></h4><p>The last step and last section of unit 1 before an example is shown, is about the third Thought-Action-Observation-step: <strong>Observations</strong>. ‘<em>Observations are how an Agent perceives the consequences of its actions.’ </em>In this step, the Agent (1) collects the output of the action, (2) adds results to the existing information and (3) adapts the strategy for subsequent thoughts and actions. The Agent decides whether additional information — and therefore a new cycle run — is needed or if it’s ready to provide a final answer.</p><p>The first unit commences with a tedious example — as the authors named it themselves — just to show that building agents is complex without using one of the many frameworks that make it much more feasible to build one. After that a first real example is shown, using the smolagents library to build your own agent. It’s a nice way to see a first simple Agent in action and to get familiar with thesmolagentslibrary, with some predefined tools available and also to experience how to add a custom tool. All of this is a first exploration, getting you ready to go into much more detail of designing your own Agents in the units to follow. Unit 1 is concluded with the Quiz that checks your understanding on unit 1. Don’t worry, its not that difficult. If you value the certificate, make sure you download and store it at the end — i dont think you can download it later without retaking the quiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8oboU-VQp9h5z6Y4G7xCw.jpeg" /></figure><h4><strong>Unit 1: Wrapping it up</strong></h4><p>In total, this first unit contains many valuable concepts that are important to understand when working with agents. For several reasons, it is advisable to go through this unit at your own pace, and revisit the material once more after you got to the end of it. First of all, many concepts are discussed and many come with interesting links to other courses or sources. Secondly, at least for me, the relationship between some of the concepts discussed was not inmmediately clear. Cycles have nested approaches, action types and agent types are intertwined and the distinction between JSON Agents, Code agents and function calling Agents was not very intuitive at first, the same goes for the tool decorators vs Classes. For me, things fell in their place much better the second time I read through unit 1 — it prepared me much better for the units to come.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b289f90799ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/the-ai-agents-course-a-review-b289f90799ea">The 🤗 AI Agents Course: A review</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging the Gap: How AI Translates Sign Language Into Speech]]></title>
            <link>https://medium.com/cmotions/bridging-the-gap-how-ai-translates-sign-language-into-speech-ebe865ff6266?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/ebe865ff6266</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sign-language-recognition]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[video-to-text-converter]]></category>
            <dc:creator><![CDATA[Jurriaan Nagelkerke]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 08:58:06 GMT</pubDate>
            <atom:updated>2025-03-10T08:58:06.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdgalCaKizOGEB6HnZ3Jvg.png" /></figure><h3>Exploring how AI-powered models transform sign language into natural-sounding spoken words</h3><p>At Cmotions, we enjoy leveraging AI to solve business or societal challenges. One of the challenges we set out to address is communication accessibility for individuals who rely on sign language. <strong>What if AI could bridge the gap between sign language and spoken language, making interactions more seamless?</strong></p><p>With that vision in mind, we embarked on a journey to explore if we can create something that is able to interpret (WL)ASL sign language and convert it into English speech. In other words, a sign-to-speech translation using AI. The complete process consists of several steps. First, we fine-tuned a pre-trained model to enable translating videos of sign language into predicted ‘glosses’ (textual representation of signs). In <a href="https://theanalyticslab.nl/fine-tuning-a-video-classification-model-for-hand-sign-recognition-in-python/">another article</a> we walk you through the process of finetuning a specialized model for that. In this notebook we use that finetuned model to interpret short video clips of sign language and convert them into written glosses. These glosses are then fed into a large language model (LLM), which transforms them into grammatically correct English sentences. Finally, the written output is converted into speech, making sign language accessible through audio. In short, below we show how we can use the model we have trained to (1) transform a handsign video into glosses (the words or terms expressed), then (2) into a sentence everyone can understand and finally (3) into spoken text.</p><p>Follow along to see how a video of someone signing the sentence <em>“Where do you prefer to go on vacation?”</em> is converted into a clear, natural-sounding audio note.</p><p>Let’s start by displaying the video. As you can see this video is a combination of the separate expressed signs. This also shows how we have currently trained our model: on separate signs expressed. Our model classifies the most probable sign (or ‘gloss’ in sign language lingo) expressed.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1064205690%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1064205690&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1991474607-4485562030eddf812a6d7a2af9ec5b07d393a09248efdca1805fbb048ff27821-d_1280&amp;type=text%2Fhtml&amp;schema=vimeo" width="1440" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfe123023d1d0127bd34d5f2c0bdfbf2/href">https://medium.com/media/cfe123023d1d0127bd34d5f2c0bdfbf2/href</a></iframe><h3>Tools &amp; Packages</h3><p>What packages do we use? Here’s an overview:</p><ul><li><strong>Torch:</strong> Torch is an open-source machine learning library, the backbone for many deep learning use cases.</li><li><strong>Ollama:</strong> Ollama is a lightweight, extensible framework for building and running language models efficiently.</li><li><strong>Langchain:</strong> LangChain is a framework for developing applications powered by large language models (LLMs).</li></ul><p>In the three steps (video to glosses, glosses to natural text sentence, and natural text sentence to audio) we use different tools and models:</p><ul><li><strong>Transformers</strong>, <strong>opencv-python</strong>, <strong>torchvision</strong> and <strong>pytorchvideo</strong>: to apply our finetuned model to the new video file snippets to predict the glosses.</li><li><strong>Ollama</strong> and <strong>langchain</strong>: to transform the predicted glosses to a natural sentence.</li><li><strong>gTTS</strong> and <strong>ipython audio</strong>: to create and play the natural sentence as an audio file.</li></ul><p>You can learn more about these packages in the following resources:</p><ul><li><a href="https://ipython.org/ipython-doc/3/api/generated/IPython.display.html">https://ipython.org/ipython-doc/3/api/generated/IPython.display.html</a></li><li><a href="https://pytorch.org/">https://pytorch.org/</a></li><li><a href="https://ollama.com/">https://ollama.com/</a></li><li><a href="https://www.langchain.com/">https://www.langchain.com/</a></li><li><a href="https://pypi.org/project/opencv-python/">https://pypi.org/project/opencv-python/</a></li><li><a href="https://pytorch.org/vision/stable/index.html">https://pytorch.org/vision/stable/index.html</a></li><li><a href="https://pypi.org/project/pytorchvideo/">https://pypi.org/project/pytorchvideo/</a></li><li><a href="https://pypi.org/project/gTTS/">https://pypi.org/project/gTTS/</a></li></ul><pre># make sure you have ollama installed and pulled the llm used:  %sh  ollama pull qwen2.5:32b-instruct </pre><pre>import torch<br>import os<br>import pytorchvideo<br>from transformers import VideoMAEImageProcessor, VideoMAEForVideoClassification<br>from pytorchvideo.transforms import ApplyTransformToKey, UniformTemporalSubsample<br>from torchvision.transforms import Compose, Lambda, Normalize, Resize<br>import pytorchvideo.transforms as transforms<br>import pytorchvideo.data<br>from pytorchvideo.data.encoded_video import EncodedVideo<br>import imageio<br>import numpy as np<br>from IPython.display import Image<br>import glob<br>import itertools</pre><p><em>Code snippet 1: Import the packages we use</em></p><h3>Data Collection</h3><p>For this project we aim to develop an AI-driven tool capable of interpreting (WL)ASL sign language and converting it into English speech. Interpreting short video clips of sign language and convert them into written glosses.</p><h3>What is a gloss?</h3><p>“When a word is associated with a sign it’s called a GLOSS: In simplest terms, a GLOSS is a label. In <a href="https://en.wikipedia.org/wiki/American_Sign_Language">ASL</a> it is an English word or words that we use to name ASL signs so that we can talk about these signs. The word or words associated with that sign do not represent the full meaning of the sign; at best they approximate its meaning. A GLOSS is a label with very weak adhesive, it’s not stuck on very securely. Some signs have several different possible glosses. For instance, the words: “IMPORTANT”; “WORTH” and “VALUE” could all be used to label the same ASL sign a gloss is a brief notation, especially a marginal or interlinear one, of the meaning of a word or wording in a text.” — <a href="https://www2.bellevuecollege.edu/artshum/materials/lang/Mangan/Winter2006/103/GlossExplained.pdf">Rick Mangan 2002</a></p><h3>Training Data</h3><p>To train a model that can translate a video fragment of a sign to the most probable gloss, we use the dataset <a href="https://dxli94.github.io/WLASL/">“Word-level Deep Sign Language Recognition from Video: A New Large-scale Dataset and Methods Comparison”</a>. This WLASL dataset is the largest video dataset for Word-Level American Sign Language (ASL) recognition, which features 2,000 common different words in ASL.</p><h3>Connect to blob storage</h3><p>To develop our solution, we created a subset of signs from this huge dataset. Based on the subset (29 hand getures) we split the data into training, testing and validation to develop and test our finetuned model.</p><h3>Load finetuned-trained model</h3><p>The model was finetuned based on the selection of the training data. In our <a href="https://theanalyticslab.nl/fine-tuning-a-video-classification-model-for-hand-sign-recognition-in-python/">other blog</a> we show how we finetuned the model to predict glosses. Here we load our model and apply it to a sequence of glosses. Now we want to use it in practice! Since we used a pretrained open weights model, which we could download and finetune using the Transformers package, we can use the same package to use the model for inference (applying it to our new series of sign videos).</p><pre>from transformers import VideoMAEImageProcessor, VideoMAEForVideoClassification</pre><pre>model_ckpt = &#39;/dbfs/mnt/handsigntospeech/Models/-sign_finetuned-2024-11-03T08/best_model/&#39; </pre><pre>image_processor = VideoMAEImageProcessor.from_pretrained(model_ckpt)<br>model = VideoMAEForVideoClassification.from_pretrained(<br>    model_ckpt,<br>    ignore_mismatched_sizes=True,  <br>)</pre><pre>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)</pre><pre>model = model.to(device)</pre><p><em>Code snippet 2: Load the model we finetuned</em></p><h3>Pre-processing</h3><p>An important step before we can apply our model to the sequence of sign videos, we have to preprocess those videos. This preprocessing transforms the videos in the format similar to how the training videos are preprocessed before we finetuned the Transformer model. The following custom function pre-processses the videos in terms of size and encoding, in order to be classified.</p><pre># Defaults for all videos<br>mean = image_processor.image_mean  <br>std = image_processor.image_std<br>clip_duration = 1.71 </pre><pre># Define the inference function for a single video<br>def predict_video_class(video_path, model=model):</pre><pre>    # Set size for resize transform<br>    if &quot;shortest_edge&quot; in image_processor.size:<br>        height = width = image_processor.size[&quot;shortest_edge&quot;]<br>    else:<br>        height = image_processor.size[&quot;height&quot;]<br>        width = image_processor.size[&quot;width&quot;]<br>    resize_to = (height, width)</pre><pre>    # Define video transformations<br>    val_transform = Compose([<br>        UniformTemporalSubsample(model.config.num_frames), <br>        Lambda(lambda x: x / 255.0),                    <br>        Resize(resize_to, antialias=True),              <br>        Lambda(lambda x: x.permute(1, 0, 2, 3)),        <br>        Normalize(mean, std)                            <br>    ])</pre><pre>    # Load and decode the video<br>    video = EncodedVideo.from_path(video_path)<br>    <br>    # Extract a clip from the video <br>    video_data = video.get_clip(start_sec=0, end_sec=clip_duration)  <br>    <br>    # Apply transformations to the video<br>    video_frames = video_data[&#39;video&#39;]  <br>    video_frames = val_transform(video_frames)</pre><pre>    # Add batch dimension (batch_size=1) before passing to the model<br>    video_frames = video_frames.unsqueeze(0)  <br>    # Shape: [1, T, C, H, W]</pre><pre>    # Run inference on the model<br>    video_frames = video_frames.to(device)</pre><pre>    # Run inference on the model<br>    with torch.no_grad():<br>        output = model(pixel_values=video_frames)  <br>        # Pass inputs into model</pre><pre>    # Extract logits and get the predicted class<br>    logits = output.logits<br>    predicted_class_idx = logits.argmax(-1).item()<br>    predicted_class_label = model.config.id2label[predicted_class_idx]</pre><pre>    return predicted_class_label</pre><p><em>Code snippet 3: Function to preprocess video and score with our finetuned model</em></p><h3>Inference</h3><p>Now that we have the packages loaded and the preprocessing function ready, we can load the separate sign videos (<a href="https://bhciaaablob.blob.core.windows.net/handsigntospeech/article%20sentence/GLOSS_1.mp4">GLOSS_1</a>, <a href="https://bhciaaablob.blob.core.windows.net/handsigntospeech/article%20sentence/GLOSS_2.mp4">GLOSS_2</a>, <a href="https://bhciaaablob.blob.core.windows.net/handsigntospeech/article%20sentence/GLOSS_3.mp4">GLOSS_3</a> and <a href="https://bhciaaablob.blob.core.windows.net/handsigntospeech/article%20sentence/GLOSS_4.mp4">GLOSS_4</a> ) , preprocess them and run them through our finetuned model. This will result in the glosses.</p><pre>import requests<br>import os</pre><pre># Blob storage URL<br>blob_path = &#39;https://bhciaaablob.blob.core.windows.net/handsigntospeech/article sentence/&#39;<br>video_names = [&#39;GLOSS_1.mp4&#39;, &#39;GLOSS_2.mp4&#39;, &#39;GLOSS_3.mp4&#39;, &#39;GLOSS_4.mp4&#39;]</pre><pre># Create URL list<br>video_list = [blob_path + video_name for video_name in video_names]</pre><pre># Local storage path<br>save_dir = &#39;/dbfs/mnt/handsigntospeech/&#39;</pre><pre># Ensure directory exists<br>os.makedirs(save_dir, exist_ok=True)</pre><pre>gloss_list = []</pre><pre>for video_name, video_url in zip(video_names, video_list):<br>    try:<br>        # Download video<br>        response = requests.get(video_url)<br>        response.raise_for_status()  # Raise error if request fails</pre><pre>        # Save video with unique filename<br>        local_video_path = os.path.join(save_dir, video_name)<br>        with open(local_video_path, &#39;wb&#39;) as f:<br>            f.write(response.content)</pre><pre>        # Process video using model<br>        predicted_class = predict_video_class(local_video_path, <br>                                              model)<br>        gloss_list.append(predicted_class)</pre><pre>        print(f&quot;Processed {video_name} -&gt; Predicted class:   <br>                {predicted_class}&quot;)</pre><pre>    except requests.RequestException as e:<br>        print(f&quot;Failed to download {video_name}: {e}&quot;)<br>    except Exception as e:<br>        print(f&quot;Error processing {video_name}: {e}&quot;)</pre><pre># Print final results<br>print(&quot;Final Gloss List:&quot;, gloss_list)<br></pre><pre>2/14/2025 (6s)<br>19<br>19<br>import requests<br>import os</pre><pre># Blob storage URL<br>blob_path = &#39;https://bhciaaablob.blob.core.windows.net/handsigntospeech/article sentence/&#39;<br>video_names = [&#39;GLOSS_1.mp4&#39;, &#39;GLOSS_2.mp4&#39;, &#39;GLOSS_3.mp4&#39;, &#39;GLOSS_4.mp4&#39;]</pre><pre># Create URL list<br>video_list = [blob_path + video_name for video_name in video_names]<br></pre><pre>#&gt; Processed GLOSS_1.mp4 -&gt; Predicted class: where<br>#&gt; Processed GLOSS_2.mp4 -&gt; Predicted class: vacation<br>#&gt; Processed GLOSS_3.mp4 -&gt; Predicted class: you<br>#&gt; Processed GLOSS_4.mp4 -&gt; Predicted class: prefer<br>#&gt; Final Gloss List: [&#39;where&#39;, &#39;vacation&#39;, &#39;you&#39;, &#39;prefer&#39;]</pre><p><em>Code snippet 4: Load the sign language videos and process them with our finetuned model</em></p><p>This result already looks pretty understandable right? <strong>‘where’</strong>, <strong>‘vacation’</strong>, <strong>‘you’</strong> and <strong>‘prefer’</strong> are the predicted glosses. Maybe you can guess the meaning of this set of glosses, but you will also recognize that its not that ‘fluent’ yet and can lead to misinterpretation quite easily. In American English the grammatical structure is as follows: Subject-Verb-Object (SOV) word order, however in ASL the word order depends on the topic-comment relations. Therefore, we can find multiple word orders, such as Subject-Verb-Object or Subject-Verb order and also Time-Subject-Verb-Object or Time-Subject-Verb word order. Luckily, uch in depth knowlegde of sign language is to a great extent present in most powerful pretrained language models. Therefore, in the next step we take advantage of the great power of large language models to transform the list of glosses into a naturally sounding sentence that everyone can understand.</p><p>We use the popular langchain package in combination with ollama — the hub where many large language models are made easily accessible. The <em>template</em> contains the prompt we engineered (prompt engineering is short for trial and error to end up with a prompt that makes the LLM do what you want it to do) to translate the gloss texts to a fluent sentence representing the meaning of the video. We use the LLM <a href="https://huggingface.co/Qwen/Qwen2.5-32B">qwen2.5 32b</a> for this task since it has a good performance in many tasks and is not too big in size (still 32 billion parameters… but had a good performance compared to other models at time of our project).</p><p>The last step is to transform the written text into audio. We can use Google’s great gtts package (Google Text To Speach) to do this with one line of code. Listen to the result below!</p><pre>from typing import List<br>from langchain import PromptTemplate, LLMChain<br>from langchain_ollama import OllamaLLM<br>from gtts import gTTS<br>import os<br>import IPython</pre><pre>def gloss_list_to_speech(gloss_text_list: str, llm: OllamaLLM, template: PromptTemplate) -&gt; gTTS:<br>    &quot;&quot;&quot;<br>    Converts a sequence of glosses into natural language text and then into speech.</pre><pre>    Args:<br>        gloss_text_list (List[str]): A list of strings of glosses.<br>        llm (OllamaLLM): The language model to use for converting glosses to natural language.<br>        prompt (PromptTemplate): The prompt template to use for the language model.</pre><pre>    Returns:<br>        gTTS: The generated speech object.<br>    &quot;&quot;&quot;<br>    prompt = PromptTemplate(template=template, input_variables=[&quot;text&quot;])<br>    llm_chain = LLMChain(prompt=prompt, llm=llm)<br>    gloss_text = &#39; | &#39;.join(gloss_text_list)<br>    natural_text = llm_chain.invoke(gloss_text)[&#39;text&#39;]<br>    language = &#39;en&#39;<br>    natural_audio = gTTS(text=natural_text, lang=language, slow=False)<br>    audio_name = gloss_text.replace(&#39; | &#39;,&#39;_&#39;) + &#39;.mp3&#39;<br>    natural_audio.save(audio_name)<br>    IPython.display.display(IPython.display.Audio(audio_name, autoplay=True))<br>    return natural_audio<br></pre><pre>llm = OllamaLLM(model=&quot;qwen2.5:32b-instruct&quot;)</pre><pre>template = &quot;&quot;&quot;<br>[INST] &lt;&lt;SYS&gt;&gt;<br>You are a professional WLASL (World Level American Sign Language) sign language translator. You receive a sequence of glosses, each delimited by a pipeline (|) symbol. Each gloss represents a word or phrase that conveys the meaning of a sign in WLASL. Your task is to convert the sequence of glosses into a well-structured, concise sentence that can be easily understood by someone who does not know sign language. Ensure the sentence is grammatically correct and natural in tone. Important: the output must not contain the pipeline (|) delimiter.</pre><pre>Here are some examples:<br>input: &#39;You | Name | What | You&#39;<br>output: &#39;What is your name?&#39;<br>input: &#39;You | Live | Where | You&#39; <br>output: &#39;Where do you live?&#39;</pre><pre>Only provide back the requested output, do not introduce your answer! Here is the glosses string, between three backticks: &lt;&lt;/SYS&gt;&gt;<br>```{text}```[/INST]<br>Your answer:<br>&quot;&quot;&quot;</pre><pre>gloss_list_to_speech(gloss_list, llm, template)</pre><p><em>Code snippet 5: Translate gloss labels to natural text and audio</em></p><p>Here is the result of our pipeline, that transforms a handsign video into gloss labels, those labels into a sentence everyone can understand and finally into spoken text:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F2050717536%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fjurriaan-nagelkerke-25466358%2Fwhere_vacation_you_prefer%3Fsi%3Dd495bca5842a413db17621de3e3eb6aa%26utm_source%3Dclipboard%26utm_medium%3Dtext%26utm_campaign%3Dsocial_sharing&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-41QY4hb7yI9hfFuy-4Uvjcg-t500x500.jpg&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc236924a5cfb55b145c6c9a5ce32776/href">https://medium.com/media/dc236924a5cfb55b145c6c9a5ce32776/href</a></iframe><p>We hope you like how in our project we combined a pretrained model and public data to fine tune a model, apply it to videos and use large language models and text-to-speech technologies available to translate sign videos to fluent, spoken text. This can help those who are dependent on sign language to communicate more easily with the big audience many of them deserve, not limited by the knowledge their audience has of sign language. This is how techniques can help improving life and thats why we love it!</p><p><em>Originally published at </em><a href="https://theanalyticslab.nl/bridging-the-gap-how-ai-translates-sign-language-into-speech/"><em>https://www.theanalyticslab.nl</em></a><em> on February 28, 2025.</em></p><p><em>Want to read more about the cool stuff we do at </em><a href="https://cmotions.com/"><em>Cmotions</em></a><em> and </em><a href="https://www.theanalyticslab.nl/"><em>The Analytics Lab</em></a><em>? Check out our </em><a href="https://www.theanalyticslab.nl/blogs/"><em>blogs</em></a><em>, </em><a href="https://www.theanalyticslab.nl/projects/"><em>projects</em></a><em> and </em><a href="https://www.theanalyticslab.nl/videos/"><em>videos</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe865ff6266" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/bridging-the-gap-how-ai-translates-sign-language-into-speech-ebe865ff6266">Bridging the Gap: How AI Translates Sign Language Into Speech</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s get balanced! A simple guide on how to deal with class imbalance in your binary data]]></title>
            <link>https://medium.com/cmotions/lets-get-balanced-a-simple-guide-on-how-to-deal-with-class-imbalance-in-your-binary-data-c3ced8d78645?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/c3ced8d78645</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[class-imbalance]]></category>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[binary-data]]></category>
            <category><![CDATA[predictive-model]]></category>
            <dc:creator><![CDATA[Jeanine Schoonemann]]></dc:creator>
            <pubDate>Mon, 08 May 2023 05:06:13 GMT</pubDate>
            <atom:updated>2023-05-08T05:06:13.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*K9XT-SGeEtwIAJrK.jpg" /></figure><p>At <a href="http://www.cmotions.nl/">Cmotions </a>we’ve always had a lot of discussion amongst colleagues whether or not to balance our datasets when building a predictive model. Everyone has their own personal preference and way of working, but which approach is “the best”? We simply didn’t know until we stumbled <a href="https://www.researchgate.net/publication/328332744_An_empirical_evaluation_of_imbalanced_data_strategies_from_a_practitioner&#39;s_point_of_view">upon this paper written by Jacques Wainer and Rodrigo A. Franceschinell in October 2018</a>. Unlike a lot of other research papers, this paper focuses on the practitioners (us) and not so much on researchers, since in general, a practitioner has a couple of days or weeks to build a model on a dataset, while a researcher may spend several years working with the same dataset. Because not everybody likes to dive into scientific papers, I’ve tried to summarize their conclusions in this blog as best I can.</p><h3>Research setting</h3><p>Let’s start with the setting of the research:</p><ol><li>Binary classification problems</li><li>82 datasets</li><li>The datasets were altered (if possible) to have an imbalance between 0.1% (severe) and 5% (moderate)</li><li>Focus on strong general classifiers:</li><li>Focus on easy to implement balancing strategies:<br><strong>Baseline</strong>: no balancing<br><strong>Class weight</strong>: assign more weight to the small class, the general setting used here is that the large class has a weight of 1 and the small class a weight of the inverse of the imbalance rate. Thus, if this rate is 1% the weight of the small class would be 100<br><strong>SMOTE </strong>(synthetic minority over-sampling): use KNN to find neighbours of the small class to randomly create a new data point for this class<br><strong>Underbagging</strong>: bagging of the base classifier, where each instance is trained on a balanced sample of the dataset, where the small class is preserved and the large class is randomly undersampled. This strategy has a parameter n, the number of sampled datasets created, in this research they used <em>n</em> as a hyperparameter to find the best value for each dataset</li><li>Focus on most used metrics (in research):<br><strong>Area under the ROC curve (AUC)</strong>: the estimated probability that a random positive example will have a higher score than a randomly selected negative example<br><strong>Accuracy (acc)</strong>: the proportion of correct predictions<br><strong>Balanced accuracy (bac)</strong>: the corrected accuracy based on the caculation of the arithmetic mean of the recall (the proportion of true predictions for the positive examples) and specificity (the proportion of true predictions for the negative examples)<br><strong>F-measure (F1)</strong>: the corrected accuracy based on the harmonic mean of recall and specificity<br><strong>G-mean (gmean)</strong>: the corrected accuracy based on the geometric means of recall and specificity<br><strong>Matthew’s correlation coefficient (mcc)</strong>: the Pearson correlation between the prediction and the correct class</li></ol><p>The researchers mainly made these choices based on what we as practitioners have in our most-used-toolbox. For myself, I can support this for most of the decisions. Although I must say, I very rarely use SVM.</p><p>The key take aways when looking at these settings:</p><ul><li>The lowest class imbalance is 5%, which is considered moderate in this paper, thus more balanced datasets are not taken into account here</li><li>This only holds for binary problems and not multiclass</li><li>The researchers chose to use strong general classifiers on purpose, since we would use them in practice too, just keep in mind this affects the extent to which the balancing strategy has an effect on result, since some of these classifiers are able to deal with imbalancing to some extent</li></ul><h3>Research questions</h3><p>In this paper Wainer and Franceschinell answer multiple questions, we will focus on the five questions that are most relevant to us. Which leads down to determining the best balancing strategy in general, for a given metric and if the data is severely or moderately imbalanced. They’ve also looked at which classifier works best with which balancing strategy or without using any balancing strategy. All questions we as Data Scientists have to think about every time we are building a predictive model.</p><p>If in the tables below multiple answers are given for the same metric, keep in mind that the order given is random, since the difference will be insignificant so we can’t order them based on that.</p><p><strong>What is in general the best strategy for imbalanced data (for each metric)?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*z0Fy0IychHBd5H2TM2FNZg.png" /></figure><p><strong>What is the best balancing strategy for moderately (5%) imbalanced data?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*a0VPAKeHXD8Z_6dKKrwX1g.png" /></figure><p><strong>What is the best balancing strategy for severely (0.1%) imbalanced data?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*HmLxhTaiJUtxDt8ngMmfbw.png" /></figure><p><strong>What is the best combination of base classifier and balancing strategy?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*oD5PQDSTupWYmHM_d2NL-w.png" /></figure><p><strong>What is the best base classifier when not using as balancing strategy?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*n1G4w4Z8KrM6IKuIxXbcoQ.png" /></figure><h3>Conclusion</h3><p>The first conclusion will probably be no surprise for most of us. The XGB classifier is a very strong and stable classifier, which performs better than the other classifiers in most use cases.</p><p>The next conclusion surprised us a lot more. We never expected that balancing data isn’t even necessary in most cases, let alone that it is even less necessary if your data is severely imbalanced.</p><p>The last conclusion is the fact that the best balancing strategy strongly depends on the metric chosen to evaluate the model performance. Which would mean that we should base our balancing strategy on the metric we think is the best to use in a given use case. Unfortunately, this is never an easy decision to make, as it depends on a lot of factors.</p><p>These are the guidelines given in the papers conclusion about this:</p><ul><li>If the user is using AUC as the metric of quality then baseline or class weight strategies are likely the best alternatives (regardless if the imbalance is moderate (5%) or severe (0.1%). If the practitioner has control over which base classifier to use, then one should opt for a gradient boosting or a random forest.</li><li>If one is using accuracy as metric then baseline or class weight are the best strategies and the best classifier is gradient boosting.</li><li>If one is using f-measure as metric then SMOTE is a good strategy for any imbalance rate and the best classifier is gradient boosting.</li><li>If one is using G-mean as metric then Underbagging is the best strategy for any imbalance rate and the best classifiers are random forest and gradient boosting.</li><li>If one is using Matthew’s correlation coefficient as metric then almost all strategies perform equally well in general, but SMOTE seems to perform better for less imbalanced data and the best classifier is gradient boosting.</li><li>If one is using the balanced accuracy as metric then Underbagging is the best strategy for any imbalance rate and best classifier are random forest and gradient boosting.</li></ul><h3>How do we use this in our day-to-day work</h3><p>You might wonder, did this settle all our discussions for once and for all? To be honest, not really, since we just love to debate and question every decision we make. That is how we make sure we keep growing and learning. But it did help us a lot in our daily work.</p><p>The biggest insight for most of us was that balancing the data is often not even necessary, and the most counterintuitive is that this is even more the case for severely imbalanced datasets.</p><p>The biggest change for me actually had nothing to do with choosing the right balancing strategy, but with more deliberately picking a metric (or a couple of metrics) when evaluating a model. When it comes to picking a balancing strategy my own preferred way of working is still to simply try a couple of balancing strategies and evaluating all of the resulting models coming from this. Maybe some of you are horrified by this, but it works for me.</p><p>What is your prefered way of working when it comes to choosing a metric and/or choosing a balancing strategy? I’m always looking for people who can convince me to change my habits 😉</p><p><em>Originally published at </em><a href="https://www.theanalyticslab.nl/lets-get-balanced-a-simple-guide-on-how-to-deal-with-class-imbalance-in-your-binary-data/"><em>https://www.theanalyticslab.nl</em></a><em> on April 17, 2023.</em></p><p><em>Want to read more about the cool stuff we do at </em><a href="https://cmotions.nl/"><em>Cmotions</em></a><em> and </em><a href="https://www.theanalyticslab.nl/"><em>The Analytics Lab</em></a><em>? Check out our </em><a href="https://www.theanalyticslab.nl/blogs/"><em>blogs</em></a><em>, </em><a href="https://www.theanalyticslab.nl/projects/"><em>projects</em></a><em> and </em><a href="https://www.theanalyticslab.nl/videos/"><em>videos</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3ced8d78645" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/lets-get-balanced-a-simple-guide-on-how-to-deal-with-class-imbalance-in-your-binary-data-c3ced8d78645">Let’s get balanced! A simple guide on how to deal with class imbalance in your binary data</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is your Power BI report slow? Let’s fix that]]></title>
            <link>https://medium.com/cmotions/is-your-power-bi-report-slow-lets-fix-that-99627a62baf7?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/99627a62baf7</guid>
            <category><![CDATA[performance-analysis]]></category>
            <category><![CDATA[dax-studio]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[Coen van der Snoek]]></dc:creator>
            <pubDate>Mon, 08 May 2023 05:02:10 GMT</pubDate>
            <atom:updated>2023-05-08T05:02:48.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_cNQ_mZdON-9qv77.jpg" /></figure><p>In this blog I explain how you can improve the performance of your Power BI report. For a long time I was struggling with a bad performing report I used for a training. Now I finally found the solution I’m happy to share my insights with you.</p><p>So if your Power BI report is running slow or you want to avoid it to run slow, you probably should optimize your data model. This is usually where the most performance gains can be made. Reducing the memory of your model has a direct impact on the performance of your reports and dashboards. To find out which optimizations potentially have the most impact, you need information about the used memory in your data model. VertiPaq*1 analyzer is the tool to accomplish this. This tool is available on <a href="https://www.sqlbi.com/tools">sqlbi</a>. Personally I prefer the version which is integrated in <a href="https://www.sqlbi.com/tools/dax-studio/">DAX Studio</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*c7Yp-sb0tWsxQjwsh4-NwA.png" /></figure><p>In this blog I work with an example database called ‘Mrbean’. It holds data on customers and their orders for a fictive coffee retailer in the Netherlands.</p><p><strong>Perform an analysis</strong></p><p>Open your report in Power BI desktop. Then launch DAX Studio (from the external tools tab) to perform an analysis of the used memory in your data model.</p><p>Within DAX Studio select View Metrics (Advanced tab) to perform the analysis (you have to be connected to a model (Home tab &gt; Connect). The results will be discussed in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*1xrlzcpVmKfPEt1umT5zSQ.png" /></figure><p>It is also possible to generate a VPAX file in DAX Studio (use Export Metrics). This file has a very limited size and can be shared easily. Making it possible to do a (quick) analysis of a model of which you can’t access the PBIX file.</p><p><strong>Interpret the results</strong></p><p>Before you start investigating the results, first look at the <em>summary</em> tab. Here you’ll find the total in memory size of your model in MB. In the example the model is 160 MB, which is pretty large.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*b5oWi-37uyV2CBKDhG3sjA.png" /></figure><p>The <em>tables</em> tab provides an overview of the tables in the data model. The total size of each table is displayed. As well as how much a table is taking up as percentage of the total size of all tables. In this example the Orders table accounts for 95% of the total size. By expanding the view of the Orders table it becomes clear the orders_ID column is the primary cause. This is also shown on the <em>columns </em>tab, which gives an overview of the most expensive columns in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-9o0qFWxvHZKgNVu.png" /></figure><p><strong>Performance optimalisation steps</strong></p><p>Based on the results of the analysis I took the following 5 steps to optimize the model.</p><ol><li><strong>Disable auto date/time</strong></li></ol><p>If the table overview shows tables starting with LocalDateTable auto date/time is enabled. Meaning Power BI generates hidden calculated tables for each date column in your model. These tables increase the model size. Therefore it is better to create your own date table and disable this file setting. In this example this saves only 4 MB (2,5%), but the impact can be much bigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*51mZVr7qBHxb523_S1NAlg.png" /></figure><p><strong>2. Choose the right datatype for a column</strong></p><p>Vertipaq is datatype independent. Therefore it doesn’t matter if a column has a text, bigint or float data type.Vertipaqneeds to create a dictionary for each of those columns. The size of this dictionary determines the performance, both in terms of speed and memory space allocated.</p><p>Since the orders_id column has the largest share in the size of the model this is the place to start optimizing. It is a string column with many distinct values. This means low compression. Vertipaq uses the hash algorithm * 2to store the data. Resulting in a large dictionary size (106 MB). This is being referred to as a high cardinality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*xprhUHSnFmCYQ9aPsuoPWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*zFkb4CNBMFpEjHi0.png" /></figure><p>With an integer datatype value encoding may be enabled. This is why I converted the orders_ID column to an integer. I replaced the store (S) and webshop (W) indicator in the orders_ID with a number. Unfortunately what I expected did not happen. There was no change in dictionary size. Hash encoding is still applied to compress the column, because the orders_ID values fluctuate significantly within the range (81.000 to 9.999.990).</p><p>To overcome this problem I created an index column based on the orders_ID. This change was made in the data source. Now the number range is smaller (1 to 3.252.459) and the numbers linearly increase. Making VertiPaq assume that it is a primary key and choose value encoding. This has a major impact on the size of the data model. The dictionary of 106 MB disappears and the hierarchy size decreased tremendously (13 MB). Resulting in a way smaller model size of 45 MB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*-Qw1BZtDg5yhACVn5bzX0g.png" /></figure><p>Enabeling the right encoding is also applicable for other columns. The customers_ID column in the Orders table also consumes a considerable amount of memory. This is an integer column stored as text. After changing the datatype value encoding is enabled. However, because the customers_ID has a lot of digits the size to store the data remains high. Replacing the customers_ID column with an index column in the Orders and Customers table in the data source solves this problem. Saving another 3 MB in model size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9915QvdJnXpqiH-5nybObw.png" /></figure><p><strong>3. Selecting the appropriate decimal features</strong></p><p>If your decimal numbers have a precision of four or fewer decimals it is recommended to use the fixed decimal number data type. This data type is internally stored as an integer and therefore can be stored more efficiently. Applying this to several columns (i.e. wholesale price, consumer price, margin and discount) saved 1 MB in the data model.</p><p><strong>4. Remove unnecessary columns</strong></p><p>A logical step in optimizing your data model is to remove the columns you don’t need. Especially the ones with a high column size. Don’t let the thought that you potentially might need a column later stop you. If you remove a column in the Power Query editor you can always undo this later. In this example birthday is not needed, because there is also an age column available. For the geographical analysis the customers region is needed, so latitude, longitude and city are not needed. Finally customer type can be removed from the orders table, because it is a customer property already available in the customers table. Bringing the total model size to 40 MB.</p><p><strong>5. Set available in MDX to false</strong></p><p>Another way to optimize your model is by looking at the size of the automatically generated hierarchy of a column (used by MDX). These hierarchies are used to improve the user experience in Excel and other client applications that use the MDX query language against tabular models and Power BI datasets. The size can be set to zero in <a href="https://www.sqlbi.com/tools/tabular-editor/">Tabular Editor</a> by changing the option <em>available in MDX</em> to false. After applying this option to the columns with the largest hierarchy size (orders_ID and customers_ID), the model size decreased to 28 MB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/0*r8ImidWMi8ijFIvC.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*tZNrYCLSkIRhKBK9.png" /></figure><p>Within Tabular Editor select a column an go to the options menu on the right, here you can set Available In MDX to False</p><p><strong>The result</strong></p><p>The 5 performed optimization steps resulted in a saving of <strong>82,5%</strong>. The performance problems I often faced during my trainings with this dataset now disappeared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*zBVnrSwsCBq-JnC0GNtNTg.png" /></figure><p><strong>Learnings when working on this article</strong></p><ul><li>After performing optimization steps in Power Query editor you have to close and re-open the PBI file in order to see the real size of the data model. Otherwise the string columns will default have an allocated size of 1MB. Making you think that your optimizations steps didn’t make the expected impact.</li><li>Sometimes all properties of a column seem to be fitted for value encoding, but Vertipaq still uses the hash algorithm. Changing the <em>encoding hint </em>setting in Tabular Editor to value may help to solve this problem. In order to be able to change this setting you’ve to select the <em>allow unsupported Power BI features (experimental) </em>option within preferences (in the file menu).</li><li>Sometimes encoding settings changed after I made changes to columns used in a relationship. Value encoding switched back to hash encoding bringing the dictionary size back to the model. When I created the relationships in the data model after performing all optimization steps this behavior didn’t occur.</li></ul><p><strong>Useful links</strong></p><p><a href="https://www.sqlbi.com/">https://www.sqlbi.com/</a><br><a href="https://www.alphabold.com/brain-muscles-of-powerbi/">https://www.alphabold.com/brain-muscles-of-powerbi/</a><br><a href="https://towardsdatascience.com/how-to-reduce-your-power-bi-model-size-by-90-76d7c4377f2d">https://towardsdatascience.com/how-to-reduce-your-power-bi-model-size-by-90-76d7c4377f2d</a></p><p><em>Originally published at </em><a href="https://www.theanalyticslab.nl/is-your-power-bi-report-slow-lets-fix-that/"><em>https://www.theanalyticslab.nl</em></a><em> on October 31, 2022.</em></p><p><em>Want to read more about the cool stuff we do at </em><a href="https://cmotions.nl/"><em>Cmotions</em></a><em> and </em><a href="https://www.theanalyticslab.nl/"><em>The Analytics Lab</em></a><em>? Check out our </em><a href="https://www.theanalyticslab.nl/blogs/"><em>blogs</em></a><em>, </em><a href="https://www.theanalyticslab.nl/projects/"><em>projects</em></a><em> and </em><a href="https://www.theanalyticslab.nl/videos/"><em>videos</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99627a62baf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/is-your-power-bi-report-slow-lets-fix-that-99627a62baf7">Is your Power BI report slow? Let’s fix that</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find your “high risk files” according to GDPR using our DriveScanner]]></title>
            <link>https://medium.com/cmotions/find-your-high-risk-files-according-to-gdpr-using-our-drivescanner-5944a36ae541?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/5944a36ae541</guid>
            <category><![CDATA[python-packages]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[gdpr]]></category>
            <dc:creator><![CDATA[Jeanine Schoonemann]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 12:14:40 GMT</pubDate>
            <atom:updated>2023-04-18T12:14:40.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*Rdy0r8ZcodrO6D6n0ODjDQ.png" /></figure><p>In every company it’s a struggle to make sure we only keep the documents we want and need in the future, to minimize our total amount of files, but even more important, to make sure we’re not violating any GDPR legislation. Not only important for our Privacy Officer, but for all of us of course.</p><h3>GDPR, we love (to hate) it</h3><p>We just have to comply with the rules, sounds simple enough! But what sounds simple might be more complicated in practice. The daily hustle and bustle occupies our minds and might make us forget to clean up after a project is done. And isn’t GDPR sometimes just inconvenient too… We just need to share that resume and we need to do it now! And yes, there might be some contact information in that Excel file, but you will remove that as soon as you do not need it anymore, right?</p><p>Right… Wrong! Well, at least sometimes. We are all human, which means our actions are not always in line with our intentions. Which doesn’t mean we are willingly violating the GDPR legislation, but it also doesn’t mean this doesn’t happen at all.</p><p>Your Privacy Officer may be aware of this and is trying to encourage all users to clean up: check your downloads folder, delete stored attachments, empty your trash, clean up the project folder at the end of the project. But that doesn’t mean an extra check wouldn’t be an excellent idea.</p><h3>Excuse me, how many?!</h3><p>At Cmotions, we knew we might be at risk, simply due to the sheer number of files on our filesystem. Even while we are only keeping our own project files and don’t store data of our customers anywhere on our own filesystem. That’s why our Privacy Officer tried to come up with rules to eliminate GDPR sensitive files as much as possible. To the other employees, it felt these rules were not doing what they were meant to be doing and we, as data professionals, were convinced we should be able to do better. This is when we first came up with the idea to create a Python package to do these checks for us. The idea of this package was to make work a lot easier and to solve all our aforementioned problems. With just a few clicks you should be able to see a list of files you would need to check on GDPR sensitive information. Preferably, you should also be able to see which GDPR rule was violated and how.</p><p>With this in mind, we started building our Python package ‘DriveScanner’, and now we’re proud to be sharing <a href="https://dev.azure.com/Cmotions/Packages/_git/DriveScanner">our first version</a> with you. It might not be perfect yet, it’s work in progress, but what better way to improve than with the help of our community. <a href="https://dev.azure.com/Cmotions/Packages/_git/DriveScanner">Check out our code in our repository</a>, or simply start using our package by <a href="https://pypi.org/project/drivescanner/">pip installing it</a>: <em>pip install drivescanner.</em></p><h3>The birth of the DriveScanner</h3><p>So how has this package helped us? First, it gave us an insight into the number of different file types we have saved in our filesystem. A shocking 223,976 files! Assuming it would take you about 10 to 15 minutes to check each file and knowing we only have one Privacy Officer; we now knew for sure that it would be impossible for us to check all these files manually. So, by setting up the GDPR ruling that checks every file automatically, we provided an output in a table that contains the number of times a specific GDPR violation was made for a specific file. Currently the package scans for Dutch social security numbers, bank account information, email addresses, telephone numbers, addresses in general, credentials of any kind, credit card of passport numbers. It will also check for credential tags like login information. Optionally the scan is also able to detect Named Entities in Dutch and other languages.</p><p>Based on the scan result, files are given a score based on the severity of the violation. With these scores our Privacy Officer was able to filter files based on a specific violation or on an overall score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*Rdy0r8ZcodrO6D6n0ODjDQ.png" /></figure><h3>How we used our own DriveScanner</h3><p>So, now what? Knowing which files contained sensitive information, it might still cost a lot of time to see where and what kind of violation was made. This is why we also added the sort of violation to the output table. This way, our Privacy Officer did not only know which file to look at but also which violation. Within only a few clicks, and some waiting time, we were able to scan 223.976 files on GDPR violations. Not only did this help us to clear some files of some sensitive information but it also saved us a lot of time. For example, it identified that 90% of the files on our Drive don’t need any human assessment. Of the 10% that did, we started with the Excel output and this way we could disregard another 7% of the files. Leaving us with 3% that needed to be opened and assessed. Still a substantial number of files, but a lot less than what we started with.</p><p>And you might wonder, were all these files a harm at all? Luckily, not at all! We mostly found some points of improvement for the Drivescanner itself. Although some of the examples were correct from the DriveScanner point of view, like:</p><ol><li>A file created by our DataSampler, containing fictional personal information like telephone numbers, addresses and email addresses;</li><li>A project file where we had multiple external stakeholders, where the name, telephone number and email address of all reviewers were stated in the document</li></ol><h3>What’s next? Will you be there with us?</h3><p>So, it seems our assumptions were right. And why keep something so simple and powerful to ourselves? That is why we would like to share this with you. <a href="https://dev.azure.com/Cmotions/Packages/_git/DriveScanner">Have a look at our repo</a>, <a href="https://pypi.org/project/drivescanner/">pip install our package</a>, see how it works and help us improve!</p><p>And yes, we are aware that our package definitely has a lot of points to improve on :)</p><p><em>Originally published at </em><a href="https://cmotions.nl/en/find-your-high-risk-files-according-to-gdpr-using-our-drivescanner/"><em>https://cmotions.nl</em></a><em> on April 17, 2023.</em></p><p><em>Want to read more about the cool stuff we do at </em><a href="https://cmotions.nl/"><em>Cmotions</em></a><em> and </em><a href="https://www.theanalyticslab.nl/"><em>The Analytics Lab</em></a><em>? Check out our </em><a href="https://www.theanalyticslab.nl/blogs/"><em>blogs</em></a><em>, </em><a href="https://www.theanalyticslab.nl/projects/"><em>projects</em></a><em> and </em><a href="https://www.theanalyticslab.nl/videos/"><em>videos</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5944a36ae541" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/find-your-high-risk-files-according-to-gdpr-using-our-drivescanner-5944a36ae541">Find your “high risk files” according to GDPR using our DriveScanner</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Opening the Black Box of Machine Learning Models: SHAP vs LIME for Model Explanation]]></title>
            <link>https://medium.com/cmotions/opening-the-black-box-of-machine-learning-models-shap-vs-lime-for-model-explanation-d7bf545ce15f?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/d7bf545ce15f</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Thomas ten Heuvel]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 09:49:42 GMT</pubDate>
            <atom:updated>2023-03-21T09:49:42.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*SKUbyVmAA5rlhzPxJkS8pw.jpeg" /></figure><p>In recent years, the use of machine learning models within organizations has become more and more common. With applications such as customer churn prediction, fraud detection or predicting response to a marketing campaign, predictive models have proven to be a powerful tool within many businesses domains. Predictive models create value by allowing businesses to respond and adapt quickly to insights from data. The more accurate predictive models get, the better they can be used to optimize processes thus the more value they create.</p><p>Hence, many data scientist seek for the model with the highest accuracy, which are often complex, non-linear models such as XGBoost or Random Forest. While these models are very powerful, they also come with a significant disadvantage: due to their complexity, it is often difficult to find out why a certain prediction was made and how variables contributed to the decision. This is problematic because it is important for organizations to use data science methods in a responsible and ethical manner. Especially in sensitive cases with personal data involved, organizations need to be able to demonstrate that their models and processes are justifiable and not discriminating. This includes having an open and transparent decision making process, avoiding the so-called black box model. The second reason why we want to avoid black box models, is that explanations of predictions provide valuable insights. For example in churn prediction, it is not only valuable to have an accurate prediction of whether a customer is likely to leave, but also to know how the variables are related to churn. In short, opening the black box provides both transparency and actionable insights that organizations can benefit from.</p><p>Two well-known methods for explaining tree-based models such as RandomForest and XGBoost are SHAP and LIME. In this article, we will demonstrate how these work and how they can be used to open the black box of machine learning models. The following section will elaborate on the difference between global and local interpretability, followed by a short theoretical description of SHAP and LIME. We then train a RandomForest model and demonstrate how SHAP and LIME can be used for model explanation and compare the two methods. The focus of this article will be on the practical implementation of the two methods, so I will refer to other articles for more theoretical background.</p><h3>Global vs. Local Interpretability</h3><p>Before we start, it is important to distinguish between global and local interpretability. Global interpretability refers to insights in how predictor variables generally contribute to the target variable, either positive or negative. It allows us to get a sense of the importance or relevance of the predictors in our model, and how they relate to the target variable.</p><p>In contrast, local interpretability refers to insights in why an individual case received its prediction and how predictor variables contributed to the prediction. This is especially useful in models like RandomForest and XGBoost, because in these kind of models the contribution of variables to the prediction can vary per individual case.</p><h3>SHAP</h3><p>SHAP (SHapley Additive exPlanations) is a game theoretic approach to explaining machine learning models. It is based upon Shapley values, that quantify the contribution that each feature brings to the outcome of the model. Every prediction starts with the expected value (or average prediction) as the base value, and the SHAP value of each feature tells us how that feature contributes to the actual predicted probability relative to the base value. Hence, the final prediction is the sum of the average prediction and all the SHAP values.</p><p>In the first place, SHAP is a method for local interpretation of the model, because SHAP values quantify the contribution of each feature to a single prediction case. However, SHAP can also be used for global interpretation, where the SHAP values of multiple prediction cases are combined or aggregated to get a sense of the more general contribution of the features to the outcome. If you want to know more about how SHAP values are actually computed, I recommend you to read <a href="https://towardsdatascience.com/shap-explained-the-way-i-wish-someone-explained-it-to-me-ab81cc69ef30">this</a> article.</p><h3>LIME</h3><p>Another popular method for explaining machine learning models is LIME, which builds upon four basic principles:</p><ul><li><strong>L</strong>ocal: The explanation must be locally faithful, i.e. it must correspond to how the model behaves in vicinity of the instance being predicted.</li><li><strong>I</strong>nterpretable: Provide a qualitative understanding between the input variables and the output. The best way is to use a linear model with few variables.</li><li><strong>M</strong>odel-Agnostic: You can apply any model — i.e. Deep Learning Model, Regression, XGBoost, etc.- and it will always work. This also holds for future models.</li><li><strong>E</strong>xplanation: Explains predictions on the individual level.</li></ul><p>LIME works by fitting a so-called local surrogate model that approximates the predictions of the underlying black box model. In contrast to SHAP, LIME can only be used for local interpretation, because the locally fitted surrogate model only applies in proximity of the data point being explained.</p><p>In the following section, we will prepare our dataset and fit a model, followed by a demonstration how SHAP and LIME can be used to explain the model. We will demonstrate the different functions and features of the SHAP and LIME package and compare them.</p><h3>Preparing some data</h3><p>Imagine you are working for a telecom company and you are responsible for the collection of subscription payments. In this role, it is your job to minimize defaults by customers. You decide to use customer data to train a model that can be used to predict whether someone is likely to be a defaulter or not. The model can then be used to recognize defaults in an early stage so that measures can be taken to minimize payment arrears. We are working with a dataset that contains information on mobile phone subscriptions, including an indicator for whether that subscription is defaulted. After training a model that predicts defaults, we are going to use SHAP and LIME to explain the model and explore how our predictor variables relate to our target variable.</p><pre>#Firstly, we install the required packages:<br><br>!pip install SHAP<br>!pip install lime<br>!pip install Pillow==9.0.0 # The newest version results in plotting issues.</pre><pre>import pandas as pd<br><br># In 90% of the cases, subscr_default has the same value as ind_debt_collector.<br>print(&#39;Proportion of cases where subscr_default == ind_debt_collector:&#39;, (df.subscr_default == df.ind_debt_collector).mean())<br><br># We therefore drop the indicator for debt collector.<br>df = df.drop(&#39;ind_debt_collector&#39;, axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZngsb3OXjxPElPbyQ2DPw.png" /></figure><p>We have loaded and prepared a dataset in the variable df that describes whether a subscription is defaulted or not. We can preview the data using df.head():</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uw8kwoTVNk1j5T-JIZlSJw.png" /></figure><p>Our dataset contains information on mobile phone subscriptions, and the column subscr_default indicates whether that subscription is defaulted. Therefore, subscr_default is our target variable that we are going to predict. Our predictor variables contain information on the subscriptions, such as the monthly amount of the subscription, the price of the mobile phone, and the average minutes of calls per week. We will first train a model in order to predict default, and then we will demonstrate how SHAP and LIME can be used to explain the predictions of the model. Please note that since we want to explain SHAP and LIME, we need a trained model, but the focus of this article is not on how to train a prediction model. If you want to learn more about how to train a predictive model in python, I recommend you to read our series <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-introducing-our-data-science-rock-stars/">&#39;No Data Scientist is the Same&#39;</a>. In this series, we go into detail on how different types of data scientists build predictive models.</p><h3>Training the model</h3><p>In the code below, we first separate our target variable from our predictor variables, followed by a train/test split in order to be able to validate our model performance. We then train a Random Forest model and assess it’s performance on test dataset.</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score<br>from sklearn.metrics import classification_report<br>from sklearn.metrics import plot_roc_curve<br><br># Specifying our target variable:<br>target = &#39;subscr_default&#39;<br><br># Seperating our target variable from our features:<br>y = df[target]<br>X = df.drop(target, axis = 1)<br><br># Splitting the dataset into a 70% train and 30% test <br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 17)<br><br># Initialize and fit the model:<br>rf = RandomForestClassifier(max_depth=10).fit(X_train, y_train)<br><br># Predict: <br>y_pred_rf = rf.predict(X_test)<br>y_pred_rf_train = rf.predict(X_train)<br><br>#Evaluate<br>print(&quot;Accuracy train set:&quot;, accuracy_score(y_train, y_pred_rf_train))<br>print(&quot;Accuracy test set:&quot;, accuracy_score(y_test, y_pred_rf))<br><br>cr = classification_report(y_test, y_pred_rf)<br>print(cr)<br><br>plot_roc_curve(rf, X_test, y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27cAUYbUfIR0f_3u2GlXVQ.png" /></figure><h3>Global model interpretation</h3><p>Not bad, our model a has fairly decent predictive value with an AUC of 0.87. Now it’s time for some interpretation of our model! We start off with interpreting our model on the global level, so we can get an idea of the general relations between variables in the model. Scikit-learn has built in the attribute feature_importances_ to get a first idea of what features are important in the model. We can access the feature importances by using rf.feature_importances_, and we create a dataframe to store the feature importance values and their corresponding feature names:</p><pre>df_fi = pd.DataFrame()<br>df_fi[&#39;feature&#39;] = X.columns<br>df_fi[&#39;importance&#39;] = rf.feature_importances_<br><br>df_fi.sort_values(&#39;importance&#39;, ascending=False).head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ollruJrUPWPEcSYYyf79kA.png" /></figure><h3>SHAP for global interpretation</h3><p>Great! We now know that the <em>average minutes of calls per week</em> is the most important feature in our model, followed by the <em>monthly subscription price</em> and <em>number of visits to the online portal (MyCall)</em>. However, this only tells us that these features are important for predicting defaults, but not <strong>how</strong> these features are related to defaults. In other words, we don’t know whether a high number of avg_min_call_wk in general contributes <em>positively</em> or <em>negatively</em> to our prediction. This is what we can use SHAP for!</p><p>The SHAP package computes SHAP values by iteratively giving input to the prediction model, while leaving a different feature out every iteration. By doing so, it can quantify the contribution that each feature brings to the prediction. Please note that SHAP values for a prediction only apply to that specific prediction, and other predictions are likely to have different SHAP values. So because we want to start off with globally interpreting our model, we want to compute SHAP values for more than one data point. In the code below, we take a subsample of 5000 data points. We initialize a SHAP-explainer for our random forest model by using shap.TreeExplainer(rf), and we use the .shap_values() method to compute the SHAP values for our subsample of data points:</p><pre>import shap<br>from shap import TreeExplainer<br><br>X_train_sample = X_train.sample(5000, random_state=17) # Take a sample because calculating SHAP values for the entire dataset would take way too much time.<br><br>explainer = shap.TreeExplainer(rf)<br>shap_values = explainer.shap_values(X_train_sample)</pre><pre>print(f&quot;length of shap_values: {len(shap_values)} \n&quot;)<br>print(f&quot;shape of elements within shap_values: {[i.shape for i in shap_values]} \n&quot;)<br><br>shap_values[0][1]#class0<br>shap_values[1][1] # class 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iYBIzftXs_MEZY63yHHgzw.png" /></figure><p>explainer.shap_values() returns a list of length 2, where each element is a matrix of SHAP values with size n_samples x n_features. The length of this list is 2, because the predict_proba method of our RandomForest model returns an array of length two, holding the predicted probabilities for each of the classes. As a result, we also get separate SHAP values for each of the classes: shap_values[0] holds the SHAP values that quantify the contribution of features for predicting class 0 (no defaulter) and shap_values[1] holds the SHAP values that quantify the contribution of features towards predicting class 1 (defaulter). Note in the output above that these have the exact same magnitude, but in the opposite direction (negative gets positive and vice versa).</p><p>In our case, we want to explain how variables contribute to predicting if someone is a defaulter, which is class 1. We therefore use shap_values[1] as the values to visualize. We can do so by using the shap.summary_plot() function:</p><pre>from matplotlib import pyplot as plt<br><br>f = plt.figure()<br>shap.summary_plot(shap_values[1], X_train_sample, plot_type=&#39;dot&#39;, show=False, plot_size=[16,8])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIGPjYs2eNmZUYuaAoNgNg.png" /></figure><p>The dots in the plot above visualize the SHAP values for the 5000 records in our subsample. The color of a dot represents the feature value for the specific data point, and the position on the x-axis displays the corresponding SHAP value. A high SHAP value indicates a higher (positive) predicted probability by the model, whereas a lower (negative) SHAP value contributes negatively to the predicted probability by the model. If we look at the avg_min_call_wk feature of the model, we see that generally, high values for the average minutes of calls per week correspond with high SHAP values and thus, a higher probability of someone being a defaulter. Conversely, high value for the number of visits to the online portal (MyCall) generally indicates a lower probabilty of someone being a defaulter. Similar to sklearn&#39;s feature_importance_ attribute, the higher a feature appears in the summary plot, the more important or relevant the feature is in the model. The advantage of the SHAP summary plot is that we not only can see what the important features in our model are, but also how (positive or negative) feature values relate to the prediction.</p><p>In the summary plot above, color is used to represent the value of the features, and position on the x-axis is used to represent the SHAP values. This allows us to get a general idea of the relation between feature values and SHAP values, but if we want to zoom in on a feature and have a more detailed insight, SHAP offers the dependence_plot to explain the relation between individual features and the target variable. For instance, the dependence_plot below shows that when the monthly subscription amount exceeds 30, the probability to the subscription being defaulted increases significantly.</p><pre>shap.dependence_plot(X_train_sample.columns.get_indexer([&#39;monthly_subscr_amount&#39;]), shap_values[1], X_train_sample, interaction_index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sR_tuoILAkH04BwdGYVUEg.png" /></figure><p>Although we now have a general idea of how our features contribute to the model predictions, we still have no insight into the individual predictions. If we want to know how all features together result in the final prediction, we are locally interpreting our model. Luckily SHAP also offers methods for explaining individual predictions!</p><h3>Explain individual predictions</h3><p>Let’s say that now that we have a general idea of the relation between our features and target variable, we decide to take our model into production and send all customers with a predicted probability above 0.8 an extra reminder to pay for their subscription. After sending the payment reminders, a customer, Jimmy, calls and asks why he has received a reminder while his friend Jack hasn’t. In order for an organization to comply with GDPR, you are obligated to provide a customer’s data when requested. In this case, you are requested to provide the data on the basis of which the customer received the payment reminder.</p><p>We can use the shap.force_plot() function to see how features contributed to the individual prediction for this person:</p><pre>shap.initjs()<br><br>j = 49 # index of person with high probability (&gt;0.8)<br><br>explainer = shap.TreeExplainer(rf)<br>shap.force_plot(explainer.expected_value[1], # Note that we use the expected value of class [1] (defaulter) as a base value<br>                shap_values[1][j, :], # So we also want the SHAP vaues for class [1]<br>                X_train_sample.iloc[j, :], <br>                matplotlib=True,<br>                text_rotation=20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZCD6KMNey9DS_wh2teSYw.png" /></figure><pre>import numpy as np<br><br>expected_value = y_train.astype(np.float32).mean()<br><br>print(&#39;Proportion of samples with class 1 in training dataset: &#39; + str(expected_value))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDDQz6zF0kuA72Swanw-EA.png" /></figure><p>The plot above explains why a probability of 0.81 was assigned to Jimmy. Note that the base value represents the expected value of our model, which is the proportion of samples with class 1 in our training dataset. In other words, this is the probability that a random person in our training dataset is a defaulter. Based on the information that we have about Jimmy, the probability increases towards 0.81. The features in red are the features that contributed most positively to the predicted probabilty, while the features in blue contributed negatively to the probability. We can see that the fact that Jimmy has been in contact with our company (ind_customercontact_lastmonth) has a strong positive effect on the predicted value. This aligns what what we would expect according to the summary plot that we saw earlier, where all the red dots (ind_customercontact_lastmonth = 1) have positive SHAP-values. Furthermore, Jimmy calls on average 250 minutes per week, and avg_min_call_wk appears in red, which indicates that this is also one of the reasons that Jimmy&#39;s subscription was predicted to be defaulted.</p><p>Although the force plot reveals the positive or negative contribution of feature values to the prediction, we do not see how much probability is added to the baseline value for each feature value. A way to visualise this, is by using the waterfall plot. For this plot, we first need to generate another type of explainer and differently prepared shap values. As the run time shows, this method is quite expensive and therefore slow. However, it provides a nice breakdown of how the variables contributed to the final predicted probability. Note that we are still looking at the same customer, Jimmy.</p><pre>import shap<br>explainer = shap.Explainer(rf, X_train_sample)<br>shap_values = explainer(X_train_sample,check_additivity=False)<br>shap.plots.waterfall(shap_values[:,:,1][j, :],max_display=20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*90Tv3RKI-H1Eq0SJqAJptQ.png" /></figure><h3>LIME</h3><p>Another method for explaining model predictions is LIME. Unlike SHAP, LIME does not support functionality for global interpretation. But we can use LIME to interpret individual predictions locally, like we just did with SHAP. We can instantiate a LIME explainer by calling lime_tabular.LimeTabularExplainer():</p><pre>import numpy as np<br>import lime<br>from lime import lime_tabular<br><br>explainer = lime_tabular.LimeTabularExplainer(<br>    training_data=np.array(X_train_sample.astype(&#39;int&#39;)),<br>    feature_names=X_train_sample.columns,<br>    class_names=[&#39;0&#39;, &#39;1&#39;],<br>    mode=&#39;classification&#39;<br>)</pre><p>Now let’s use LIME to explain the same data point that we just explained with SHAP and compare the differences:</p><pre>exp = explainer.explain_instance(<br>    data_row=X_train_sample.astype(&#39;int&#39;).iloc[j], <br>    predict_fn=rf.predict_proba<br>)<br><br># exp.show_in_notebook(show_table=True) # Does not work in databricks<br><br>exp_html = exp.as_html()<br>displayHTML(exp_html) # good fix</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8B_lkvB7NXar2FII7MJsA.png" /></figure><p>Note that features are vertically sorted based on their importance for this specific prediction. In agreement with the SHAP explainer, ind_customercontact_lastmonth and avg_min_call_wk are the features that have the strongest positive effect on the predicted probability. However, for the features that contributed negatively to the probability, we see some differences between the two methods. For example, the negative effect of ind_payment_arrears seems to be more important according to LIME than it seems according to SHAP waterfall plot. The slight differences between the two methods are caused by the fact that SHAP and LIME work in a different way: SHAP iteratively removes features from predictions to evaluate the effect of that feature on the prediction. Conversely, LIME fits a local surrogate model, that only applies in vicinity of the data point being explained. Therefore, it seems that in vicinity to the data point of Jimmy, ind_payment_arrears has a stronger negative effect on the prediction compared to what SHAP would suggest. However, in general both methods suggest similar contributions of features, so I would not care too much about these differences.</p><h3>SHAP versus LIME: the verdict</h3><p>We have now seen how SHAP and LIME can be used to open the black box of ML-models. At first sight, SHAP seems more versatile: it offers methods for both local and global interpretation of models, and there are multiple options with regard to visualization. In contrast, LIME only offers a method for local interpretation of models, and is more restricted in terms of visualization. So why would we ever use LIME? Well, if we look at the running time for SHAP, computing the SHAP values for a subset of only 5000 samples already took 3 minutes. Furthermore, if we look at the computation time for the SHAP waterfall plot, we see that it takes a very long time for the algorithm to compute the values that indicate the contribution of each variable to the output. Conversely, a similar plot in LIME computes much faster. Therefore, it can be a good practice to choose SHAP over LIME when you want to explain your model on a global level, or when you only want to explain a few specific predictions. In situations where you want to explain large volumes of predictions and SHAP gets too slow, LIME can be a nice alternative!</p><p>Want to read more about the cool stuff we do at <a href="https://cmotions.nl/">Cmotions </a>and <a href="https://www.theanalyticslab.nl/">The Analytics Lab</a>? Check out our <a href="https://www.theanalyticslab.nl/blogs/">blogs</a>, <a href="https://www.theanalyticslab.nl/projects/">projects </a>and <a href="https://www.theanalyticslab.nl/videos/">videos</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7bf545ce15f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/opening-the-black-box-of-machine-learning-models-shap-vs-lime-for-model-explanation-d7bf545ce15f">Opening the Black Box of Machine Learning Models: SHAP vs LIME for Model Explanation</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Equal Opportunities in AI: an Example]]></title>
            <link>https://medium.com/cmotions/equal-opportunities-in-ai-an-example-54e6505f43ed?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/54e6505f43ed</guid>
            <category><![CDATA[equality]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ethics]]></category>
            <category><![CDATA[ethics-in-tech]]></category>
            <category><![CDATA[fairlearn]]></category>
            <dc:creator><![CDATA[Matthijs Otten]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 08:34:59 GMT</pubDate>
            <atom:updated>2023-03-21T08:34:59.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jHn-PMHfZIvv88dX.jpg" /></figure><h3>Using Fairlearn to investigate whether a recidivism model distributes equal opportunities to different societal groups</h3><p>In the past decades, human kind has been profiting from the assistance of Artificial Intelligence (AI) models in many areas. AI should be, and often is, helping us to make better informed decisions to support a healthy, just and thriving society. These models can be used in trivial matters like showing a marketing banner on a website, but can also pop up in scenarios with a risk of serious harm. For example, when deciding which patients could safely leave the hospital, what businesses should not get a loan from the bank or which suspects might be deemed dangerous by the judicial authorities.</p><p>For clarity, we understand that space must be created on Intensive Care Units, banks should get return on investment and crimes have to be prevented. Nevertheless, today we address a serious concern: do people in all societal groups have an equal chance of getting <em>what they deserve</em> ? Does a sick 14 year old boy have the same chance of getting the hospital care he needs as a senior woman and has a female entrepreneur the same opportunity to receive a loan as a male entrepreneur with an equally promising business model?</p><p>Whenever such important decisions are being made based on data that has strong correlations with unknown sensitive information of people, even when not explicitly feeding this sensitive information like ethnicity to an AI model, it can implicitly withhold people belonging to certain societal groups from what they deserve. In other words, there might be no Equal Opportunity to be correctly assigned to the desirable class among people from different societal groups. In this blog we look at an example: building a model to predict whether someone will be a recidivist or not. We will work with the <a href="https://www.propublica.org/datastore/dataset/compas-recidivism-risk-score-data-and-analysis">COMPAS dataset</a> on criminals in the USA, which we enrich with data on whether they commit a new crime within 2 years or not, thereby becoming a recidivist. The desired outcome for a person here is to be predicted as staying innocent in the future. We will try to give actually innocent people from different ethnicities a ‘fair’ chance to be predicted as such.</p><p>A whole paper could be written on the definition of ‘fairness’ in AI models. For a classification challenge like we face, one could for example use the metric of Demographic Parity, implying that the fraction of predicted recidivists should be equal in all ethnic groups. Though this might seem ‘fair’ at first glance, it bypasses the fact that the fraction of recidivists is very unlikely to be equal in different societal groups. In our dataset for example, Hispanic criminals have more often repented and stopped committing crimes. An alternative could be to look for Equalized Odds, meaning the model should perform equally well among groups in predicting who are recidivists or not. However, one could argue that we want to catch criminals as good as we can, therefore reaching for a maximum performance in identifying these future criminals without correcting for potential racial inequality, not risking to accidentally deem someone as ‘safe’ in the name of equality. Therefore, we end up with a relaxed form of Equalized Odds, namely Equal Opportunity. This means that the average chance to correctly be predicted as innocent within every ethnic group must be equal.</p><p>Continue reading and find out how the <a href="https://fairlearn.org/">Fairlearn Python package</a> can help to make a prediction model more ‘fair’ in terms of giving Equal Opportunities to people from different societal groups.</p><h3>Import Python Packages</h3><p>We start by importing Pandas, Numpy and Seaborn to load and explore our data.</p><pre>import pandas as pd<br>import numpy as np<br>import seaborn as sns</pre><h3>Set random seed</h3><p>To make the results in this notebook that depend on random number generators reproducible, we set the random seed.</p><pre>seed = 42</pre><h3>Load and Explore Data</h3><p>We load a Pandas Dataframe that is constructed of the original COMPAS dataset and the Cox dataset on recidivism or not within 2 years. We have deduplicated double records and encoded text data (for example on ethnicity) into numerical variables.</p><pre>df = pd.read_pickle(&#39;230113_DataFrame_Fairlearn.pkl&#39;)</pre><p>We have 4667 entries, of which 1735 correspond to recidivists (37%). To fit a model for predicting ‘Recidivism’, we use the age, number of prior crimes, severity of the original charge two years ago, marital status and gender of the person.<br>Ethnicity is used to verify Equality of Opportunity among ethnic groups after fitting the model.<br>The dataset has 54% Afro-American, 31% Caucasian, 9% Hispanic and 6% other people.</p><p>In the table below, we see that the number of recidivists is a little unbalanced between groups. In this particular dataset for example, the proportion of Afro-Americans is higher in the group of recidivists than in the group of criminals that weren’t charged again within 2 years.</p><pre>round(df.groupby(&#39;Recidivism&#39;).mean().transpose(),2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*84lQvwuVXVE_G_5fttD61g.png" /></figure><p>We see a moderate correlation in this particular dataset of Prior_Crimes with both Recidivism and the Afro-American ethnicity. This yields the risk that when creating a model to predict Recidivism with Prior_Crimes, this Prior_Crimes could become a <a href="https://aiblindspot.media.mit.edu/discrimination_by_proxy.html">proxy</a> for Afro-American whereby an implicit relation arises between Ethnicity and Recidivism resulting in significantly different results for people from different ethnic groups. We shall see what this will imply for ‘fairness’.</p><pre>cor_col_order = [&#39;Prior_Crimes&#39;,&#39;Recidivism&#39;, &#39;Afro-Americans&#39;, &#39;Caucasian&#39;, &#39;Hispanic&#39;, &#39;Age&#39;, <br>                 &#39;Original_Charge_Scale&#39;,&#39;Married&#39;,&#39;Female&#39;]<br>dfcor = round(df[cor_col_order].corr(),1)<br>_ = sns.heatmap(dfcor,cmap=&#39;vlag&#39;,vmin=-0.3,vmax=0.3,annot=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*xMB9NFEU3a1guDodaN8LfA.png" /><figcaption>Correlations rounded to one decimal</figcaption></figure><h3>Split Train and Test Set</h3><p>We split the data in 5 batches of 20% to train the model (on 4 batches) and test predictive performance (1 batch) 5 times and therefore with cross-validation draw conclusions that are not based on only one random sampling of the data. To do so, we import the sklearn package.</p><pre>import sklearn as sk<br>from sklearn import model_selection<br>from sklearn.ensemble import RandomForestClassifier as RFC</pre><pre>from sklearn.model_selection import KFold<br>cv = KFold(n_splits = 5, random_state = seed, shuffle = True)<br>dff, dfv = model_selection.train_test_split(df,test_size=0.2,random_state = seed)</pre><h3>Select features</h3><p>We select known covariates to fit a baseline model for recidivism, note that we do not include ethnicity as a predictor.</p><pre>xcols = [&#39;Prior_Crimes&#39;,&#39;Married&#39;, &#39;Age&#39;, &#39;Original_Charge_Scale&#39;,&#39;Female&#39;]<br>ethnicities = [&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;]<br><br>dfx = df[xcols]<br>dfe = df[ethnicities]<br>dfy = df[&#39;Recidivism&#39;]</pre><h3>Fit Random Forest Model</h3><p>We choose to use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">Random Forest</a> as a relatively simple Machine Learning algorithm to create a predictive model between our covariates and Recidivism.</p><p>We use the cross-validation to prevent drawing a conclusion based on one random sample in the data.</p><p>We collect performance metrics, information about the predictive power of each covariate and fairness metrics.</p><p>To collect these fairness metrics, we import the fairlearn package and specifically the function MetricFrame.</p><pre>import fairlearn as fl<br>from fairlearn.metrics import MetricFrame as MF</pre><p>After running the following code, we will go over each of these results.</p><pre>model = RFC(n_estimators = 100, max_depth = 5, max_features = &#39;sqrt&#39;,random_state = seed)<br>dfperf = pd.DataFrame(index = [&#39;Accuracy&#39;,&#39;AUROC&#39;] ,columns = range(5))<br>dffi = pd.DataFrame(index = xcols,columns = range(5))<br>df_tnr = pd.DataFrame(index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;<br>                                            ,&#39;Other&#39;], columns=range(5))<br>df_tpr = pd.DataFrame(index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;<br>                                            ,&#39;Other&#39;], columns=range(5))<br><br>for i, (train, test) in enumerate(cv.split(df)):<br>    model.fit(dfx.iloc[train,:],dfy[train])<br>    yvpred = model.predict(dfx.iloc[test,:])<br>    dfperf.loc[&#39;Accuracy&#39;,i] = sk.metrics.accuracy_score(dfy[test],yvpred)<br>    dfperf.loc[&#39;AUROC&#39;,i] = sk.metrics.roc_auc_score(dfy[test],yvpred)<br>    dffi.iloc[:,i] =  (pd.DataFrame(data = model.feature_importances_,index=xcols,columns=[&#39;Feature Importance %&#39;]))<br>    tnr = MF(metrics=fl.metrics.true_negative_rate,y_true = dfy[test], y_pred = yvpred,sensitive_features=dfe.iloc[test,:])<br>    df_tnr.iloc[:,i] = pd.DataFrame(data=[tnr.overall,tnr.by_group[1][0][0],tnr.by_group[0][1][0],tnr.by_group[0][0][1],tnr.by_group[0][0][0]],index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;], columns=[&#39;TNR %&#39;])<br>    <br>    <br>    tpr = MF(metrics=fl.metrics.true_positive_rate,y_true = dfy[test], y_pred = yvpred,sensitive_features=dfe.iloc[test,:])<br>    df_tpr.iloc[:,i] = pd.DataFrame(data=[tpr.overall,tpr.by_group[1][0][0],tpr.by_group[0][1][0],tpr.by_group[0][0][1],tpr.by_group[0][0][0]],index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;], columns=[&#39;TPR %&#39;])<br>av_tpr = round(pd.DataFrame(data = df_tpr.mean(axis=1),index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;],columns=[&#39;TPR %&#39;])*100).astype(int)</pre><h3>Attain Performance</h3><p>The benchmark for accuracy is the fraction of the majority outcome.</p><pre>bench = max(1-df[&#39;Recidivism&#39;].mean(),df[&#39;Recidivism&#39;].mean())<br>print(f&#39;Benchmark:  {round(bench,2)} \n&#39;)</pre><pre>Benchmark: 0.63</pre><p>Accuracy (the fraction of correct predictions) is the first performance metric we look at. This baseline model has a mediocre performance with an accuracy of 0.67, slightly above benchmark.</p><pre>av_acc = dfperf.loc[&#39;Accuracy&#39;,:].mean()<br>print(f&#39;Accuracy: {round(av_acc,2)} (so {int(round(100*(av_acc - bench)))}%-point higher than benchmark)\n&#39;)</pre><pre>Accuracy: 0.67 (so 4%-point higher than benchmark)</pre><p>A more sophisticated performance metric for classification (recidivist or not) is the Area Under the Receiver Operating Curve (<a href="https://scikit-learn.org/stable/modules/model_evaluation.html#roc-metrics">AUC</a>). It is a combination of how well the model can classify the actual recidivists as such and how precise it is in not classifying the innocent people as recidivists. An AUC of 0.5 resembles a randomly guessing model. We only achieve an AUC of 0.63, which is mediocre. Of course we could optimize this model further by tuning the hyperparameters or to use feature engineering to add additional features. However, for the purpose of this tutorial notebook we focus on the fairness of the model instead of optimizing its performance.</p><pre>av_auroc = dfperf.loc[&#39;AUROC&#39;,:].mean()<br>print(f&#39;Area under the ROC: {round(av_auroc,2)} (Our {round(av_auroc,2)} is only slightly better than 0.5)&#39;)</pre><pre>Area under the ROC: 0.6 (Our 0.6 is only slightly better than 0.5)</pre><h3>How important is the contribution of each covariate to the model performance</h3><p>The number of prior crimes is by far the most important covariate in building the prediction model (58% average Feature Importance).</p><pre>fis = (pd.DataFrame(data = dffi.mean(axis=1),index=xcols,columns=[&#39;Feature Importance %&#39;])*100).astype(int)<br>fis.sort_values(&#39;Feature Importance %&#39;,ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*wndVFnTxfa-oHL1XSYC-ug.png" /></figure><h3>What is the chance innocent people are predicted as such (True Negative Rate)</h3><p>Many performance metrics exist and we focus on the True Negative Rate (TNR). In our case, this is the fraction of innocent people that is predicted as such. So, it is the statistical equivalent of opportunity level of getting the desired outcome in each group.</p><p>Innocent Afro-Americans in our dataset have an 84% chance of being predicted as such, but this is 6% higher for Caucasians (90%) and 8% for Hispanics (92%).</p><p>Although these percentages are all quite high, they also imply that an innocent Afro-American has a 16% chance to be predicted as a recidivist, which is twice as large as for Hispanics (8%). Arguably, this is ‘unfair’, as this 16% is innocent.</p><pre>av_tnr = round(pd.DataFrame(data = df_tnr.mean(axis=1),index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;],columns=[&#39;TNR %&#39;])*100).astype(int)<br>av_tnr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*1JaFRzlWr4OEOSIKK4NkmQ.png" /></figure><h3>Give innocent people Equality of Opportunity to be predicted as such</h3><p>From the fairlearn package, we import the mitigator ExponentiatedGradient and equality constraint FalsePositiveRateParity for optimizing the model to equalize among groups the chance for innocent people to be regarded as such. In this optimization process, the relations in the Random Forest between covariates and Recidivism will be refitted, hopefully leading to more fair results, while not having a too negative impact on the predictive power of the Random Forest.</p><p>We have seen a positive correlation between the number of prior crimes and being Afro-American and that Prior_Crimes had the hightest Feature Importance. Therefore, opportunities especially lie in refitting the relations between Prior_Crimes and Recidivism to give Afro-Americans a higher TNR.</p><p>The <a href="http://proceedings.mlr.press/v80/agarwal18a.html">ExponentiatedGradient</a> is a mitigating algorithm that incorporates fairness constraints into a cost function that should be minimized while fitting a given classifier (like our Random Forest). A few predefined fairness constraints exist in the fairlearn package. For example, to equalize the True Negative Rate, we can tell the ExponentiatedGradient to equalize the opposite of TNR, namely False Positive Rate (this is 1 - TNR). If this False Positive Rate is equalized, also the TNR will be equal. Therefore, we use FalsePositiveRateParity as the constraint for the mitigator.</p><pre>from fairlearn.reductions import ExponentiatedGradient as EG, FalsePositiveRateParity as FPRP</pre><p>We fit the Random Forest and iteratively improve it 100 times on training data to give innocent people in the training set Equal Opportunity. It has to be seen if this Equality of Opportunity will also be attained when deploying the model on the test data.</p><pre>m_dfperf = pd.DataFrame(index = [&#39;Accuracy&#39;,&#39;AUROC&#39;] ,columns = range(5))<br>m_dffi = pd.DataFrame(index = xcols,columns = range(5))<br>m_df_tnr = pd.DataFrame(index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;], columns=range(5))<br>m_df_tpr = pd.DataFrame(index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;], columns=range(5))<br><br>for i, (train, test) in enumerate(cv.split(df)):<br>    classifier = RFC(n_estimators = 100, max_depth = 5, max_features = &#39;sqrt&#39;,random_state = seed)<br>    constraint = FPRP()<br>    np.random.seed(seed) #We set the random seed so that random results can be replicated<br>    mitigator = EG(classifier,constraint,eps=0.01,max_iter = 100)<br>    mitigator.fit(dfx.iloc[train,:],dfy[train],sensitive_features=dfe.iloc[train,:])<br>    yvpred = mitigator.predict(dfx.iloc[test,:])<br>    m_dfperf.loc[&#39;Accuracy&#39;,i] = sk.metrics.accuracy_score(dfy[test],yvpred)<br>    m_dfperf.loc[&#39;AUROC&#39;,i] = sk.metrics.roc_auc_score(dfy[test],yvpred)<br>    m_dffi.iloc[:,i] =  (pd.DataFrame(data = model.feature_importances_,index=xcols,columns=[&#39;Feature Importance %&#39;]))<br>    tnr = MF(metrics=fl.metrics.true_negative_rate,y_true = dfy[test], y_pred = yvpred,sensitive_features=dfe.iloc[test,:])<br>    m_df_tnr.iloc[:,i] = pd.DataFrame(data=[tnr.overall,tnr.by_group[1][0][0],tnr.by_group[0][1][0],tnr.by_group[0][0][1],tnr.by_group[0][0][0]],index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;], columns=[&#39;TNR %&#39;])<br>    tpr = MF(metrics=fl.metrics.true_positive_rate,y_true = dfy[test], y_pred = yvpred,sensitive_features=dfe.iloc[test,:])<br>    m_df_tpr.iloc[:,i] = pd.DataFrame(data=[tpr.overall,tpr.by_group[1][0][0],tpr.by_group[0][1][0],tpr.by_group[0][0][1],tpr.by_group[0][0][0]],index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;], columns=[&#39;TPR %&#39;])</pre><h3>Results after mitigation</h3><p>The accuracy attained by this new model is the same as for the original model and the AUROC is only slightly lower (0.59 instead of 0.60), so we lose little predictive power with the mitigated model. Also, no large differences exist in the Feature Importances between the original and mitigated model. We are most interested in seeing how well the mitigated model can equalize the opportunities for innocent people to be regarded as such, without losing True Negative Rate for any group.</p><pre>m_av_acc = m_dfperf.loc[&#39;Accuracy&#39;,:].mean()<br>print(f&#39;Accuracy: {round(m_av_acc,2)} (so {int(round(100*(m_av_acc - bench)))}%-point higher than benchmark)\n&#39;)<br>m_av_auroc = m_dfperf.loc[&#39;AUROC&#39;,:].mean()<br>print(f&#39;Area under the ROC: {round(m_av_auroc,2)} (Our {round(m_av_auroc,2)} is only slightly better than 0.5)\n&#39;)<br>m_fis = (pd.DataFrame(data = m_dffi.mean(axis=1),index=xcols,columns=[&#39;Feature Importance %&#39;])*100).astype(int)<br>m_fis.loc[:,&#39;Feature Importance % (old model)&#39;] = fis[&#39;Feature Importance %&#39;]<br>m_fis.sort_values(&#39;Feature Importance %&#39;,ascending=False)</pre><pre>Accuracy: 0.67 (so 4%-point higher than benchmark)<br>Area under the ROC: 0.59 (Our 0.59 is only slightly better than 0.5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*ZKCm3A93AgVZ9HqVitfhXA.png" /></figure><p>The chance for innocent people to be regarded as such has on average increased from 87% to 91% and the gaps between ethnic groups have also decreased on average (from 8% to 4% between Afro-Americans and Hispanics), though not fully closing.</p><pre>m_av_tnr = round(pd.DataFrame(data = m_df_tnr.mean(axis=1),index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;],columns=[&#39;TNR %&#39;])*100).astype(int)<br>m_av_tnr.loc[:,&#39;TNR % (old model)&#39;] = av_tnr[&#39;TNR %&#39;]<br>m_av_tnr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*_qCtz-vTByocfX8g-vUJrg.png" /></figure><h3>“All magic comes with a price”</h3><p>Though the predictive performance didn’t drop much overall, it didn’t increase either, but the TNR did. This implies that the fraction of recidivists correctly being predicted, the True Positive Rate, must have decreased. It indeed did so for all ethnic groups (overall from 33% to 27%) and especially within the group of Afro-Americans (from 39% to 32%).</p><pre>m_av_tpr = round(pd.DataFrame(data = m_df_tpr.mean(axis=1),index=[&#39;Overall&#39;,&#39;Afro-Americans&#39;,&#39;Caucasian&#39;,&#39;Hispanic&#39;,&#39;Other&#39;],columns=[&#39;TPR %&#39;])*100).astype(int)<br>m_av_tpr.loc[:,&#39;TPR % (old model)&#39;] = av_tpr[&#39;TPR %&#39;]<br>m_av_tpr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*0MZ7AOnB-gDJfP373LTEIQ.png" /></figure><h3>Conclusion</h3><p>With our dataset, using the fairlearn package to retrain the model 100 times not only helped approaching Equality of Opportunity for innocent people among several ethnic groups in the validation data, but also increased the opportunity for innocent people to be predicted as such in all groups.</p><p>The cost of the mitigation was limited in terms of overall predictive performance, as the accuracy on the validation data was equal for both models and the AUROC only decreased from 60% in the original model to 59% after mitigation. Nevertheless, the new model performed less in correctly predicting the recidivists, as the TPR dropped from 33% to 27%.</p><p>The most important achievement of the mitigator was that the chance to be erroneously predicted as recidivist for Afro-Americans declined from 16% to 10%. Our new model did not only make the results more ‘fair’, but also increased opportunities to correctly be regarded as innocent for all groups involved.</p><h3>Discussion</h3><p>One could focus on Equality a lot, but the result that benefits the innocent people as individuals the most, is not being seen as recidivist. If our mitigation resulted in the gap in TNR staying 8% (and the TPR also dropping from 33% to 27%), but this was because of the TNR became 100% for Hispanics and 92% for Afro-Americans, it would arguably have been a societal better result than what we achieved now with a TNR of 94% for Hispanics and 90% for Afro-Americans.</p><p>By telling the mitigating algorithm which people have which ethnicity, so the group with a lower opportunity can benefit, you are using ethnic data. It could be argued that this is racial discrimination. What if indeed increasing the TNR of Afro-Americans from 84% to 90% is accompanied by a decrease in TNR for Hispanics from 92% to 91%? Is it then still allowed to use the mitigator, since using it with racial data has a negative effect on people from a certain ethnic group?</p><p>Also, the decrease in performance on correctly predicting recidivists raises the question how much of this loss is allowed in name of Equal Opportunities among ethnic groups. Do the societal costs of losing 6% TPR outweigh increasing and equalizing the opportunities for innocent people among different groups?</p><p>In this blog I showed how you are able to detect possible unfairness in models and what can be done to prevent possible harmful outcomes. Please feel free to use this example to investigate possible unfairness in your own models. However, what is considered ‘fair’ is not always clear upfront, therefore a technical solution is just one part of the puzzle. So you might find yourself discussing the definition of ‘fair’ within your team, which is valuable on its own.</p><p>In the future, I will discover more challenges around fairness and the other concepts of Responsible AI, but for now: thanks for reading!</p><p>Want to read more about the cool stuff we do at <a href="https://cmotions.nl/">Cmotions</a> and <a href="https://www.theanalyticslab.nl/">The Analytics Lab</a>? Check out our <a href="https://www.theanalyticslab.nl/blogs/">blogs</a>, <a href="https://www.theanalyticslab.nl/projects/">projects</a> and <a href="https://www.theanalyticslab.nl/videos/">videos</a>!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54e6505f43ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/equal-opportunities-in-ai-an-example-54e6505f43ed">Equal Opportunities in AI: an Example</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Azure DevOps CI/CD guide for your Azure Synapse based Data Platform — part I]]></title>
            <link>https://medium.com/cmotions/complete-azure-devops-ci-cd-guide-for-your-azure-synapse-based-data-platform-part-i-132a542bca96?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/132a542bca96</guid>
            <category><![CDATA[azure-synapse-analytics]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Koen Leijsten]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 07:58:27 GMT</pubDate>
            <atom:updated>2023-03-06T09:10:36.460Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete Azure DevOps CI/CD guide for your Azure Synapse based Data Platform — part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dLNFAgCMr6rFWNnM.png" /></figure><p><em>This guide includes code snippets which you can use yourself. Credits to my colleagues at Delegate who have contributed a lot to this domain. If you would like to check out more extensive CI/CD code or contribute yourself check out: </em><a href="https://github.com/atc-net/atc-snippets/tree/main/azure-cli/synapse/Publish"><em>https://github.com/atc-net/atc-snippets/tree/main/azure-cli/synapse/Publish</em></a><em>.</em></p><p>You have setup your synapse workspace and are busy developing your data platform, there are already some reports that make use of that data platform. You receive some complaints from the analysts that your development work is causing problems for the reports depending on the output of the data platform. You conclude that it is time to separate the development environment from the production environment. You want a professional approach and automate deployment to production in a structured way. Continuous Integration and Continuous Development (CI/CD) is the perfect way to automate your deployment process, but you don’t know where to start.</p><p>No worries, this guide will help you from beginning to end with implementing CI/CD for your Azure Synapse based data platform. In this first part we will take a deep dive into CI/CD with Azure DevOps and in the second part we will highlight some of the best practices.</p><h4>Azure DevOps CI/CD process for your Synapse data platform</h4><p>We start with a high-level overview of the CI/CD architecture in figure 1. This is the architecture that we are going to setup, but before we can set up this architecture we need to make some assumptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*r-6qUs95qtqPriLJ.png" /></figure><p><em>Figure 1: CI/CD architecture for Azure Synapse with Azure DevOps</em></p><ul><li>You have an organisation, project and repository ready to go in Azure DevOps in the same tenant as your Synapse workspace.</li><li>You have one development Azure Synapse workspace and one empty production Azure Synapse workspace. In this guide we are going to assume that these are in different subscriptions, but this does not have to be the case (although it is recommended).</li><li>You have two service principals (app registrations) in your Tenant, one for each of the subscriptions. Find out more about Application and service principal objects in the <a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals">Microsoft documentation</a>.</li><li>These service principals need to have Contributor permissions on the resource group in order to create azure resources in their dedicated subscription.</li><li>An Azure Active Directory (Azure AD) administrator must install the Azure DevOps Synapse Workspace Deployment Agent extension in your Azure DevOps organization. You can find out how you can install extensions in the following <a href="https://learn.microsoft.com/en-us/azure/devops/marketplace/install-extension?view=azure-devops&amp;tabs=browser">link</a>.</li></ul><p>In order to continue with this guide, the assumptions need to be met or at least take them in consideration while reading the guide.</p><h4>Connect your Azure Synapse workspace to an Azure DevOps repository</h4><p>Before we can start implementing CI/CD we need to make sure that the Azure Synapse workspace is connected to your Azure DevOps repository, which will result in the DevOps branches shown in figure 1. The advantage of setting up the connection between Azure Synapse and Azure DevOps is that we can use Git for source control and versioning. We can set this up by going through the following steps.</p><ol><li>Navigate to your Azure Synapse Workspace and select “manage” from the left-side menu.</li><li>Select “Git configuration” and “configure”.</li><li>Select the option “Azure DevOps Git” from the dropdown menu in “Repository type”</li><li>Choose the correct tenant which contains the Azure DevOps organisation and project.</li><li>Choose your DevOps organisation, project and repository which you already setup.</li><li>Create a “Collaboration branch” which will be your development branch.</li><li>The “Publish branch” will contain the JSON file which defines your Synapse workspace and will be updated when you press publish (we will come back to this later on).</li><li>Make sure the box beneath “Import existing resources” is checked. This will make sure that everything that you have built up to this point is pushed to the repository.</li><li>Select “Apply”</li></ol><p>You now have successfully connected your Synapse workspace to your Azure DevOps workspace and we can continue with setting up your Azure DevOps environment.</p><h4>Create service connections in Azure DevOps to your Azure subscriptions</h4><p>In order to automatically deploy the Synapse workspace from development to production we need to authenticate and authorize. We will be doing this using Azure service connections which make use of service principals in Azure (in figure 1 these are the lines between the Synapse workspaces and the DevOps resources). We already have a service principal with the sufficient rights for each subscription. The following steps will describe how we can access and use these service principals in Azure DevOps.</p><ol><li>Go to your project settings at the bottom in the left-side menu of Azure DevOps.</li><li>Navigate to “service connections” beneath the header “Pipelines” and select “New service connection” in the top right corner.</li><li>Choose the option “Azure Resource Manager”.</li><li>Next choose the option “Service principal (manual)”.</li><li>Select the option “Subscription” for the scope level and fill in the correct subscription id. You can find the subscription Id in the Azure Portal under subscriptions.</li><li>Fill in all the required fields. Remember we are going to create a service connection for both the development and production requirement, so make sure you select the corresponding service principal.</li><li>Select Verify to test if the connection works.</li><li>If the connection works, give a name to the service connection, make sure to include the environment in the name (so development or production).</li><li>To finish up select “Verify and save”.</li></ol><p>We need to repeat these steps twice, once for development and once for production. When you went through the steps for both development and production, you will be able to authenticate and authorize automatically when deploying to your Synapse workspace.</p><h4>Create your first Azure DevOps Pipeline</h4><p>Now we can continue creating our Azure DevOps Pipeline. We will first create a starter pipeline which will serve as the starting point for our deployment pipeline. We will create this starter pipeline using the Azure DevOps UI, which will result in a YAML file. We will expand this YAML file during the rest of this guide.</p><ol><li>Log into your Azure DevOps environment and go to the repository where you connected your Synapse workspace.</li><li>Go to the main branch.</li><li>Select “Pipelines” in the left-side menu and select “New pipeline” in the top-right corner.</li><li>Select “Azure Repos Git YAML” and select your repository.</li><li>Configure your pipeline as a “Starter pipeline”.</li><li>You will now see the YAML file, select “Save and run”.</li></ol><p>Your starter pipeline will now run. You can click on “Job”, now you will see the steps that the YAML file is performing. Let’s take a closer look at the YAML file.</p><pre>trigger:<br>- main<br> <br>pool:<br>  vmImage: ubuntu-latest<br> <br>steps:<br>- script: echo Hello, world!<br>  displayName: &#39;Run a one-line script&#39;<br> <br>- script: |<br>    echo Add other tasks to build, test, and deploy your project.<br>    echo See https://aka.ms/yaml<br>  displayName: &#39;Run a multi-line script&#39;</pre><p>Firstly, the trigger of the pipeline is defined, the pipeline will trigger when the main branch is updated. Secondly virtual machine (VM) on which the pipeline runs is specified, the pipeline runs on a Linux VM with the latest ubuntu distribution. Next, the steps of the pipeline are defined. The starter pipeline contains two steps which both run an inline shell (Bash) script. Step one prints “Hello, world!” and the second step prints two strings in the shell. You can see that the second step contains “displayName” parameter which is used to give a step a descriptive name. When you run the pipeline you will see a step with the name “Run a multi-line script”.</p><h4>Deploy a Synapse workspace with your Azure DevOps pipeline</h4><p>Now that we have a starting point for our deployment pipeline we can start configuring the YAML file to our needs. We will start with deploying our development Synapse workspace to our production Synapse workspace. This will only be a “simple” copy paste action on which we can build.</p><p>We will start with adding some parameters to the file.</p><pre>parameters:<br>- name: subscriptionPrd<br>  type: string<br>  default: service-connection-prd<br> <br>- name: subscriptionDev<br>  type: string<br>  default: service-connection-dev<br> <br>- name: resourceGroupNamePrd<br>  type: string<br>  default: resource-group-prd<br> <br>- name: resourceGroupNameDev<br>  type: string<br>  default: resource-group-dev<br> <br>- name: synapseWorkspaceNamePrd<br>  type: string<br>  default: service-connection-prd<br>   <br>- name: synapseWorkspaceNameDev<br>  type: string<br>  default: service-connection-dev</pre><p>We start with the parameters for the service connections to both the development and production subscriptions. These will make sure we can authenticate and authorize. Next, we have the names for our development and production resource groups and Synapse workspaces.</p><p>We talked about the workspace_publish branch in the previous section, we will now further elaborate on this branch. Our development Synapse workspace is defined in the workspace_publish branch which is automatically created when you connect your Synapse workspace to Azure DevOps. This branch contains two JSON files; “TemplateForWorkspace.json” and “TemplateParametersForWorkspace.json”. The first file contains the complete definition of our Synapse workspace and the second file contains global parameters in the Synapse workspace. We will be adjusting the parameter file later on, for now we will be doing a simple deployment where we just copy the development environment to the production environment.</p><pre>resources:<br>  repositories:<br>  - repository: PublishBranch<br>    type: git<br>    name: &#39;name of your repository&#39;<br>    ref: workspace_publish<br> <br>steps:<br> <br>- checkout: PublishBranch<br>  path: PublishBranch</pre><p>We need these files in order to deploy to our production environment. Therefore, we need to make sure that we can access the files during deployment. In the code above we add the “workspace_publish” branch as resource to our pipeline. In next we checkout the “the workspace_publish” branch so that we can make changes to the files if needed, we will come back to this later on.</p><p>Now we can finally implement the most important step, deploying the Synapse workspace in our production environment.</p><pre>#Deploy synapse production environment<br>- task: Synapse workspace deployment@2<br>  continueOnError: false<br>  displayName: &#39;Deploy Synapse Workspace&#39;<br>  inputs:<br>    operation: &#39;deploy&#39;<br>    TemplateFile: &#39;$(Agent.BuildDirectory)/PublishBranch/main/TemplateForWorkspace.json&#39;<br>    ParametersFile: &#39;$(Agent.BuildDirectory)/PublishBranch/TemplateWorkspaceParameters.json&#39;<br>    azureSubscription: &#39;${{ parameters.subscriptionPrd }}&#39;<br>    ResourceGroupName: &#39;${{ parameters.resourceGroupNamePrd }}&#39;<br>    TargetWorkspaceName: &#39;${{ parameters.synapseWorkspaceNamePrd}}&#39;<br>    DeleteArtifactsNotInTemplate: true</pre><p>This task will execute our Synapse workspace deployment. First, we specify that this task must not be executed if we get any errors in the previous steps, to make sure we don’t deploy faulty code. In the input parameter we specify the definition of our Synapse workspace. In the “Templatefile” parameter we will refer to the “TemplateForWorkspace.json” file in our checked out “publishBranch”. We will do the same for “ParametersFile”. Because we are deploying to our production Synapse workspace we will authenticate and authorize with our production service connection in the “azureSubscription” parameter. To make sure our development and production environment stay aligned we include the “DeleteArtifactsNotInTemplate” parameter and set it to true. This setting will delete everything in the production Synapse workspace that is not defined in the “TemplateForWorkspace.json” file that we deploy.</p><p>When we now run the Azure DevOps Pipeline we will deploy our development Synapse workspace to our production Synapse workspace in an automated way. We will continue with parameterizing our deployment to production.</p><h4>Parameterizing the deployment to production</h4><p>Because our development Synapse workspace is in a different environment than our production Synapse workspace we need to make some adjustments to our parameters. For example, we have a connection string to a storage account. The connection string will be different in the production environment, because we want to connect to a different storage account. The “TemplateParametersForWorkspace.json” file contains key value pairs where we need to replace the value. We will use the adjusted “TemplateParametersForWorkspace.json” file with the replaced values in our deployment step.</p><p>Let’s walk through the process. First we are going to create a new folder in our main branch root and name it “deploy”. In this folder we are going to create a JSON file named “synapse-parameters.json”. This file contains the key value pairs of the parameters we would like to replace in our “TemplateParametersForWorkspace.json” file, for example:</p><pre>{ <br>  &quot;workspaceName&quot;: &quot;synapse_workspace-prd&quot;, <br>}</pre><p>Next we create a PowerShell file in the “deploy” folder and name it “initialize-synapse-parameters.ps1”. This file contains the following code:</p><pre>function Initialize-SynapseParameters {<br>    param (<br>        [Parameter(Mandatory = $true)]<br>        [ValidateNotNullOrEmpty()]<br>        [string]<br>        $SynapseParameterJsonPath,<br>       <br>        [Parameter(Mandatory = $true)]<br>        [ValidateNotNullOrEmpty()]<br>        [string]<br>        $OutputPath,<br> <br>        [Parameter(Mandatory = $true)]<br>        [ValidateNotNullOrEmpty()]<br>        [string]<br>        $ParameterJsonPath<br>    )<br>     <br>    # Get the Synapse generated Parameters file<br>    $synapseParameters = Get-Content -Raw $SynapseParameterJsonPath | ConvertFrom-Json -AsHashTable<br>     <br>    Write-Host &quot;Parameterize using jsonfile: $ParameterJsonPath&quot; -ForegroundColor Yellow<br>    $parameterUpdates = Get-Content -Raw $ParameterJsonPath | ConvertFrom-Json -AsHashTable<br>         <br>    foreach ($parameter in $parameterUpdates.GetEnumerator()) {<br>        $synapseParameters.parameters.$($parameter.Name).value = $parameter.Value<br>    }<br>     <br>    # New re-parameterized file ready for prod<br>    Write-Host &quot;Saved parameterized workspace file at: $OutputPath&quot;<br>    $synapseParameters | ConvertTo-Json | Out-File &quot;$($OutputPath)&quot;<br>}<br> <br>Initialize-SynapseParameters `<br>  -OutputPath $OutputPath `<br>  -SynapseWorkspaceParameterJsonPath $SynapseParameterJsonPath `<br>  -ParameterJsonPath $ParameterJsonPath</pre><p>This PowerShell file contains a function that will replace the values based on their key in the “TemplateParametersForWorkspace.json” file and output it to the specified path. We are going to call this function in our DevOps pipeline with YAML code. But first we need to make sure we can access the PowerShell file we just created. Therefore we need to checkout the main branch which we will add underneath the checkout of the “PublishBranch” we did earlier.</p><pre>resources:<br>  repositories:<br>  - repository: PublishBranch<br>    type: git<br>    name: &#39;name of your repository&#39;<br>    ref: workspace_publish<br> <br>steps:<br> <br>- checkout: PublishBranch<br>  path: PublishBranch<br> <br>- checkout: self<br>  path: main</pre><p>Now that we are able to access the files in the main branch, we can also access the PowerShell file and call the function with the YAML code below.</p><pre>#Parameterize Workspace Parameter File<br>- task: PowerShell@2<br>  displayName: &#39;Parameterize Workspace Parameter File&#39;<br>  inputs:<br>   targetType: inline<br>   script: |<br>     cd $(Agent.BuildDirectory)/main<br>     ./deploy/publish-synapse-parameters.ps1 `<br>       -OutputPath &#39;$(Agent.BuildDirectory)/main/CustomWorkspaceParameters.json&#39; `<br>       -SynapseParameterJsonPath &#39;$(Agent.BuildDirectory)/PublishBranch/TemplateParametersForWorkspace.json&#39; `<br>       -ParameterJsonPath &#39;$(Agent.BuildDirectory)/main/deploy/synapse-parameters.json&#39;</pre><p>This YAML code first changes the directory to our checked-out main branch and then runs the PowerShell script we just created. We specify the parameters as follows:</p><ul><li>OutputPath: we set the path for our output file with the replaced values.</li><li>SynapseParameterJsonPath: this points to the “TemplateParametersForWorkspace.json” file.</li><li>ParameterJsonPath: we set the path to the “synapse-parameters.json” file which contains the new values for the production environment.</li></ul><p>All of this results in a new “CustomWorkspaceParameters.json” file which contains the new values for the production environment that we can use for the Synapse deployment step. Instead of referring to the “TemplateParametersForWorkspace.json” file we can now refer to the “CustomWorkspaceParameters.json” file when deploying to production.</p><h4>Summary</h4><p>Congratulations! You are now able to deploy your Synapse based data platform in an automated way using Azure DevOps. We talked about setting up your Synapse workspace and Azure DevOps environments, doing a simple deployment and customizing your deployment using parametrization. These are the first important steps for setting up your CI/CD process.</p><p>In the next part we will dig even deeper and highlight some of the specific use cases that we can add to make our CI/CD process and make it even more automated and dynamic.</p><p><em>Originally published at </em><a href="https://www.theanalyticslab.nl/complete-azure-devops-ci-cd-guide-for-your-azure-synapse-based-data-platform-part-i/"><em>https://www.theanalyticslab.nl</em></a><em> on February 28, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=132a542bca96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/complete-azure-devops-ci-cd-guide-for-your-azure-synapse-based-data-platform-part-i-132a542bca96">Complete Azure DevOps CI/CD guide for your Azure Synapse based Data Platform — part I</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get an overview of all Gitlab members using Python]]></title>
            <link>https://medium.com/cmotions/get-an-overview-of-all-gitlab-members-using-python-402fb1deee4e?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/402fb1deee4e</guid>
            <dc:creator><![CDATA[Jeanine Schoonemann]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 18:46:09 GMT</pubDate>
            <atom:updated>2023-02-21T18:46:08.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BxT1Wpa7HYSwXtzn.png" /></figure><h3>Get an overview of all Gitlab members using Python</h3><p>At the moment of writing this, it has been a <a href="https://gitlab.com/gitlab-org/gitlab/-/issues/18552#note_1282951798">long-lasting desire for Gitlab users to be able to see all members to any project within a group at a single glance or press of a button</a>. It was also something I was looking for myself, since we use Gitlab as a company and therefore have to deal with people leaving us from time to time. When that happens we, of course, have to make sure they can no longer access the private repositories we keep in our Gitlab group. This is not only we feel the desire to do, but it’s also something which is simply an obligation, even more so since we got our ISO-27001 certificate.</p><p>That is why I started to look for my own solution and luckily I came across the very easy and useful <a href="https://python-gitlab.readthedocs.io/en/stable/api-usage.html">gitlab Python package</a>. This made my life so much easier. The only thing I need to do now is to regularly run the script below, this gives me a complete overview in Excel of all users that are a member of our Cmotions group on Gitlab and it immediately shows me which repositories they can access and even what their access rights are. Easy does it!</p><p>I start this script by importing the necessary packages, setting the value for the group_id I would like to get an overview of, and loading the .env file, where I’ve stored <a href="https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html">my personal access token</a> for Gitlab. Just for myself, I’ve also created a dictionary to translate the access rights into readable values.</p><pre>import pandas as pd <br>from dotenv import load_dotenv <br>import os <br>import gitlab <br><br>load_dotenv() <br><br># you can find the group ID right on the home page of your group, <br># just underneath the name of your group <br>group_id = 123456789 <br><br># the translation of the access level codes according to Gitlab: https://docs.gitlab.com/ee/api/members.html <br>access_dict = {0: &quot;no access&quot;, 5: &quot;minimal access&quot;, 10: &quot;guest&quot;, 20: &quot;reporter&quot;, 30: &quot;developer&quot;, 40: &quot;maintainer&quot;, 50: &quot;owner&quot;}</pre><p>Now we can initialize the Gitlab API and start listing all information from within our group, this way we get a list of all projects (repositories) in the group and all of its subgroups.</p><pre># init the gitlab object <br>gl = gitlab.Gitlab(private_token=os.getenv(&quot;PRIVATE-TOKEN&quot;)) <br><br># get gitlab group <br>group = gl.groups.get(group_id, lazy=True) <br><br># get all projects <br>projects = group.projects.list(include_subgroups=True, all=True, owned=True) <br><br># get all project ids <br>project_ids = [] <br>for project in projects:     <br>  project_ids.append((project.id, project.path_with_namespace, project.name)) <br><br>df_project = pd.DataFrame(project_ids, columns=[&quot;id&quot;, &quot;path&quot;, &quot;name&quot;])</pre><p>After retrieving all the projects, we can loop through them and get all members of each of the groups. This way, we end up with a complete list with all members within our group, to which repositories they have access and which access rights they have for each of these repositories.</p><pre># get all members <br>members = [] <br><br>for _, row in df_project.iterrows():     <br>  proj = gl.projects.get(row[&quot;id&quot;], all=True)     <br>  for member in proj.members_all.list(get_all=True):         <br>    members.append((row[&quot;id&quot;], row[&quot;path&quot;], row[&quot;name&quot;], member.username, member.state, member.access_level)) <br><br>df_members = pd.DataFrame(members, columns=[&quot;project_id&quot;, &quot;project_path&quot;, &quot;project_name&quot;, &quot;username&quot;, &quot;state&quot;, &quot;access_level_code&quot;]).drop_duplicates() <br>df_members[&quot;access_level&quot;] = df_members[&quot;access_level_code&quot;].map(access_dict) df_members.sort_values(&quot;username&quot;, inplace=True)</pre><p>And this list we can store as a csv file, which makes it easier to share with other people within the business if needed.</p><pre># store as csv <br>df_members.to_csv(&quot;gitlab_members.csv&quot;, sep=&quot;;&quot;, header=True, index=False)</pre><p>Good luck!</p><p><em>Originally published at </em><a href="https://www.theanalyticslab.nl/get-an-overview-of-all-gitlab-members-using-python/"><em>https://www.theanalyticslab.nl</em></a><em> on February 20, 2023. Want to read more about the cool stuff we do at </em><a href="https://cmotions.nl/"><em>Cmotions</em></a><em> and </em><a href="https://www.theanalyticslab.nl/"><em>The Analytics Lab</em></a><em>? Check out our </em><a href="https://www.theanalyticslab.nl/blogs/"><em>blogs</em></a><em>, </em><a href="https://www.theanalyticslab.nl/projects/"><em>projects</em></a><em> and </em><a href="https://www.theanalyticslab.nl/videos/"><em>videos</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=402fb1deee4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/get-an-overview-of-all-gitlab-members-using-python-402fb1deee4e">Get an overview of all Gitlab members using Python</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Reinforcement Learning to teach the computer to play Snake]]></title>
            <link>https://medium.com/cmotions/use-reinforcement-learning-to-teach-the-computer-to-play-snake-7650a56816ae?source=rss----5d5661bf36c6---4</link>
            <guid isPermaLink="false">https://medium.com/p/7650a56816ae</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Matthijs Otten]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 08:58:17 GMT</pubDate>
            <atom:updated>2023-02-21T08:58:16.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*q100vkucHJK0m3eg.jpg" /></figure><p>At <a href="http://www.cmotions.nl/">Cmotions</a>, the Data Consultancy firm I work for, we love to learn from each other and that is why we regularly collaborate on internal projects, in which we can express our creativity, curiosity and eagerness to learn. In this article we want to share what we did in the ‘Snake’ project, where we learned the computer to play snake using Reinforcement Learning. Never heard of Reinforcement Learning before? Not to worry, we’ll start our explanation of this project at the very beginning. Intrigued by this project and curious what our code looks like, we’ve <a href="https://www.theanalyticslab.nl/reinforcement-learning-in-python-to-play-snake/">shared that too!</a></p><h3>Introduction</h3><p>You have learned to walk on your feet when you were only 8–15 months old and before you were two years old you could speak your first small sentences. Your parents’ encouragement was probably an important incentive for you to try to walk after falling. And maybe the ability to reach for other things felt like a victory when you stood on your feet for even a moment and helped you to try it over and over again. Not every time you succeeded, but in the end, you learned how to be stable on your feet and move forward. You learned using Reinforcement Learning! We as humans have amazing learning capabilities and when you dedicate your time and energy in any kind of task you can become extremely good at performing this task. Acrobats, musicians and artists are living examples of human expertise.</p><p>As humans we are very skilled at gaining new skills based on what we already learned in the past, we’re quite good at generalizing our knowledge to use in new tasks. But we definitely also have our weaknesses, like we are unable to memorize and process huge amounts of information. That is why we try to program computers to perform these kind of tasks for us. Even though computers have some clear advantages versus humans, it can be difficult to make a computer smart enough to win against a human expert in decision making situations like playing games. In 1996, for the first time, a computer was able to defeat a grandmaster in chess; Kasparov. The computer was able to defeat Kasparov by computing every possible move until there are no more possibilities. This took enormous computing power, but the progress in playing games didn’t end here. Between 2016 and 2019 Computer Algorithms learned to defeat human experts in Go and Chess with a lot less computing power needed. The acceleration in this technology has only grown in the last years with day-to-day implementations such as self-driving cars, robotics and complex strategic games such as Starcraft II and No Limit Holdem Poker. You might wonder how they did this. Well, remember Reinforcement Learning?</p><h3>Introduction to Reinforcement Learning</h3><p>When working on trying to defeat the grandmaster of chess, it was quickly recognized that computing all the possible solutions and choosing the best solution is not a very efficient way to play (and win) a game. Reinforcement Learning came to the stage and very soon was able to prove its effectivity when it comes to playing, and winning, games. With Reinforcement Learning the computer learns to make optimal decisions for the future.</p><p>The process of Reinforcement Learning looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*j7USQNKvpbjMufG2.png" /></figure><p>In Reinforcement Learning the computer ( <em>agent</em>) takes actions within a given set of rules and possibilities ( <em>environment</em>). Actions can lead to a positive encouragement ( <em>rewards</em>) or negative encouragement (<em>punishments</em>). By taking an action, the <em>agent </em>is moving from one situation (<em>state</em>) to the next. Moreover, the environment holds, in case of chess, the rules of the game like physical size of the board and possible steps per type of piece. In Reinforcement Learning it’s about taking the best possible action or path to gain maximum rewards and minimum punishment in the future through observations in a specific situation.</p><p>In the chess game the state of the game would be the situation on the chess board, meaning where each piece is located on the board. This state gives us a possible action space for each piece, meaning all the possible actions at that moment for each piece on the board, of course keeping in mind the rules of the chess game. When the agent (player) moves a piece, the games reaches a new state. Which also means the possible actions for each piece on the board might change as well. Just like when we play chess ourselves, before the computer decides which move to make, it tries to predict what would be the most valuable move, i.e. which move would lead to winning the game as fast as possible.</p><p>Let’s see how this would work for chess. The first image shows the start of the game, the first state, for the knight we show its actionspace, but of course each piece of the board has its own. Let’s assume the agent decides to move the knight. Leading to the second image, and second state, of the game. Also meaning the knight, and other pieces, have an updated actionspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*UmmI3y4GIe9g8bvd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*N8PVVVZQurTnsK6a.png" /><figcaption>Image by <a href="https://pixabay.com/users/dg-ra-4854875/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3694692">Rafael Javier</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3694692">Pixabay</a></figcaption></figure><p>Of course, at the beginning of a game it can be quite difficult to predict which move would be the most valuable, but as the game progresses, this is becoming more and more clear and easier to predict. Something every chess player will recognize.</p><p>In Reinforcement Learning, the agent starts learning by using trial and error. It remembers which moves were made, how long the game lasted and what the outcome was. Like for ourselves, the more we play, the better we know what a good next move would be, giving the current state of the game. But unlike us, a computer can play games at ligthning speed and has a huge memory to remember every little detail.</p><p>In more technical terms, in Reinforcement Learning we can use a algorithm which uses the current state and action (next move) as input and expected reward as output. The goal is to find a suitable action model within the environment in which the agent increases the <em>expected cumulative reward</em> of the agent in the future. The expected cumulative future reward is expressed in a <em>value function</em>. Reinforcement Learning models update their value function by interacting with the environment, choosing an action, looking at the new state, looking at the reward, then updating. With multiple iterations the model will keep learning and we expect this value function to increase, meaning the agent will keep improving at playing (winning) the game.</p><h3>Choosing the right Reinforcement Learning algorithm</h3><p>In order to teach our agent to take the best actions in all possible states for acquiring the maximum reward over time, we need to choose a Reinforcement Learning Algorithm (RLA) with which our agent can learn what actions work best in the different states.</p><p>We call the collection of these preferred actions in the different states the <em>policy</em> of the agent. In the end, the agent should have a policy that will give her the highest lifetime reward. A large variety of algorithms to find the optimal policy exist and we will group them into three categories to make things understandable:</p><ol><li>Model Based</li><li>Policy Based</li><li>Value Based</li></ol><p><strong>Model Based</strong></p><p>The first category is that of <em>Model-Based </em>RLA’s, where the algorithm uses a model to predict how the environment reacts to actions, thereby giving the agent ‘understanding’ of what her future state will be if she chooses for a particular action. In <em>Model-Free</em> algorithms, the agent will not have an explicit prediction of what her environment will look like after taking an action. So, although every RLA could be seen as a Machine Learning model for the agent to base its actions upon, the distinction between <em>Model-Based </em>and <em>Model-Free </em>is about whether an explicit (predictive) model about the future state is used or not.</p><p><strong>Policy Based</strong></p><p>Although not explicitly having an expectation of the future environment, some of these Model-Free algorithms can find the ultimate policy, based on searching for an optimal combination of states and wise actions to take in these states. These are called <em>Policy-Based </em>RLA’s. One of the most common algorithms of this sort is the <a href="https://towardsdatascience.com/reinforcement-learning-policy-approximation-f5606ad3d909"><em>Policy Gradient Method</em></a><em>.</em></p><p><strong>Value Based</strong></p><p>Some algorithms go one step deeper than these Policy-Based algorithms by optimizing the expected future reward per state. In doing so, these <em>Value-Based </em>algorithms find the best actions to take in these different states, thereby having a collection of state-action combinations which ultimately make up the <em>policy</em> of the agent in her environment. So, <em>Policy-Based </em>and <em>Value-Based </em>algorithms seem very similar, but the main difference is that policies are stored and updated in <em>Policy-Based </em>algorithms, but in <em>Value-Based </em>algorithms the value function is stored and updated, from which the combinations of states and actions can be derived, and the policy thereby constructed. We will be using such an algorithm: <em>Double Deep Q-Network (Double DQN).</em></p><h3>Defining the SNAKE game</h3><p>Now that we know what Reinforcement Learning is and how it teaches an agent to achieve goals by interacting with its environment, it is time to try it ourselves! Remember the game we used to play in the early 2000’s on our good old Nokia mobile phone? We have all been playing the nostalgic game Snake at least once in our life, right? The goal is simple: being a snake you navigate through a square playground looking for food. As you eat more food, the difficulty increases because your snake will grow longer, and you cannot crash into yourself. Snake is a good choice for a first introduction to Reinforcement Learning, because it lets us define the environment, agent, states, actions and rewards relatively simple.</p><p>Our game environment can be defined as a grid of points, with a piece of food at a random coordinate in that grid. In our version of Snake there are no walls, which means that the only way the snake can die is by a collision into its own body. Our agent — the snake — is encoded by a list of coordinates that are covered by the snake, and the state is the current representation of the environment. The picture below shows an example of what the environment could look like. Where the F is food, H is the head of the snake and T is its tail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/0*lb0sqa-BjtzvgWtS.png" /></figure><p>For this article, we have experimented with different representations of the state, incorporating various sources of information such as the direction of the snake and the distance to the food. Additionally, we have experimented with adding spatial features extracted by convolutional filters. Convolutional filters extract spatial information of an image by multiplying regions of pixels in an input with weights that are learned by a neural network. This results in a feature mapping that encodes spatial information of the playground, like we will explain more in detail later on.</p><p>As the snake navigates through the environment, it can either move up, down, left or right. However, according to the rules of the game, the snake cannot move in the opposite direction of the current direction. Therefore, given the state, we can only take three out of four actions. This subset of actions is what we call the <em>action space</em>. Our goal is, given a certain state, to choose the action that maximizes the future lifetime reward, which can consist of multiple features. In the first place, our snake is rewarded when it eats food, and the score increases. Conversely, the snake is negatively rewarded when it collides into its own body. Additionally, we have included a small penalty to the reward when the snake moves further away from the food, and we added a small positive reward when the snake moves closer to the food. This encourages the snake to pursue eating food instead of only avoiding a collision.</p><p>It is very informative to play around with these rewards and punishments, since the result of your decisions on what to reward and what to punish might surprise you from time to time (actually, a lot of the times). For example, before introducing the small rewards and punishments for getting closer to or moving away from the food, the snake would sometimes run in circles in order to survive, thereby not scoring any points. On the contrary, a penalty for walking around for too long without eating, resulted in the snake wanting to commit suicide immediately to avoid “suffering” from walking around without eating. Taking into account how simple the game of snake is, imagine how hard it is to define good rewards and punishments in real life, to avoid “toxic” behaviour.</p><p>Now that we know what the actions, rewards and states in our situation are, it’s time to have a look at how we are going to incorporate this in a model that can be trained.</p><h3>Optimizing Reinforcement Learning</h3><p>By using a neural network with Python library Tensorflow we estimate the total future rewards of our possible actions given our state. So, given a set of input features, which is the current state, we are going to predict the future rewards given our possible actions. In other words, we are training our neural network by updating our Q function based on the reward for a given action. Such a neural network is called a Deep Q-Network (DQN). This Q-function is the prediction of total future reward for the agent, when choosing action <em>a</em> in state <em>s</em>. The formula representing the way the function is updated is called the “Bellman-equation” and given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*kUevH0NHAcaN4_GG.png" /></figure><p>So, besides the Q function, the equation has parameter alpha as the learning rate of the algorithm that influences how fast the Q function is updated and therefore the rate at which the perception of the agent changes while learning her best actions. Reward function <em>R</em> shows the immediate reward of taking action <em>a </em>in state <em>s.</em> Discount rate gamma discounts future rewards that come after the immediate reward. This is necessary to reflect real life, in which a reward in the far future is most of the times deemed (slightly) less important than immediate reward. These hyperparameters alpha and gamma are set by the programmer before the algorithm is deployed.</p><p>By learning which actions give us the most future reward in which states, the agent can learn to effectively play snake.</p><p>We are going to train two different models with different input features/states in order to compare the performance and complexity of both versions.</p><h3>Model V1 — a simple model</h3><p>The first step we must take in building a DQN model is to define the features/states that we will use to predict the Q-values. This is one of the most important steps in setting up a Reinforcement Learning model as it yields all the information the model will use, such that giving too little information will result in a poor model performance. Nonetheless, we do not want to overcomplicate our first model and therefore choose fairly simple input features that contain signals about the location of the food and if there is a snake cell (i.e. her own body) beside the head of the snake.</p><p>For the first model we tried to keep the features as easy as possible to understand for our neural network (and ourselves 😉). The features used by this first model are as follows:</p><ul><li>X-coordinate of the food minus the x-coordinate of the snake’s head.</li><li>Y-coordinate of the food minus the y-coordinate of the snake’s head.</li><li>Dummy variable: if there is snake cell below head</li><li>Dummy variable: if there is snake cell above head</li><li>Dummy variable: if there is snake cell left of head</li><li>Dummy variable: if there is snake cell right of head</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*uGzfOc5eGwqsYZDs.png" /></figure><h3>Model V2 — a more strategic model</h3><p>As we chose our first model to be fairly simple, it could not look further ahead on the snake’s body to understand the full current state of the game and therefore the snake could be trapped easily inside its body such that it dies. To improve the model, we want to use a convolutional neural network to understand the full picture of the game such that it can make strategic choices so that it will not trap itself.</p><p>However, by using convolutional filters to understand the game’s image there is a tradeoff between simplifying the input by aggregating the pixels of the game, such that it will lose precision on the whereabouts of the snake’s body, and size of the network such that the network can understand the many pixels given by the image, where a too large size will make the model so complex that it will take very long to train.</p><p>To deal with this problem we create a combined network of the input features from the last model, that gives very precise information about dangers and directions, and combine them with the snake’s snapshot image such that it will give the snake more strategic insights about the state of the game.</p><p>In order to let the neural network understand the image, we transform the game into an array of shape: (game width, game height, 3). This array will then have an array with the length of three for each point in the snake’s map, that will be used to indicate if there is a snake body, snake head or food by using dummy variables. For example, if the pixel is filled with a snake’s body, the array will then be given by [1,0,0] and if there is food placed on the pixel the array will be given by [0, 0, 1]. Then, an example of what the full input array for the convolutional layers could be is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*S3TzqCArMSJ3cP6U.png" /></figure><p>Now the input of the DQN model for this version will be a tuple with the state features of our first model’s version and the game state array for the convolutional part of the model. Because of this combination of two parts, it is a Double DQN.</p><p>As previously mentioned, the input of the model will be a combined input of model V1 on features and the image as converted to an array. Our model will first split our tuple containing both features by the features array and the convolution array. Once we have our separated array containing the snake’s game snapshot, we will let this go through two separate convolutional layers containing 8 filters, a kernel with size=(4, 4) and strides=2, where the padding is ‘same’ which makes sure that we also account for the border pixels in our model. After the input has gone through both convolutional layers, we will have extracted signals about the game like “there are a lot of body parts in the bottom right corner”, which can help the snake to stay away from there. Flattening this array of signals makes us able to use these signals in a normal dense layer. Next, after flattening the array, we use two dense layers of 256 and 64 neurons to further extract signals about the state of the game.</p><p>For the normal features we use one dense layer of 16 neurons to extract signals about immediate threats and the position of the food. The moment comes when we concatenate both the normal signals and our convolutional signals together such that we can use them simultaneously in a dense layer which will finally be used to predict the Q-values for each action.</p><p>Next, we train our multi-input model until the model converges to an optimum where the average reward is not improving anymore. As we have a much larger network containing convolutional filters, it will take the algorithm a lot longer to train. Again, we help the model by giving example actions for 20% of the time. Once the model has had a good amount of training loops (around 1 million iterations) this part can be removed to get more exploration observations and have more data to find a good strategy in the training data.</p><p>For this second version of the model, we find that it converges after approximately 5 million training iterations which take around 4–7 hours of training, depending on the processor speed.</p><h3>Results</h3><p>Finally, we come to the most important part of the project where we assess the performance of our models. To validate the performance, we want our models to play 100 games till the snake dies. Then we are going to compare the average score and the maximum score out of these 100 games to compare the models. Exploration is avoided, which means that the algorithm is never randomly choosing actions. These are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*zZjwuMvbthF-P_IfHJ22dw.png" /></figure><p>For the model V1 the average score out of 100 games is 22.28 with a maximum of 47 which is not bad for the fact that this model is not able to lookout for threats ahead. However, incorporating the snapshot of the whole game into the model V2 gave us a significant improvement with an average of 27.16 and a maximum of 72. This shows us that the V2 model, the more strategic one, is indeed capable of determining strategies that look ahead to prevent the snake from getting trapped. However, the training time of this model was also significantly longer with 4–7 hours in respect to 30 to 60 minutes. Therefore, we really see a clear trade-off between performance and required training time to reach the optimum. In practice, this is always a hard decision as there is always a better solution, however the question arises: “Is it worth the time?”. From our first model’s output we saw that the performance was not bad either, so was it worth all the trouble to enhance it? For this article it definitely was!</p><h3>Can you use Reinforcement Learning in your daily life?</h3><p>Apart from interesting applications of Reinforcement Learning in games, these algorithms can also be used in business to improve how data can create value. Essentially, if decisions must be made about which actions to take given the current situation an organization is in, a Reinforcement Learning agent can be trained to make decisions or at least give advice on what the next best action should be.</p><p>One of these scenarios could be when a marketing team should decide whether to include a customer or prospect in a certain campaign and which offer or communication she should receive. For example, the <em>agent</em> here is the digital assistant of the marketeer, <em>state</em> the characteristics of the (potential) customer plus the timestamp and the <em>actions</em> are choosing between the different offers (or no offer at all) and communications. The <em>environment</em>, which is the real world, will give feedback such as clicks on weblinks, conversion or churn. The designer of the Reinforcement Learning Algorithm should then define the <em>rewards</em> corresponding to these events to steer the <em>agent</em> in the right direction for finding its optimal <em>policy</em>.</p><p>Another example could be that of personalizing the homepage on a website based on how a visitor is navigating through the website. The <em>agent</em> is not the visitor, but the digital content manager behind the website, who is choosing which banners to show on which places of the homepage ( <em>actions</em>), given online navigation history ( <em>states</em>) of the visitor and other information if the visitor is logged in with a profile or from cookies. If the visitor clicks on the shown banner, a positive <em>reward</em> is given by the environment, as this click shows the banner is relevant to the visitor and the homepage is being optimized for this type of visitor. The algorithm will find which <em>actions</em> (show a banner) link best to the possible <em>states </em>(collection of navigation history) to compose the <em>policy</em>.</p><p><a href="https://www.theanalyticslab.nl/reinforcement-learning-in-python-to-play-snake/">Curious to see our code for both of our Reinforcement Learning models, check out our other article!</a></p><p>This article is not just written by me, but also by:</p><p>Wim Verboom (<a href="https://www.linkedin.com/in/wim-verboom/">linkedin.com/in/wim-verboom/</a>)<br><a href="https://medium.com/u/b0b356bb79e0">Jeanine Schoonemann</a> (<a href="https://www.linkedin.com/in/jeanine-schoonemann-16b88b20/">linkedin.com/in/jeanine-schoonemann-16b88b20/</a>)<br>Frank van der Bas (<a href="https://www.linkedin.com/in/frank-van-der-bas-946b111a9/">linkedin.com/in/frank-van-der-bas-946b111a9/</a>)<br>Thomas ten Heuvel (<a href="https://www.linkedin.com/in/thomas-ten-heuvel-750247118/">linkedin.com/in/thomas-ten-heuvel-750247118/</a>)</p><p><em>Originally published at </em><a href="https://www.theanalyticslab.nl/use-reinforcement-learning-to-teach-the-computer-to-play-snake/"><em>https://www.theanalyticslab.nl</em></a><em> on February 2, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7650a56816ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/use-reinforcement-learning-to-teach-the-computer-to-play-snake-7650a56816ae">Use Reinforcement Learning to teach the computer to play Snake</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>