<?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 Quantiphi Inc. on Medium]]></title>
        <description><![CDATA[Stories by Quantiphi Inc. on Medium]]></description>
        <link>https://medium.com/@datalab_70093?source=rss-bed61d3313b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3ea7PUhqmrv8KJgR3Vpv8Q.jpeg</url>
            <title>Stories by Quantiphi Inc. on Medium</title>
            <link>https://medium.com/@datalab_70093?source=rss-bed61d3313b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:36:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@datalab_70093/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[Unlocking the Potential of User-Delegated SAS for Storage Account Access through Web or Native Apps]]></title>
            <link>https://medium.com/@datalab_70093/unlocking-the-potential-of-user-delegated-sas-for-storage-account-access-through-web-or-native-apps-f342c4f1f906?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f342c4f1f906</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[azure-storage-account]]></category>
            <category><![CDATA[shared-access-signature]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 13:21:18 GMT</pubDate>
            <atom:updated>2024-02-22T13:21:18.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2DkahKllPzPlHmBr" /></figure><p><em>A </em><strong><em>S</em></strong><em>hared </em><strong><em>A</em></strong><em>ccess </em><strong><em>S</em></strong><em>ignature (SAS) token is a secure, time-limited token that allows you to grant delegated access to an Azure Storage Account. In today’s world, secure sharing of data amongst customers and stakeholders has become a key requirement. So, in this article, we’ll look at the most recommended and secure method of creating a SAS token with User-Delegation SAS.</em></p><p>An SAS token can be generated for a specific resource, such as a storage account or a queue, and can be configured to allow different types of access, such as read-only or read-write. The token includes a signature that is verified by Azure when the client makes a request, and the token can be set to expire after a certain period. This allows you to control and manage access to your Azure Storage Account in a granular and secure way.</p><p>An SAS token is created by an SAS issuer, typically an application or service that has access to the resource that the token provides access to. This can be useful for scenarios such as allowing a third-party application to access your storage account for a limited period, or for allowing a client application to read the blobs from the storage account without having to share the connection string for the blob container.</p><p>Azure Storage account SAS (Shared Access Signature) is useful for a few reasons:</p><ul><li><strong>Controlled access:</strong> SAS tokens allow you to grant granular access to specific resources in your storage account, such as a container or a blob, without having to share the primary key or connection string of the storage account. This gives you greater control over who can access your data and what actions they can perform on it.</li><li><strong>Secure access:</strong> SAS tokens include a signature that is verified by Azure, ensuring that only authorized clients can access the resources. Additionally, SAS tokens can be set to expire after a certain period, providing an additional layer of security.</li><li><strong>Flexible access:</strong> SAS tokens can be created with different permissions such as read, write, delete, and list and can be used in combination with other Azure authentication and authorization mechanisms such as Azure AD.</li><li><strong>Cost-effective:</strong> Using SAS tokens to grant access to specific resources in a storage account can be more cost-effective than granting access to the entire storage account or creating multiple storage accounts.</li><li><strong>Easy to implement:</strong> SAS tokens can be easily implemented in both REST and SDK interfaces of Azure Storage and are supported by many Azure SDKs, libraries, and tools.</li></ul><p>All these features make SAS tokens a powerful and flexible way to control and secure access to your Azure Storage resources, and are widely used in various scenarios like, data sharing, data distribution, and data archival.</p><p>There are three types of SAS (Shared Access Signature):</p><ul><li><strong>Account SAS:</strong> An account SAS delegates access to resources in one or more of the storage services and is secured with the storage account key</li><li><strong>Service SAS:</strong> It is secured with the storage account key. A service SAS delegates access to a resource in only one of the Azure Storage services: Table Storage, Blob Storage, Queue Storage, or Azure Files.</li><li><strong>User-Delegation SAS:</strong> A user delegation SAS is secured by Azure Active Directory (Azure AD) credentials as well as the permissions assigned to the SAS. It only applies to Blob storage.</li></ul><h4><strong>User-Delegation SAS</strong></h4><p>User-delegated SAS (Shared Access Signature) is considered more secure and important because it allows for granular control over access to specific resources within a storage account. With user-delegated SAS, a specific user/managed identity/group or service principal is given a SAS token with a defined set of permissions for a specific resource or set of resources. This allows for a more fine-grained level of access control, as opposed to using a SAS token that provides access to all resources within a storage account. Additionally, user-delegated SAS tokens have a defined expiration time, further increasing security.</p><p>User-delegated SAS tokens are also beneficial because they allow for easy revocation of access. If a user’s access to a resource is no longer needed, the SAS token associated with that user can be easily revoked without affecting access for other users.</p><p>Another advantage of user-delegated SAS tokens is that they can be used to provide access to resources to users who are external to the organization. This can be useful in situations where external partners or collaborators need to access specific resources, but should not have access to the entire storage account.</p><p>Additionally, user-delegated SAS tokens can provide access to resources in a cross-account scenario, allowing you to share resources with other Azure subscriptions or storage accounts without providing them with your storage account key.</p><p>In summary, user-delegated SAS tokens are more secure and important because they provide a more granular level of access control, allow for easy revocation of access, and can be used to share resources with external users and cross-account scenarios.</p><p>Let’s go over a scenario where we grant access to the storage account from a web/native application registered in Azure AD using user-delegation SAS. The following schematic diagram describes the user-delegated SAS token creation flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qXy05yAdQsv1AqkH" /></figure><ol><li><strong>Register an application in Azure AD</strong></li></ol><p>This creates an application object in Azure AD, which is used to authenticate the web application and obtain an access token.</p><p>Follow these steps to create an app registration:</p><ol><li>Sign in to Azure Portal and Select the Tenant in which you want to register your application</li><li>Select App registrations &gt; New registration from Manage’s menu.</li><li>Enter the display Name for your application</li><li>Under Supported types, select Accounts in this organizational directory only</li><li>To finish the initial app registration, select Register.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NDwTwCcf_IJJvwOv" /></figure><p>The Overview pane for the app registration appears on the Azure site after registration is complete. The Application (client) ID and Tenant ID are visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WMYDbwvc_WI3ZZ-P" /></figure><p>6. In the Azure Portal, select your Application from the App Registration menu</p><p>7. Under Manage, select Authentication &gt; Platform Configuration &gt; Add a Platform</p><p>8. Select the application type (for eg. Web) from the Configure Platforms pane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6WHWMQkRlj9mK8db" /></figure><p>9. In the Redirect URIs section, add your https or <a href="http://localhost/">http://localhost</a> URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*nCG4fEcJNaLSygJ1" /></figure><p>10. To finish the platform configuration, choose Configure.</p><p><strong>2. Assign the appropriate role to the Service Principal (App)</strong></p><p>Assign the appropriate role to the service principal i.e. Application registered in Azure AD, such as “Storage Blob Data Contributor” or “Storage Blob Data Reader” to grant the necessary permissions to access the blob</p><ol><li>Sign in to Azure Portal. Open your required Storage Account resource. Click Access Control (IAM).</li><li>Select Add &gt; Role Assignment.<br>The Add role assignment option will be disabled if you do not have the necessary permissions to assign roles.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CfJhTblawPNKCRJ9" /></figure><p>3. In the Roles tab, Select the appropriate role that you want to assign such as “Storage Blob Data Contributor” or “Storage Blob Data Reader”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*accelrkdjhuuWLJX" /></figure><p>You can view the details of the selected role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WuL3BMOhgZ5o5Gkk" /></figure><p>4. On the Members tab, select Use, group, or service principal. Add then click on Select Members button. You can type your application name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UacdGsns5sh4nzyH" /></figure><p>4. Click Next &gt; Review + assign.<br>After few moments, the role will be assigned to the service principal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o8OfVsU37yCJ3npe" /></figure><p><strong>3. Create a Client Secret</strong></p><p>When requesting a token, the application requires a client secret to prove its identity.</p><ol><li>In the Azure Portal, select your Application from theApp Registration menu</li><li>Choose the Certificates &amp; secrets option.</li><li>To create a new secret, click New Client Secret under Client Secrets.</li><li>Give the secret a description and select the desired expiration interval.</li><li>Copy the new secret’s value to a secure location right away. You will only see the full value once.</li></ol><p><strong>4. The Code</strong></p><p>You can use the Azure SDK for your web application’s programming language to generate the SAS token using the user delegation method. Here’s an example of how to do this in NodeJS:</p><ol><li>Install the <strong>azure-storage</strong> npm package by running the following command in your terminal:</li></ol><p><em>npm install @azure/storage-blob</em></p><p>2. Import the BlobServiceClient and generateAccountSASQueryParameters modules from the azure-storage package in your Node.js file:</p><pre>const { BlobServiceClient, <br>generateAccountSASQueryParameters, BlobSASPermissions } = <br>require(&#39;@azure/storage-blob&#39;);</pre><p>3. Get the Azure Storage account name, container name, client secret, client ID, and tenant ID values from the env file.</p><pre>const accountName = process.env.accountName;<br>const clientId =  process.env.clientId;<br>const tenantId =  process.env.tenantId;<br>const clientSecret = process.env.clientSecret;<br>const containerName = process.env.containerName</pre><p>4. Create a ClientSecretCredential object with your Azure AD tenant ID, client ID, and client secret.</p><ul><li><strong>Client ID</strong>: Client ID is a unique unique identifier for an application that is registered in Azure AD</li><li><strong>Client Secret:</strong> It is used to authenticate your application and provide it with the necessary permissions to access Azure resources.</li><li><strong>Tenant ID: </strong>A unique identifier for an Azure Active Directory tenant, which is the organization or directory that the application is associated with.</li><li><strong>ClientSecretCredential Object:</strong> It is used to authenticate your web application with Azure Active Directory (Azure AD) and obtain an access token. This access token is then used to authorize the application to access the desired Azure resource, such as the blob storage in this case.</li></ul><pre>const credential = new ClientSecretCredential(tenantID, <br>clientID, clientSecret);</pre><p>5. Create a BlobServiceClient object using the credential object and the storage account URL:</p><pre>const blobServiceClient = new <br>BlobServiceClient(`https://${accountName <br>}.blob.core.windows.net`, credential);</pre><p>6. Create userDelegationKey using BlobServiceClient Object and the start and expiry date</p><pre>//set the startOn and expiresOn time.Keep a short expiration <br>time maybe an hour or so.<br>const userDelegationKey = await <br>blobServiceClient.getUserDelegationKey(startsOn, expiresOn);</pre><p>7. Create the SAS token using the generateAccountSASQueryParameters method by passing in the container name, account name, user delegation key, and the start and expiry date of the SAS token.</p><pre>const sasToken = generateBlobSASQueryParameters({<br>            containerName: containerName,<br>            blobName: BLOB_NAME,<br>            startsOn: startsOn,<br>            expiresOn: expiresOn,<br>            permissions: BlobSASPermissions.parse(&#39;r&#39;)<br>        }, userDelegationKey, accountName );</pre><p>8. Append the SAS token to the blob URL to access the blob</p><pre>let blobUrl = &#39;https://&#39; + accountName+ <br>&#39;.blob.core.windows.net/&#39; + containerName+ &#39;/&#39; + blobName;<br><br>let blobSASURL = `${blobUrl}?${sasToken}`</pre><p>You can then use the blobSASUrl to access the blob and also you may include an error handling mechanism.</p><h4>Best Practices while using SAS:</h4><p>There are several best practices to follow when working with SAS tokens in Azure Storage:</p><ul><li>Use SAS tokens with stored access policy: You can use Stored Access Policy to manage the SAS tokens, by setting expiration time, permissions, and IP address restrictions for the SAS tokens.</li><li>Use user-delegated SAS tokens: Use user-delegated SAS tokens to grant access to specific resources, rather than providing access to all resources within a storage account. This allows for more granular control over access to resources.</li><li>Use a unique SAS token for each user: Generate a unique SAS token for each user, rather than sharing a single SAS token among multiple users. This allows for easy revocation of access for individual users.</li><li>Keep the SAS token secret: Do not share SAS tokens in plain text or in unsecured communications, such as email. Instead, use a secure method to share the SAS token, such as a secure file transfer.</li><li>Monitor and Audit SAS token usage: Keep track of all SAS tokens that are generated and keep a log of the usage. This will allow you to detect and investigate any suspicious activities.</li><li>Revoke SAS tokens when no longer needed: Revoke SAS tokens when they are no longer needed, or when a user’s access to a resource is no longer required.</li><li>Use HTTPS endpoints: Use HTTPS endpoints to encrypt the communication between the client and the storage service.</li></ul><p>The security and administration of your SAS tokens can be enhanced by adhering to these best practices. In conclusion, Azure SAS is a secure and convenient way to grant limited access to Azure resources. Whether you’re building a web application, mobile app, or IoT solution, Azure SAS can help you securely manage access to your data and resources in the cloud.</p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/akhil-adapa-aa7151b1/"><em>Akhil Ram Adapa</em></a><em> (Senior Architect — Machine Learning), </em><a href="https://www.linkedin.com/in/siddhita-gurav-a9929b135/"><em>Siddhita Ashok Gurav</em></a><em> (Senior Platform Engineer) at Quantiphi)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f342c4f1f906" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End MLOps on AWS: Part3.3- Time Series Forecasting: Components Deep Dive]]></title>
            <link>https://medium.com/@datalab_70093/end-to-end-mlops-on-aws-part3-3-time-series-forecasting-components-deep-dive-49080b3be79f?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/49080b3be79f</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 10:56:35 GMT</pubDate>
            <atom:updated>2024-01-22T10:56:35.111Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is the third and last of a series of blogs based on MLOps workflows we built. In this blog, we will talk about the various components used in the time series pipeline developed using the AWS SageMaker pipeline. Also, for an overview of the time series pipeline workflow refer to <a href="https://sagemaker-mlops-samples.github.io/blogs/time-series/time-series-forecasting-mlops-overview-and-simulation/">our first blog in Time-Series Domain</a>. To understand the workings of the pipeline in depth, the various steps, and the AWS services involved, refer to our previous <a href="https://sagemaker-mlops-samples.github.io/blogs/time-series/time-series-forecasting-detailed-working-of-pipelines/">blog</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*XC8JUUbQKh5ZARa8" /><figcaption>Components of the Sagemaker Pipeline</figcaption></figure><p>From the diagram above we can observe that the end-to-end pipeline solution consists of two major pipelines: The training pipeline and the Inference pipeline. Both pipelines consist of four main components they are –</p><h3>Components in Detail:</h3><ol><li><em>Processing component</em></li><li><em>Algorithm component</em></li><li><em>Explainability component</em></li><li><em>Monitoring component</em></li></ol><p>Every component supports two run modes namely the train mode and serve mode. All components are executed in the <strong>train mode for the training pipeline</strong> and in the <strong>serve mode for the inference pipeline</strong>. In each component, we use the parameter ‘run_mode’ to specify the run mode. Let’s dive into every component to understand its working.</p><h4>1. Processing Component:</h4><p>The processing component handles data preprocessing<strong> in batch mode</strong>. This component reads the input CSV file based on the inference date parameter, performs cleaning, preprocessing, and scaling steps and saves the preprocessed data in s3. This component will also apply specific filters to extract data for ‘Birmingham’ city. A processing job is created to run this component. The key differences in the run modes are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qG8Fwr3lcEGNXFbW" /><figcaption>Processing Component Lifecycle</figcaption></figure><ul><li><strong><em>Train Mode:</em></strong><em><br></em>In train mode, it splits the data in train and validation splits. It saves the artifacts of the scalar.</li><li><strong><em>Serve Mode:</em></strong><em><br></em>In serve mode, it separates the target column from the input columns as ‘inference_Y.csv’ and ‘inference_X.csv’ respectively. The artifacts (scalers) output path of this component in train mode is passed as input and used to scale the inference_X dataset.</li></ul><h4>2. Algorithm Component:</h4><p>The algorithm component performs two major tasks, which are <strong>model training and model inference in a batch setting</strong>. The key differences in the run modes are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ZdMm0xWiBo5sfU1x" /><figcaption>Algorithm Component Lifecycle</figcaption></figure><ul><li><strong><em>Train Mode:</em></strong><em><br></em>In train mode, this component will perform the task of training the LSTM-based model on the training dataset and evaluate the model on the validation dataset. The generated model artifacts are saved in S3. The train and validation data are passed as input to this component. Additionally, the total number of epochs, features, early stopping value, and look-back period are <strong>passed as hyperparameters.</strong> The training is carried out in batch mode by creating a SageMaker training job.</li><li><strong><em>Serve Mode:</em></strong><em><br></em>In serve mode, it uses the model trained in the training mode to perform batch inference on the inference data. This component consists of two sub-steps in the inference pipeline. The first step is the <strong>‘model step</strong>’ where a SageMaker model is created using the model artifact path obtained from the train mode output of this component. This SageMaker model is used in the next step which is the <strong>‘transform step’</strong> where a SageMaker batch transform job is created to <strong>perform batch inference </strong>on the inference data. Look back and look ahead periods are also passed as environment variables. The transform step is carried out after the model step is completed. The generated forecast is saved in s3.</li></ul><h4>3. Explainability Component:</h4><p>The explainability component is tasked with <strong>providing interpretability to the model</strong>. To achieve this task this component computes shape values by comparing the predicted and actual values. It then generates and saves a clear report. It uses a SageMaker processing job to execute this task. The clarify reports generated are saved in s3. It is defined as a processing step within the training pipeline and it is triggered only after the algorithm component is executed. The key differences in the run modes are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ubnOz-1eU6ftcaqQ" /><figcaption>Explainability Component Lifecycle</figcaption></figure><ul><li><strong><em>Train Mode:</em></strong><em><br></em>The input in the train mode is the train data.</li><li><strong><em>Serve Mode:</em></strong><em><br></em>In serve mode, the inputs to this component are the test data which is the output of the processing component in serve mode and the train data which is the output of the processing component in train mode.</li></ul><h4>4. Monitoring Component:</h4><p>The monitoring component detects performance issues by <strong>detecting drift</strong> in the performance of machine learning <strong>models or data</strong>. It uses a SageMaker processing job to monitor the performance of models. It is defined as a processing step within the training pipeline and it is triggered only after the algorithm component is executed in parallel with the explainability component. The key differences in the run modes are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*JKuncnXQekRjor0N" /><figcaption>Monitoring Component Lifecycle</figcaption></figure><ul><li><strong><em>Train Mode:</em></strong><em><br></em>In train mode, the monitoring component <strong>generates two baselines </strong>to detect drift in data and model. It uses the train data to generate the baseline report for data drift and validation data for model drift. It saves the data and model drift baseline reports in s3 as CSV files.</li><li><strong><em>Serve Mode:</em></strong><em><br></em>In the serve mode, this component <strong>detects data and model drift.</strong> It will compare the detected drift with the baseline drift computed by this component in the train mode. Model drift is detected by comparing the forecast value generated with the actual value corresponding to that date. Since actual values will always lag the forecasted value, the date for which drift is detected is the date that is looking ahead days before the inference date (<strong>drift_detect_date </strong>= inference date — [look_ahead+1] days). The inputs to this component are the inference data, forecast generated, and actual value corresponding to the drift_detect_date and the monitoring baseline artifact path which is the output of the monitoring component in train mode. It generates and saves the drift analysis report in s3.</li></ul><p>If you find our work interesting you can replicate it for your use case. Feel free to contact us if you have any feedback, suggestions, or comments. Happy learning.</p><h3>References:</h3><ul><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/define-pipeline.html">https://docs.aws.amazon.com/sagemaker/latest/dg/define-pipeline.html</a></li><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html">https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html</a></li><li><a href="https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-pipelines/tabular/abalone_build_train_deploy/sagemaker-pipelines-preprocess-train-evaluate-batch-transform.html">https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-pipelines/tabular/abalone_build_train_deploy/sagemaker-pipelines-preprocess-train-evaluate-batch-transform.html</a></li></ul><p>For more updates from Quantiphi follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a> and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/palash-nimodia-94975b4b/"><em>Palash Nimodia</em></a><em>(Architect — Machine Learning), </em><a href="https://www.linkedin.com/in/thinkabhishek/"><em>Abhishek Tawar</em></a><em> (Associate Architect — Machine Learning) at Quantiphi)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49080b3be79f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End MLOps on AWS: Part3.2- Time Series Forecasting: Detailed Working of Pipelines]]></title>
            <link>https://medium.com/@datalab_70093/end-to-end-mlops-on-aws-part3-2-time-series-forecasting-detailed-working-of-pipelines-8ad408ebffc2?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ad408ebffc2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 15:57:12 GMT</pubDate>
            <atom:updated>2024-01-02T15:57:12.432Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is part of a series of blogs explaining the MLOps workflows we built. In this blog, we will talk about the end-to-end time series forecasting pipelines developed using the AWS SageMaker pipeline. We will explain the workings of the pipeline in detail including the steps involved and the various AWS services used. For more details and an overview of MLOps, the components used and the types of components; go through <a href="https://sagemaker-mlops-samples.github.io/blogs/end-to-end-mlops-on-aws-part1-introduction/">this blog</a>. Also, for an overview of the time series pipeline refer to the <a href="https://sagemaker-mlops-samples.github.io/blogs/time-series/time-series-forecasting-mlops-overview-and-simulation">previous blog</a>.</p><p>The <strong>pipelines consist of components</strong>, each component has a specific task in the pipeline based on their function. Each component needs to be executed using an appropriate <strong>step in the SageMaker pipeline</strong>. Our pipelines have different steps for different components. These are the steps we used for each component: Lambda, Processing, Training, Model, Transform and Condition.</p><p>The <strong><em>Parameter store</em></strong> is a JSON file saved in S3. Alternatively, the AWS Systems Manager Parameter Store could also be used.</p><h3>Communication between Steps in the Pipeline</h3><p>SageMaker Pipeline steps define the actions that the pipeline takes and the relationship between steps using properties. Each step requires certain parameters to be passed. Three types of parameters are used in the pipelines: These parameters can be categorized into three types:</p><ul><li><strong>Sagemaker Pipeline Parameters:</strong><br>Variables are introduced into your pipeline definition using <strong>pipeline parameters</strong> and can be referenced throughout the pipeline. Parameters have a default value, which can be updated by specifying parameter values when starting a pipeline execution.</li><li><strong>Parameter fetched from the parameter store:</strong><br>To enable the model lifecycle management workflow it is required to version control important parameters. Some of such parameters are model artifacts location, drift baseline reports location, training data location, etc. We maintain a parameter store to version all these parameters.</li><li><strong>Parameter fetched from the previous step:</strong><br>The <strong>step properties</strong> attribute is used to add data dependencies between steps in the pipeline. These properties are referenced as placeholder values and are resolved at runtime. The properties of one step are passed as input to another step in the pipeline.</li></ul><h3>End-to-End Pipeline Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ztzklgf2b5No0Byz" /><figcaption>AWS End-to-End Pipeline Architecture Diagram: Entries in the bracket indicate component names</figcaption></figure><p>As discussed in the previous blogs, the end-to-end pipeline consists of two distinct SageMaker pipelines — The<strong><em> training pipeline</em></strong> and the <strong><em>Inference pipeline</em></strong>. Both pipelines contain four distinct components i.e. <strong>processing, training, inference, explainability, and monitoring</strong>. Additionally, there are a few additional helper steps. Each component supports two run modes — Train mode and Serve mode. For the inference and training pipeline, every component will be running in the <strong>“Serve” mode</strong> and <strong>“Train” mode</strong> respectively. Let’s discuss the individual pipeline flows in detail —</p><h4><strong><em>Training Pipeline Flow:</em></strong></h4><ol><li>The training pipeline can be <strong>triggered by the inference pipeline</strong> when there is drift detected and the <strong>cooling period</strong> is over. The cooling period starts on the day the latest model was trained and continues for days equal to the look-ahead period.</li><li>The first step is the <strong>processing component</strong> that reads the training data, performs data cleaning/preprocessing and finally saves the training and validation data in s3.</li><li>The <strong>algorithm component</strong> is the next step and it uses the training data to train an LSTM model and validation data to calculate the validation accuracy. The generated model artifacts are saved in S3.</li><li>Next, the <strong>explainability component</strong> computes shap values. It generates and saves a clear report. This step is triggered only after the algorithm component step is completed.</li><li>The <strong>monitoring component</strong> uses a SageMaker processing job to generate baseline drift artifacts. It generates two kinds of baselines to detect drift in data and model and saves the drift baseline reports in s3. This step is triggered only after the algorithm component step is completed and runs in parallel with the explainability step.</li><li>The <em>last step</em> of the training pipeline ‘<strong>update parameters’</strong> is the lambda step that updates the parameter store with the latest model and other artifact paths generated by the training pipeline. These parameters act as pipeline input parameters for the inference pipeline.</li></ol><h4><strong><em>Inference Pipeline Flow</em></strong></h4><ol><li>The first step in the pipeline is <strong>‘get parameter’</strong>, it fetches the parameters from the parameter store and assigns them to the step properties which can be used throughout the pipeline. This step is defined as a lambda step. This step also <strong>checks if there is a forecast</strong> (generated by a previous inference pipeline run) <strong>available for the actual date </strong>(Actual date is the latest date for which actuals are available = inference date — [Look ahead + 1] days). The first lambda step sets the condition variable as “true” if the forecast data is available else “false”.</li><li>Next, the <strong><em>processing component</em></strong> reads the inference data, performs cleaning/preprocessing steps and finally saves the preprocessed data in s3.</li><li>The algorithm component consists of two sub-steps. The first sub-step is the ‘<strong><em>model step</em></strong>’ where a SageMaker model is created using the model artifact path obtained from the parameter store. This SageMaker model is then used in the next step which is the <strong>‘<em>transform step</em>’</strong> to perform batch inference.</li><li>The <strong><em>explainability component</em></strong> uses SageMaker processing jobs to compute shap values for the generated forecast. It generates and saves a clear report.</li><li>The next step is the<strong> <em>condition step</em></strong> which is executed in parallel with the explainability step as they both have dependency on the transform step. This conditioning step will reference the condition variable set by the first step <strong>‘get parameter’</strong> and check if it is equal to “true”. If the condition is satisfied, it will execute the monitoring component and the final drift check lambda step else end the pipeline execution.</li><li>The<strong> <em>monitoring component</em></strong> detects drift in batch mode. It generates and saves the data and model drift report in s3. This step is also defined as a processing step and it is triggered if the condition step was satisfied.</li><li>The <em>final step</em> is ‘<strong>Check Drift’</strong> defined as a lambda step. It is used to first check if the cooling period is over and then check the output of the monitoring component to identify if drift was detected in the data or model. If the cooling period is over and drift is detected, this step will trigger the training pipeline and complete the execution.</li></ol><p>We now have an understanding of the workings of the end-to-end SageMaker pipeline, the various steps involved and the AWS services used. In the next and also the final blog of the series based on forecasting, we will deep dive into the functionality and working of the individual pipeline components in detail. You can find the next blog <a href="https://sagemaker-mlops-samples.github.io/blogs/time-series/time-series-forecasting-components-deep-dive">here</a>.</p><h3>References</h3><ul><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/define-pipeline.html">https://docs.aws.amazon.com/sagemaker/latest/dg/define-pipeline.html</a></li><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html">https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html</a></li><li><a href="https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-pipelines/tabular/abalone_build_train_deploy/sagemaker-pipelines-preprocess-train-evaluate-batch-transform.html">https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-pipelines/tabular/abalone_build_train_deploy/sagemaker-pipelines-preprocess-train-evaluate-batch-transform.html</a></li></ul><p>For more updates from Quantiphi follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a> and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/palash-nimodia-94975b4b/"><em>Palash Nimodia</em></a><em>(Architect — Machine Learning), </em><a href="https://www.linkedin.com/in/thinkabhishek/"><em>Abhishek Tawar</em></a><em> (Associate Architect — Machine Learning) at Quantiphi)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ad408ebffc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End MLOps on AWS: Part3.1- Time Series Forecasting: MLOps Overview and Simulation]]></title>
            <link>https://medium.com/@datalab_70093/end-to-end-mlops-on-aws-part3-1-time-series-forecasting-mlops-overview-and-simulation-99553558d3ba?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/99553558d3ba</guid>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 15:16:29 GMT</pubDate>
            <atom:updated>2023-12-18T15:16:29.422Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is part of a series of blogs based on MLOps workflows we built. In this blog, we will be talking about the time series solution developed using the AWS SageMaker pipeline. For more details and a deeper understanding of MLOps, the components used and the types of components; go through our <a href="https://sagemaker-mlops-samples.github.io/blogs/end-to-end-mlops-on-aws-part1-introduction/">previous blog</a>.</p><h3>Use Case</h3><p>The problem statement of this use case is to <strong>build an end-to-end MLOps solution for time series data</strong>. The solution will consist of a training pipeline and an inference pipeline built using SageMaker pipelines. The training pipeline will train an LSTM-based forecasting model using the training data and save the model in s3. The inference pipeline will generate forecasts using the trained model in batch mode. It will also detect drift in the model, data, or both and retrain the model if drift is detected.</p><h3>About Dataset</h3><p><strong>We used an open-source city temperature dataset from Kaggle</strong>. It contains the daily average temperature values for multiple cities with few other features. This pipeline is built to forecast the temperature of one city at a time hence we filter out data for ‘Birmingham’ city for simulation. The granularity of the dataset was at a daily level. We will forecast the average temperature value as it is the target column. You can download the dataset from this <a href="https://www.kaggle.com/datasets/sudalairajkumar/daily-temperature-of-major-cities">site</a>.</p><h3>Forecasting Parameters and Metrics</h3><p><a href="https://sagemaker-mlops-samples.github.io/blogs/time-series/time-series-forecasting-mlops-overview-and-simulation/#forecasting-parameters-and-metrics">Reference</a></p><ul><li>Based on the granularity of the dataset used, the <strong>forecasting frequency was set to a daily leve</strong>l.</li><li>The <strong>look back is 15 days</strong> and the <strong>look ahead period is 7 days</strong>.</li><li>We generated a <strong>forecast for one day</strong> after the look-ahead period (referred to here as inference day/forecast day.)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*sRKljBpdhkgfMwd-" /><figcaption>Forecasting Period Window</figcaption></figure><h4><strong><em>Forecasting Period Window</em></strong></h4><ul><li>The pipeline will be triggered daily to <strong>forecast the average temperature</strong> <strong><em>(Target column)</em>.</strong></li><li>The evaluation metric considered to measure the forecasting accuracy is <strong>MAPE (Mean Average Percentage Error).</strong> This metric will be used to identify if model drift is detected.</li></ul><h3><strong>High-Level Workflow</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*b3aYhoTduWnsJcxw" /><figcaption>End-to-end AWS Sagemaker Pipeline</figcaption></figure><p>The forecasting solution consists of two main pipelines: <strong>Training pipeline and Inference pipeline.</strong> Both pipelines consist of four main components that are tied together in a specific sequence to build the pipeline, they are:</p><ul><li>Processing</li><li>Algorithm</li><li>Explainability</li><li>Monitoring</li></ul><h4><strong>Inference Pipeline</strong></h4><ul><li>All components in the inference pipeline are run in the <strong>serve mode</strong>. The inference pipeline will <strong>fetch the trained ML model, inference data and pipeline parameters</strong>. Using these inputs it <strong>generates a temperature forecast in batch mode</strong>.</li><li>The pipeline will also check for<strong> drift if the cooling period has passed. The cooling period</strong> prevents the retraining pipeline from being triggered on consecutive days and waits for a lookaheads period for the forecast from the new model to be evaluated for drift.</li><li><strong>If drift is detected, it will trigger the training pipeline</strong> and complete the execution of the inference pipeline.</li></ul><h4><strong>Training Pipeline</strong></h4><ul><li>All components in the training pipeline are run in the <strong>train mode</strong>. The training pipeline takes the latest actual data (split into a training set and validation set) as input.</li><li>The pipeline trains a model and <strong>updates the parameter store</strong> with the latest model artifact paths generated. This ensures that in the next run of the inference pipeline, it uses the latest model artifacts.</li></ul><h3><strong>Simulation</strong></h3><p>A simulation exercise was planned to test the entire ML lifecycle. For this simulation, we ran the pipeline as they would in an actual production environment. Since we worked with daily level data, we simulated <strong>14 inference dates, from 01–03–2020 to 14–03–2020.</strong> The monitoring components can measure both data drift and model drift. We chose the <strong>retraining trigger to be model drift</strong> which is measured by degradation of <strong>MAPE value</strong>.</p><p>Each run of the inference pipeline is defined in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*VQswEFHqHvO6dUqy" /></figure><p>The <strong>input data files required</strong> to generate inference for each ‘inference date’ for both pipelines in the simulation were <strong>saved in s3</strong>. When a pipeline runs for a particular inference day it will <strong>fetch the inference or train data file for that day</strong>. Every file was identified by including the corresponding inference date in its nomenclature.</p><p>Two lambda functions were created and scheduled. The first lambda function (named “Update-inference-date-lambda”) was created <strong>to update the inference date </strong>(increment by one day) parameter in the parameter store. This parameter defined the date for which the inference pipeline had to generate inference. The second lambda function (named “BT-pipeline-trigger-lambda”) was <strong>used to trigger the inference pipeline</strong>. Both lambda functions were <strong>scheduled using event bridge rules</strong>. The event rules were enabled to trigger the first lambda function 2 minutes before the second since this will make sure every new run of the inference pipeline is different (the next day of the previous run). Also note, that the event bridge in scheduled mode cannot pass parameters to the pipeline hence lambda (with event bridge rule) is a better trigger for the pipeline.</p><h4><strong>Execution</strong></h4><ul><li>To run the simulation inference pipeline was scheduled to run every hour, for 14 hours: to generate inference for <strong>14 consecutive days.</strong></li><li>The table above shows the details of all the 14 runs. Before starting the inference pipeline runs we ran the train pipeline to train the model on the latest actual data (till date 22–02–2020).</li><li>The inference pipeline also checks if the <strong>cooling period</strong> is going on for the trained model which in our case is 7 days (= lookahead period). Hence, we will not check for model drift in the first 7 runs, and so the retraining pipeline won’t be triggered till the 07–03–2020 inference date.</li><li>For the first 10 runs, no drift was detected. The data had <strong>natural drift</strong> which was <strong>detected on the 11th run</strong> (highlighted with green in the table). Therefore, the inference pipeline triggers the training pipeline.</li><li>The training pipeline then trained a new model (with the latest actuals data till 03–03–2020) and saved the artifacts in s3, updated the parameter store with new artifact paths generated during re-training.</li><li>In the next 3 runs, the inference pipeline generated a forecast with the newly trained model.</li></ul><h3><strong>Conclusions</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*n3SECY-Eb5HAu4sR" /></figure><ul><li>On the inference pipeline run for 11–03–2020, <strong>model drift was detected</strong> and the training pipeline was triggered. There was natural drift in the data to cause model drift and hence there was no need to add external noise to the data.</li><li>For the 3 dates that used retrained models, we also generated the forecast for these dates using the older model. This was done to check the effect of model retraining on forecast accuracy. The experiment shows that <strong>accuracy improved for all the dates after retraining.</strong></li></ul><p>This blog gave you an overview of the end-to-end workflow of the time series forecasting pipeline developed using AWS Sagemaker pipelines. In the next blog, we will discuss the working of the end-to-end Sagemaker pipeline, the various steps involved and the AWS services used. You can find the next blog <a href="https://sagemaker-mlops-samples.github.io/blogs/time-series/time-series-forecasting-detailed-working-of-pipelines">here</a>.</p><h3>References</h3><ul><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/define-pipeline.html">https://docs.aws.amazon.com/sagemaker/latest/dg/define-pipeline.html</a></li><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html">https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html</a></li><li><a href="https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-pipelines/tabular/abalone_build_train_deploy/sagemaker-pipelines-preprocess-train-evaluate-batch-transform.html">https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-pipelines/tabular/abalone_build_train_deploy/sagemaker-pipelines-preprocess-train-evaluate-batch-transform.html</a></li><li><a href="https://awstip.com/how-to-automatically-trigger-a-sagemaker-pipeline-using-eventbridge-3b71829a9e5">https://awstip.com/how-to-automatically-trigger-a-sagemaker-pipeline-using-eventbridge-3b71829a9e5</a></li></ul><p>For more updates from Quantiphi follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a> and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/palash-nimodia-94975b4b/"><em>Palash Nimodia</em></a><em>(Architect — Machine Learning), </em><a href="https://www.linkedin.com/in/thinkabhishek/"><em>Abhishek Tawar</em></a><em> (Associate Architect — Machine Learning) at Quantiphi)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99553558d3ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End MLOps on AWS: Part2.2 — Computer Vision Components and Pipelines Deep Dive]]></title>
            <link>https://medium.com/@datalab_70093/sagemaker-pipelinessagemaker-pipelinesend-to-end-mlops-on-aws-part2-2-c912cca9ef35?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c912cca9ef35</guid>
            <category><![CDATA[amazon-sagemaker]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 10:56:55 GMT</pubDate>
            <atom:updated>2023-12-12T11:53:28.566Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In </em><a href="https://medium.com/@datalab_70093/end-to-end-mlops-on-aws-part2-1-computer-vision-simulation-with-drift-retraining-268f5033bb7f"><em>part 2.1</em></a><em> of our series, we gave a high-level overview of an MLOps system that handles large-scale image classification, end-to-end simulation and retraining evaluation to address drift. In this part, we will dive deeper into computer vision components and pipelines that make up this system. Specifically: how we designed components for batch workloads, how we implemented them on AWS using SageMaker and how we orchestrated them into MLOps pipelines using SageMaker Pipelines.</em></p><figure><img alt="Component Mode and SageMaker Service" src="https://cdn-images-1.medium.com/max/1024/0*8hYywqUErkRDFvxk" /><figcaption>Component Mode and SageMaker Service</figcaption></figure><h3>Quick Recap:</h3><p>A <strong>component</strong> is an independent ML functionality or an ML operation that is a part of the larger process. A <strong>pipeline</strong> is a workflow that constitutes one or more components that execute a holistic task.</p><p>There are <strong>4 components</strong> and <strong>2 pipelines</strong> as seen from the image above, where each component has 2 modes, which are:</p><ul><li><strong>Train mode</strong> and <strong>Serve mode</strong>.</li></ul><p>Each component mode will be executed with any one of the following <strong>Sagemaker Jobs</strong> which are:</p><ul><li>SageMaker Training Job or</li><li>SageMaker Processing Job or</li><li>SageMaker BatchTransform Job</li></ul><p>As discussed in <a href="https://medium.com/@datalab_70093/end-to-end-mlops-on-aws-part2-1-computer-vision-simulation-with-drift-retraining-268f5033bb7f">part 1</a> of our blog, all the Sagemaker workloads are developed using docker <strong>containers (BYOC — Bring Your Own Container</strong>).</p><h3>Components in detail:</h3><h4>1. Processing Component:</h4><p>The processing component handles batch processing of large amounts of image data, using various data augmentation techniques. The batch-processing is usually performed before model training and inference.</p><ul><li>On AWS, the processing component will be built using<a href="https://docs.aws.amazon.com/sagemaker/latest/dg/build-your-own-processing-container.html"> <strong>Amazon Sagemaker Processing Jobs</strong></a>. On completion of the SageMaker Processing job, the output processed data is saved back in AWS S3.</li><li>In the <strong>train mode</strong>, the processing job will transform train and validation data and in the <strong>serve mode</strong>, it will transform the production images.</li></ul><p>In our processing component, the augmentation pipeline performed <strong>image resizing</strong> for both modes, while <strong>random rotation</strong> was only applied to the <strong>training mode</strong>.</p><figure><img alt="Processing Component Lifecycle" src="https://cdn-images-1.medium.com/max/1024/0*urYXEJqnDeaCz6WL" /><figcaption>Processing Component Lifecycle</figcaption></figure><h4>2. Algorithm Component:</h4><p>The algorithm component performs 2 major tasks, which are <strong>model training</strong> and <strong>model inference</strong>.</p><figure><img alt="Algorithm Component Lifecycle" src="https://cdn-images-1.medium.com/max/1024/0*PxLVBAxDbvsL1Vsx" /><figcaption>Algorithm Component Lifecycle</figcaption></figure><p>Unlike the processing component, the 2 modes of the algorithm component will perform completely different tasks.</p><ul><li>The <strong>training mode</strong> will perform the task of <strong>ML model training</strong> on the training dataset and compute the evaluation metric on the validation dataset. Based on the ML model used, the training mode will also support <strong>model retraining capabilities</strong>. On AWS, the training mode of the algorithm component will be implemented using the <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/train-model.html"><strong>Sagemaker Training Job</strong></a>. In our use case, we <strong>trained a CNN model with ResNet</strong> as the base pre-trained model (ReseNet 50/100/150).</li><li>In <strong>serve mode</strong>, the production data is fed into the trained ML model for prediction. This model is the same one that was <strong>trained in train mode</strong>. On AWS, the serving mode of the algorithm component will be implemented using the <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html"><strong>Sagemaker BatchTransform Job</strong></a>.</li></ul><blockquote><strong>The data input to the algorithm component is processed train, validation, or production data that are the outputs of the processing component.</strong></blockquote><h4>3. Monitoring Component:</h4><p><strong>Model monitoring</strong> refers to the process of closely tracking the performance of machine learning models in production. It enables us to detect any technical or performance issues, but mainly it is <strong>used to detect drift</strong>. There are two main types of drift:</p><ul><li><strong>Data drift:</strong> Drift when characteristics of the underlying data on which the model has trained change over time.</li><li><strong>Concept Drift:</strong> Concept drift occurs when the characteristics of the target variable and its relationship with the training variables themselves change over time.</li></ul><p>The easiest way to tackle drift (mainly data drift) is by model retraining on the newly updated data.</p><figure><img alt="Monitoring Component Lifecycle" src="https://cdn-images-1.medium.com/max/1024/0*MVapRvmRACk5xg-C" /><figcaption>Monitoring Component Lifecycle</figcaption></figure><p>On AWS, both the <strong>train</strong> and <strong>serve</strong> modes of the monitoring component are developed using <strong>SageMaker Processing Job</strong>.</p><ul><li>In the <strong>train</strong> mode, the processing job learns the training image data distribution and saves it in a file which is also known as <strong>drift detection artifacts</strong>.</li><li>In the <strong>serving</strong> mode, using the <strong>drift</strong> artifacts from the training mode, <strong>drift is identified on the production data</strong>.</li></ul><p>There are various popular algorithms/methods to develop a drift detection solution which can be seen in the below image:</p><figure><img alt="Ways to detect drift" src="https://cdn-images-1.medium.com/max/1000/0*PE-o0SO8di2TNWUn" /><figcaption>Ways to detect drift</figcaption></figure><p>In our monitoring component, we used the<a href="https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test"> <strong>Kolmogorov-Smirnov</strong></a> statistical test to identify the drift between two probability distributions. This was implemented using a popular Python package known as<a href="https://github.com/SeldonIO/alibi-detect"> <strong>alibi-detect</strong></a><strong>.</strong></p><blockquote><strong><em>The data input to the monitoring component is usually the raw data itself, as </em>augmentations <em>performed by the processing component might change the input data distribution.</em></strong></blockquote><h4>4. Explainability Component:</h4><p>As the name suggests, the explainability component is used to understand the <strong>model interpretability and the cause of its inference decision</strong> behind every inferred data sample. In any production MLOps system, explainable AI is very important as it <strong>adds accountability and compliance</strong> to our production system.</p><figure><img alt="Explainability Component Lifecycle" src="https://cdn-images-1.medium.com/max/1024/0*U70Yqtog2OqHXfDS" /><figcaption>Explainability Component Lifecycle</figcaption></figure><p>On AWS, both the <strong>train</strong> and <strong>serve</strong> modes of the explainability component are developed using <strong>SageMaker Processing Job</strong>.</p><p><strong>The data input to the explainability component is processed train, validation, or production data which are the outputs of the processing component.</strong></p><p>The second input during both modes of the processing job is the trained ML model itself, which is the output of the <strong>algorithm component train mode.</strong></p><p>In our case of CV image classification, the explainability component computes the <strong>integrated gradients</strong> for each data sample, from the production data in <strong>serve mode</strong> and training data in <strong>train mode</strong> using the <strong>trained classification model</strong>.</p><h3>Pipelines in detail:</h3><p>From the image classification use-case (part-2 blog), we are already aware that we have 2 pipelines which are:</p><ul><li><strong>Training Pipeline</strong></li><li><strong>Batch-Inference Pipeline</strong></li></ul><p>The 2 pipelines seen in the below image are developed using<a href="https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-sdk.html"> AWS SageMaker Pipelines (LINK)</a></p><h3>About SageMaker Pipelines:</h3><p><em>An Amazon SageMaker Model Building Pipelines pipeline is a series of interconnected steps that are defined using the Pipelines SDK. This pipeline definition encodes a pipeline using a directed acyclic graph (DAG) that can be exported as a JSON definition. This DAG gives information on the requirements for and relationships between each step of the defined pipeline. The structure of a pipeline’s DAG is determined by the data dependencies between steps.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RetHrZspRDLEB5r0" /><figcaption>SageMaker Pipelines</figcaption></figure><ul><li>We have already seen that each component has 2 modes of execution, which are the <strong>“Train”</strong> mode and <strong>“Serve”</strong> mode. All the components chained together in the <strong>training</strong> pipeline are set to run in the <strong>“Train”</strong> mode. Similarly, all the components chained together in the <strong>batch-inference</strong> pipeline are set to run in the <strong>“Serve”</strong> mode.</li><li>The inputs and outputs of each pipeline execution are stored in <strong>AWS S3</strong>. The S3 paths are then updated in the <strong>AWS Parameter Store</strong>. <strong><em>This allows components from different pipelines to access each other’s outputs</em></strong>. The Parameter Store keys have a fixed prefix for each component output.</li><li>As we learned in blog 2 (part 2), the batch-inference pipeline runs on a schedule. We used <strong>AWS EventBridge</strong> to set up this scheduled trigger for the SageMaker pipeline.</li><li>On the other hand, we saw that when drift was detected in the batch-inference pipeline, the training pipeline was triggered automatically to tackle drift. This automatic trigger is carried out using the <strong>AWS Lambda Function</strong>.</li><li>The component execution and pipeline execution logs are pushed to <strong>AWS CloudWatch</strong>.</li><li>The containers used to execute individual components are stored in <strong>AWS ECR (Elastic Container Registry)</strong>.</li></ul><h3>Conclusion</h3><p>Thank you for reading this blog. We hope you gained some new and valuable insights from it. In this blog, we explained the different components of our project and how we developed them on AWS. We also showed you how we used SageMaker Pipelines to orchestrate the workflow and automate the deployment.</p><p>For more updates from Quantiphi follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a> and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/palash-nimodia-94975b4b/"><em>Palash Nimodia</em></a><em> (Architect — Machine Learning), </em><a href="https://www.linkedin.com/in/yogendra-yatnalkar-2477b3148/"><em>Yogendra Yatnalkar</em></a><em> (Senior Machine Learning Engineer)at </em><a href="https://quantiphi.com/"><em>Quantiphi</em></a><em>)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c912cca9ef35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End MLOps on AWS: Part2.1 — Computer Vision Simulation with Drift & Retraining]]></title>
            <link>https://medium.com/@datalab_70093/end-to-end-mlops-on-aws-part2-1-computer-vision-simulation-with-drift-retraining-268f5033bb7f?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/268f5033bb7f</guid>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 14:39:36 GMT</pubDate>
            <atom:updated>2023-11-21T14:39:36.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-End MLOps on AWS: Part2.1 — Computer Vision Simulation with Drift &amp; Retraining</h3><p><em>In our previous blog, we explored the concept of MLOps and its core elements which are components and pipelines. In this second part of our series, we will demonstrate how we created a comprehensive simulation for computer-vision batch workloads and later present the results of the same. Some of the key features of our simulation include drift monitoring, model retraining on drift and model redeployment.</em></p><h3>Use-case details:</h3><p>The goal is to create an MLOps system for Image Classification at a large scale. We will <strong>focus on batch-inference workloads</strong> only, which are tasks that involve processing large batches of images using machine-learning models. The MLOps system is based on AWS cloud services, but we will discuss them in more detail in future blog posts. <strong>The goal of this second part of our blog series is to give you an overview of the MLOps system, show you how we conducted the simulation and present the simulation results.</strong></p><p>The Image Classification MLOps system has four components and two pipelines. The four components are:</p><ul><li><strong>Processing Component:</strong> To batch process the images</li><li><strong>Algorithm Component:</strong> To train a CNN model and perform batch inference using the same.</li><li><strong>Monitoring Component:</strong> To learn training image dataset distribution and detect drift on production images.</li><li><strong>Explainability Component:</strong> Explainable insight generation on the input images using the trained ML model.</li></ul><p>The two pipelines are:</p><ul><li><strong>Training Pipeline:</strong> The training pipeline encapsulates all the components listed above and runs them in the <strong>“Train”</strong> mode.</li><li><strong>Batch-Inference Pipeline:</strong> The batch-inference pipeline encapsulates all the components listed above and runs them in the <strong>“Serve”</strong> mode.<br> Note: For more details on Train and Serve mode, please refer to the previous blog.</li></ul><blockquote><strong>The upcoming blogs will discuss components and pipelines in detail (stay tuned)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2wgz78zKzqXxhqwJ" /><figcaption>Overview of the entire MLOps system</figcaption></figure><h3>Simulation and its goal:</h3><ul><li>The end goal of the simulation is to test the robustness of the MLOps system discussed above. As a part of this simulation, <strong>we ran this system on 7 different datasets</strong> in a sequential manner. The 7 datasets include 1 original dataset and 6 variants of the same set with varying levels of drift.</li><li>The simulation was performed with complete automation and helped us answer the following questions:</li><li><strong>Does the system detect drift when it should?</strong></li><li><strong>If it does, does it trigger the retraining pipeline and train on the new data?</strong></li><li><strong>How does drift affect model performance and can retraining fix it?</strong></li></ul><h3>Dataset and its variations:</h3><ul><li>The dataset used for the simulation was a sample of the <strong>“Dog Breed Identification”</strong> dataset taken from<a href="https://www.kaggle.com/competitions/dog-breed-identification/data"> Kaggle</a>.</li><li>The sample dataset includes <strong>6 classes out of 120 classes</strong> from the original dataset. The 6 classes are <strong>boston_bull, chow, collie, dhole, doberman, golden_retriever.</strong></li><li>The sample dataset was divided into train-set, validation-set and test-set where the strength of each class being:</li><li>Train set: <strong>408 images</strong>, Validation set: <strong>34 images</strong>, Test set: <strong>42 images</strong></li><li>The original sample set is further augmented with 6 varying levels of drift. Hence, in total, there are 7 variations of the same set which are:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*NrR6KoMf9J6qazZzLZgOJA.png" /></figure><ul><li>The 7 variation sample dataset can be found on <a href="https://www.kaggle.com/datasets/yogendrayatnalkar/dog-breed-classifier-subsample-for-mlops">Kaggle</a>.</li></ul><h3>Dataset Visualization:</h3><blockquote><strong>Please Note: Since the display image is small, the random noise will not be easily visible to human eyes in the below plot</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KR1xgUE9H76wni6V" /></figure><h3>Simulation Execution and Result:</h3><p>With all the components, pipelines and data variants, we are ready to start the simulation execution. Without getting into the specifics of the AWS implementation, let’s take a look at how we completed the whole simulation:</p><ul><li>We maintained a <strong>key-value pair database (DB)</strong> which will store the output location of every pipeline run. We used <strong>AWS Parameter Store</strong> as our key-value store (DB).</li><li>On the first run, the training pipeline was <strong>run once on the original set</strong> and the DB was updated.</li><li>Next, the <strong>Batch-Inference pipeline was hosted to run on a schedule.</strong> The schedule was set to <strong>1 hour</strong> (example: 12:05, 13:05, ….etc). On AWS, this was done using <strong>AWS Event Bridge Scheduler.</strong></li><li>At each scheduled trigger, <strong>the input to the inference pipeline was changed in a cyclical manner</strong> starting from the original test set. The input test-set cycle was as follows:</li></ul><p><strong><em>Original Set → Stage-1 → Stage-2 → Stage-3 → Stage-4 → Stage-5 → Stage-Noisy → (Cycle complete) Original</em></strong></p><ul><li>Hence, till the cycle completes, after every run, a slightly higher drift set will be passed as input to the inference pipeline.</li><li>An important rule that we followed was: that <strong>the training pipeline would use the same stage of training and validation set as the test set that caused drift</strong>.</li><li>For example, if the stage-3 test set triggered the training pipeline, then the input will be set to the stage-3 training and validation. <strong>This means that the training pipeline would always run on the latest data available for each test set.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*ap1dxTcstP_kRcK_nbNF6g.png" /></figure><ul><li>For the input visualization, please refer to the above table. From there, we can clearly see that at every hour the test set path is changing and <strong>if drift gets detected at any point, the same hours of training and validation set will be passed as input.</strong></li><li>After running the training pipeline once and setting up the inference pipeline to run on an hourly schedule as discussed above, we ran the simulation and its results are as follows:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*Mr6yrHZbQ-nLqwCz3w0hMA.png" /></figure><ul><li>From the above results table, we can see that the <strong>“Time”</strong> column tells us at what time the batch-inference pipeline was triggered. The <strong>“Input Test Path”</strong> shows the test dataset inputted at each time interval.</li><li>The column <strong>“Drift Artifacts Trained On Set”</strong> shows us which training run was used to create the monitoring artifacts. We previously mentioned that we ran the Train pipeline once before the simulation using the Original train and validation set. Therefore, we can see that <strong>at 12.05</strong>, even though the <strong>inference pipeline takes stage 1 as the input test path, the monitoring artifacts are based on the original set.</strong></li><li><strong><em>One important observation</em></strong> is, at any point when the drift was detected i.e. at 14.05 and 16.05, the training pipeline was re-run with the latest train and validation set (i.e. stage-3 set at 14.05 and stage-5 set at 16.05). <strong>Hence, at 15.05, when the inference pipeline was running on the stage-4 test set, the monitoring artifacts were trained on the stage-3 train set.</strong></li><li>We ran the pipeline for <strong>10+ hours</strong>, recorded all the results and concluded the simulation process. <strong>We can say that we were successful in building a system that actively detected drift and tackled it with a proper retraining strategy.</strong></li><li><strong><em>After completing the simulation, we were left with only 1 question, do we actually need retraining to tackle drift?</em></strong></li></ul><h3>Need for retraining?</h3><ul><li>The inference pipeline only received the test set as input and not its ground-truth labels, hence we could not verify whether our model performance had really deteriorated on the subsequent drift sets or not.</li><li>Since this was a simulation of production and not actual production, we had access to the ground-truth labels for all the test sets. We conducted a small experiment, where we <strong>trained multiple CNN models on one of the sets and measured the test-set accuracy and loss across all variations of the drifted test sets.</strong></li><li>The simulation result shows that <strong>drift occurred on the stage-3 set when the ML model and monitoring artifacts were trained on the original set.</strong> Therefore, we need to compare the performance of our model trained on the original set and stage-3 set with all the other sets.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*madtzERzc1X9t-8xOUuBPA.png" /></figure><ul><li><strong><em>The training results table above and the simulation result table from before show a clear correlation between drift detection and model accuracy degradation. When artifacts were trained on the original set and drift was detected on the stage-3 set, the model accuracy dropped by about 4% (from the stage-2 test set to the stage-3 test set).</em></strong></li><li><strong><em>However, after retraining the model on the stage-3 train set and testing it on the stage-4 train set, the model accuracy did not fall below a certain threshold. This suggests that retraining is an effective way to deal with drift.</em></strong></li></ul><h4><strong>Conclusion</strong></h4><p>This is the first post in our Computer Vision domain-specific series, where we briefly explained our Image Classification MLOps system. We also covered the various datasets we used, the simulation method and the simulation result. Finally, we found out that retraining is an effective way to deal with drift.</p><p>For more updates from Quantiphi follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a> and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/palash-nimodia-94975b4b/"><em>Palash Nimodia</em></a><em> (Architect — Machine Learning), </em><a href="https://www.linkedin.com/in/yogendra-yatnalkar-2477b3148/"><em>Yogendra Yatnalkar</em></a><em> (Senior Machine Learning Engineer)at </em><a href="https://quantiphi.com/"><em>Quantiphi</em></a><em>)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=268f5033bb7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing End-to-End MLOps on AWS: Part1]]></title>
            <link>https://medium.com/@datalab_70093/introducing-end-to-end-mlops-on-aws-part1-ae42dad5c487?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae42dad5c487</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 09:51:28 GMT</pubDate>
            <atom:updated>2023-11-15T09:51:28.910Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The upcoming series of blogs will explain how to build a complete MLOps system on Amazon Web Service (AWS), mainly revolving around the AWS SageMaker ecosystem. Part 1 of this blog introduces the concept of MLOps, its various constituents and the AWS services that are needed to build them.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*34b2PNzgCKpxP3i7" /></figure><p><strong>Prerequisites</strong>: The blog series expects the reader to have a basic understanding of the following concepts:</p><ul><li>Docker</li><li>Basic AWS Ecosystem (S3, ECR, AWS Systems Manager Parameter Store, etc)</li><li>Advance knowledge of AWS SageMaker (and experience with Bring Your Own Container — BYOC for SageMaker jobs and SageMaker Pipelines)</li><li>Basics of machine learning and deep learning techniques</li></ul><h3>Why MLOps?</h3><p><em>According to several sources available on the internet, 85–90% of the ML models never make it into production.</em> <em>Some of the reasons for this low success rate are:</em></p><ul><li>Difficulty in scaling the tools and services around the AI ecosystem; and providing positive return on investment</li><li>Difficulty in detecting drift and deciding the best strategy to retrain the hosted models</li><li>Complexity of governance and deployment of numerous AI models</li><li>Lack of leadership support and understanding of machine learning models</li></ul><p><em>Most of the above-listed concerns can be resolved using the right MLOps practices, hence MLOps has been gaining prominence in recent years.</em></p><h3>MLOps Definition:</h3><p><strong><em>MLOps refers to a standard set of practices for businesses that want to deploy and manage ML models in production.</em></strong></p><p>Any MLOps system includes many tools for different purposes, e.g.</p><ul><li><strong>Code Version Control</strong>: Git (GitHub, GitLab, Bitbucket, etc)</li><li><strong>Data Version Control</strong>: DVC, Git LFS, etc</li><li><strong>Testing and building services</strong>: Jenkins, AWS CodePipeline, etc</li><li><strong>Infrastructure as a code</strong>: Terraform, AWS CloudFormation</li><li><strong>Machine Learning Platform:</strong> AWS SageMaker, GCP VertexAI</li><li><strong>Workflow Orchestration:</strong> SageMaker Pipelines, Apache Airflow, AWS Step Functions, Kubeflow</li></ul><p>In this series of blogs, we will use SageMaker as our main toolbox. We will demonstrate how to manage the entire lifecycle of an ML model with automation for use cases in multiple domains.</p><pre>NOTE: For this blog, we will only assume that we are working with batch <br>workload i.e. the use-case will carry out batch inference and no real-time <br>inference. In future blogs, we will also touch upon the topic of real-time <br>workloads.</pre><h3>Definitions:</h3><p>The two essential constituents of any MLOps System are components and pipelines.</p><h4>Components:</h4><p>A Component can be defined as an independent ML functionality or an ML operation that is a part of the larger process. A few examples of components could be data processing, ML model training, model inference, etc.</p><h4>Pipeline:</h4><p>A pipeline is a workflow that constitutes one or more components that execute a holistic task. Examples of pipelines include training pipelines, inference pipelines, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*PHHyR78iTQTG2iJM" /><figcaption>Pipeline and component representation</figcaption></figure><p>With our assumption of batch workload, let’s define 2 pipelines, namely:</p><h4>Training Pipeline:</h4><ul><li>The training pipeline will have a sequence of steps where the first step will process the training and validation datasets.</li><li>The next step will carry out model training and tuning on the processed training and validation sets.</li><li>In the monitoring step, we will learn the distribution of the training, which will be used to detect data drift.</li><li>The last step will be the explainability step, where we will generate explainable insights from our ML model on the training and validation sets.</li></ul><h4>Inference Pipeline:</h4><ul><li>The inference pipeline will be running in the batch-inference setting where the first step will consist of processing of production data as required by the ML model.</li><li>On completion of the processing step, the processed data will be passed to the trained ML model for Scoring.</li><li>The next step will include drift detection on the production data, using the data distribution artifacts from the training pipeline. If drift is detected, then retraining the ML model on a new set of data is one way to resolve it.</li><li>Lastly, the explainability step will be executed to generate explainable insights from our ML model on the production data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0dIZ4W6izwoA1WS7" /></figure><p>To execute the above pipeline steps, we will have to develop the respective components.</p><p><strong><em>We believe that most of the MLOps workloads consisting of multiple pipelines can be covered with 4 components which are:</em></strong></p><ul><li>Processing Component</li><li>Algorithm Component</li><li>Monitoring Component</li><li>Explainability Component</li></ul><p><strong>We recommend that every component has 2 modes, which are the Train mode and the Serve mode. This is to ensure that for every operation the training data undergoes, there is a corresponding operation during inference.</strong></p><p>As the name suggests, when a component is executed in the <strong>training pipeline</strong>, it will be running in the “<strong>Train” mode</strong>. Similarly, when a component is getting executed in the <strong>inference pipeline</strong>, it will be set to run in the “<strong>Serve</strong>” <strong>mode</strong>.</p><h3>Why SageMaker?</h3><p>Amazon SageMaker is a fully managed machine learning service. With SageMaker, data scientists and developers can quickly and easily build and train machine learning models, and then directly deploy them into a production-ready hosted environment.</p><p>Over time SageMaker has incorporated features that have made it an end-to-end platform for MLOps and reduced the need to integrate with other tools and services. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*OEMuAahL3s3K9pX3HuUIRA.png" /><figcaption><a href="https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html">AWS StepFunction of Managed MWAA</a></figcaption></figure><h3>Our AWS Stack?</h3><p>As we said earlier, our MLOps system is built on top of AWS Cloud. The AWS services required are:</p><ul><li><strong>AWS S3</strong>: Stores large volumes of data</li><li><strong>AWS SageMaker</strong>:</li></ul><ol><li>The processing component, monitoring component and explainability component for batch-workloads discussed above are developed using <strong>SageMaker Processing Job.</strong></li><li>The training component is developed using <strong>SageMaker Training Job.</strong></li><li>The batch-inference component is developed using <strong>SageMaker BatchTransform Job.</strong></li><li>The Training and Batch-Inference pipelines are built using <strong>SageMaker Pipelines</strong></li></ol><ul><li><strong>AWS Systems Manager Parameter Store</strong>: Used as a key-value store and for version tracking</li><li><strong>Other misc</strong>. Services: AWS CloudWatch, AWS Lambda, AWS EventBridge</li></ul><h3>How to create SageMaker Workloads?</h3><ul><li>We have seen how our components are developed on AWS using different types of SageMaker workloads, such as processing jobs, training jobs, batch transform jobs, and so on. To create these workloads, we have two main options:</li></ul><ol><li>Use the<strong> pre-built containers that AWS provides and maintains.</strong> We only need to write our code scripts that define the custom logic we want to run. This is called the<strong> “script” mode of execution.</strong></li><li><strong>Build our custom containers</strong> that include the compute logic we want to run. Push these containers to<strong> AWS ECR and give the ECR URI </strong>as the input to the SageMaker workload. This is called the<strong> “bring your own container (BYOC)” mode of execution.</strong></li></ol><pre>To handle complex dependencies and have full control over the modules, we <br>recommend building custom containers and using the “BYOC” mode for SageMaker <br>workload execution.</pre><ul><li>For detailed information, please refer to the AWS Documentation:</li><li>SageMaker Processing Job (BYOC): <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/build-your-own-processing-container.html">LINK</a></li><li>SageMaker Training Job (BYOC): <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/model-train-storage.html#model-train-storage-env-var-summary">LINK1</a> and <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html">LINK2</a></li><li>SageMaker BatchTransform Job (BYOC): <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-batch-code.html">LINK</a></li><li>For an end-to-end example of SageMaker workloads with custom containers, please refer to the following example: <a href="https://github.com/aws/amazon-sagemaker-examples/blob/main/advanced_functionality/scikit_bring_your_own/scikit_bring_your_own.ipynb">LINK</a></li></ul><h3>Conclusion</h3><p>We hope that you found this blog informative and useful. To summarize, we started our blog with the definition of MLOps and then discussed its core constituents which are components and pipelines. Later, we saw in detail what is the role of each component and how they can be developed. We ended our blog with a discussion about BYOC, its importance and example links.</p><p>For more updates from Quantiphi follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a> and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/palash-nimodia-94975b4b/"><em>Palash Nimodia</em></a><em> (Architect — Machine Learning), </em><a href="https://www.linkedin.com/in/yogendra-yatnalkar-2477b3148/"><em>Yogendra Yatnalkar</em></a><em> (Senior Machine Learning Engineer) at </em><a href="https://quantiphi.com/"><em>Quantiphi</em></a><em>)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae42dad5c487" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Data to Dollars — A Deep Dive in Time-Series Forecasting V]]></title>
            <link>https://medium.com/@datalab_70093/from-data-to-dollars-a-deep-dive-in-time-series-forecasting-v-b7f0d2ec9b50?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7f0d2ec9b50</guid>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[demand-forecasting]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 11:34:39 GMT</pubDate>
            <atom:updated>2023-10-30T11:34:39.035Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From Data to Dollars — A Deep Dive in Time-Series Forecasting V</strong></h3><p>Welcome back to part 5 of our series on univariate time-series forecasting models! In this series, we have delved into a variety of powerful models for time-series forecasting, including statistical models such as ARIMA, gradient boosting models like XGBoost and LGBM, and deep learning-based models like Neural Prophet and TFT. In the last part, we explored the use of ensembles.</p><p>Now, in this blog, we will take a closer look at all the results of models we have evaluated so far and compare their performance. Our goal is to determine the best model for the dataset that we have selected at the outset of this series.</p><p>Let’s revisit the real-world example of demand forecasting that we introduced in our first blog.</p><h3><strong>Metrics</strong></h3><pre>The proof is in the numbers - let&#39;s dive into the evaluation metrics to see <br>how we measure the performance of our models.</pre><p>We’ll be primarily looking at the following metrics to compare different models.</p><ul><li>Mean Absolute Error (MAE)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/0*oWiHryBMMhWbeaGY" /></figure><ul><li>Root Mean Squared Error (RMSE)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*_EEha0DapMnJZr3D" /></figure><ul><li>Symmetric Mean Absolute Error (sMAPE)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*NMahWkgPAlpuLO7y" /></figure><ul><li>Training Time (t)</li></ul><h3><strong>Data</strong></h3><p>As a quick recap, we had access to 5 years of store-item sales data and needed to predict 1 month of sales for 50 different items across 10 different stores. Our preliminary examination of data revealed a mean daily sale of around 52 items across all stores, a median sale of close to 47, and an interquartile range of 40, indicating significant variances in demand throughout the data.</p><pre>kaggle competitions download -c demand-forecasting-kernels-only</pre><h3><strong>Models</strong></h3><pre>Choosing the best model depends on the characteristics of the time-series data <br>and the specific forecasting task.</pre><p>Following is a short description of models we have explored so far:</p><blockquote><strong>1. ARIMA:</strong> A statistical model that captures linear dependencies between previous observations to forecast future values.</blockquote><blockquote><strong>2. XGBoost and LightGBM: </strong>Gradient boosting frameworks that use an ensemble of decision trees to model complex nonlinear relationships and predict trends in time-series data.</blockquote><blockquote><strong>3. NeuralProphet:</strong> A deep learning-based model that uses a feedforward neural network to model the trend and seasonality in time-series data and handle nonlinearity and non-stationarity.</blockquote><blockquote><strong>4. TFT:</strong> A deep learning-based model that uses a transformer-based architecture to model temporal dependencies in the data and handle multiple seasonalities.</blockquote><blockquote><strong>5. Ensemble:</strong> A combination of multiple models to improve overall accuracy and robustness.</blockquote><h3><strong>Results</strong></h3><pre>Numbers speak louder than words</pre><p>Here comes the interesting part the following tables show the breakdown of evaluation metrics that we have calculated for each of the models that we explored in this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*ujnx7XssgzOY4bdvqP86Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*EGRoKdZtWvA2cWqoYqROdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*ruBq9ywCcuA6XwES0mZhSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*XaN52SJ3g0vhUsmv2Qq2GA.png" /></figure><p>Let’s put numbers side by side for better comparison and evaluation of the models we have explored so far. As we have discussed earlier we will be judging models based on sMAPE and training time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*E0i2mvQzXiUnDmVEPbhugw.png" /></figure><p>Upon analyzing the numbers, it’s clear that NeuralProphet has delivered the most accurate results, with LightGBM following closely behind. However, when it comes to training time, XGBoost emerges as the fastest model. Interestingly, we observed that as the number of features increased, XGBoost slowed down while LightGBM remained relatively stable. This suggests that for datasets with a large number of features, LightGBM might eventually surpass XGBoost in terms of training time.</p><p>While NeuralProphet offers the best accuracy, it takes significantly longer to train compared to LightGBM and XGBoost. Upon closer examination, we found that LightGBM’s accuracy is not far off from NeuralProphet, with an error difference of just 0.412. Additionally, its training time of 4.219 seconds is not too far off from XGBoost’s 1.455 seconds, unlike NeuralProphet which takes 44.759 seconds.</p><p>Overall, choosing the best model depends on the priorities of the specific forecasting task, as it’s a trade-off between accuracy and time. Based on our observations, LightGBM seems to strike a good balance between accuracy and training time, making it a well-rounded option that doesn’t sacrifice much in either department.</p><h3><strong>Closing Thoughts</strong></h3><pre>The journey may have ended, but the insights gained from our experiments will <br>last a lifetime.</pre><p>As we come to the end of this blog and series, it’s important to remember that the field of machine learning is constantly evolving with new and more powerful models being developed. This means that the process of exploration and learning never truly ends. There will always be new techniques to discover and insights to be gained.</p><p>So, as you continue your journey in machine learning, don’t be afraid to try new approaches and push the boundaries of what’s possible. Keep exploring, keep learning, and never stop striving for improvement. With dedication and perseverance, you can become a true expert in this exciting and rapidly evolving field.</p><p>For more updates from Quantiphi follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a> and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/akhil-adapa-aa7151b1/"><em>Akhil Ram Adapa</em></a><em> (Senior Architect — Machine Learning), </em><a href="http://linkedin.com/in/mohdsaifullah-inamdar-10b5701a2"><em>Mohdsaifullah Sadiq Inamdar</em></a><em> (Machine Learning Engineer)at Quantiphi)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7f0d2ec9b50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Data to Dollars — A Deep Dive in Time-Series Forecasting IV]]></title>
            <link>https://medium.com/@datalab_70093/from-data-to-dollars-a-deep-dive-in-time-series-forecasting-iv-495f999998b3?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/495f999998b3</guid>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lightgbm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 10:19:29 GMT</pubDate>
            <atom:updated>2023-10-05T10:19:29.705Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From Data to Dollars — A Deep Dive in Time-Series Forecasting IV</strong></h3><blockquote>Sometimes the sum is greater than its parts — let’s explore the magic of combining models for better predictions.</blockquote><p>In our previous blog posts, we’ve explored various models for demand forecasting, such as LightGBM, XGBoost, NeuralProphet, and TFT, and evaluated their individual performance. However, in this blog post, we’ll dive into an effective method of combining models to achieve even better results. This method is known as <strong>ensembling</strong>, a powerful technique that involves merging the predictions of multiple models to improve overall performance.</p><h3><strong>Ensembles</strong></h3><blockquote>A group of musicians, actors, or dancers who perform together.</blockquote><figure><img alt="Ensembles process" src="https://cdn-images-1.medium.com/max/800/0*mz1ors79YAhUN-fj" /></figure><p>Ensembles are powerful techniques in machine learning and data science that involve combining the predictions of multiple models to produce a more accurate and robust final prediction. There are several ways to create an ensemble, including bagging, boosting, and stacking.</p><p><strong>Bagging:</strong> In bagging, multiple models are trained independently on random subsets of the training data.</p><p><strong>Boosting: </strong>In boosting, multiple models are trained sequentially, with each model correcting the errors of the previous model.</p><p><strong>Stacking: </strong>In stacking, multiple models are trained, and their outputs are used as features for another model, which learns how to combine the outputs of the base models.</p><p>As an experiment, we combined our most lightweight models, LightGBM and XGBoost, using the stacking method. This technique involves training multiple models and using their outputs as input for another model, which learns how to combine them effectively. In our case, the LightGBM and XGBoost models were trained independently and their outputs were combined using a linear regression model.</p><p>The linear regression model was trained on the outputs of the LightGBM and XGBoost models, as well as the actual values as ground truth.</p><p>Some salient features of ensemble methods include:</p><ol><li><strong>Improved accuracy-</strong> Ensembles can improve the accuracy of predictive models by leveraging the strengths of multiple models.</li><li><strong>Reduced overfitting-</strong> Ensembles can help reduce overfitting by combining the predictions of multiple models with different biases.</li><li><strong>Robustness-</strong> Ensembles can be more robust to noisy or outlier data because the predictions are based on multiple models.</li><li><strong>Increased computational cost-</strong> Ensembles can be computationally expensive because they require training multiple models and combining their predictions.</li></ol><p>Overall, ensemble methods are a powerful and flexible technique for improving the accuracy and robustness of predictive models.</p><h3><strong>The Experiment</strong></h3><blockquote>Unlock the full potential of your models with the secret ingredient to predictive success — experimentation!</blockquote><p>Following the same drill for model training and evaluation, we’ll train two base models, LightGBM and XGBoost, and one meta-model, Linear Regression, combining both predictions to generate the final output.</p><p>The code looks almost the same as in <a href="https://medium.com/@datalab_70093/from-data-to-dollars-a-deep-dive-in-time-series-forecasting-ii-ab3733085878">blog-II</a>, for training LightGBM and XGBoost, with slight changes to incorporate the training and prediction of a linear regression model.</p><h4><strong>Imports</strong></h4><blockquote>With the right imports, programming is like playing with Legos.</blockquote><pre>#Import required packages<br>import numpy as np<br>import pandas as pd<br>import time<br>import os<br>from ast import literal_eval<br>from tqdm import tqdm<br>import warnings<br>import matplotlib.pyplot as plt<br>from sklearn.linear_model import LinearRegression<br>import lightgbm as lgb<br>import xgboost as xgb<br><br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h4><strong>Evaluation Functions</strong></h4><blockquote>Measure twice, cut once: The importance of choosing the right evaluation function.</blockquote><p>We will be using the same evaluation method that has been used in all previous blogs.</p><pre>from sklearn.metrics import mean_squared_error,mean_absolute_error<br><br>def smape(y_true, y_pred):<br> &quot;&quot;&quot;<br> Defines the smape (Symmetric Mean Average Percentage Error) metric<br> Args:<br>  1) True values for forecast period<br>  2) Model Forecasts<br> Returns:<br>  sMAPE value<br> &quot;&quot;&quot;<br>  mask = ~((y_true == 0) &amp; (y_pred == 0))<br>  y_true = y_true[mask]<br>  y_pred = y_pred[mask]<br>  return np.mean(np.abs((y_true-y_pred))/((np.abs(y_true)+np.abs(y_pred))/2))*100<br><br>def extract_metrics_from_predicted(y_true, y_pred):<br> &quot;&quot;&quot;<br> Extract all relevant metrics (MAE, RMSE, sMAPE) from the forecasted values<br> Args:<br>  1) True values for forecast period<br>  2) Model Forecasts<br> Returns:<br>  Dictionary containing:<br>   a) RMSE<br>   b) MAE<br>   c) sMAPE<br> &quot;&quot;&quot;<br>  mse = mean_squared_error(y_true, y_pred)<br>  rmse = np.sqrt(mse)<br>  mae = mean_absolute_error(y_true, y_pred)<br>  smape_val = smape(y_true, y_pred)<br>  return {&quot;rmse&quot;:rmse, &quot;mae&quot;:mae, &quot;smape&quot;:smape_val}</pre><p>The above code is used for calculating the error between the forecast and the actuals.</p><h4><strong>Model Training and Evaluation</strong></h4><blockquote>Together we can climb mountains, conquer obstacles, and achieve greatness through the power of training and evaluation.</blockquote><p>For NeuralProphet we can utilize the following function</p><pre>def lgbm_smape(preds, train_data):<br> &quot;&quot;&quot;<br> Return evaluation metric for optimisation of LightGBM model training<br> Args:<br>  1) Forecasted values<br>  2) Training data<br> Returns:<br>  1) Metric name for evaluation<br>  2) Metric value for evaluation<br>  3) Bool value<br> &quot;&quot;&quot;<br> labels = train_data.get_label()<br> smape_val = smape(preds, labels)<br> return &#39;SMAPE&#39;, smape_val, False<br><br>def ensemble_run(temp_df):<br> &quot;&quot;&quot;<br> Train and evaluate the ensemble model<br> Args:<br>  1) Timeseries data<br> Returns:<br>  1) Actual Ground Truth values<br>  2) Forecasted values<br>  3) Training time<br> &quot;&quot;&quot;<br>  lgb_params = {&#39;num_leaves&#39;: 5,<br>              &#39;learning_rate&#39;: 0.0001,<br>              &#39;feature_fraction&#39;: 0.8,<br>              &#39;max_depth&#39;: 5,<br>              &#39;verbose&#39;: 0,<br>              &#39;num_boost_round&#39;: 1000,<br>              &#39;nthread&#39;: -1}<br><br>  temp_df = create_features2(temp_df)<br>  <br>  temp_df.dropna(inplace=True)<br>  temp_df.drop(&#39;date&#39;, axis=True, inplace=True)<br><br>  n_test = 30<br>  train_X, train_y = temp_df.iloc[:-n_test].drop([&#39;sales&#39;], axis=1).reset_index(drop=True), temp_df[&#39;sales&#39;].iloc[:-n_test].reset_index(drop=True)<br>  test_X, test_y = temp_df.iloc[-n_test:].drop([&#39;sales&#39;], axis=1).reset_index(drop=True), temp_df[&#39;sales&#39;].iloc[-n_test:].reset_index(drop=True)<br>  # # print(train_y)<br>  base_n_test = int(len(train_X)*0.25)<br>  base_train_X, base_train_y = train_X.iloc[:-base_n_test].reset_index(drop=True), train_y.iloc[:-base_n_test].reset_index(drop=True)<br>  base_test_X, base_test_y = train_X.iloc[-base_n_test:].reset_index(drop=True), train_y.iloc[-base_n_test:].reset_index(drop=True)<br>  <br>  # Train Base models<br>  lgbtrain = lgb.Dataset(data=base_train_X, label=base_train_y, feature_name=list(base_train_X.columns))<br>  xgb_model = xgb.XGBRegressor(n_estimators=1000, max_depth=5, eta=0.1, <br>                                  objective=&quot;reg:squarederror&quot;, seed=42,<br>                                 tree_method=&#39;auto&#39;, <br>                                 booster = &#39;gblinear&#39;)<br><br>  start_time = time.time()<br><br>  lgbm_model = lgb.train(lgb_params, lgbtrain,<br>        valid_sets=[lgbtrain],<br>        num_boost_round=lgb_params[&#39;num_boost_round&#39;],<br>        #early_stopping_rounds=lgb_params[&#39;early_stopping_rounds&#39;],<br>        feval=lgbm_smape,<br>        verbose_eval=False)<br>  <br>  xgb_model.fit(base_train_X, base_train_y)<br><br>  total_time = time.time() - start_time<br>  <br>  # Predict<br>  lgbm_predicted = lgbm_model.predict(base_test_X, num_iteration=lgbm_model.best_iteration).tolist()<br>  xgb_predicted = xgb_model.predict(base_test_X).tolist()<br><br>  # Training Meta model<br>  ensemble_train_X = pd.DataFrame({<br>    &#39;lgbm_pred&#39;: lgbm_predicted,<br>    &#39;xgb_pred&#39;: xgb_predicted<br>  })<br>  ensemble_train_y = base_test_y<br><br>  meta_model = LinearRegression(fit_intercept=False)<br><br>  start_time = time.time()<br>  meta_model.fit(ensemble_train_X, ensemble_train_y)<br>  total_time = total_time + time.time() - start_time<br>  <br>  # Final forecast<br>  lgbm_pred = lgbm_model.predict(test_X, num_iteration=lgbm_model.best_iteration).tolist()<br>  xgb_pred = xgb_model.predict(test_X).tolist()<br>  ensemble_test_X = pd.DataFrame({<br>    &#39;lgbm_pred&#39;: lgbm_pred,<br>  &#39;xgb_pred&#39;: xgb_pred<br>  })<br><br>  final_forecast = meta_model.predict(ensemble_test_X)<br>  actual = test_y.values.tolist()<br><br>  return actual, final_forecast, total_time</pre><h4>Training Loop</h4><blockquote>In the training loop, every iteration is a step closer to success.</blockquote><pre>def update_dictionary(res_dict, store, item, actual, predicted, rmse, mae, smape, training_time):<br>  &quot;&quot;&quot;<br> Update the results dictionary<br> Args:<br>  1) Store<br>  2) Item<br>  3) Actual Values in the forecast period<br>  4) Predicted Values in the forecast period<br>  5) RMSE Value<br>  6) MAE Value<br>  7) sMAPE Value<br>  8) Training time in seconds<br> Returns:<br> None<br> &quot;&quot;&quot;<br><br> res_dict[&#39;store&#39;].append(store)<br>  res_dict[&#39;item&#39;].append(item)<br>  res_dict[&#39;actual&#39;].append(actual)<br>  res_dict[&#39;predicted&#39;].append(predicted)<br>  res_dict[&#39;rmse&#39;].append(rmse)<br>  res_dict[&#39;mae&#39;].append(mae)<br>  res_dict[&#39;smape&#39;].append(smape)<br>  res_dict[&#39;training_time&#39;].append(training_time)<br>  return<br><br># Read the train and test data<br>train_df = pd.read_csv(TRAIN_PATH)<br>test_df = pd.read_csv(TEST_PATH)<br><br># Get store item combinations and store in an ordered tuple<br>store_item_combinations = train_df[[&#39;store&#39;, &#39;item&#39;]].drop_duplicates().sort_values(by = [&#39;store&#39;, &#39;item&#39;])<br>store_item_tup = [(store, item) for store, item in zip(store_item_combinations[&#39;store&#39;].to_list(), store_item_combinations[&#39;item&#39;].to_list())]<br><br># Initialise a results dictionary<br>res_dict = {&#39;store&#39;: [], &#39;item&#39;: [], &#39;actual&#39;: [], &#39;predicted&#39;: [], &#39;mae&#39;: [], &#39;rmse&#39;: [], &#39;smape&#39;: [], &#39;training_time&#39;: []}<br><br># Loop over all the tuples<br>for store, item in tqdm(store_item_tup):<br>  # Get the timeseries for a particular store-item combination<br> temp_df = train_df[(train_df[&#39;store&#39;]==store) &amp; (train_df[&#39;item&#39;]==item)].copy()<br>  temp_df.drop([&#39;store&#39;, &#39;item&#39;], axis=1, inplace=True)<br><br>  try:<br>    # Train and evaluate the model<br>    actual, predicted, total_time = ensemble_run(temp_df)<br>  except Exception as e:<br>    print(f&#39;Store: {store}; Item: {item} error encountered. {e}&#39;)<br>    predicted = []<br>    actual = []<br>  <br>  # Extract the relevant metrics from the predicted values<br>  error_mat = extract_metrics_from_predicted(actual, predicted)<br>  <br>  # Update the results dictionary<br>  update_dictionary(res_dict, store, item, actual, predicted, error_mat[&#39;mae&#39;], error_mat[&#39;rmse&#39;], error_mat[&#39;smape&#39;], total_time)<br><br># Write the results<br>pd.DataFrame(res_dict).to_csv(f&quot;{WRITE_PATH}/results.csv&quot;, index=False)</pre><h4>Overall Comparison</h4><blockquote>Choosing the right tool is important, but what truly matters is how we use it.</blockquote><p>As discussed in the preceding article, we’ll be focusing on the weighted value of sMAPE across all store item combinations.</p><pre>def get_overall_performance(smape_list, true_values_list, training_time):<br> &quot;&quot;&quot;<br> Compute the performance in terms of the weighted and unweighted sMAPE and training time<br> Args:<br>  1) sMAPE list of all store-item combinations<br>  2) True values during the forecast period<br>  3) Training time across all store-item combinations<br> Returns:<br>  1) Unweighted mean of sMAPE<br>  2) Weighted mean of sMAPE<br>  3) Mean training time<br> for all store-item combinations <br> &quot;&quot;&quot;<br><br>  summed_demand = np.sum(np.asarray(true_values_list), axis = 1)<br>  summed_demand_ratio = summed_demand/np.sum(summed_demand)<br>  weighted_smape = np.multiply(summed_demand_ratio, np.asarray(smape_list), dtype = np.float64)<br>  weighted_smape = np.sum(weighted_smape)<br>  unweighted_smape = np.mean(np.asarray(smape_list))<br>  return unweighted_smape, weighted_smape, np.mean(np.asarray(training_time))<br><br>result_df = pd.read_csv(f&quot;{WRITE_PATH}/results.csv&quot;)<br><br>unweighted_smape, weighted_smape, average_training_time = get_overall_performance(result_df[&#39;smape&#39;].to_list(),result_df[&#39;actual&#39;].apply(literal_eval).to_list(), result_df[&#39;training_time&#39;].to_list())<br><br>print(&quot;unweighted_smape\t&quot;, unweighted_smape)<br>print(&quot;weighted_smape\t&quot;, weighted_smape)<br>print(&quot;average_training_time\t&quot;, average_training_time)</pre><h3>Results and Conclusions</h3><blockquote>The best results come from a combination of hard work and smart choices.</blockquote><p>The following plot shows sMAPE per Item.</p><figure><img alt="The following plot shows sMAPE per Item" src="https://cdn-images-1.medium.com/max/382/0*0c7BtRfxRpUcLeSs" /></figure><p>The plot below illustrates the mean sMAPE per store.</p><figure><img alt="The plot below illustrates the mean sMAPE per store." src="https://cdn-images-1.medium.com/max/382/0*6dRp9W7SQuJ-S1rJ" /></figure><p>The following tables show the breakdown of error matrics calculated for evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*EcjAXtiqYnGEClTQgQr-EA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*xSNpGmGMds1peDxpMdbN1Q.png" /></figure><p>We hope you found this blog helpful in learning how to build an ensemble with LightGBM and XGBoost. Remember, there are endless possibilities for building ensembles with different model combinations, and a more powerful metamodel can improve your results. Additionally, there are three types of ensembles to explore, not just stacked ensembles.</p><p>In the next blog, we’ll collate and compare all the results we have collected to date. Until then, happy modeling!</p><p>For more Quantiphi updates, follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a> and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/akhil-adapa-aa7151b1/"><em>Akhil Ram Adapa</em></a><em> (Senior Architect — Machine Learning), </em><a href="http://linkedin.com/in/mohdsaifullah-inamdar-10b5701a2"><em>Mohdsaifullah Sadiq Inamdar</em></a><em> (Machine Learning Engineer)at Quantiphi)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495f999998b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Data to Dollars — A Deep Dive in Time-Series Forecasting III]]></title>
            <link>https://medium.com/@datalab_70093/from-data-to-dollars-a-deep-dive-in-time-series-forecasting-iii-18557be51c2c?source=rss-bed61d3313b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/18557be51c2c</guid>
            <category><![CDATA[deep-learning-models]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[regression-modeling]]></category>
            <category><![CDATA[tft]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Quantiphi Inc.]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 11:14:13 GMT</pubDate>
            <atom:updated>2023-09-08T11:14:13.500Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From Data to Dollars — A Deep Dive in Time-Series Forecasting III</strong></h3><pre>The best engineering is often inspired by nature</pre><p>Welcome back! In part 3 of our series, we discussed how regression models like XGBoost and LGBM could be used for time series forecasting, and we evaluated their performance on our dataset. In this blog, we will take a deep dive into deep learning-based forecasting models and assess their effectiveness on our data.</p><h3><strong>Neural Networks</strong></h3><pre>The next best thing to human intelligence</pre><figure><img alt="Neural Networks" src="https://cdn-images-1.medium.com/max/600/0*549Nn5FPtUDAb1_W" /></figure><p>Neural networks are a class of machine learning models inspired by the structure and function of the human brain. They are composed of interconnected nodes, or “neurons,” organized into layers that process and transform data.</p><p>Training a neural network involves feeding it a large dataset of inputs and desired outputs, allowing it to learn to make accurate predictions through a process of adjusting the weights and biases of its connections between neurons. This process, known as backpropagation, involves propagating errors from the output layer back through the network and using them to adjust the weights and biases in a way that reduces future prediction errors. With enough training data and careful tuning, neural networks can achieve state-of-the-art performance on a wide range of tasks, including time series forecasting.</p><h3><strong>NeuralProphet</strong></h3><pre>To see the future, look to the past.</pre><figure><img alt="NeuralProphet" src="https://cdn-images-1.medium.com/max/1024/0*pCqK4QNj3OeyzLVj" /></figure><p>NeuralProphet is an advanced time series forecasting model that is built upon a decomposable architecture. The model is composed of various components such as trend, seasonality, auto-regression, special events, future regressors, and lagged regressors.</p><p>The salient features of the NeuralProphet are:</p><ol><li>NeuralProphet <strong>handles univariate and multivariate time series data</strong>. The model can automatically detect the presence of multiple seasonality patterns in the data and incorporate them into the forecast.</li><li>NeuralProphet<strong> can handle missing data and impute missing values for more accurate forecasts</strong>. The model is easy to use and requires minimal data preprocessing.</li><li>NeuralProphet <strong>is open-source and can be easily customized </strong>and extended to fit specific forecasting needs.</li></ol><p>Future regressors are external variables that have known future values for the forecast period, whereas lagged regressors are those external variables that only have values for the observed period.</p><p>Since we are focusing specifically on univariate time series forecasting, we will not be utilizing the advanced features of NeuralProphet such as Future regressors or lagged regressors.</p><h3><strong>Temporal Fusion Transformer (TFT)</strong></h3><pre>Who can talk about sequences and not think about transformer models?</pre><p>The Temporal Fusion Transformer(TFT) is a state-of-the-art deep learning model for time series forecasting developed by Google’s AI research team. TFT is an extension of the Transformer architecture, a powerful neural network model used for natural language processing, that has been adapted to handle time series data.</p><p>The salient features of the TFT are:</p><ol><li>Ability to handle multiple time series with different lengths and varying frequencies.</li><li>Multiple attention mechanisms allow it to capture temporal dependencies within the data.</li><li>The gating mechanism allows it to incorporate both historical and future information into the forecast for improved accuracy.</li><li>Ability to handle missing data and impute missing values for more accurate forecasts.</li></ol><p>TFT has achieved state-of-the-art performance on a range of benchmark datasets and has been widely adopted in the industry for real-world forecasting applications.</p><h3>The Experiment</h3><pre>If at first you don&#39;t succeed, try, try again.</pre><p>As discussed in the preceding part of this series, we’ll be training one model for every store-item combination. In this set of experiments particularly, we’ll be looking at the NeuralProphet and TFT models for our experimentation.</p><p><strong>Imports</strong></p><pre>A smart programmer knows what to write. A smarter programmer knows what to <br>borrow.</pre><p><em>Note: While training these models, we found that NeuralProphet module gives errors when NeuralProphet and NeuralForecast are installed within the same environment. So we recommend using two separate environments for training these two models.</em></p><pre>import numpy as np<br>import pandas as pd<br>import time<br>from datetime import datetime, timedelta<br>from dateutil.relativedelta import relativedelta<br>import os<br>from ast import literal_eval<br>from neuralforecast.core import NeuralForecast<br>from neuralforecast.models import TFT<br>from neuralprophet import NeuralProphet<br>from neuralprophet import utils<br><br>from tqdm import tqdm<br>import warnings<br>import matplotlib.pyplot as plt<br><br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p><strong>Evaluation Functions</strong></p><pre>Measuring progress without defining success is like racing without a <br>finish line.</pre><p>To keep things consistent, we’ve used the same evaluation metrics throughout our experiments.</p><pre>from sklearn.metrics import mean_squared_error,mean_absolute_error<br><br>def smape(y_true, y_pred):<br> &quot;&quot;&quot;<br> Defines the smape (Symmetric Mean Average Percentage Error) metric<br> Args:<br>  1) True values for forecast period<br>  2) Model Forecasts<br> Returns:<br>  sMAPE value<br> &quot;&quot;&quot;<br>  mask = ~((y_true == 0) &amp; (y_pred == 0))<br>  y_true = y_true[mask]<br>  y_pred = y_pred[mask]<br>  return np.mean(np.abs((y_true-y_pred))/((np.abs(y_true)+np.abs(y_pred))/2))*100<br><br>def extract_metrics_from_predicted(y_true, y_pred):<br> &quot;&quot;&quot;<br> Extract all relevant metrics (MAE, RMSE, sMAPE) from the forecasted values<br> Args:<br>  1) True values for forecast period<br>  2) Model Forecasts<br> Returns:<br>  Dictionary containing:<br>   a) RMSE<br>   b) MAE<br>   c) sMAPE<br> &quot;&quot;&quot;<br>  mse = mean_squared_error(y_true, y_pred)<br>  rmse = np.sqrt(mse)<br>  mae = mean_absolute_error(y_true, y_pred)<br>  smape_val = smape(y_true, y_pred)<br>  return {&quot;rmse&quot;:rmse, &quot;mae&quot;:mae, &quot;smape&quot;:smape_val}</pre><p><strong>Model Training and Evaluation</strong></p><pre>The journey is just as important as the destination.</pre><p>For NeuralProphet we can utilize the following function</p><pre>def neuralprophet_run(temp_df, epochs):<br> &quot;&quot;&quot;<br> Train and evaluate the NeuralProphet model<br> Args:<br>  1) Timeseries data<br>  2) Epochs<br> Returns:<br>  1) Actual Ground Truth values<br>  2) Forecasted values<br>  3) Training time<br> &quot;&quot;&quot;<br><br>  temp_df.rename(columns = {&quot;date&quot;:&quot;ds&quot;, &quot;sales&quot;:&quot;y&quot;}, inplace = True)<br>  n_test = 30<br>  train, test = temp_df.iloc[:-n_test, :], temp_df.iloc[-n_test:,:]<br>  utils.set_log_level(log_level=&quot;CRITICAL&quot;)<br>  utils.set_random_seed(seed = 42)<br><br>  neural_proph = NeuralProphet()<br>  <br>  start_time = time.time()<br>  neural_proph.fit(train, epochs=epochs, freq=&#39;D&#39;, progress=None)<br><br>  future = neural_proph.make_future_dataframe(df = train, periods = n_test, n_historic_predictions = True)<br>  y_int = &#39;yhat1&#39;<br><br>  ################# RUN INFERENCE ###############################<br>  predicted = neural_proph.predict(future)<br>  predicted = predicted.iloc[-n_test:, :]<br><br>  total_time = time.time() - start_time<br>  actual = test[&#39;y&#39;].values.tolist()<br>  return actual, predicted[y_int].tolist(), total_time</pre><p>For TFT we can use the following function</p><pre>#@title TFT<br>def tft_run(temp_df, epochs):<br> &quot;&quot;&quot;<br> Train and evaluate the TFT model<br> Args:<br>  1) Timeseries data<br>  2) Epochs<br> Returns:<br>  1) Actual Ground Truth values<br>  2) Forecasted values<br>  3) Training time<br> &quot;&quot;&quot;<br>  temp_df.rename(columns = {&quot;date&quot;:&quot;ds&quot;, &quot;sales&quot;:&quot;y&quot;}, inplace = True)<br>  temp_df[&#39;ds&#39;] = pd.to_datetime(temp_df[&#39;ds&#39;])<br>  temp_df[&#39;unique_id&#39;] = 1.0<br>  n_test = 30<br>  train, test = temp_df.iloc[:-n_test, :], temp_df.iloc[-n_test:,:]<br>  utils.set_log_level(log_level=&quot;CRITICAL&quot;)<br>  utils.set_random_seed(seed = 42)<br><br>  neural_proph = NeuralProphet()<br>  <br>  start_time = time.time()<br>  nforecast = NeuralForecast(models=[TFT(input_size = 14, h = 30,   <br>learning_rate=1e-4,<br>max_epochs = epochs, <br>random_seed=42,<br>enable_progress_bar=True,<br>callbacks =None,<br>hidden_size=128,n_head=16,<br>auto_select_gpus=True)],<br>                             freq=&quot;D&quot;)<br><br>  nforecast.fit(df = train)<br>  ################# RUN INFERENCE ###############################<br>  predicted = nforecast.predict(futr_df=test[[&#39;unique_id&#39;, &#39;ds&#39;]].reset_index(drop=True))<br>  predicted = predicted.iloc[-n_test:, :]<br>  predicted = predicted[&#39;TFT&#39;].values.tolist()<br>  total_time = time.time() - start_time<br>  actual = test[&#39;y&#39;].values.tolist()<br>  return actual, predicted, total_time</pre><p><strong>Training Loop</strong></p><pre>In training, it&#39;s not about perfection - it&#39;s about progress</pre><pre>def update_dictionary(res_dict, store, item, actual, predicted, rmse, mae, smape, training_time):<br>  &quot;&quot;&quot;<br> Update the results dictionary<br> Args:<br>  1) Store<br>  2) Item<br>  3) Actual Values in the forecast period<br>  4) Predicted Values in the forecast period<br>  5) RMSE Value<br>  6) MAE Value<br>  7) sMAPE Value<br>  8) Training time in seconds<br> Returns:<br> None<br> &quot;&quot;&quot;<br><br> res_dict[&#39;store&#39;].append(store)<br>  res_dict[&#39;item&#39;].append(item)<br>  res_dict[&#39;actual&#39;].append(actual)<br>  res_dict[&#39;predicted&#39;].append(predicted)<br>  res_dict[&#39;rmse&#39;].append(rmse)<br>  res_dict[&#39;mae&#39;].append(mae)<br>  res_dict[&#39;smape&#39;].append(smape)<br>  res_dict[&#39;training_time&#39;].append(training_time)<br>  return<br><br># Read the train and test data<br>train_df = pd.read_csv(TRAIN_PATH)<br>test_df = pd.read_csv(TEST_PATH)<br><br># Get store item combinations and store in an ordered tuple<br>store_item_combinations = train_df[[&#39;store&#39;, &#39;item&#39;]].drop_duplicates().sort_values(by = [&#39;store&#39;, &#39;item&#39;])<br>store_item_tup = [(store, item) for store, item in zip(store_item_combinations[&#39;store&#39;].to_list(), store_item_combinations[&#39;item&#39;].to_list())]<br><br># Initialise a results dictionary<br>res_dict = {&#39;store&#39;: [], &#39;item&#39;: [], &#39;actual&#39;: [], &#39;predicted&#39;: [], &#39;mae&#39;: [], &#39;rmse&#39;: [], &#39;smape&#39;: [], &#39;training_time&#39;: []}</pre><p>For NeuralProphet, we have the following code.</p><pre># Loop over all the tuples<br>for store, item in tqdm(store_item_tup):<br>  # Get the timeseries for a particular store-item combination<br> temp_df = train_df[(train_df[&#39;store&#39;]==store) &amp; (train_df[&#39;item&#39;]==item)].copy()<br>  temp_df.drop([&#39;store&#39;, &#39;item&#39;], axis=1, inplace=True)<br><br>  try:<br>  # Train and evaluate the model<br>    actual, predicted, total_time = neuralprophet_run(temp_df, epochs=100)<br>  except Exception as e:<br>    print(f&#39;Store: {store}; Item: {item} error encountered. {e}&#39;)<br>    predicted = []<br>    actual = []<br>  <br>  # Extract the relevant metrics from the predicted values<br>  error_mat = extract_metrics_from_predicted(actual, predicted)<br>  <br>  # Update the results dictionary<br>  update_dictionary(res_dict, store, item, actual, predicted, error_mat[&#39;mae&#39;], error_mat[&#39;rmse&#39;], error_mat[&#39;smape&#39;], total_time)<br><br># Write the results<br>pd.DataFrame(res_dict).to_csv(f&quot;{WRITE_PATH}/results.csv&quot;, index=False)</pre><p>For TFT, the training loop looks virtually the same, except for replacing the neuralprophet_run with the tft_run.</p><h3>Overall Comparison</h3><pre>The good, the bad, and the better</pre><p>As discussed in the preceding article, we’ll be focusing on the weighted value of sMAPE across all store item combinations.</p><pre>def get_overall_performance(smape_list, true_values_list, training_time):<br> &quot;&quot;&quot;<br> Compute the performance in terms of the weighted and unweighted sMAPE and training time<br> Args:<br>  1) sMAPE list of all store-item combinations<br>  2) True values during the forecast period<br>  3) Training time across all store-item combinations<br> Returns:<br>  1) Unweighted mean of sMAPE<br>  2) Weighted mean of sMAPE<br>  3) Mean training time<br> for all store-item combinations <br> &quot;&quot;&quot;<br><br>  summed_demand = np.sum(np.asarray(true_values_list), axis = 1)<br>  summed_demand_ratio = summed_demand/np.sum(summed_demand)<br>  weighted_smape = np.multiply(summed_demand_ratio, np.asarray(smape_list), dtype = np.float64)<br>  weighted_smape = np.sum(weighted_smape)<br>  unweighted_smape = np.mean(np.asarray(smape_list))<br>  return unweighted_smape, weighted_smape, np.mean(np.asarray(training_time))<br><br>result_df = pd.read_csv(f&quot;{WRITE_PATH}/results.csv&quot;)<br><br>unweighted_smape, weighted_smape, average_training_time = get_overall_performance(result_df[&#39;smape&#39;].to_list(),result_df[&#39;actual&#39;].apply(literal_eval).to_list(), result_df[&#39;training_time&#39;].to_list())<br><br>print(&quot;unweighted_smape\t&quot;, unweighted_smape)<br>print(&quot;weighted_smape\t&quot;, weighted_smape)<br>print(&quot;average_training_time\t&quot;, average_training_time)</pre><p><strong>Results and Conclusions</strong></p><pre>Conclusions are not set in stone, they are stepping stones to greater <br>discoveries.</pre><p>The following plots show sMAPE per Item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*ICHve0lVlZeg8kWU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*Vp02WPQoGmYV-4ui" /></figure><p>The plots presented below illustrate the mean sMAPE per store for two models. Consistent with both models, store 1 demonstrates the highest mean sMAPE, while store 3 exhibits the lowest. This information is crucial in identifying stores that require more attention and in enhancing the models for improved forecasting outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*-BJw_2Ine2vY-HM3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*iGQLMKOtDLexNhE4" /></figure><p>The following tables show the breakdown of error matrices calculated for evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*QDrr033Kb9cj1uQh-bIb5A.png" /></figure><p>After comparing the performance of NeuralProphet and TFT models in terms of sMAPE and training time, it is evident that NeuralProphet outperforms TFT in accuracy. However, TFT has an advantage when it comes to training time, being twice as fast as NeuralProphet. This presents a trade-off between prioritizing accuracy or speed, depending on the specific requirements of the task at hand. Ultimately, the choice of model should align with the goals and priorities of the user, whether it be accuracy, speed, or a balance between the two.</p><p>As we conclude this blog, we can reflect on the significant progress we have made from the baseline model results. However, our journey of exploration to enhance our predictive abilities does not end here. We are excited to embark on a new approach to tackle this problem, and we look forward to sharing our findings with you in the future. Stay tuned!</p><p>For more updates from <a href="https://quantiphi.com/">Quantiphi</a> follow us on <a href="https://www.linkedin.com/company/quantiphi">Linkedin</a>, <a href="https://twitter.com/Quantiphi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</a>, <a href="https://www.instagram.com/quantiphi/?hl=en">Instagram</a>, and <a href="https://www.youtube.com/c/quantiphianalytics">YouTube.</a></p><p><em>(With contributions from </em><a href="https://www.linkedin.com/in/akhil-adapa-aa7151b1/"><em>Akhil Ram Adapa</em></a><em> (Senior Architect — Machine Learning), </em><a href="http://linkedin.com/in/mohdsaifullah-inamdar-10b5701a2"><em>Mohdsaifullah Sadiq Inamdar</em></a><em> (Machine Learning Engineer)at Quantiphi)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18557be51c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>