<?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 Rafaelle A on Medium]]></title>
        <description><![CDATA[Stories by Rafaelle A on Medium]]></description>
        <link>https://medium.com/@rafaelleaylq?source=rss-78d8cbfbb42b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wO4755VXYBuTcIAbmcEFIw.jpeg</url>
            <title>Stories by Rafaelle A on Medium</title>
            <link>https://medium.com/@rafaelleaylq?source=rss-78d8cbfbb42b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:05:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafaelleaylq/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[How to deploy and secure your Streamlit app on GCP?]]></title>
            <link>https://medium.com/artefact-engineering-and-data-science/how-to-deploy-and-secure-your-streamlit-app-on-gcp-4ab5fd873ed0?source=rss-78d8cbfbb42b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ab5fd873ed0</guid>
            <category><![CDATA[app-engine]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[cloudrun]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Rafaelle A]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 12:13:34 GMT</pubDate>
            <atom:updated>2021-06-23T14:49:50.379Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>Streamlit is a great tool to create beautiful data applications quite easily but when it comes to deploying them and making them accessible, it can be more complicated for non-specialists. In this article we aim at presenting our journey to <strong>deploying our application on GCP</strong> ensuring a <strong>restricted access</strong> to specific people. We implemented two solutions: one with Cloud Run, the other with App Engine and we chose to keep <strong>App Engine for its ease of securing the application </strong>with IAP (Identity-Aware Proxy).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xD_VaiZ9le3rnJlM" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Deployment motivations</h3><p>In this article, we will take the example of the Text Data Explorer, a Streamlit application that we have developed aiming to provide insights on raw text data in few minutes and few clicks. This application will be presented in a future article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*YWfiTrZP4oJYwIbk_ra4wQ.png" /><figcaption>Example of the app that will be deployed on GCP</figcaption></figure><p>There are two main options to launch this application and this process:</p><ul><li>Either the user clones the GitHub repository on his computer, installs all the dependencies and launches the application on a local environment.</li><li>Or the user has direct access to the application using a dedicated URL without any prior installation.</li></ul><p>In order to make the application available to the largest number of people within our company, and therefore people who are not necessarily used to dealing with GitHub, we have decided to <strong>deploy the application on GCP</strong> (Google Cloud Platform) and make it accessible via a single URL in a <strong>secure</strong> <strong>environment</strong>.</p><h3>Step-by-step deployment on GCP</h3><p>Two different approaches have been tested to deploy the application on GCP:</p><ul><li>Using Cloud Run</li><li>Using App Engine</li></ul><p>However, there is a preliminary common step that concerns both of these approaches which consists in the “dockerization” of our application.</p><h4>Dockerizing the application</h4><p>If you are not familiar with Docker, here is a small introduction but do not hesitate to check out the <a href="https://www.docker.com/">documentation</a> or more specific articles for further details.</p><p><strong><em>What is docker?</em></strong></p><p><em>Docker is an open platform for developing, shipping, and running applications. It allows you to package an application with all of its dependencies into a standardized unit for software development.</em> <em>In practice, this involves building what is called a Docker image, i.e. the blueprints of the application which form the basis of Docker containers, the content at rest. In order to build this image, we need to define a Dockerfile, i.e. a simple text-file that contains a list of commands that the Docker client calls while creating an image. Once built, the image is stored in a registry (e.g. Container Registry on GCP) and can be deployed on a dedicated instance, via Cloud Run or App Engine for example.</em></p><p>Therefore in our case we have to:</p><ul><li>Create a Dockerfile</li><li>Build our application image</li><li>Store the image on a registry</li></ul><p>Let’s start with the creation of the Dockerfile. As mentioned before, this consists in a succession of commands used to create the Docker image. In the case of a Streamlit application, the Dockerfile can be divided into several blocks:</p><ul><li>Define the runtime environment: in our case python 3.7</li><li>Define the port on which the application will run</li><li>Install the needed libraries and their dependencies using a <em>requirements.txt</em> file</li><li>Copy the code of your application and define the working directory from where the application will be launched</li><li>Define the command to run the application</li></ul><p>Our code is organized in the following way:</p><pre>├── app.py           &lt;- Main script to launch the Streamlit app<br>├── text_explorer    &lt;- Folder gathering all the functions and code<br>├── requirements.txt &lt;- File listing needed libraries to install<br>└── references       &lt;- Folder containing logos and images</pre><p>With this structure, here is an example of the Dockerfile we used for our application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd6668839694651ec8513fbf1cd30faa/href">https://medium.com/media/fd6668839694651ec8513fbf1cd30faa/href</a></iframe><p>Once the Dockerfile is created, we can build our image, following a GCP-friendly naming convention that will be helpful for the deployment later on. This is done via the following command:</p><pre>docker build -t eu.gcr.io/gcp_project_name/app_name:v1 .</pre><p>To adapt it to your own application, replace the <em>‘gcp_project_name’</em> by your own GCP project name and the <em>‘app_name’ </em>by your own application name. You can also update the version number as your application evolves by modifying the <em>‘v1’</em> suffix with your current version.</p><p>From there, with our application packaged in a docker image, we can deploy it on GCP to make it accessible to our teammates.</p><h4>Deploy your app with Cloud Run</h4><p>Cloud Run is a GCP serverless cloud service used to easily deploy pre-built applications. One of its main advantages is that it automates most of the resources management process. Therefore, all you have to do is to tell Cloud Run where your Docker image is, and then Cloud Run will deploy it on a serverless environment without needing to specify the optimal number of resources for example.</p><p>In order to do that, you can follow the steps listed below:</p><ul><li>Initialize <em>gcloud</em> module on the right GCP project with the following command:</li></ul><pre>gcloud init</pre><ul><li>Push the docker to the GCP Container Registry with the following command:</li></ul><pre>docker push eu.gcr.io/gcp_project_name/app_name:v1</pre><ul><li>Go on your GCP project, on the Cloud run section. Click on “Create service”, choose the region and define your service name. Then, select the Docker image that corresponds to your Streamlit app and update the port with the one you defined in your Dockerfile</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*JfM3iABOaUTzvE1b1_kXVg.png" /><figcaption>Cloud Run interface</figcaption></figure><ul><li>Finally, you can test your app by following the URL linked to the newly created Cloud Run service</li></ul><p>As you can see, the deployment is done in just a few steps and is quite easy, even for newcomers to application deployment. However, in our case, on top of the deployment, we also wanted to secure our application so that it would only be accessible within our company and at that time, we did not find any “easy” solution that would fit with Cloud Run. That is why we decided to look for an alternative solution that would allow us to have this security layer without too much difficulty and we finally ended up with App Engine.</p><h4>Deploy your app with App Engine</h4><p>App Engine is a cloud-based computing service used to host web apps that are already in the Google infrastructure. In a nutshell, it allows you to do the same thing as Cloud Run in the sense that they are both Google cloud services that allow you to deploy applications. However, unlike Cloud Run where you only pay for the requests that come in, on App Engine you pay for the entire run time, whether there are requests or not. Thus at the end, App Engine may be a more expensive solution. Despite this, we still decided to go for this solution because App Engine has the advantage of having a native integration with IAP (Identity-Aware Proxy) that allows to easily secure your application.</p><p>The steps to achieve a deployment on App Engine are not more numerous nor more complicated than for Cloud Run, here is what you need to do:</p><ul><li>Check the port specified in your Dockefile, it has to be <strong>8080</strong> to be compatible with App Engine</li><li>Initialize <em>gcloud</em> module on the right GCP project with the following command:</li></ul><pre>gcloud init</pre><ul><li>Create a YAML file for your app (named <strong><em>app.yaml</em></strong>) at the root of your project (i.e. at the same level as your main script and your Dockerfile) with the following template:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*kdB89Hja5Ecfui_Dfvz4Jg.png" /><figcaption>app.yaml file example</figcaption></figure><p><em>Update the </em><strong><em>service</em></strong><em> name with your own application service name</em></p><p>Here we defined the <strong><em>runtime: custom</em></strong> option because custom runtimes let you build apps that run in an environment defined by a Dockerfile as it is the case for us. The <strong><em>env:flex</em></strong> option means that our application will be run in the flexible environment (by opposition to the standard environment). This choice was made because the flexible environment runs the application in Docker containers on Google Compute Engine virtual machines (VMs), which have fewer restrictions than in the standard environment (e.g. your app cannot write to disk). More details about the key differences are available in the <a href="https://cloud.google.com/appengine/docs/flexible/go/flexible-for-standard-users">Google documentation</a>.</p><p>You can also include more detailed <a href="https://cloud.google.com/appengine/docs/flexible/custom-runtimes/configuring-your-app-with-app-yaml#network_settings">network</a>, <a href="https://cloud.google.com/appengine/docs/flexible/custom-runtimes/configuring-your-app-with-app-yaml#resource-settings">resources</a> and <a href="https://cloud.google.com/appengine/docs/flexible/custom-runtimes/configuring-your-app-with-app-yaml#services">scaling</a> settings within the YAML file such as the minimum number of instances given to your service or the number of CPUs for example. You can also define some <a href="https://cloud.google.com/appengine/docs/flexible/custom-runtimes/configuring-your-app-with-app-yaml#defining_environment_variables">environment variables</a> in that file to make them accessible to your application.</p><ul><li>Run the following command <em>(this could take several minutes)</em>:</li></ul><pre>gcloud app deploy app.yaml</pre><ul><li>Once done with the deploy command, the app will be available on App Engine and you will find its dedicated URL directly on GCP</li></ul><p>If you want to <strong>secure your app and give a restricted access</strong> to some people, go to your GCP project, in the <em>“IAM &amp; Admin”</em> / <em>“Identity-Aware Proxy”</em> section:</p><ul><li>In “All Web Services” you should see an “App Engine app” section. If IAP is off, turn it on and click on your Streamlit service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*eYqB02VUQY_gvYp_tsjglQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*kpjA2pBaEVONBRuBt1NMjQ.png" /><figcaption>IAP sections to manage permissions</figcaption></figure><ul><li>On the right, click on “Add member”, enter all the email addresses you want (or an alias linked to a mailing list) and select the “IAP-secured Web App User” role.</li></ul><p>And you’re done. Your application is now deployed and secured.</p><h4>Tips if you have trouble with images display in your deployed app</h4><p>When using <em>st.pyplot()</em> or <em>st.image()</em>, you may encounter some display troubles when looking at your deployed application (i.e. <em>“0”</em> displayed instead of your plot or image). We recommend to use <em>st.plotly_chart()</em> whenever you can to avoid that and to use HTML code snippets otherwise. For example, in our case, we wanted to display some wordclouds and that could not be done with Plotly. Thus we decided to save the wordcloud image as PNG in a dedicated GCS bucket, download it as bytes and display it with some HTML code like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e993d60bd1e4726aa7aea0d97c1af841/href">https://medium.com/media/e993d60bd1e4726aa7aea0d97c1af841/href</a></iframe><p>In that example, the variable “<em>image</em>” is a bytes object coming from the method <a href="https://googleapis.dev/python/storage/latest/blobs.html"><em>.dowload_as_bytes()</em></a> of Google cloud storage python package.</p><h3>Conclusion</h3><p>The purpose of this article was to give you some tips and examples of cloud services that can be used for deploying Streamlit applications. In our experience, if you need a security layer to ensure restricted access to some people, App Engine will be the appropriate solution. Otherwise, Cloud Run remains an easy way to deploy a Streamlit application.</p><p>Thanks a lot for reading up to now, do not hesitate to reach out if you have any questions. You can find more about our projects by visiting our <a href="https://medium.com/artefact-engineering-and-data-science">blog</a>.</p><p><em>Credits: Paul Devienne, Amale El Hamri</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ab5fd873ed0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/artefact-engineering-and-data-science/how-to-deploy-and-secure-your-streamlit-app-on-gcp-4ab5fd873ed0">How to deploy and secure your Streamlit app on GCP?</a> was originally published in <a href="https://medium.com/artefact-engineering-and-data-science">Artefact Engineering and Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 tips to better take promotional data into account]]></title>
            <link>https://medium.com/artefact-engineering-and-data-science/the-path-to-developing-a-high-performance-demand-forecasting-model-part-2-8193e87fc9ac?source=rss-78d8cbfbb42b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8193e87fc9ac</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[demand-sensing]]></category>
            <category><![CDATA[retail]]></category>
            <dc:creator><![CDATA[Rafaelle A]]></dc:creator>
            <pubDate>Wed, 26 May 2021 11:12:06 GMT</pubDate>
            <atom:updated>2021-11-24T13:21:44.405Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>The path to developing a high-performance demand forecasting model — Part 2</strong></h4><h3>TL;DR</h3><p>In this following article of a large series of posts dedicated to demand forecasting, we will focus on how to model promotions, a key driver in sales forecasting, looking at what a typical promo dataset looks like, how features should be crafted, with a step-by-step example in Python, and how complex promotional granularity can be dealt with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jHC8EBQiz9FR0yMv" /><figcaption>Photo by <a href="https://unsplash.com/@belart84?utm_source=medium&amp;utm_medium=referral">Artem Beliaikin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Context</h3><p>When forecasting demand as retailers, we often can leverage several useful data sources such as historical sell-in, product and customer hierarchies, holidays, sell-out and promotions. It is important to pay particular attention to the latter as, in real life, promotional activity is often much more than just a dummy flag you should add as a feature to your model. It is a real complex business mechanism which can yield additional performance to your model if processed well.</p><h3><strong>Tips 1: Understanding promotions referentials</strong></h3><p>Sales dataset often do not include promo data. You need to plug in a specific referential into your training data. Promotional data often come as a set of columns, in the format of a promotion plan with promotion characteristics such as:</p><ul><li>SKU concerned by the promotion</li><li>Retailer benefiting from the promotion</li><li>Start and end dates</li><li>Promotion ID <em>(unique ID for identifying a promotion for a given SKU, retailer, start date, end date)</em></li><li>Promotion type <em>(e.g. 3 for 2)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*yzFPLk8iDin3zB7a-Xfxlg.png" /><figcaption>Example of promotion data</figcaption></figure><p>Before starting the feature engineering and modeling parts, it is recommended to perform interviews with the business owners in order to understand how promotion are created and handled. Let’s take the example of dates. In the case of a sell-in prediction, a promotion will be associated with several dates:</p><ul><li>official start and end dates for shipping orders from the distributor to the retailers (1)</li><li>and official start and end dates of promotions set up in stores by retailers (2)</li></ul><p>It is really important to understand which dates impact the most the target variable and to check with the business owners if there are any specificities to take into account (<em>e.g.</em> if some retailers may apply the promotions before or after the official start and end dates).</p><p>Performing Exploratory Data Analysis (EDA) can help you understand the fluctuations and the impact promotions can have on the target variable. For example, below one can see that a particular type of promotion has a greater impact than others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*mziarRYecMAMlVootFs-2g.png" /><figcaption>Example of the impact of two different promotions on the sales of a given product</figcaption></figure><p>EDA can also be performed to validate insights previously highlighted by business teams. Below, it seems retailers are starting promotions well before the official start date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*BJPTl5R5mYz81n_kUbvfpw.png" /><figcaption>Example of difference between official and real start date of promotions</figcaption></figure><p>After the exploration, we need to process the raw promotion data in order for it to be used. The dates have first to be expanded and processed in order to have a continuous timeline. Some of them may need to be shifted based on what was found during the exploration and business interview phases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KcbqpLQQ4iVNNIyKqfiaA.png" /><figcaption>Illustration of promotion data before and after preprocessing</figcaption></figure><h3><strong>Tips 2: Choosing the right granularity</strong></h3><p>As your EDA will show, promotions impacts differ greatly across products, retailers (or stores if you’re working with sell-out data), types of promotions. Ideally, you’d like to be as much precise as possible and keep a SKU x retailer x promotion type granularity.</p><p>For example, you may have two different geographic granularity: retailer and warehouse (<em>i.e. </em>a warehouse contains severals retailers). By plotting your time-series at each granularity, you may find out that the impact of promotion is really visible at retailer level but seems smoothed for warehouses. This can be explained by the fact that not all retailers of a the warehouse are impacted by the promotion in the same way. Therefore in that example, it is preferable to work at the retailer granularity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*zcyEZRUM7QLzeItRdAMX_Q.png" /><figcaption>Difference of the promotion impact depending on the granularity</figcaption></figure><p>Once the EDA has been done and the promotion data is at the right granularity, the objective is to create the most relevant features for future planned promotions for which we want to predict the associated sales.</p><h3><strong>Tips 3: Crafting the right features</strong></h3><p>People may think that just adding a dummy variable in your training dataset will be enough. This works to guide the model in understanding why demand or sales is higher at one point in time. However, it is a really poor way to model how promotion may impact sales. Typically, some promotion types may be more efficient than others, the impact of promotions may also be higher near the start date, lower after (as there are few people left that could benefit from the reduction).</p><p>A more sophisticated feature we found useful when using <strong>boosting</strong> algorithms is to compute sales rolling means so as to give your model insights about how much each promo type was successful in the past.</p><h4><strong>1. Theory</strong></h4><p>The idea behind this kind of feature is to measure, for a given promotion, the average volume recently generated by “similar promotions” in the past. We are going to compute the average historical sell-in on a similar scope (same promotion type, same SKU, same retailer) on a rolling window with a given horizon (<em>e.g.</em> on the 7 past days).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*SC8vmUw3GL5hvx-0UJvsIw.png" /><figcaption>Example of a rolling mean with a 7-days window</figcaption></figure><p><strong>For this kind of features, a particular attention should be paid to data leakage, especially when setting the time horizon.</strong></p><h4><strong>2. Python implementation</strong></h4><p>Let’s see how to implement a 7-days rolling mean feature step by step in Python. First of all, let’s define our DataFrame with the following information:</p><ul><li>SKU</li><li>Retailer</li><li>Promotion type</li><li>Promotion ID</li><li>Date</li><li>Sell-in <em>(our target variable)</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bdde5de8b3c157d90857ac56302fe05/href">https://medium.com/media/1bdde5de8b3c157d90857ac56302fe05/href</a></iframe><p>Once created, our DataFrame looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*rAPq3mL3EXFdVYSWiO7qKA.png" /><figcaption>Initial DataFrame</figcaption></figure><p>Next we will create two important columns : the start date of promotion and the rolling mean <em>(empty for now)</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcdb8be272d011cf84c9e6141a0296ae/href">https://medium.com/media/bcdb8be272d011cf84c9e6141a0296ae/href</a></iframe><p>Now, the DataFrame should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*QfU68xZb1F92xSSRQptrXw.png" /><figcaption><em>Head of the DataFrame with the two new columns</em></figcaption></figure><p>From there, we can start filling in the <em>promo_rolling_mean </em>column. Remember that the goal is to compute the mean of sell-in of previous similar promotions but the <strong>notion of</strong> <strong>similarity can be</strong> <strong>tricky</strong>. In the best case scenario, we have in our history a promotion with the same type, for the same retailer, for the same SKU. In worst case scenario, there is a new promotion with a new type for which we do not have any history for any SKU, any retailer. Therefore the idea is to define several levels of granularity for which we will see if we have a history and therefore a possibility to calculate a rolling mean, starting from the most granular level <em>(e.g. SKU x retailer x promotion type)</em> to the least granular level <em>(e.g. SKU)</em>.</p><p>For example, let’s take SKU : 1, retailer : A, promotion type : 1, date : 2020–01–01. We look for a similar promotion in the past. Lucky for us, there has been a promotion with the same promotion type, for the same SKU, the same retailer <em>(i.e. the most granular level)</em> in 2019 <em>(promotion_id = ‘A1–2019’). </em>Thus we will take the mean of the sell-in for the 7 most recent dates where this kind of promotion happened. In other cases we may not find any match for this granularity so we will be looking for a match by SKU and promotion type only. Again, if there is no match, we will finally take the mean at the SKU level only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01f00db0ae967d9f9f55e928174b62ac/href">https://medium.com/media/01f00db0ae967d9f9f55e928174b62ac/href</a></iframe><p>At the end of the for loop, as you merge this new feature with the train set, you must pay attention at data leakage and only take rolling means computed for dates before each observation date (the date for which you want to make forecasts). Here, we have decided to use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html">merge_asof</a> method. This allows us to merge two datasets avoiding exact matches. The idea behind it is: do not take the exact date match <em>(with the allow_exact_matches=False parameter)</em>, but take the previous ones <em>(with the direction=”backward” parameter)</em>.</p><p>Here is what our dataset looks like with the rolling mean feature filled after this step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*v5bRVH95M_Y56s6bJcnXcQ.png" /><figcaption>Final DataFrame with the rolling mean feature</figcaption></figure><p>We can first see that there are some missing values for the rolling mean feature at the top of the DataFrame. This is normal and is due to the fact that for the first rows, we do not have any history on any SKU, any retailer, therefore no possibility to compute a rolling mean. This is the only case where the rolling mean will be empty, any other case can be handled by the definition of the granularity aggregation levels.</p><p>For example, for the specific row we have defined at the beginning <em>(SKU: 1, Retailer A, Promotion type: 3, Date: 2020–06–01)</em>, the one for which we don’t know the sell-in yet, the rolling mean value will be the mean of the sell-in for the most similar and recent promotion. In our case, there is no history for the promotion type 3 for the retailer A, but there is for retailer B. Therefore, the rolling mean value will be the mean of sell-in for SKU=1, Promotion type= 3, Retailer=B, here: mean([134, 146]) = 140.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*V_wM8LfuQOmEcMFFsYn13Q.png" /><figcaption>Example for a new promotion type for a couple SKU x retailer</figcaption></figure><p>This logic can be extended to several other cases that can be encountered in this type of projects. For example, an additional level could be created which would be the product family and which could be used in the case where there is no history for a given product. In that case we will take the average based on products belonging to the same family. It is therefore important to think about these levels of granularity and prioritize them according to your own definition of “promotion similarity” which can be based on your EDA or business insights, for example.</p><p>Instead of the rolling means, you can also measure the <strong>promotional uplift</strong> <em>(i.e. the additional volume generated by a given promotion)</em> for a given product and a given customer. The idea would be to compute a <strong>ratio between sales during a given promotion and the sales without any promotion instead</strong>.</p><h3><strong>Tips 4: Dealing with big data</strong></h3><p>Working at such a level of granularity can drastically increase complexity and the need for computational power. If like us you are dealing with hundreds of SKUs, retailers and several years of daily historical sell-in, it will be essential to find a way to <strong>parallelize computations</strong>. For example, if you have no need to get any information from other SKUs for your promotion features, you can partition your data on the <em>sku</em> column and use distributed computing. We found it useful to use <a href="https://dask.org/"><strong>Dask</strong></a><em> </em>for this task:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58473a358c8a509e01a3ae13a4d93d8a/href">https://medium.com/media/58473a358c8a509e01a3ae13a4d93d8a/href</a></iframe><h3><strong>Tips 5: Taking into account demand transfers across products</strong></h3><p>Don’t forget that each SKU sales will be impacted by its promotions, but also by promotions from substitutable products, such phenomena is known as cannibalization. In order to have a performant model, it is mandatory to <strong>anticipate the potential downlift</strong> on some products resulting from cannibalization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*SzoFc8BrkgsJbU1AbyYqnA.png" /><figcaption>Cannibalization illustration</figcaption></figure><p>In order to be able to model the phenomenon, we first have to <strong>detect the cannibalization relationships</strong> between products. Two main approaches can be distinguished:</p><ul><li>Use an existing mapping: if such mapping exists, all we have to do is to add this information to our dataset (<em>e.g.</em> a column “associated cannibalizing product”) and create specific features based on that.</li><li>Detect the cannibalization relationships automatically: the idea will be to establish relationships by looking at product similarities and behaviors in the past.</li></ul><h4><strong>Automatic detection deep dive</strong></h4><p>One possibility to automatically detect cannibalization relationships is to use <strong>correlation scores.</strong> The idea is to bring together products that are really likely to cannibalize each other, not on the basis of their category, but on the basis of correlations between the evolution of their historical sales. Correlation scores are calculated for each pair of products and if they are <strong>strongly negative</strong> then we can assume that these products are cannibalizing each other</p><h4><strong>Cannibalization features deep dive</strong></h4><p>From these cannibalization relationships we can create features following the same approach as for direct promotions. For example:</p><ul><li>Associate to each cannibalized product, the <strong>promotion rolling mean</strong> computed for the cannibalizing product. The “volume” in those features is therefore the “volume”of the <strong>cannibalizing</strong> <strong>products</strong>.</li><li>Associate to each cannibalized product, the <strong>downlift (loss of volume)</strong> that generally appears when the associated cannibalizing product is sold. The “volume” in those features is therefore the “volume”of the <strong>cannibalized products</strong>.</li></ul><h3>Results and conclusion</h3><p>In our projects, we have observed that, in most cases, rolling mean features tended to work better for the model than uplift/downlift features. For example, for a given country, the <strong>rolling mean features resulted in a 2.8% increase in forecast accuracy while the uplift features resulted in a 2% increase</strong>.</p><p>However, each project is different and our main learning is that the exploration phase is essential and serves as a basis for the creation of features later on. It is necessary to really understand how promotions work and their impact in order to model them correctly. This involves discussions with the business owners as well as Exploratory Data Analysis.</p><p>A big thank you to all the team who worked on this mission who made it possible to write this article, especially Kasra Mansouri and Cédric Magnan. Stay tuned for the next articles in this series and do not hesitate to reach out if you have any comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8193e87fc9ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/artefact-engineering-and-data-science/the-path-to-developing-a-high-performance-demand-forecasting-model-part-2-8193e87fc9ac">5 tips to better take promotional data into account</a> was originally published in <a href="https://medium.com/artefact-engineering-and-data-science">Artefact Engineering and Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLU benchmark for intent detection and named-entity recognition in call center conversations]]></title>
            <link>https://medium.com/artefact-engineering-and-data-science/nlu-benchmark-for-intent-detection-and-named-entity-recognition-in-call-center-conversations-f58e5b4c8d3d?source=rss-78d8cbfbb42b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f58e5b4c8d3d</guid>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[nlu]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ner]]></category>
            <category><![CDATA[text-classification]]></category>
            <dc:creator><![CDATA[Rafaelle A]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 08:45:17 GMT</pubDate>
            <atom:updated>2020-11-17T08:45:17.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>Call centers advisors are starting to see NLU emerging in their day to day lives, helping them answering customers’ requests more easily. For a tool to do that, it must be able to recognize at the same time the customer request and its characteristics, in other words, an intent and named-entities. A lot of frameworks have been created to perform those two tasks and this article aims at describing them and presenting their baseline performances on a real project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8s2sOQe-Ahq0JHnb" /></figure><p><em>“OK Google, play the Rolling Stones on Spotify.”, “Alexa, what is the weather like in Paris today?”, “Siri, who is the French president?”</em></p><p>If you have ever used vocal assistants, you have indirectly used some Natural Language Understanding (NLU) processes. The same logic applies to chatbot assistants or automated routing of tickets in customer services. For some time now, NLU has been part of our everyday life and it’s probably not about to stop.</p><p>Automating the extraction of customer intent for example, NLU can definitely help us answering better and faster our clients’ requests. That is why every large company has embarked on the development of its own solution. Yet, with all the libraries and models existing in the NLU field, all claiming state-of-the-art or easy-to-get results, it is sometimes complicated to find one’s way around. Having experimented with various libraries in our NLU projects at Artefact, we wanted to share our results and help you get a better understanding of the current tools in NLU</p><h3>What is NLU ?</h3><p>Natural Language Understanding (NLU) is defined by <a href="https://www.gartner.com/en/information-technology/glossary/nlu-natural-language-understanding">Gartner</a> as “the comprehension by computers of the structure and meaning of human language (<em>e.g.</em>, English, Spanish, Japanese), allowing users to interact with the computer using natural sentences”. In other words, NLU is a subdomain of artificial intelligence that enables the interpretation of text by analyzing it, converting it into computer language and producing an output in an understandable form for humans. If you look closely at how chatbots and virtual assistants work, from your request to their answer, NLU is one layer extracting your main intent and any information important to the machine so that it can answer your request best. Say you call your favorite brand customer service to know if your dream bag is finally available in your city: NLU will tell the assistant you have a product availability request and look for the particular item in the product database to find out if it is available at your desired location. Thanks to NLU, we have extracted an intent, a product name and a location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*I1biKTnMgj7kziLM" /><figcaption>Illustration of a customer intent and several entities that are extracted from conversation</figcaption></figure><p>Natural language is instilled in most companies’ data and, with the recent breakthroughs in this field, considering the democratization of the NLU algorithms, the access to more computing power &amp; more data, a lot of NLU projects have been launched. Let’s look at one of them.</p><h3>Project presentation</h3><p>A typical project using NLU is, as mentioned before, helping call center advisors answering customers’ requests more easily as the conversation goes. This would require us to perform two different tasks:</p><ul><li><strong>understand the customer’s intent</strong> during the call (i.e.: text classification)</li><li>and <strong>catch the important elements</strong> that would make it possible to answer the customer’s request (i.e.: named-entity recognition), for example contract numbers, product type, product color, etc…</li></ul><p>When we first looked at the simple and off-the-shelf solutions released for both of these tasks we were able to find more than a dozen frameworks, some developed by the GAFAM, some by open source platform contributors. Impossible to know which one to choose for our use case, how each one of them performs on a concrete project and real data, here call center audio conversations transcribed into text. That is why we have decided to share our performance benchmark with some tips as well as pros and cons for each solution that we have tested.</p><p><em>It is important to note that this benchmark has been done with english data and transcribed speech text and therefore can be used less as a reference for other languages or applications directly using written text, </em>e.g.<em> chatbot use cases.</em></p><h3>Benchmark</h3><h4>Intent detection</h4><p>The goal here is to be able to detect what the customer wants, his/her intent. Given a sentence, the model has to be able to classify it into the right class, each class corresponding to a predefined intent. When there are multiple classes, it is called a multi-class classification task. For example an intent can be “wantsToPurchaseProduct” or “isLookingForInformation”. In our case we had defined <strong>5 different intents</strong> and the six following solutions were used for the benchmark:</p><ul><li><a href="https://fasttext.cc/docs/en/supervised-tutorial.html"><strong>FastText</strong></a><strong>:</strong> library for efficient learning of word representations and sentence classification created by Facebook’s AI Research lab.</li><li><a href="https://uber.github.io/ludwig/examples/#natural-language-understanding"><strong>Ludwig</strong></a><strong>:</strong> toolbox that allows to train and test deep learning models without the need to write code, using the command line or the programmatic API. The user just has to provide a CSV file (or a pandas DataFrame with the programmatic API) containing his/her data, a list of columns to use as inputs, and a list of columns to use as outputs, Ludwig will do the rest.</li><li><strong>Logistic regression with </strong><a href="https://spacy.io/usage/spacy-101"><strong>spaCy preprocessing</strong></a><strong>:</strong> classic logistic regression using scikit-learn library with custom preprocessing using spaCy library (tokenization, lemmatization, removing stopwords).</li><li><a href="https://github.com/explosion/spacy-transformers"><strong>BERT with spaCy pipeline</strong></a><strong>:</strong> spaCy model pipelines that wrap Hugging Face’s transformers package to access state-of-the-art transformer architectures such as BERT easily.</li><li><a href="https://docs.microsoft.com/en-us/azure/cognitive-services/luis/"><strong>LUIS</strong></a><strong>:</strong> Microsoft cloud-based API service that applies custom machine-learning intelligence to a user’s conversational, natural language text to predict intent and entities.</li><li><a href="https://github.com/flairNLP/flair"><strong>Flair</strong></a><strong>:</strong> framework for state-of-the-art NLP for several tasks such as named entity recognition (NER), part-of-speech tagging (PoS), sense disambiguation and classification.</li></ul><p>The following models have all been trained and tested on the same datasets: 1600 utterances for training, 400 for testing. Models have not been fine-tuned therefore some of them could potentially have better performances than what is presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*OjPKI5wNoTgCuUKG" /><figcaption>Performance results of different models for intent detection</figcaption></figure><p><em>*Inference time on local Macbook Air (1.6GHz dual-core Intel Core i5–8 Go 1600 MHz DDR3 RAM).</em></p><ul><li>Overall, in terms of performance, all the solutions achieve good or even very good results (F1-score &gt; 70%).</li><li>One of the inconveniences of Ludwig and LUIS is that they are very “black-box” models which make them more difficult to understand and fine-tune.</li><li>LUIS is the only solution tested that is not open source thus it is much more expensive. In addition, the use of its Python API can be complex since it has been initially designed to be used via a click-button interface. However, it can be a solution to prefer if you are in the context of a project that aims to go into production and whose infrastructure is built on Azure for example, the integration of the model will then be easier.</li></ul><h4>Entities extraction</h4><p>The goal is to be able to locate specific words and classify them correctly into predefined categories. Indeed, one you have detected what your customer would like to do, you may need to find further information in his/her request. For instance, if a client wants to buy something you may want to know which product it is, in which color or if a client wants to return a product, you may want to know at which date or which store the purchase was made. In our case we had defined <strong>16 custom entities</strong>: 9 product related entities (name, color, type, material, size, …) and additional entities related to geography and time. As for intent detection, several solutions have been used in order to make a benchmark:</p><ul><li><a href="https://spacy.io/usage/training#ner"><strong>spaCy</strong></a><strong>:</strong> open-source library for advanced Natural Language Processing in Python that provides different features including Named Entity Recognition.</li><li><strong>LUIS:</strong> <em>see above</em></li><li><strong>Ludwig:</strong><em> see above</em></li><li><strong>Flair:</strong> <em>see above</em></li></ul><p>The following models have all been trained and tested on the same datasets: 1600 utterances for training, 400 for testing. Models have not been fine-tuned therefore some of them could potentially have better performances than what is presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*xOx9HfmdoP11xP-r" /><figcaption>Performance results of different models for named entity recognition</figcaption></figure><ul><li>Two models perform really well on custom named-entity recognition, spaCy and LUIS. Ludwig and Flair would require some fine-tuning to obtain better results, especially in terms of recall.</li><li>One advantage of LUIS is that the user can leverage some advanced features for entity recognition such as <a href="https://docs.microsoft.com/en-us/azure/cognitive-services/luis/luis-how-to-add-features">descriptors</a> which provides hints that certain words and phrases are part of an entity domain vocabulary (e.g.: color vocabulary = black, white, red, blue, navy, green, …).</li></ul><h3><strong>Conclusion</strong></h3><p>Among the solutions tested on our call center dataset, whether for intention detection or entity recognition, none stands out in terms of performance. In our experience, the choice of one solution over another should therefore be based on their practicality and according to your specific use case (do you already use Azure, do you prefer to have more freedom to fine-tune your models…). As a reminder, we just took the libraries as they are to produce this benchmark, without fine-tuning the models, so the results displayed are to be taken with a slight hindsight and could vary on a different use case or with more training data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f58e5b4c8d3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/artefact-engineering-and-data-science/nlu-benchmark-for-intent-detection-and-named-entity-recognition-in-call-center-conversations-f58e5b4c8d3d">NLU benchmark for intent detection and named-entity recognition in call center conversations</a> was originally published in <a href="https://medium.com/artefact-engineering-and-data-science">Artefact Engineering and Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>