<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Brendan McKenna on Medium]]></title>
        <description><![CDATA[Stories by Brendan McKenna on Medium]]></description>
        <link>https://medium.com/@brendan.mckenna?source=rss-845c262a6ac5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vgohwVd4wLHi4jWpw_a3MQ.jpeg</url>
            <title>Stories by Brendan McKenna on Medium</title>
            <link>https://medium.com/@brendan.mckenna?source=rss-845c262a6ac5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:09:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brendan.mckenna/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Accelerating fraud prevention using agentic workflows]]></title>
            <link>https://medium.com/@brendan.mckenna/accelerating-fraud-prevention-using-agentic-workflows-147d38b4d722?source=rss-845c262a6ac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/147d38b4d722</guid>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[fraud-prevention]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <dc:creator><![CDATA[Brendan McKenna]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 03:04:59 GMT</pubDate>
            <atom:updated>2024-08-08T03:04:59.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-djNxVtYLJkVX1xclJXeLw.jpeg" /></figure><p>In today’s fast-paced world, efficient research is crucial for success across various industries. Whether it’s financial institutions investigating transactions for compliance, sales reps preparing for meetings, investors running due diligence, or oil companies searching for new drill sites, the need for thorough and timely research is ever-present. Agentic workflows are posed to significantly reduce the time, cost, and manpower necessary to conduct research. By automating part of the research process, agents enable organizations to gather accurate and relevant information quickly, ensuring better decision-making and productivity.</p><p>Let’s use an age-old example from financial services: preventing fraud. The general steps banks take to investigate suspicious transactions are:</p><ul><li>Initial detection: Review the alert generated by the monitoring tool or fraud detection system</li><li>Preliminary assessment: Determine if the alert warrants a full investigation</li><li>In-depth analysis: Gather information about the transaction</li><li>Analysis and evaluation: Use the evidence to understand the nature and extent of the fraud</li><li>Assessment and decision making: Decide on the appropriate course of action</li></ul><p>Banks must also ensure that their investigations comply with relevant laws, regulations, and internal policies. For example, the Bank Secrecy Act (BSA) requires financial institutions to report signs of suspicious activity to the authorities within 30 days.</p><p>Fraud has always been a significant challenge for banks, given the vast number of transactions they handle daily. With the increasing sophistication of fraudulent activities, traditional methods of detection are often insufficient, leading to substantial financial losses and reputational damage. Banks must continuously evolve their detection strategies to stay ahead of fraudsters, requiring advanced technologies and extensive data analysis to identify and mitigate potential threats effectively. This necessitates a robust and dynamic approach to fraud detection, combining machine learning algorithms, real-time monitoring, and comprehensive data integration.</p><p>While machine learning systems are remarkably capable at detecting fraud at a massive scale, they also flag many legitimate transactions. If the process were fully automated, declining legitimate transactions would negatively impact business. The business would lose revenue on the transaction, damage their reputation, and their customers would feel frustrated by incorrect blocks on their accounts or transactions.</p><p>Instead, the machine learning system monitors all transactions and flags anything suspicious for a human investigator to take over. The human proceeds with an investigation by searching internal and external sources for evidence of fraud or illegal activity, and ultimately approves or declines the transaction. The speed at which a human evaluator investigates each transaction has a direct impact on customer experience; there’s a massive incentive to reduce the research time.</p><p>Agentic workflows can drastically enhance the investigation process by automatically searching for relevant information and generating an initial report to kickstart the human investigator. Unlike traditional workflows, agentic workflows can generate new questions, discover new sources, and draw conclusions from information it finds. Compared to keyword search, they can follow flexible guidelines and return information you hadn’t even thought of searching for.</p><p>What is an agentic workflow? Let’s first define the core components:</p><p><strong>Workflow</strong>: A workflow is a structured sequence of steps or tasks that guide a process from start to finish. It represents the way work is organized and completed within an organization or for a specific project.</p><p><strong>Agent</strong>: autonomous or semi-autonomous programs that complete tasks or goals using decision-making processes, human input, tools, APIs, and knowledge sources.</p><p><strong>Task</strong>: Discrete units of work such as researching a website, writing a document draft, or calculating numbers.</p><p>Agentic workflows use LLMs to dynamically create workflow structure and complete individual tasks to achieve objectives. Let’s look at the spectrum from traditional, deterministic workflows to autonomous agents.</p><ol><li><strong>Deterministic workflows</strong>. The workflow and all its tasks are predefined with deterministic code, designed and built with the help of a copilot of course!</li><li><strong>Deterministic workflows with LLM tasks.</strong> The workflow structure and tasks are predefined with deterministic code, with individual calls to an LLM for a narrow task such as summarization, completion, generation, categorization, etc. For example, “which category does the following paragraph fit best?”</li><li><strong>Deterministic workflows with agentic tasks.</strong> The workflow structure is predefined in deterministic code, with some tasks handled by agents that make decisions, utilize tools, search knowledge, and take actions.</li><li><strong>Agentic workflows. </strong>The workflow structure is a combination of tasks predefined in code and tasks dynamically generated by agents. Each task can be a combination of deterministic code and agents.</li><li><strong>Autonomous Agents.</strong> The workflow structure and tasks are dynamically created by a team of agents based on a predefined objective and criteria.</li></ol><p>Deterministic workflows work for predefined processes, where each task is explicitly defined, such as retrieving a user profile from a database. Investigating a new transaction between two largely unknown parties contains repeatable workflow tasks such as a database query, social media search, and listing previous transactions. But any investigation also includes unplanned tasks such as a recursive query to dig deeper into a court case one of the parties was involved in. Therefore, a combination of deterministic workflows and agents is best for this use case. A developer can write a base workflow with some tasks explicitly written in code and others handled by an agent or team of agents. These agents can dynamically extend the base workflow and add new tasks.</p><p>Agents can investigate a person or company similar to how a human would. They can reason, consume information, search various data sources, and compare what they find with a search criteria. Unlike traditional code, agents can handle a range of inputs. When defining a search criteria, you can ask it to retrieve specific details, like a person’s current job title, employer name, or precise location. Or you can ask it to use abstract descriptors like “have technical skills”, “works for a publicly traded company”, or “anywhere in Eastern Europe”. You can add other qualifications such as “don’t use information from the following URLs” or “only include news if there are multiple sources”.</p><p>But aren’t Autonomous Agents better than agentic workflows for investigation? Not necessarily. Because an investigation follows a methodology and has standard checks relating to information that violates the law. An agentic workflow ensures those repeated checks are always conducted.</p><p>Preventing fraud includes three critical elements: flagging a transaction, investigating the transaction, and making a decision to approve or decline the transaction. The evolution from deterministic workflows to agentic workflows is a significant advancement in the end-to-end process. Although decision-making remains primarily human-driven, the integration of agentic workflows can empower individuals by eliminating the need for manual research and providing superior information, enabling faster and more effective decisions. And as the technology improves, the research and decision-making phases will increasingly integrate with the initial flagging process, reducing the number of transactions requiring human intervention. Ultimately, this evolution may lead to a future where human involvement is minimal or unnecessary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=147d38b4d722" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How ChatGPT falls short as a data engineering assistant]]></title>
            <link>https://medium.com/@brendan.mckenna/why-chatgpt-is-a-lousy-assistant-for-data-engineers-657476089be9?source=rss-845c262a6ac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/657476089be9</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[ai-copilot]]></category>
            <dc:creator><![CDATA[Brendan McKenna]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 01:49:03 GMT</pubDate>
            <atom:updated>2024-07-29T18:54:26.110Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re a data engineer and not using Chatgpt, there’s a good chance you’re working harder than you need to. Large Language Models have transformed the way we work, and while there’s a slight learning curve to applying it in your workflow, when you do it’s like magic.</p><p>ChatGPT wields an unfathomably large chunk of the internet to answer questions, generate images, and write code. It can debug code or help you troubleshoot your DIY home projects. Overall, it’s great to work with except for a few small things.</p><p>First of all, it never comes to you. Kind of like that guy who sits on the 3rd floor who knows every table schema in the org but doesn’t answer DMs forcing you to walk around the corner, down the hall, to the elevators, up to the 3rd floor, past the snack room and to his desk just to ask him a question. It’s not a big deal every once in a while, but gets old really fast.</p><p>Second, if you imagine the most helpful people, they are good at asking a lot of questions before trying to answer your question. Without proper context, their best answer probably won’t be completely correct and you’ll waste time spinning your wheels and getting frustrated. ChatGPT is doing it’s best to answer your question, but all too often your prompt doesn’t include all the relevant context and you’re forced to return to your development environment to retrieve additional information. For complex questions especially, it’s a huge hassle to gather, structure, and provide all the relevant context. It’s nontrivial to collect the table schemas, project plan, and data flows and draft a coherent prompt.</p><p>Third, describing how to complete a task is nice, but actually <em>doing it </em>is much more helpful. The most ChatGPT can do is generate text, code, and images. But what if it could take menial tasks off your plate and let you focus on what’s most important?</p><h3>What are AI Copilots?</h3><p>That’s where copilots come in. Copilots are embedded in your application to be easily accessible and contextually aware of your work. Data engineering copilots know the screen you’re on, the code you’re drafting in your editor, and the tables relevant to your query. It’s always available and not even a click away.</p><p>But beyond just context, copilots also have access to various data sources and tools (such as application APIs, microservices, or agents). These capabilities allow copilots to:</p><ul><li>Answer questions: leveraging their underlying LLMs general knowledge and connected data sources, copilots can provide instant and specific answers to users in the flow of work.</li><li>Complete tasks: copilots can complete actions in connected applications or tools on behalf of the user.</li></ul><p>These capabilities make a well-designed copilot a formidable ally. Studies have shown significant improvements in task completion speed and overall productivity. For example, Microsoft Copilot users were 4 times faster at catching up on missed meetings and 29% faster in tasks like searching, writing, and summarizing information (<a href="https://www.continual.ai/blog-post/what-is-an-ai-copilot">Source</a>). AI copilots can reduce user friction, boost engagement, lower support costs, and potentially generate additional revenue through premium pricing tiers.</p><p>Some of my favorite copilot examples are <a href="https://github.com/features/copilot">Github Copilot</a>,<a href="https://www.youtube.com/watch?v=S7xTBa93TX8"> </a><a href="https://www.databricks.com/blog/introducing-databricks-assistant">Databricks Assistant</a>, <a href="https://www.snowflake.com/blog/use-ai-snowflake-cortex/">Snowflake Copilot</a>, <a href="https://www.getdbt.com/blog/introducing-dbt-assist">dbt assist</a>, and <a href="https://learn.microsoft.com/en-us/fabric/get-started/copilot-fabric-overview">Microsoft Fabric Copilot</a>.</p><h3>How are Copilots useful in data engineering?</h3><p>Data engineers play a crucial role in enabling organizations to leverage data for decision-making, strategic planning, automation, and more. There are many ways copilots can help data engineers. To illustrate how, let’s use an example scenario.</p><p>Suppose I’m a data engineer supporting the sales org at a Fortune 1000 enterprise. My biggest client, the VP of North American Sales, comes to me with a problem. Her SDRs and AEs waste dozens of hours each week manually creating lists of target personas. They use Hubspot as their CRM and have thousands of companies categorized into industries, but industries aren’t specific enough to personalize messaging with. The VP of Sales is wondering if my team can automatically generate a lists of personas for the sales team to use for targeted outreach. The time savings will be an estimated 12,000 hours a week across the org!</p><p>How is a copilot helpful in my process?</p><p><strong>Brainstorming and Planning</strong></p><p>Copilots are great brainstorming partners. They are capable of generating diverse architectural options. They analyze requirements, suggest optimal data flow models, identify bottlenecks, recommend technologies, provide real-time feedback, and streamline the ideation process for a robust, efficient, and scalable pipeline design.</p><p>They can help you explore your options: what data sources are available? what format is the data in? is this real-time or batch? what are the scale constraints?</p><p>Using the example above, I could start a brainstorming session with my copilot by asking:</p><ul><li>You are an experienced data architect tasked with helping me, a data engineer, design a data pipeline that creates prospect batches and personalized outreach emails for the sales team. Using our current data architecture and the attached PRD draft, generate 3 high level design approaches to achieve the goal and describe the tradeoffs of each.</li><li>What does the response object look like for the Hubspot lists API?</li><li>What data sources could be useful for {PROJECT_OVERVIEW}?</li></ul><p><em>Copilot features</em></p><ul><li>Automatic retrieval of relevant information such as architectural diagrams, architectural components documentation (i.e. Databricks docs), system documentation, product requirements document, sales systems (i.e. Hubspot, Apollo, Microsoft Outlook, etc).</li><li>Custom, role-specific system prompt</li><li>Inline document rewrite, feedback, and initial draft</li></ul><p><strong>Answering questions</strong></p><p>Copilots can utilize the general knowledge of the underlying LLM to answer all kinds of questions related to data engineering. But unlike LLMs, copilots have access to local context such as table schemas, data warehouse configurations, and data lineage.</p><p>Working off the example use case, the copilot can help with a myriad of different questions. For instance, I want to learn how I can plug into Hubspot.</p><ul><li>Does Hubspot have a Python SDK?</li><li>What API endpoints does Hubspot have?</li><li>What are the required parameters for Hubspot’s /cms/v3/hubdb/?</li></ul><p><em>Copilot features</em></p><ul><li>Automatic retrieval of Hubspot documentation including the developer documentation</li><li>Creating and executing Hubspot’s API requests</li><li>Rendering graphs and charts</li></ul><p><strong>Generate code</strong></p><p>The first task is to retrieve all computer software companies from Hubspot. I’ve never used the Hubspot API before and will rely on my Copilot to figure out the exact syntax.</p><ul><li>Use the python sdk to retrieve all computer software companies in Hubspot and write them into a list of company ids, industries, and descriptions. Be mindful that it may take multiple calls to get ids, industries, and descriptions. Count the total number of companies at the end.</li></ul><p><em>Copilot features</em></p><ul><li>Retrieval across Hubspot API documentation</li><li>Creating and executing Hubspot’s API requests</li><li>Code autocomplete</li></ul><p><strong>Debug queries</strong></p><p>Copilots can significantly aid in debugging errors by quickly analyzing code to identify and diagnose issues, suggesting potential fixes based on patterns from extensive datasets. It can also provide real-time recommendations and highlight error-prone areas, enabling data engineers to resolve problems more efficiently. This streamlines the debugging process, reducing downtime and improving overall productivity.</p><p>The copilot does an outstanding job in one-shot, but the count of software companies in Hubspot is 0 which can’t be correct. I could troubleshoot myself… or I could put it on the copilot to figure out.</p><ul><li>(User) The total number of software companies is not 0. The code has a problem. Add in tests to help me troubleshoot.</li></ul><p><em>Copilot features</em></p><ul><li>Automatically add error message and files to context</li><li>Auto debugging</li></ul><p><strong>Optimize queries</strong></p><p>The last mile is usually the hardest. Copilots can optimize slow queries by analyzing query performance, identifying bottlenecks, and suggesting efficient query modifications. It can recommend indexing strategies, query restructuring, and alternative approaches to improve execution times. This enables data engineers to enhance database performance and achieve faster query results with minimal manual effort.</p><ul><li>(User) “Please analyze my query and suggest optimizations to improve its performance. Refer to the [COMPANY] Query Performance Guide.</li></ul><p><em>Copilot features</em></p><ul><li>Automatically add query draft and table schemas to context</li><li>Retrieval from proprietary data source</li></ul><p>ChatGPT does a great job for many one-off tasks, but there’s much to be desired of a true assistant.</p><h3>Copilots for Data Engineering</h3><p>Copilots are much better at helping with data engineering tasks because they are embedded in your application, context-aware, automatically connected to various data sources, and can take actions.</p><p><a href="http://continual.ai/">Continual.ai</a> makes it easy to build, manage, and continually improve AI Copilots. Come check us out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=657476089be9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How-to configure Sagemaker with Github Actions]]></title>
            <link>https://medium.com/@brendan.mckenna/how-to-configure-sagemaker-with-github-actions-60e0d15f3d60?source=rss-845c262a6ac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/60e0d15f3d60</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Brendan McKenna]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 20:48:34 GMT</pubDate>
            <atom:updated>2023-04-25T20:48:34.229Z</atom:updated>
            <content:encoded><![CDATA[<p>GitHub Actions is a powerful continuous integration and continuous delivery (CI/CD) platform that allows developers to automate build, test, and deployment pipelines. Workflows automatically build and test code whenever an event occurs, such as a pull request or a deployment of merged pull requests to production. Best of all, you can use it without leaving the comfort of your own repository!</p><p>Since its release in 2018, Github Actions is a popular CI/CD choice for Machine Learning Engineers and Data Scientists. But for users of one of the most common ML platforms,<a href="https://aws.amazon.com/sagemaker/"> AWS SageMaker</a>, granting Github permission to automate ML workflows is an arduous first task. However steep the climb, there’s ample motivation to configure these two together. SageMaker users can leverage GitHub Actions to automate the entire machine learning workflow, from development to operations. This includes automating data preprocessing tasks, creating and submitting training jobs to SageMaker, and deploying trained models directly into production environments where they can be used for real world applications such as drug discovery, fraud detection or recommendation systems. Using GitHub Actions to automate your machine learning lifecycle saves time and improves accuracy through automated testing along each step in the pipeline process. It’s worth the initial setup and the purpose of this post is to step you through how to do just that.</p><p>There are two options to configure AWS credentials on GitHub Actions. The first is easier but less secure and often doesn’t meet organizational security requirements. The second option requires more up-front work but is more secure and recommended by AWS and security experts.</p><h3>Option 1: Saving IAM credentials as secrets in GitHub</h3><p>The first option is to save the IAM access key and secret of a SageMaker user as a GitHub Actions repository secret. This isn’t generally recommended because it requires you to create credentials in AWS <em>and then</em> <em>duplicate</em> them in GitHub as a secret. However it’s the easiest method to hookup GitHub Actions and SageMaker.</p><p>Each of the following steps are well-trodden so I’ll link to these tasks for you to complete on your own:</p><p>1a. <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/security-iam.html">Create an IAM user and role for SageMaker</a></p><p>1b. <a href="https://docs.aws.amazon.com/keyspaces/latest/devguide/access.credentials.html">Create an IAM user access key and secret</a></p><p>1c. <a href="https://docs.github.com/en/actions/security-guides/encrypted-secrets#creating-encrypted-secrets-for-a-repository">Add the IAM user access key and secret to Github Actions as Secrets</a></p><p>1d. [Optional] Add the AWS region as a secret</p><p>Once the AWS credentials are saved in GitHub, you can configure your credentials in your Github workflow using aws-actions and the saved secrets.</p><p>1e: Add the action to your GitHub workflow yaml:</p><pre>- name: Configure AWS Credentials<br>  uses: aws-actions/configure-aws-credentials@v1<br>  with:<br>    aws-access-key-id: ${{secrets.AWS_ACCESS_KEY_ID}}<br>    aws-secret-access-key: ${{secrets.AWS_SECRET_ACCESS_KEY}}<br>    aws-region: ${{secrets.AWS_REGION}}</pre><h3>Option 2: Use short-lived credentials via OIDC</h3><p>If you can get away with Option 1 in your business, just know you live the good life because storing AWS credentials in GitHub repos, as simple as it is, is not generally recommended. The more secure option is to use <a href="https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect">OpenID Connect (OIDC)</a> to request short-lived credentials for your workflow each time it runs.</p><p>OpenID Connect (OIDC) is a protocol built on top of the OAuth 2.0 protocol for authenticating users. You can configure IAM to establish a trust between an OIDC-compatible identity provider and your AWS account and generate short-lived credentials for your Github workflow to access AWS resources. As soon as your Github workflow completes, the credentials expire and cannot be reused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sYLxzRqVngNt4PJUMlvfg.png" /></figure><p>There are many OIDC-compatible identity providers you can use such as Google, Facebook, or Amazon Cognito, but since we’re already using GitHub Actions we will use GitHub.</p><h3>2a: Add GitHub as an identity provider to IAM</h3><p>The first step is to <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html">add GitHub as a federated identity provider in IAM</a> to create trust.</p><p>Go to <a href="https://console.aws.amazon.com/iam/">https://console.aws.amazon.com/iam/</a> and, in the navigation pane, choose <strong>Identity Providers</strong>, and then select <strong>Add provider</strong>.</p><ul><li>For the <strong>provider URL</strong>: Use <a href="https://token.actions.githubusercontent.com/">https://token.actions.githubusercontent.com</a></li><li>Click on<strong> Get thumbprint </strong>to verify the server certificate of our identity provider, GitHub</li><li>For the <strong>Audience</strong>: Use sts.amazonaws.com since we’re using the <a href="https://github.com/aws-actions/configure-aws-credentials">official action</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXfvVAnTmy6qpt15wroxQQ.png" /></figure><h3>2b: Create an IAM role for our identity provider</h3><p>Now you need to create a new IAM role to assign to our identity provider. This gives GitHub permission to access AWS resources in your account. Naturally we don’t want to grant <em>all</em> of GitHub permission, so set a permission scope by defining conditions. <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html">Conditions</a> in your IAM role trust policy can be set so only a specified repository, branch, or organization can request tokens from AWS.</p><ol><li>Return to <a href="https://console.aws.amazon.com/iam/">https://console.aws.amazon.com/iam/</a> and click <strong>Create Role</strong></li><li>Select <strong>Custom trust policy</strong></li><li>For the <strong>Principal</strong> element, use the string {“Federated”:providerArn} and substitute providerArn for the Amazon Resource Name (ARN) of the identity provider (GitHub) you created above</li><li>For the <strong>Condition</strong> element, add the repository or branch of your Sagemaker project to token.actions.githubusercontent.com:sub. For example, “repo:GITHUB_ORG_OR_USER/GITHUB_REPO:*”</li></ol><p>Use the following JSON for your IAM role’s trust policy. Substitute your identity provider’s ARN in for “arn:aws:iam::7000000001:oidc-provider/token.actions.githubusercontent.com” and your Github repository for “repo:GITHUB_ORG_OR_USER/GITHUB_REPO:*”</p><pre>{<br>   &quot;Version&quot;: &quot;2012-10-17&quot;,<br>   &quot;Statement&quot;: [<br>       {<br>           &quot;Effect&quot;: &quot;Allow&quot;,<br>           &quot;Principal&quot;:{&quot;Federated&quot;:&quot;arn:aws:iam::7000000001:oidc-provider/token.actions.githubusercontent.com&quot;},<br>           &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>           &quot;Condition&quot;: {<br>               &quot;StringEquals&quot;: {<br>                   &quot;token.actions.githubusercontent.com:sub&quot;: &quot;repo:GITHUB_ORG_OR_USER/GITHUB_REPO:*&quot;<br>},<br>“StringLike”: {<br>                   &quot;token.actions.githubusercontent.com:aud&quot;: &quot;sts.amazonaws.com&quot;<br>   }<br>              }<br>           }<br>       }<br>   ]<br>}</pre><p>Using <strong>role-to-assume </strong>without providing an<strong> aws-access-key-id </strong>or a <strong>web-identity-token-file</strong> to the<a href="https://github.com/aws-actions/configure-aws-credentials"> pre-built action</a> that you wish to use the OIDC provider.</p><p>5. After your role has been created, attach whatever SageMaker policy you used for your execution role. The IAM managed policy is AmazonSageMakerFullAccess.</p><h3>2c. Add permissions to your GitHub workflow</h3><p>In your Github workflow yaml, set the permissions at the workflow level:</p><pre>permissions:<br>  id-token: write # This is required for requesting the JWT<br>  contents: write  # This is required for actions/checkout</pre><h3>2d. Add the access token request to your GitHub workflow</h3><p>The aws-actions/configure-aws-credentials action receives a JWT from the GitHub OIDC provider, and then requests an access token from AWS.</p><p>Under jobs, add the action to the workflow yaml and replace the aws-region, role-to-assume, and role-session-name values with your own:</p><pre>- name: Configure AWS Credentials<br>      uses: aws-actions/configure-aws-credentials@v1<br>      with:<br>        aws-region: us-east-1<br>        role-to-assume: arn:aws:iam::765936207681:role/github-iam-role<br>        role-session-name: OIDCsession</pre><p><strong>BOOM! AWS has been configured!</strong></p><p>When your workflow is triggered, it’ll run the job and request and use a short-lived access token to execute the SageMaker job. If you are creating a SageMaker training job in script mode, you might run a python file that looks something like this:</p><pre># Create estimator<br>estimator = SKLearn(<br>    entry_point=&#39;train.py&#39;,<br>    role=role,<br>    sagemaker_session=sagemaker_session,<br>    instance_count=1,<br>    instance_type=&#39;ml.m5.large&#39;,<br>    framework_version=&#39;1.0-1&#39;,<br>    py_version=&#39;py3&#39;,<br>    source_dir=&#39;.&#39;,<br>    hyperparameters={&#39;alpha&#39;: alpha, &#39;max_depth&#39;:max_depth, &#39;eta&#39;:eta, &#39;num_class&#39;:num_class, &#39;eval_metric&#39;:eval_metric}<br>)<br><br>train_sklearn = &quot;sklearn-training-job-{}&quot;.format(int(time.time()))<br><br>estimator.fit(job_name=train_sklearn)</pre><p>Because of the AWS action in my workflow, the python file will be able to submit the training job to SageMaker.</p><p><strong>Helpful Links</strong></p><p><a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html">AWS: Creating and managing an OIDC provider (console)</a></p><p><a href="https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services">GitHub: Configuring OpenID Connect with AWS</a></p><p><a href="https://github.com/aws-actions/configure-aws-credentials">AWS-Actions</a></p><p><a href="https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/">Elias</a>: AWS Deploys with Github Actions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60e0d15f3d60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying DNA Sequences into Gene Families on SageMaker]]></title>
            <link>https://medium.com/@brendan.mckenna/classifying-dna-sequences-into-gene-families-on-sagemaker-aaa01c2bacf1?source=rss-845c262a6ac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaa01c2bacf1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[genomics]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Brendan McKenna]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 21:35:39 GMT</pubDate>
            <atom:updated>2023-04-11T21:35:39.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nwJX5W7_kwyef_m0" /></figure><p>The cost of DNA sequencing continues to decline exponentially. With the average cost of sequencing mammalian DNA hovering around $1,000 in the beginning of 2023, startups like <a href="https://www.ultimagenomics.com/">Ultima Genomics</a> and <a href="https://www.illumina.com/">Illumina</a> are working to decrease the cost to between $100-$200. That’s about the same as a new pair of <a href="https://www.brooksrunning.com/en_us/">Brooks running shoes</a>! As the sequencing cost drops, the quantity of genetic data to study and analyze explodes, making it even more important to leverage machine learning techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OMTWw8sen-oHf8ak" /></figure><p>An important biology use case for machine learning is classifying genes into gene families (also known as protein families if the gene encodes a protein). A gene family is a set of functionally similar genes that share a common ancestral gene. When a gene is duplicated, both copies accumulate mutations over time resulting in similar but different functions. Genes are often categorized into families based on shared nucleotide or protein sequences, but designing molecular phylogenetic techniques is a sprawling area of research and there are more sophisticated approaches.</p><p>Studying gene families is important in understanding the function and evolution of genes. For example, researchers might infer that a newly discovered gene that belongs to a family might serve a similar function. Or it might be useful in drug discovery as researchers can target specific gene families to increase the range of potential therapeutic applications.</p><p>In this tutorial, we’re going to step through a basic example of gene family classification using SageMaker and Continual. The tutorial is intended for Data Scientists and Machine Learning Engineers who are new to SageMaker.</p><h3>Enter the SageMaker</h3><p>SageMaker is one of the most popular machine learning platforms on the market. Companies like <a href="https://aws.amazon.com/solutions/case-studies/AstraZeneca-case-study/?p=pm&amp;c=ml&amp;pd=sm&amp;z=5">AstraZeneca</a>, <a href="https://aws.amazon.com/solutions/case-studies/bp-machine-learning-case-study?p=pm&amp;c=ml&amp;pd=sm&amp;z=5">bp</a>, and <a href="https://aws.amazon.com/solutions/case-studies/autodesk-expanding-insights-case-study?p=pm&amp;c=ml&amp;pd=sm&amp;z=5">Autodesk</a> use SageMaker to develop and deploy their machine learning (ML) use cases. SageMaker has compounded into a daunting number of services. There’s <a href="https://aws.amazon.com/sagemaker/data-wrangler/">Data Wrangler</a> for exploring and analyzing data, <a href="https://aws.amazon.com/sagemaker/clarify/">Clarify</a> for monitoring fairness and bias, <a href="https://aws.amazon.com/sagemaker/edge/?sagemaker-data-wrangler-whats-new.sort-by=item.additionalFields.postDateTime&amp;sagemaker-data-wrangler-whats-new.sort-order=desc">Edge Manager</a> for deploying models at the edge, and so much more. I’m not exaggerating when I say it’s a hairy, overwhelming mess to newcomers. But at its core SageMaker combines EC2, S3, Docker images, and managed notebooks for an easy and flexible platform for training and deploying ML use cases.</p><h3>How SageMaker works</h3><p>Once we sift through the layers of different services and features, what does SageMaker actually do and how does it work?</p><p>There are 4 essential resources required to build any ML use case (don’t @ me):</p><ol><li>Data</li><li>Code</li><li>Environment</li><li>Compute</li></ol><p>SageMaker uses 4 core services:</p><ol><li><strong>S3 </strong>to store data and model artifacts</li><li><strong>Studio</strong> to write and store code</li><li><strong>Elastic Container Registry (ECR)</strong> to store pre-built SKLearn Docker images for the training environment</li><li><strong>EC2</strong> with ML compute instances to run training</li></ol><p>Users can open <a href="https://aws.amazon.com/sagemaker/studio/">SageMaker Studio</a> through the AWS console and write their code in notebooks, shell scripts, or Python files. In Studio, users can create training and inference jobs for SageMaker to run in Docker images on EC2. SageMaker handles this execution process and even offers pre-built Docker images with popular frameworks, algorithms, and libraries. Users can also build their own images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*YgfKPE7RtpSbUAH4" /></figure><p>SageMaker offers 2 SDKs for using its API:</p><ol><li><strong>Amazon SageMaker Python SDK</strong>: an open source package for training and inference jobs on SageMaker</li><li><strong>AWS SDK for Python (Boto3)</strong>: a general purpose SDK for AWS services</li></ol><p>Both provide a higher-level, more convenient interface for interacting with SageMaker than the API. Plus, the SDKs provide additional features like retries, better error handling, and more options in terms of parameters and methods which could be helpful in certain use cases.</p><p>But which SDK is better to use? Honestly, it’s likely you’ll use a combination of both for your use case.</p><p>Boto3 makes it easy to integrate your Python app or script with AWS services. It offers an interface to create, configure, and manage <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html">more than a hundred AWS services</a> such as S3, CloudFront, and EC2. For Boto3, SageMaker is just another service, whereas the SageMaker Python SDK is built specifically for SageMaker.</p><p>With Boto3, you can use it to create, start, and monitor SageMaker Training jobs. It’s easy to configure training jobs, such as setting the input data location, the number of training instances, and other parameters. You can create and manage SageMaker model endpoints, notebook instances, hyperparameter tuning jobs, and more. Because it’s a little more general-purpose than the Python SDK, it’s great for highly customized use cases and for specific tasks like reading/writing data to/from S3.</p><p>Why would we use the Python SDK?</p><p>SageMaker heavily leverages containers to run training and inference jobs on arbitrary compute resources. The SageMaker Python SDK offers a more intuitive interface for working with SageMaker, and abstracts away the tedious work of maintaining Docker images. SageMaker offers pre-built and maintained images for popular frameworks like PyTorch, TensorFlow, and <a href="https://sagemaker.readthedocs.io/en/stable/sagemaker.sklearn.html">Scikit Learn</a>. The SageMaker Python SDK allows you to retrieve these images to run your training code without building and maintaining your own docker image by using an estimator object. Then, for deployment, the SageMaker SDK takes care of model and endpoint configuration creation using the parameters that were passed into the estimator at training time. You can directly deploy to an endpoint using a simple “deploy” API call.</p><p>The SageMaker Python SDK relieves users of building, maintaining, and retrieving Docker images via built-in frameworks. Users can create and run a custom algorithm in SageMaker Training by using script mode. Instead of SageMaker running the training automatically, script mode allows the user to implement their only training script. In this example, we’ll use script mode to train two different algorithms, compare the results, and deploy the better performing model.</p><p>Users don’t even have to write training code if they don’t want to! Built-in algorithms are just images with the algorithms and supporting code ready-to-use. Users only need to point the built-in algorithms at their dataset and start the training job as shown in <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-train-model.html">this documented example</a>.</p><p>For built-in algorithms, all a user needs to do is specify:</p><ol><li>URL of the S3 bucket where the training data is stored</li><li>The compute resources to be used</li><li>URL of the S3 bucket where output is to be stored</li><li>Elastic Container Registry (ECR) path where the training code is stored</li></ol><p>So, yeah, the SageMaker Python SDK makes things easier. But the limitations of the SageMaker Python SDK present themselves when you don’t want to use one of the SageMaker supported frameworks.</p><p>In this example, we’ll use the following SageMaker services for this use case:</p><ul><li>SageMaker Python SDK for training and inference jobs</li><li>Boto3 to access data from S3</li><li>S3 to store data</li><li>SageMaker Studio for a notebook to create and launch our training job</li><li>Pre-built Scikit Learn Docker image hosted on Elastic Container Registry (ECR) for the training environment</li><li>ML compute instances (EC2) to run training</li></ul><h3>Putting it all together</h3><p>SageMaker can be daunting to the uninitiated. Now that we’ve narrowed the scope to the precise SageMaker services we’re using for this simple example, we can tie it all together.</p><p>There are 5 steps to this example:</p><ol><li>Upload human DNA to S3</li><li>Create a SageMaker domain in the AWS Console</li><li>Use the SageMaker Python SDK to create an Estimator object for our training job in SageMaker Studio</li><li>Create a custom training script in SageMaker Studio</li><li>Deploy an endpoint for real-time inference</li></ol><h3>Preparing Data</h3><p>I used the human DNA data from a <a href="https://www.kaggle.com/datasets/nageshsingh/dna-sequence-dataset">DNA sequence dataset from Kaggle</a> for this tutorial. Like most Kaggle datasets, this one is already clean and won’t require many transformations before we can pass it into an algorithm for training. There are many publicly available DNA datasets available on Kaggle, but another place to find data is on the <a href="https://www.ncbi.nlm.nih.gov/nuccore/CM000663.2?report=fasta">National Center for Biotechnology Information</a>’s website.</p><p>The dataset consists of 4,380 sequences and their corresponding gene class. Classification algorithms require data to be numerical and the dataset in string format. There are 3 options to encoding DNA data: ordinal encoding, one-hot encoding, and k-mers counting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*9TT6SyTK6GbwdvvqgCYuqA.png" /></figure><p>Ordinal encoding is a method of encoding categorical variables (variables that have a limited number of distinct values) as integers. The basic idea behind ordinal encoding is to assign a unique integer value to each category in a categorical variable. The integer values are chosen such that they reflect the ordinal relationship between the categories (in this case, nucleotides). For example, A=0.25, C=0.50, G=0.75, T=1.00, and n=0.00. Ordinal encoding is not always a good method because, in many cases, nucleotides don’t have an inherent ordinal relationship, and encoding them as integers would not convey any meaningful information.</p><p>Another approach is one-hot encoding which is widely used in deep learning. For DNA sequencing, “ATGC” would become [0,0,0,1], [0,0,1,0], [0,1,0,0], [1,0,0,0].</p><p>K-mers is a popular approach in bioinformatics because it’s used for genome assembly and error handling. When a genome is sequenced it’s done so in “reads” or DNA subsequences. Reads are overlapping so scientists know how to connect the subsequences together and create the full genome assembly. This approach is important, not only because of the read limitation, but also because it helps with error handling. Reading DNA is an error prone process and many nucleotides are read incorrectly. When assembling a genome, scientists can analyze whether a read is accurate based on whether it has overlap with other subsequences.</p><p>K-mers also solves the problem of ensuring data input is of uniform length which is a requirement for classification algorithms. For the previous two methods, ordinal encoding and one-hot encoding, it’s common to pad the data to make each input of uniform length. With K-mers we don’t need to do that because our data has been split into k-mers of the same length.</p><p>First, we can read data from S3 using the Boto3 client:</p><pre>s3 = boto3.client(&#39;s3&#39;)<br>obj = s3.get_object(Bucket = ‘BUCKET_NAME’,Key = &#39;dna_sequence_dataset/human.txt&#39;)<br>dna_data = pd.read_csv(obj[&#39;Body&#39;],sep=&#39;\t&#39;)</pre><p>Then, we can run our dataset through a function like this:</p><pre>def kmer(sequence, k=5):<br>  return [sequence[x:x+k].lower() for x in range(len(sequence) - k + 1)]</pre><h3>Creating a Training Job with the SageMaker Python SDK</h3><p>For our training job, we’ll use the SageMaker Python SDK to create an Estimator object in a SageMaker Studio notebook. An Estimator is a high-level interface for training and deploying ML models in SageMaker. We’ll use the pre-built SKLearn image created and maintained by SageMaker to avoid the hassle of building our own image, uploading it to the Elastic Container Registry, and specifying its location to our estimator object.</p><p>Not only does SageMaker offer pre-built images, but also pre-built algorithms. We could simply specify our input data and pass it to SageMaker and it would do the rest. But because we want more control over the training process, we’ll use “<a href="https://aws.amazon.com/blogs/machine-learning/bring-your-own-model-with-amazon-sagemaker-script-mode/">script mode</a>” and pass a training python script arbitrarily called run.py and write custom training and inference code.</p><pre>estimator = SKLearn(<br>    entry_point=&#39;run.py&#39;,<br>    role=role,<br>    sagemaker_session=sagemaker_session,<br>    instance_count=1,<br>    instance_type=&#39;ml.m5.large&#39;,<br>    framework_version=&#39;1.0-1&#39;,<br>    py_version=&#39;py3&#39;,<br>    source_dir=&#39;.&#39;<br>)</pre><p>Once an estimator object is created, calling “fit” on the estimator object will spin up a compute instance, start the pre-built Scikit Learn container, and execute the training script.</p><pre>train_sklearn = &quot;sklearn-training-job-{}&quot;.format(int(time.time()))<br><br>estimator.fit(<br>    job_name=train_sklearn,<br>)</pre><h3>Experimenting with two algorithms and tracking with Continual</h3><p>Experimentation to understand the behavior and performance of different algorithms and approaches is often an important part of production ML use-case development. Continual is an ML delivery platform that makes it easy to automate testing, monitoring and governance across the production ML development life cycle. It’s simple to use Continual with SageMaker and other ML development platforms to add a useful layer of visibility, automation and control to your production ML pipelines.</p><p>The run.py training script can do whatever we want. In this case, the script reads data from s3, transforms it into kmers as described in the Data section, and executes two experiments to evaluate which algorithm will perform better. One experiment uses the Multinomial Naives Bayes classifier while the second experiment uses XGBoost.</p><p>I’m using Continual to track everything in the training script: my input dataset, model training performance metrics for two different algorithms, and evaluation artifacts. This way I can open app.continual.ai to see how my model training performs over time.</p><h3>Deployment on SageMaker</h3><p>SageMaker offers multiple deployment options depending on your requirements.</p><ol><li>Real-time: persistent endpoint for single predictions</li><li>Serverless: cold start endpoint when higher latency is okay</li><li>Asynchronous: specialized for larger payloads, longer processing time, and near real-time requirements</li><li>Batch: processing job for making predictions on an entire dataset</li></ol><p>Classifying gene families follows the sequencing of a new genome which means a batch prediction job would meet our requirement. In SageMaker, this is handled with a Transformer object. Transformer objects can be used for other batch processing tasks like pre-processing data.</p><pre>transformer = estimator.transformer(instance_count=1, instance_type=&#39;ml.m4.xlarge&#39;, output_path=&quot;S3_URI&quot;)<br>transformer.transform(&#39;S3_URI, content_type=&quot;text/csv&quot;, split_type=&quot;Line&quot;)<br>transformer.wait()</pre><p>Real-time is much different. If our use case had real-time requirements then we could deploy a persistent or cold-start endpoint. Just because it’s a little more fun, let’s deploy a real-time endpoint as the last step.</p><pre>model = estimator.create_model()<br><br>predictor = estimator.deploy(initial_instance_count=1,instance_type=&#39;ml.m4.xlarge&#39;,endpoint_name=’prod-endpoint&#39;)</pre><h3>Conclusion</h3><p>We’ve only scratched the surface of SageMaker and there’s much more it can do. The core platform makes data processing, model training, inference, and deployment easier and customizable by utilizing Docker images loaded with the most popular ML frameworks, S3 storage, and specialized ML compute. We’ve also seen how easy it is to add a helpful layer of visibility, automation and control to the production ML development lifecycle with the Continual ML delivery platform. Please checkout the <a href="https://github.com/b-mckenna/Continual-and-Sagemaker.git">GitHub repo</a> corresponding to this project. If you have any questions or comments, email me at <a href="/service/mailto:brendan@continual.ai">brendan@continual.ai</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaa01c2bacf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Evaluation Metric]]></title>
            <link>https://medium.com/@brendan.mckenna/choosing-the-right-evaluation-metric-833adce73b22?source=rss-845c262a6ac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/833adce73b22</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[model]]></category>
            <dc:creator><![CDATA[Brendan McKenna]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 21:52:42 GMT</pubDate>
            <atom:updated>2022-02-09T21:52:42.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWIOWT6WX2_wPH2dYEI9lw.png" /></figure><p>Is your model ready for production? It depends on how it’s measured. And measuring it with the right metric can unlock even better performance. Evaluating model performance is a vital step in building effective machine learning models. As you <a href="https://cloud.continual.ai/register">get started on Continual </a>and start building models, understanding evaluation metrics helps to productionize the best performing model for your use case. While Continual’s <a href="https://continual.ai/post/getting-started-with-ci-cd-and-continual">modern gitops workflow</a> and <a href="https://continual.ai/post/introducing-continual-integration-for-dbt">smooth dbt integration</a> tend to attract attention from data teams, it’s also very important to learn how to use evaluation metrics correctly.</p><p>In this two part blog, we’ll cover Continual’s configurable evaluation metrics for optimizing and selecting the best performing model in Continual.</p><h3>What is an evaluation metric?</h3><p>A model evaluation metric is a mechanism for assessing the performance of a machine learning model. A good metric should provide an informative summary of the error distribution. An ideal metric would be reliable, computationally and conceptually simple, scale-independent, outlier protected, and sensitive to changes. No single metric outperforms all others across this criteria. Therefore, it’s recommended to consider multiple metrics when selecting a model. By understanding the strengths and limitations of each metric, we are more likely to use them effectively.</p><p>Different problems require different classes of metrics. For example, for classification problems, accuracy can be a useful metric because we want to know how often the model predicts the correct class. But accuracy is not useful when making a value prediction for, say, a dollar amount or inventory supply because the target values are continuous and not discrete. Instead, for regression problems, we want to measure how close our predictions are to the actual values.</p><p>In part 1, we’ll cover 4 evaluation metrics used for <a href="https://en.wikipedia.org/wiki/Regression_analysis">regression</a> problems. In part 2, we’ll cover the 4 main metrics for <a href="https://en.wikipedia.org/wiki/Statistical_classification">classification</a> problems.</p><h3>Evaluation Metrics for Regression</h3><h3>Mean Absolute Error (MAE)</h3><p>The <strong>Mean Absolute Error (MAE) </strong>is simply the average distance between the model’s predicted values and the actual observed values. It disregards the direction of the error (whether it’s positive or negative) and computes the average distance. The lower the score the better. Its simplicity makes it easy to compute and to understand, even for business stakeholders which is a huge advantage. MAE is very popular for time series use cases. Nice and simple, right? What’s not to like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*k_N2ZkB4I5NjhlWT.png" /></figure><p>Well, in its grand simplicity MAE treats every error the same no matter how small or how large. It’s hard to knock fairness but for use cases where extreme values are intolerable or even dangerous, another metric like RSME might be better suited. For example, a nuclear power plant device controller setting the temperature too high would be literally disastrous. But forecasting a music concert attendance too high wouldn’t be the end of the world.</p><p>When interpreting MAE it’s important to remember it’s scale-dependent; the size of the error is relative to the training data scale. This means interpreting the magnitude of the error depends on the context of the problem. For example, if you are predicting house prices then the MAE value would be in hundreds, tens of thousands, or millions of dollars. But if you’re predicting the volume of houses sold in a city then your MAE error will be in the hundreds or maybe thousands. It’s recommended for assessing model performance on a single problem series, but not adequate for comparing different series of different units.</p><p>For training models, the units we’re using aren’t terribly important because we only need to know whether we’re decreasing or increasing the error at each iteration. We care more about the relative size of the error. But when evaluating trained models, as you would on Continual, we do care about what units we’re using because we want to know whether the trained model is adequately solving our real-world problem.</p><p>MAE is a simple metric to evaluate the performance of your model but it’s important to be mindful of its scale-dependence and handling of outliers.</p><h3>Symmetric Mean Absolute Percentage Error (sMAPE)</h3><p>To help us understand sMAPE, lets first talk about its predecessor: Mean Absolute Percentage Error (MAPE).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*DEdouw5WTWnXZIOg.png" /></figure><p>Just like MAE, MAPE calculates the absolute distance between the predicted values (F) and the actual values (A) but then divides the distance by the actual, outputting a percentage. Expressing the error as a percentage makes it easy to compare model performance across different scales. This is helpful for situations like forecasting inventory for various product SKUs. The business can rely on a consistent error percentage across different products of various price ranges, for example, a cheaper product like a laptop charger and a more expensive product like the laptop itself.</p><p>A problem with MAPE occurs when actual values are at, or close to, zero. In such a case, MAPE will output infinite or undefined values. Because zeros are common in many use cases, such as intermittent sales in a sales forecast, this is a severe limitation.</p><p>Symmetric MAPE was created to fix this problem by dividing the numerator by half the sum of the absolute values of the actual value (A) and the predicted value (F). Effectively, when either the actual or predicted value is at or close to zero, the sMAPE score will automatically hit its upper bound at 200%, instead of breaking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*c0uaO0HTV2ySopK9.png" /></figure><p>The lower the score the better the prediction. But when interpreting the score, keep in mind it’s not perfectly symmetric. It penalizes positive errors (actual &gt; predicted) <em>more than </em>negative errors (actual &lt; predicted). For example, if our actual value = 100 and predicted value = 120 then sMAPE score is 18.2%. But if actual value = 100 and predicted value = 80, then sMAPE comes out to 22.2%.</p><p>Okay, so, we’ve covered sMAPE and MAE so far. Both are useful in cases where you aren’t worried about large errors. But when large errors are less tolerable, RMSE is your metric!</p><h3>Root Mean Squared Error (RMSE)</h3><p>Suppose there’s a model that predicts when the best time to deploy coolant in a nuclear power plant is. If the model forecasts too late, it could cause a literal disaster! In such a case, it’s probably good to penalize large errors.</p><p>Whereas sMAPE and MAE penalize errors proportionally, <strong>Root Mean Squared Error (RMSE)</strong> does it quadratically by squaring the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aNWLqpswHMm6XkTK.png" /></figure><p>But that doesn’t mean the units of measure are squared. RMSE takes the square root of the error, effectively converting it back to the original scale. For example, if you’re working on a digital marketing use case and your target variable is using “impressions” as a unit, then the RMSE error will also have the “impressions” unit, not “squared impressions”. Pretty nifty, eh?</p><p>The last thing to know about RMSE is it’s dataset-dependent, so it shouldn’t be used to compare across datasets. It’s better used to measure the effectiveness of the model fit per dataset and reference MAE or sMAPE for comparison purposes.</p><p><strong>R² Coefficient of Determination</strong></p><p>R², also known as the coefficient of determination, is a ratio between the <a href="https://en.wikipedia.org/wiki/Variance">variance</a> explained by the model and the total variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*PWYmJzv1S82tIJYa.png" /></figure><p>The numerator is calculated by the sum of the distance between the actual values and the best fitted line (model). The denominator is similar, but instead of finding the sum of the distance between the actual values and the best fitted line, we’re finding the distance to the mean.</p><p>The best possible score is 1.0 which means the model explains 100% of the variance and the fitted values would always equal the actual values. In other words, the independent variables explain all of the variance in the data. Conversely, if the model is zero it means it doesn’t explain any of the variance. R² can be negative because the model can be arbitrarily worse and fits the data <em>worse </em>than the mean.</p><p>When interpreting the R² error, be mindful of its propensity to be fooled. Just like any metric it has its vulnerability points and can give a high score for a bad model or a low score for a good model. It can be influenced by simply changing the range of our independent variables. And a low score might just be because it’s evaluating a non-linear model (R² is only valid for linear models). There’s a lot of ways the metric can be wrong and consequently it’s recommended to use other statistical measures to get a fuller view of your model.</p><p>Oh and don’t forget R² is dataset-dependent (after all it is a measure of variance). It isn’t ideal to use to compare across series, just like RMSE isn’t.</p><h3>Evaluation Metrics in Continual</h3><p>Now that we’ve gone through the evaluation metrics for regression problems, let’s take a look at how they’re used in Continual.</p><p>Continual calculates multiple evaluation metrics and uses a default metric to compare performance by and select the best performing model.</p><p>In Model Overview, the evaluation metrics are displayed for the currently promoted model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D8fOQrr8Wyvelexn.png" /></figure><p>Model Version shows the metrics for each model trained and how the winning model compares to the previous version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*21WoMWq7DR1NRLaO.png" /></figure><p>Users can set the default metric Continual will use to evaluate and select models in either the UI or CLI.</p><h3>Setting a default metric in the UI</h3><p>When creating or editing a model, click the Performance Metric dropdown in the “Review Policies” step and choose the metric you want to use. When Continual trains, tests, and evaluates different models for your use case, it’ll choose the model that performs best against the metric you set in the “Review Policies” step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SESliHQkVLxPXreG.png" /></figure><h3>Setting a default metric in the CLI</h3><p>To define a default metric from the CLI, edit your model YAML file with the metric of your choosing. Here I’m using root mean squared error (RMSE) as my default metric, but alternatively I could’ve listed ‘mae’ or ‘r2’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vbHJB4-ALRE37KQG.png" /></figure><p>After updating the YAML, push the new model to Continual:</p><pre>continual push example.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tnoar6wTrnZ_vuOK.png" /></figure><p>For any guidance on using the CLI, checkout our <a href="https://docs.continual.ai/cli/">documentation</a>.</p><h3>Part 2: Evaluation Metrics for Classification Problems</h3><p>In our next post, we’ll discuss the evaluation metrics used for classification problems and show how users can build better performing classification models by using the right metric for their problem.‍</p><h3>Are you new to Continual?</h3><p>Give it a whirl by <a href="https://cloud.continual.ai/register">signing up for a free trial.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833adce73b22" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>