<?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 Rhys Kilian on Medium]]></title>
        <description><![CDATA[Stories by Rhys Kilian on Medium]]></description>
        <link>https://medium.com/@rtkilian?source=rss-40e98576066e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EPASviDb4v0oCGWJQZmE3g.jpeg</url>
            <title>Stories by Rhys Kilian on Medium</title>
            <link>https://medium.com/@rtkilian?source=rss-40e98576066e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:30:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rtkilian/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 Schedule Jupyter Notebooks In Amazon SageMaker]]></title>
            <link>https://medium.com/data-science/how-to-schedule-jupyter-notebooks-in-amazon-sagemaker-d50fa1c8c0ad?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d50fa1c8c0ad</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 05:32:28 GMT</pubDate>
            <atom:updated>2022-07-28T05:32:28.296Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to regularly running Jupyter Notebooks using AWS services</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eD8XqZzMzCv9zaRK" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your manager asks, “Can you rerun this analysis for me next week?”. No worries: you set a reminder to rerun it manually.</p><p>The following week comes, and you rerun the analysis. This time your manager says, “This is great. Can you send it to me weekly?” That’s annoying. You don’t like the idea of opening your Jupyter Notebook, running it, and saving the results to S3 weekly. It’s time-consuming, and you’ve got more valuable tasks on your to-do list.</p><p>This article is a how-to guide for scheduling Jupyter Notebooks in Amazon SageMaker. These are the steps I used to automate a time-series forecasting notebook (more details in <a href="https://medium.com/towards-data-science/build-complex-time-series-regression-pipelines-with-sktime-910bc25c96b6">this article</a>) at <a href="https://movember.com/">Movember</a> to run every day.</p><h3>Solution Overview</h3><p>I will show you how to schedule your Jupyter Notebooks using AWS services. I will assume your data is accessible online (e.g. S3, GitHub), and you will save it to a similar location. The Jupyter Notebook will run on an <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/nbi.html">Amazon SageMaker Notebook instance</a>. A <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">lifecycle configuration</a> will control the Notebook instance by specifying the <em>conda </em>environment and implementing the autostop functionality. Finally, we trigger the Notebook Instance on a fixed schedule using <a href="https://docs.aws.amazon.com/lambda/index.html">AWS Lambda</a> and <a href="https://docs.aws.amazon.com/eventbridge/?id=docs_gateway">Amazon EventBridge</a>.</p><p>Our architecture will look something like this.</p><figure><img alt="AWS architecture to schedule Jupyter Notebook" src="https://cdn-images-1.medium.com/max/1024/1*eoHUBrqwGlREWF5-QTPC2Q.png" /><figcaption>Image by author</figcaption></figure><p>You’ll see we’re using only AWS services. Third-party options, such as <a href="https://blog.jetbrains.com/datalore/2022/06/14/how-to-schedule-a-jupyter-notebook/">JetBrains</a>, are available, but it may be more cost-effective to do it yourself.</p><h3>Scenario and Input Data</h3><p>We will work with the <a href="https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv">JHU CSSE COVID-19 Data</a> [1], which gives the cumulative daily number of cases of COVID-19 by state and country. In our scenario, we imagine our manager has asked us to create a line plot of the daily cumulative cases for states in Australia in the past year. Our plot should be accessible in S3 in a PNG format and look like the image below.</p><figure><img alt="Cumulative daily cases for COVID-19 in Australia plot" src="https://cdn-images-1.medium.com/max/864/1*nDzK-MEScLvho9gB-1Z3Jg.png" /><figcaption>Image by author</figcaption></figure><h3>Create an Amazon SageMaker Notebook Instance</h3><p>We will run our Jupyter Notebook app in an <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/nbi.html">Amazon SageMaker Notebook Instance</a>. This service provides a fully managed cloud notebook, pre-loaded with libraries required to perform your data science tasks.</p><p>Start by creating a new notebook instance in the SageMaker console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xW6tVb5fIL05SqSEi6Kcmw.png" /><figcaption>Image by author</figcaption></figure><p>We create an <em>ml.t3.medium</em> instance using Jupyter Lab 3. I also make a new IAM role which will give access to all S3 buckets on my account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKGriwKVvVhkWRa2ra7SnQ.png" /><figcaption>Image by author</figcaption></figure><p>After creating your notebook instance, you can start it in the SageMaker console and open Jupyter Lab. I will use the <em>python3 conda</em> environment kernel, which comes pre-installed with the basic libraries you need to perform the tutorial. You should read the <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-add-external.html">documentation</a> if you need to install external libraries in your environment.</p><p>We then create our <strong>analysis.ipynb</strong> Jupyter Notebook in our environment. The notebook uses <em>pandas </em>to read and process the CSV file from GitHub. We then plot our COVID-19 data using <em>pandas</em> and <em>matplotlib </em>and export the resulting PNG file to our S3 bucket.</p><p>The code in our example looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e3797c54b7f595fafcc7508371ecd45/href">https://medium.com/media/5e3797c54b7f595fafcc7508371ecd45/href</a></iframe><p>You can also find the example on <a href="https://github.com/rtkilian/data-science-blogging/blob/main/schedule_sagemaker_notebooks.ipynb">GitHub</a>.</p><h3>Add a Lifecycle Configuration to the Notebook Instance</h3><p>A <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">lifecycle configuration</a> is a shell script we add to our SageMaker Notebook instance to install packages, select our <em>conda </em>environment and autostop our notebook to prevent overbilling.</p><p>Start by adding a new configuration for your notebook instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ct_rnmrAEyVm3BMd-NEHKQ.png" /><figcaption>Image by author</figcaption></figure><p>We will call our configuration <strong>schedule-configuration</strong> and include the below script. Our script activates the <em>python3 conda</em> environment and loads the commands to autostop our notebook instance after 5-minutes of being idle. This <a href="https://github.com/aws-samples/amazon-sagemaker-notebook-instance-lifecycle-config-samples">GitHub repo</a> provided by Amazon hosts several sample lifecycle configuration scripts which you can use to customise your notebook instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xve9NxUT7dz7iXNCkv8X2w.png" /><figcaption>Image by author</figcaption></figure><pre>set -e</pre><pre>sudo -u ec2-user -i &lt;&lt;&#39;EOF&#39;</pre><pre># PARAMETERS<br>ENVIRONMENT=python3<br>NOTEBOOK_FILE=/home/ec2-user/SageMaker/analysis.ipynb</pre><pre>echo &quot;Activating conda env&quot;<br>source /home/ec2-user/anaconda3/bin/activate &quot;$ENVIRONMENT&quot;</pre><pre>echo &quot;Starting notebook&quot;<br>jupyter nbconvert &quot;$NOTEBOOK_FILE&quot; --ExecutePreprocessor.kernel_name=python --execute --to notebook</pre><pre>echo &quot;Dectivating conda env&quot;<br>source /home/ec2-user/anaconda3/bin/deactivate</pre><pre># PARAMETERS<br>IDLE_TIME=300</pre><pre>echo &quot;Fetching the autostop script&quot;<br>wget <a href="https://raw.githubusercontent.com/aws-samples/amazon-sagemaker-notebook-instance-lifecycle-config-samples/master/scripts/auto-stop-idle/autostop.py">https://raw.githubusercontent.com/aws-samples/amazon-sagemaker-notebook-instance-lifecycle-config-samples/master/scripts/auto-stop-idle/autostop.py</a></pre><pre>echo &quot;Detecting Python install with boto3 install&quot;</pre><pre># Find which install has boto3 and use that to run the cron command. So will use default when available<br># Redirect stderr as it is unneeded<br>if /usr/bin/python -c &quot;import boto3&quot; 2&gt;/dev/null; then<br>    PYTHON_DIR=&#39;/usr/bin/python&#39;<br>elif /usr/bin/python3 -c &quot;import boto3&quot; 2&gt;/dev/null; then<br>    PYTHON_DIR=&#39;/usr/bin/python3&#39;<br>else<br>    # If no boto3 just quit because the script won&#39;t work<br>    echo &quot;No boto3 found in Python or Python3. Exiting...&quot;<br>    exit 1<br>fi</pre><pre>echo &quot;Found boto3 at $PYTHON_DIR&quot;</pre><pre>echo &quot;Starting the SageMaker autostop script in cron&quot;</pre><pre>(crontab -l 2&gt;/dev/null; echo &quot;*/5 * * * * $PYTHON_DIR $PWD/autostop.py --time $IDLE_TIME --ignore-connections &gt;&gt; /var/log/jupyter.log&quot;) | crontab -</pre><pre>EOF</pre><p>Once you’ve saved your lifecycle configuration, navigate to your notebook instance and press ‘Edit’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJ6xuz0QfaatAkpjlRBAwQ.png" /><figcaption>Image by author</figcaption></figure><p>Add your lifecycle configuration and save. Starting your notebook instance will load the <em>python3</em> environment and trigger the autostop functionality after 5-minutes of idle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_KEbgibpv-hIWkKFeON4w.png" /><figcaption>Image by author</figcaption></figure><h3>Trigger the Notebook with Amazon EventBridge and AWS Lambda</h3><p>Running our SageMaker notebook on a fixed schedule will be achieved using Amazon EventBridge and AWS Lambda. <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html">Amazon EventBridge</a> is an event service that will trigger an <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html">AWS Lambda</a> function that starts our SageMaker Notebook instance.</p><p>Firstly, start by creating a new Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXS8wzit4sN5zHyqgQIHEw.png" /><figcaption>Image by author</figcaption></figure><p>We will call our function <strong>launch_jupyter_nb</strong> and choose to write it in <em>Python 3.9</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zCnCeNjPqduCvC93J-R9Q.png" /><figcaption>Image by author</figcaption></figure><p>After saving, we add the <em>boto3</em> commands to start our SageMaker Notebook instance. You can find the code below. Press ‘Deploy’ when complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Ktk0WvuYsNMXq2XuRnhpw.png" /><figcaption>Image by author</figcaption></figure><pre>import boto3<br>import logging<br>def lambda_handler(event, context):<br>    client = boto3.client(&#39;sagemaker&#39;)<br>    client.start_notebook_instance(NotebookInstanceName=&#39;sagemaker-schedule&#39;)<br>    return 0</pre><p>We also need to give our Lambda function permission to access our SageMaker Notebook instance. Navigate to the ‘Configuration’ tab and click on the current role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERupPjg3cFTxvlQzIy0iyg.png" /><figcaption>Image by author</figcaption></figure><p>Clicking the role will direct you to IAM. Here, you should attach the ‘AmazonSageMakerFullAccess’ policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18V9F7EVodZ0zK-A-yltaA.png" /><figcaption>Image by author</figcaption></figure><p>Back in AWS Lambda, under ‘Function overview’, add a trigger to your function. We will add an EventBridge trigger called <strong>launch_jupyter_nb</strong>, which runs on a fixed schedule. We specify the schedule using a <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html">Cron expression</a>. In our example, the EventBridge trigger will run daily at 03:00 UTC.</p><pre>cron(0 3 * * ? *)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7C2I6WfII_YrFBXwVgnYQ.png" /><figcaption>Image by author</figcaption></figure><p>We’re done! Our Jupyter Notebook, hosted in a SageMaker Notebook instance, will run on a fixed schedule because of Amazon EventBridge and AWS Lambda. Once the notebook is finished running and is idle for 5-minutes, our lifecycle configuration will turn off the Notebook instance.</p><h3>Other Considerations</h3><p>You should be aware of two important considerations when scheduling your Jupyter Notebook. Firstly, the lifecycle configuration we created cannot run longer than 5-minutes. Otherwise, it will fail. According to the <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">documentation</a>, you can overcome this limitation by:</p><ul><li>Reducing the number of steps</li><li>Running tasks in parallel</li><li>Using the <a href="https://www.geeksforgeeks.org/nohup-command-in-linux-with-examples/"><em>nohup</em></a> command in your script</li></ul><p>Secondly, the tutorial has shown you how to schedule notebooks in SageMaker Notebook instances rather than <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/notebooks.html">Sagemaker Studio notebooks</a>. You can modify the steps above to work with Studio notebooks by adjusting the <a href="https://github.com/aws-samples/sagemaker-studio-lifecycle-config-examples">lifecycle configuration</a> and referring to the <em>boto3</em> <a href="https://boto3.amazonaws.com/v1/documentation/api/1.14.35/reference/services/sagemaker.html">documentation</a>.</p><p>The next time your manager asks you to repeat your Jupyter Notebook analysis, you can. In this guide, I showed you how to schedule your notebooks in SageMaker Notebook instances with Lambda and EventBridge. There’s no need to sign up for a third-party service.</p><p>Liked what you read? Follow me on <a href="https://medium.com/@rtkilian">Medium</a>. Otherwise, <a href="https://twitter.com/rtkilian">tweet me</a> or add me on <a href="https://www.linkedin.com/in/rtkilian/">LinkedIn</a>.</p><p>You can find all the code used in this post on <a href="https://github.com/rtkilian/data-science-blogging/blob/main/schedule_sagemaker_notebooks.ipynb">GitHub</a>.</p><p>[1] COVID-19 Data Repository by the Center for Systems Science and Engineering (CSSE) at Johns Hopkins University, licensed under the Creative Commons Attribution 4.0 International (CC BY 4.0)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d50fa1c8c0ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-schedule-jupyter-notebooks-in-amazon-sagemaker-d50fa1c8c0ad">How to Schedule Jupyter Notebooks In Amazon SageMaker</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Complex Time Series Regression Pipelines with sktime]]></title>
            <link>https://medium.com/data-science/build-complex-time-series-regression-pipelines-with-sktime-910bc25c96b6?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/910bc25c96b6</guid>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 04:21:02 GMT</pubDate>
            <atom:updated>2022-07-13T04:21:02.964Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to forecast with scikit-learn and XGBoost models with sktime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SWU0R_Xl2Uxj_2Zb" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Stop using <em>scikit-learn</em> for forecasting. Just because you can use your existing regression pipeline doesn’t mean you should. Alternatively, aren’t you bored of forecasting using the same old techniques, such as exponential smoothing and ARIMA? Wouldn’t it be more fun to use a more advanced algorithm such as a gradient boosted tree?</p><p>Using <em>sktime</em>, you can do this (and more). <em>Sktime</em> is a library that lets you safely use any <em>scikit-learn</em> compatible regression model for time series forecasting. This tutorial will discuss how we can convert a time series forecasting problem to a regression problem using <em>sktime</em>. I will also show you how to build a complex time series forecaster with the popular library, <em>XGBoost</em>.</p><h3>Background and motivation</h3><h4>What is time series forecasting?</h4><p>Time series forecasting is a technique to predict one or more future values. Like regression modelling, a data practitioner can fit a model based on historical data and use this model to predict future observations.</p><p>Some of the most popular models used in forecasting are univariate. Univariate models forecast using only the previous observations. <a href="https://otexts.com/fpp2/expsmooth.html">Exponential smoothing</a> models use a weighted average of past observations to predict future values, with more recent data points given more weight. <a href="https://otexts.com/fpp2/arima.html">ARIMA</a><strong> </strong>models base their predictions on the <a href="https://otexts.com/fpp2/autocorrelation.html">autocorrelations</a> in the data. Autocorrelation measures the relationship between time-shifted (i.e. lagged) values of a time series.</p><p>If time series forecasting sounds similar to regression modelling, you’re correct. We can use regression models for our time-series predictions.</p><h4>Why would we want to use regression for time series forecasting?</h4><p>One of the reasons you should use regression models is for improved model performance. Regression techniques are flexible, and you can go beyond univariate modelling of past observations. Including time-step features, such as the day of the week or holidays, can enrich your data and potentially uncover hidden trends in your data.</p><p>Secondly, you likely already use popular machine learning frameworks such as <em>scikit-learn</em> and <em>XGBoost</em>. Converting your time series forecasting task into a regression problem can save you time if you’re already familiar with these libraries.</p><p>However, modern forecasting libraries, such as Facebook’s <a href="https://facebook.github.io/prophet/"><em>Prophet</em></a>, also provide the flexibility for multivariate analysis and a simple API. Nonetheless, using regression techniques for forecasting should be another tool in your data science toolkit.</p><h4>What do we need to watch out for in time series regression?</h4><p>Time series regression isn’t without issues. Autocorrelated observations violate the assumptions of linear regression models. However, more complex regression models, such as gradient tree boosting, are generally robust to multicollinearity.</p><p>Additionally, we can introduce data leakage if we blindly fit and tune our regression model. <a href="https://towardsdatascience.com/avoiding-data-leakage-in-timeseries-101-25ea13fcb15f">Data leakage</a> is the use of information in the model training and validation phase that would not otherwise be available for forecasting. For example, randomly shuffling your data using K-fold cross-validation allows your model to peek ahead into the future. Instead, you should use <a href="https://towardsdatascience.com/dont-use-k-fold-validation-for-time-series-forecasting-30b724aaea64">temporal cross-validation</a>.</p><p>Rather than implementing time-series regression models from scratch, you can use the <a href="https://www.sktime.org/en/stable/"><em>sktime</em></a> framework.</p><h4>Why should we use sktime?</h4><p><a href="https://www.sktime.org/en/stable/"><em>Sktime</em></a> is an open-source framework for various machine learning tasks for modelling time series, including time-series regression, classification, clustering and annotation. The framework combines features from several libraries with a user experience similar to <em>scikit-learn</em>.</p><p>We will be using <em>sktime</em> for our forecasting task because it provides <a href="https://www.sktime.org/en/stable/examples/01_forecasting.html#3.-Advanced-composition-patterns---pipelines,-reduction,-autoML,-and-more">functionality</a> such as:</p><ul><li><strong>Reduction</strong>: building a time series forecaster using estimators compatible with the <em>scikit-learn </em>API</li><li><strong>Tuning</strong>: determining the value of hyperparameters using grid search strategies with temporal cross-validation</li><li><strong>Evaluation</strong>: <em>sktime </em>includes several performance metrics (e.g. MAPE, MASE) and provides an easy implementation for custom scorers and backtesting</li><li><strong>Pipelining: </strong>an extension of the <em>scikit-learn </em><a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html"><em>Pipeline</em></a>, which is a series of concatenated transformers to build a single forecaster</li><li><strong>AutoML</strong>: automated tuning strategies to determine the best forecaster across a range of models and hyperparameters</li></ul><p><em>Sktime</em> also provides <a href="https://www.sktime.org/en/stable/examples/01_forecasting.html#2.-Forecasters-in-sktime---lookup,-properties,-main-families">several other classes</a> of forecasting models, including exponential smoothing, ARIMA, BATS and Prophet. We will not discuss these forecasting models in this tutorial, but I encourage you to implement these forecasters during your model selection phase.</p><h3>Code Examples</h3><h4>Dataset</h4><p>The dataset we will be using in this tutorial is an <a href="https://data.melbourne.vic.gov.au/Transport/Pedestrian-Counting-System-Monthly-counts-per-hour/b2ak-trbp">hourly count of pedestrians</a> in the city of Melbourne, Australia [1]. We will restrict our analysis from 1st January 2010 to 31st December 2019. I’ve aggregated the data weekly.</p><p>If we visualise our data, we can see a general upwards trend from about mid-2013. We can also see more pedestrians in the city in December, likely due to Christmas shopping, and in July for end-of-financial-year sales. Our data appears non-stationary, confirmed when we run an Augmented Dickey-Fuller test.</p><figure><img alt="Count of pedestrians by week from 2011 to 2020" src="https://cdn-images-1.medium.com/max/1024/1*NXevGb3JF5m1Ql6CQ7bnIQ.png" /><figcaption>Image by author</figcaption></figure><h4>A simple forecaster with linear regression</h4><p>The first example we’ll run is a simple forecaster using linear regression. We first take the final 26 weeks of data as our test set using <em>sktime’s</em> <a href="http://temporal_train_test_split/"><em>temporal_train_test_split</em></a>. The function does not shuffle the data. Therefore it is suitable for forecasting.</p><pre>from sktime.forecasting.model_selection import temporal_train_test_split</pre><pre>y_train, y_test = temporal_train_test_split(y, test_size=26)</pre><p>We also specify our forecasting horizon, the 26 weeks of test data that we will predict. We achieve this using the <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.base.ForecastingHorizon.html"><em>ForecastingHorizon</em></a> object.</p><pre>from sktime.forecasting.base import ForecastingHorizon</pre><pre>fh = ForecastingHorizon(y_test.index, is_relative=False)</pre><p>With the preliminaries complete, we can move on to instantiating our <em>scikit-learn</em> <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html"><em>LinearRegression</em></a> object that will be the estimator for our forecaster. Alternatively, you can use other <em>scikit-learn</em> estimators or <em>scikit-learn</em> API compatible estimators, such as <em>XGBoost</em>. I will demonstrate this in the following example.</p><pre>from sklearn.linear_model import LinearRegression</pre><pre>regressor = LinearRegression()</pre><p><em>Sktime’s</em> <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.compose.make_reduction.html?highlight=make_reduction"><em>make_reduction</em></a> function transforms the time series into tabular data compatible with our <em>scikit-learn</em> estimator. The parameter, ‘window_length’, controls the number of lags in our sliding window transformation.</p><p>Consider the simple time series, denoted<em> ‘y’</em>, below. If we apply our <em>make_reduction </em>function, with a window length equal to 3, we produce a tabular dataset with three input variables, denoted <em>‘lag_1</em>’, <em>‘lag_2</em>’ and <em>‘lag_3</em>’. The function transforms our one-dimensional time series dataset into a compatible format with our regression estimator.</p><figure><img alt="Demonstration of make_reduction function" src="https://cdn-images-1.medium.com/max/1024/1*YseywQTxmFzxsc1GEO8OIA.png" /><figcaption>Image by author</figcaption></figure><p>Furthermore, the <em>make_reduction</em> function has an input ‘strategy’, which controls how the forecaster generates its predictions. The parameter is relevant when we are making more than one-step ahead forecasts. In our example, we are making predictions for the next 26 weeks of pedestrian counts (multi-step) rather than just the following week (one-step).</p><p>We have the choice of three options for our multi-step forecasting strategy:</p><ul><li><strong>Direct</strong>: we create a separate model for each period we are forecasting. In our example, we fit 26 models, each making a single prediction.</li><li><strong>Recursive</strong>: we fit a single one-step ahead model. However, we use the previous time step’s output for the following input. For example, we use next week’s prediction as an input for the prediction two weeks away, and so on.</li><li><strong>Multiple outputs</strong>: one model is used to predict the entire time series horizon in a single forecast. The use of this option is dependent on having a model capable of predicting sequences.</li></ul><p>In our example, we will use the recursive strategy.</p><pre>from sktime.forecasting.compose import make_reduction</pre><pre>forecaster = make_reduction(regressor, window_length=52, strategy=&quot;recursive&quot;)</pre><p>We can now fit our linear regression forecaster and predict the 26 weeks of pedestrian counts on our test data.</p><pre>forecaster.fit(y_train)<br>y_pred = forecaster.predict(fh)</pre><p>We then plot our predictions relative to the train and test data to determine the model’s suitability. <em>Sktime </em>makes this easy using the <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.utils.plotting.plot_series.html?highlight=plot_series"><em>plot_series</em></a> utility function.</p><pre>from sktime.utils.plotting import plot_series</pre><pre>plot_series(y_train[&#39;2018-07-01&#39;:], y_test, y_pred, labels=[&quot;y_train&quot;, &quot;y_test&quot;, &quot;y_pred&quot;], x_label=&#39;Date&#39;, y_label=&#39;Count pedestrians&#39;);</pre><figure><img alt="Plot of train, test and predict using linear regression" src="https://cdn-images-1.medium.com/max/1024/1*ISHNNYlyC8E-kBpfOyprjQ.png" /><figcaption>Image by author</figcaption></figure><p>Our linear regression forecaster appears to give us a reasonable fit. However, it is a conservative prediction and misses the peaks and troughs of the test data.</p><p>We evaluate our model using the <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.performance_metrics.forecasting.mean_absolute_percentage_error.html"><em>mean_absolute_percentage_error</em></a><em> </em>(MAPE),<em> </em>which yields a result of 4.8%.</p><pre>from sktime.performance_metrics.forecasting import mean_absolute_percentage_error</pre><pre>print(&#39;MAPE: %.4f&#39; % mean_absolute_percentage_error(y_test, y_pred, symmetric=False))</pre><p>If we put all this together, our code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e50abfde3ba7ea6822eefd4ce247f1/href">https://medium.com/media/d7e50abfde3ba7ea6822eefd4ce247f1/href</a></iframe><p>Let’s see if we can beat this using a more complex algorithm such as <em>XGBoost</em>.</p><h4>Time series forecasting with XGBoost<em> and exogenous inputs</em></h4><p><a href="https://xgboost.readthedocs.io/en/stable/"><em>XGBoost</em></a> is an implementation of a gradient boosting machine, popular for tabular machine learning tasks because of its speed and performance. We can use <em>XGBoost</em> for time series forecasting because it has a <a href="https://xgboost.readthedocs.io/en/stable/python/python_api.html#module-xgboost.sklearn"><em>scikit-learn</em> wrapper</a> compatible with <em>sktime’s</em> <em>make_reduction</em> function.</p><pre>from xgboost import XGBRegressor</pre><pre>regressor = XGBRegressor(objective=&#39;reg:squarederror&#39;, random_state=42)<br>forecaster = make_reduction(regressor, window_length=52, strategy=&quot;recursive&quot;)</pre><p>We will also include exogenous data, another time helpful series for the prediction that is not forecasted. Let’s include several dummy variables that indicate the year’s month, split into our train and test sets.</p><pre># Create an exogenous dataframe indicating the month<br>X = pd.DataFrame({&#39;month&#39;: y.index.month}, index=y.index)<br>X = pd.get_dummies(X.astype(str), drop_first=True)</pre><pre># Split into train and test<br>X_train, X_test = temporal_train_test_split(X, test_size=26)</pre><p>We include our exogenous data when we call the fit and predict methods. You can find more information in the <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.compose.RecursiveTabularRegressionForecaster.html#sktime.forecasting.compose.RecursiveTabularRegressionForecaster.fit"><em>RecursiveTabularRegressionForecaster</em></a> documentation.</p><pre>forecaster.fit(y=y_train, X=X_train)<br>y_pred = forecaster.predict(fh=fh, X=X_test)</pre><p>Visually, our predictions appear to be worse than our linear regression forecaster. Our expectation is confirmed when we look at the MAPE, which has increased to 7.1%. The <em>XGBoost</em> forecaster is likely under-fitted because we’ve used the default hyperparameter values.</p><p>The following example will demonstrate how we can tune the hyperparameters for our <em>XGBoost</em> forecaster.</p><figure><img alt="Plot of train, test and predict using XGBoost" src="https://cdn-images-1.medium.com/max/1024/1*ETrKYUgooWd3snptbqTIAQ.png" /><figcaption>Image by author</figcaption></figure><p>You can find the code for this example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bed7eb36778cddf0aa513432c706e47e/href">https://medium.com/media/bed7eb36778cddf0aa513432c706e47e/href</a></iframe><h4>Tuning the hyperparameters of our forecaster</h4><p>Our <a href="https://xgboost.readthedocs.io/en/stable/python/python_api.html#module-xgboost.sklearn"><em>XGBRegressor</em></a> has several hyperparameters that we can tune, as described in this <a href="https://towardsdatascience.com/xgboost-fine-tune-and-optimize-your-model-23d996fab663">article</a>. We want to adjust the hyperparameters of our forecaster to see if we can improve the performance.</p><p>Before tuning our hyperparameters, we must add a validation set to our data. We have several strategies implemented by <em>sktime</em>, including a <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.model_selection.SingleWindowSplitter.html"><em>SingleWindowSplitter</em></a>, <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.model_selection.SlidingWindowSplitter.html"><em>SlidingWindowSplitter</em></a>, and <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.model_selection.ExpandingWindowSplitter.html"><em>ExpandingWindowSplitter</em></a>. For simplicity, we will create a single validation set, the same size as our test set. However, this <a href="https://towardsdatascience.com/dont-use-k-fold-validation-for-time-series-forecasting-30b724aaea64">article</a> explains the differences between the various strategies.</p><pre>from sktime.forecasting.model_selection import SingleWindowSplitter</pre><pre>validation_size = 26<br>cv = SingleWindowSplitter(window_length=len(y)-validation_size, fh=validation_size)</pre><p><em>Sktime</em> has implemented two strategies for hyperparameter tuning: <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.model_selection.ForecastingRandomizedSearchCV.html">randomised search</a> and <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.model_selection.ForecastingGridSearchCV.html">grid search</a>. We will use a randomised search with 100 iterations.</p><pre>from sktime.forecasting.model_selection import ForecastingRandomizedSearchCV</pre><pre>param_grid = {<br>    &#39;estimator__max_depth&#39;: [3, 5, 6, 10, 15, 20],<br>    &#39;estimator__learning_rate&#39;: [0.01, 0.1, 0.2, 0.3],<br>    &#39;estimator__subsample&#39;: np.arange(0.5, 1.0, 0.1),<br>    &#39;estimator__colsample_bytree&#39;: np.arange(0.4, 1.0, 0.1),<br>    &#39;estimator__colsample_bylevel&#39;: np.arange(0.4, 1.0, 0.1),<br>    &#39;estimator__n_estimators&#39;: [100, 500, 1000]<br>}</pre><pre>regressor = XGBRegressor(objective=&#39;reg:squarederror&#39;, random_state=42)<br>forecaster = make_reduction(regressor, window_length=52, strategy=&quot;recursive&quot;)</pre><pre>gscv = ForecastingRandomizedSearchCV(forecaster, cv=cv, param_distributions=param_grid, n_iter=100, random_state=42)</pre><p>Again, we fit and predict.</p><pre>gscv.fit(y=y_train, X=X_train)<br>y_pred = gscv.predict(fh=fh, X=X_test)</pre><p>But this time, we can inspect our random search object to see how the forecaster performs using different combinations of hyperparameters.</p><pre>gscv.cv_results_</pre><figure><img alt="Randomised grid search results" src="https://cdn-images-1.medium.com/max/1024/1*t2DV1XWXLbT9j5C3tJW8rA.png" /><figcaption>Image by author</figcaption></figure><p>Interestingly, our forecaster performs worse on our test data, as shown by our visualisation and the MAPE increasing to 7.8%.</p><figure><img alt="Plot of train, test and predict using XGBoost with randomised grid search" src="https://cdn-images-1.medium.com/max/1024/1*GeD6sF1bg0piF2Y6MkuOjA.png" /><figcaption>Image by author</figcaption></figure><p>You can find the complete code for the example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbbeddaee66c74e2fce40c2d931f82e8/href">https://medium.com/media/cbbeddaee66c74e2fce40c2d931f82e8/href</a></iframe><h4>Adding components to our forecasting pipeline</h4><p>We previously trained our model on non-stationary data resulting in a poor forecast. Using <a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.seasonal.seasonal_decompose.html"><em>statsmodels</em></a>, we can decompose our pedestrian time series to observe the trend and seasonality.</p><pre>from statsmodels.tsa.seasonal import seasonal_decompose</pre><pre>result = seasonal_decompose(y_train, model=&#39;multiplicative&#39;)<br>result.plot()<br>plt.show()</pre><p>We assume our time series is multiplicative rather than additive because it appears the oscillation amplitude of our time series increases over time. Looking at the decomposition below, we see that our trend (second subplot) has increased since mid-2013 and that there is a seasonal pattern, with increased pedestrian traffic around Christmas and mid-year and decreased traffic in the first week of January.</p><figure><img alt="Seasonal decomposition of pedestrian data" src="https://cdn-images-1.medium.com/max/1024/1*toTsYEpTLWLWwFm8JY8gPg.png" /><figcaption>Image by author</figcaption></figure><p>Therefore, our forecaster’s performance may be improved by removing the seasonality and trend of the time series, producing a time series closer to being stationary. <em>Sktime </em>includes two classes, <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.transformations.series.detrend.Deseasonalizer.html?highlight=deseasonalizer"><em>Deseasonalizer</em></a> and <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.transformations.series.detrend.Detrender.html"><em>Detrender</em></a><em>, </em>that we can incorporate into our forecasting pipeline.</p><pre>from sktime.forecasting.compose import TransformedTargetForecaster<br>from sktime.transformations.series.detrend import Deseasonalizer, Detrender<br>from sktime.forecasting.trend import PolynomialTrendForecaster</pre><pre>regressor = XGBRegressor(objective=&#39;reg:squarederror&#39;, random_state=42)</pre><pre>forecaster = TransformedTargetForecaster(<br>    [<br>        (&quot;deseasonalize&quot;, Deseasonalizer(model=&quot;multiplicative&quot;, sp=52)),<br>        (&quot;detrend&quot;, Detrender(forecaster=PolynomialTrendForecaster(degree=1))),<br>        (&quot;forecast&quot;, make_reduction(regressor, window_length=52, strategy=&quot;recursive&quot;),<br>        ),<br>    ]<br>)</pre><p>We can tune the parameters for our <em>Deaseasonalizer</em> and <em>Detrender</em> using a randomised grid search. For example, we can see if an additive or multiplicative model is best or what degree of the polynomial we want to use to model the trend.</p><pre>param_grid = {<br>    &#39;deseasonalize__model&#39;: [&#39;multiplicative&#39;, &#39;additive&#39;],<br>    &#39;detrend__forecaster__degree&#39;: [1, 2, 3],<br>    &#39;forecast__estimator__max_depth&#39;: [3, 5, 6, 10, 15, 20],<br>    &#39;forecast__estimator__learning_rate&#39;: [0.01, 0.1, 0.2, 0.3],<br>    &#39;forecast__estimator__subsample&#39;: np.arange(0.5, 1.0, 0.1),<br>    &#39;forecast__estimator__colsample_bytree&#39;: np.arange(0.4, 1.0, 0.1),<br>    &#39;forecast__estimator__colsample_bylevel&#39;: np.arange(0.4, 1.0, 0.1),<br>    &#39;forecast__estimator__n_estimators&#39;: [100, 500, 1000]<br>}</pre><pre>gscv = ForecastingRandomizedSearchCV(forecaster, cv=cv, param_distributions=param_grid, n_iter=100, random_state=42)</pre><pre><br>gscv.fit(y=y_train, X=X_train)<br>y_pred = gscv.predict(fh=fh, X=X_test)</pre><p>After tuning our forecaster pipeline, we can visualise our predictions. We observe our predictions are much closer to our trend data, indicating that removing the seasonality and trend from our time series has improved the performance of our model. The MAPE has decreased to 4.7%, the best performance of all our models tested.</p><figure><img alt="Plot of train, test and predict using XGBoost with detrender and deseasonaliser" src="https://cdn-images-1.medium.com/max/1024/1*PNpIuiBBjj29C5sYOqg0fw.png" /><figcaption>Image by author</figcaption></figure><p>The complete code for this example is below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4895ad89dcdc73d68c0f5b0bd82d9e23/href">https://medium.com/media/4895ad89dcdc73d68c0f5b0bd82d9e23/href</a></iframe><p><em>Sktime </em>is a versatile library that lets you use your <em>scikit-learn</em> compatible regression model for time series forecasting. You can build complex multi-step pipelines that rival even the most advanced forecasting algorithms. The next time you’re doing a forecasting project, don’t just use ARIMA. Give <em>sktime</em> a go.</p><p>Liked what you read? Follow me on <a href="https://medium.com/@rtkilian">Medium</a>. Otherwise, <a href="https://twitter.com/rtkilian">tweet me</a> or add me on <a href="https://www.linkedin.com/in/rtkilian/">LinkedIn</a>.</p><p>You can find all the code used in this post on <a href="https://github.com/rtkilian/data-science-blogging/blob/main/sktime_regression_forecasting.ipynb">GitHub</a>.</p><p>[1] City of Melbourne, <a href="https://data.melbourne.vic.gov.au/Transport/Pedestrian-Counting-System-Monthly-counts-per-hour/b2ak-trbp">Pedestrian Counting System — Monthly (counts per hour)</a> (2022), City of Melbourne Open Data published under Creative Commons Attribution 3.0 Australia (CC BY 3.0 AU)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=910bc25c96b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/build-complex-time-series-regression-pipelines-with-sktime-910bc25c96b6">Build Complex Time Series Regression Pipelines with sktime</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Lessons to Deliver a Data Science Project Successfully]]></title>
            <link>https://medium.com/@rtkilian/my-lessons-to-deliver-a-data-science-project-successfully-dce7cc89c37c?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dce7cc89c37c</guid>
            <category><![CDATA[advice]]></category>
            <category><![CDATA[lessons-learned]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[retention]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Sun, 19 Jun 2022 08:09:33 GMT</pubDate>
            <atom:updated>2022-06-19T08:09:33.800Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hard-won suggestions from churn modelling in the trenches</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LgKV-vMHZ3y82dC7" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>“What do we do with this information?”</p><p>It was a simple question from the executive, but I was ready for it after the hours I’d spent preparing this presentation in the university library. I replied, “As you can see from the model, you should target the customers most likely to churn”. I swallowed while the executive who would help grade this final assignment tapped her fingers impatiently against her notepad.</p><p>“…and you should prioritise the customers with the highest lifetime value”, I added — finally, a nod. But I could tell she was expecting more guidance.</p><p>I cringe when I remember this churn modelling project and wish I could go back and give my university student self some guidance. I should have split the customers into prioritised segments. I should have suggested interventions based on the main predictors of churn. In summary, I should have been more prepared for the question.</p><p>Four years later, I completed another churn modelling project, this time with <a href="https://www.movember.com/">Movember</a>, the men’s health organisation, to predict which fundraisers will re-register next year. Gone are the days when someone writes the project requirements for me, where the data is always clean, and the final product is a report summarising the model’s performance. Now, I’m responsible for the successful outcome of the project. Here are some lessons I’ve learnt in the real world since that university assignment.</p><h3>Lesson 1: ‘Real’ data is messy, but you need to find the signal in the noise.</h3><p>In the workplace, you’ll grapple with missing values, outliers and data spread on different systems. When I was studying, cleaning data was a trivial exercise for me. Changing data types, fixing errors, and imputing missing values before I started modelling would take a few hours. Now, days can pass before I think about implementing a model.</p><p>Careful data preparation was necessary for my churn modelling project for Movember fundraisers. I spent hours tuning the hyperparameters of my model, but I saw only marginal improvements in my evaluation metrics. Finally, I went back to my data preparation. I invested my time collecting more data and feature engineering new variables to understand the behaviours of Movember’s fundraisers. I was rewarded with a significant leap in performance when I returned to modelling. Cleaning data isn’t sexy, but it’s an invaluable step.</p><h3>Lesson 2: Stakeholders want to know how the model will work for them.</h3><p>Most stakeholders don’t care if you improve the model’s performance by 10%. Unless you work at a <a href="https://www.investopedia.com/terms/f/faang-stocks.asp">FAANG</a> company, incremental improvements to the model performance won’t noticeably improve the bottom line. Instead, understanding the model is the best use of your time. Your stakeholders want to know how the model will help them make better decisions.</p><p>The easiest method to understand the model is by selecting an interpretable architecture. If you’re modelling a regression problem, select linear regression; if you’re modelling a classification problem, select logistic regression. I recommend you test various models, and if an interpretable model gives you comparable performance, you should choose it.</p><p>For black-box algorithms, I use model explainability methods, such as <a href="https://shap.readthedocs.io/en/latest/example_notebooks/overviews/An%20introduction%20to%20explainable%20AI%20with%20Shapley%20values.html">SHAP</a> (SHapley Additive exPlanations). SHAP explains any machine learning model by showing the impact of an input feature on a prediction. I used SHAP on the Movember project because I selected the XGBoost model, which is not easily interpretable. Based on the SHAP values, I could determine the fundraiser behaviours likely to predict churn. Therefore, I could suggest targeted interventions that may influence the fundraisers’ future behaviour.</p><p>However, I found that stakeholders would interpret my findings causally. <a href="https://towardsdatascience.com/be-careful-when-interpreting-predictive-models-in-search-of-causal-insights-e68626e664b6">Several authors</a> from Microsoft warn that interpreting models with SHAP will “fail to answer causal questions in many common situations accurately”. Instead, data practitioners should use causal inference methods and experimentation to interpret the model casually. Therefore, I explained the differences between predictive and causal modelling to my stakeholders in my churn project. I clarified that the project’s goal was to accurately predict which fundraisers are likely to churn without necessarily understanding the reason for a fundraiser’s departure. We agreed to run future tests to determine why a fundraiser didn’t re-register.</p><h3>Lesson 3: Become a salesperson.</h3><p>You have probably heard that a machine learning model is only as good as the data it is fed. But a machine learning model is <em>also </em>only as good as the decisions made from it. It doesn’t matter if you, your stakeholder or your customers are making the decisions; the model should be creating value for someone.</p><p>Only 13% of data science projects make it into production, according to a study by <a href="https://www.rexeranalytics.com/data-science-survey">Rexer Analytics</a>. The failure to deploy your project may be due to poor leadership or insufficient data, but whatever the reason, it is your responsibility to promote your work. You have spent hours understanding the data, tuning your hyperparameters, and speaking to so many stakeholders that your list of requirements is a mile long. Wouldn’t it be a waste if your model never made it past your Jupyter Notebook?</p><p>If you’re like me, selling doesn’t come naturally. So when it comes time to encourage stakeholders to use my model, I look for fun ways to showcase it. For example, I turned my churn prediction model into a quiz game using <a href="https://medium.com/@rtkilian/deploy-and-share-your-sentiment-analysis-app-using-streamlit-sharing-2ba3ca6a3ead">Streamlit</a>, where I challenged my stakeholders to beat my predictions. The quiz illustrated the performance of my model and gave my stakeholders an understanding of the features the model used to make the prediction. And yes, my model was the undisputed champion.</p><p>Another strategy that worked well for me was designing experiments for my model. At Movember, email is an important communication channel for connecting with our fundraisers. How would a registration email to our fundraisers perform? I split the fundraisers into groups based on their churn likelihood, suggested the email copy, and presented my experiment to my stakeholders. I completed most of the work for them. The stakeholders just had to press the send button. In your next project, think of a creative way to promote your model to your stakeholders where they don’t need to lift a finger.</p><p>Every day I work as a Data Scientist is an opportunity for me to learn. My projects are no longer academically focused and well-structured like those in university. They are now results orientated and often ambiguous. The change comes with many challenges, but I’ve learnt the importance of data preparation, communication and the art of selling to deliver a successful project outcome. And most importantly, these lessons have helped me avoid many awkward questions with executives.</p><p>Liked what you read? Follow me on <a href="https://medium.com/@rtkilian">Medium</a>. Otherwise, <a href="https://twitter.com/rtkilian">tweet me</a> or add me on <a href="https://www.linkedin.com/in/rtkilian/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dce7cc89c37c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Hypothesis Test Should I Use for My A/B Experiment?]]></title>
            <link>https://medium.com/data-science/what-hypothesis-test-should-i-use-for-my-a-b-experiment-2cfc7fd3537b?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cfc7fd3537b</guid>
            <category><![CDATA[experimentation]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Mon, 16 May 2022 19:49:17 GMT</pubDate>
            <atom:updated>2022-05-16T19:49:17.630Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick-reference guide for choosing the correct test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5CKegwv5EwlUz3R9" /><figcaption>Photo by <a href="https://unsplash.com/@soymeraki?utm_source=medium&amp;utm_medium=referral">Javier Allegue Barros</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The choice of hypothesis test after running an A/B experiment can be overwhelming for any data practitioner. Both <a href="https://docs.scipy.org/doc/scipy/reference/stats.html#statistical-tests">scipy</a> and <a href="https://docs.scipy.org/doc/scipy/reference/stats.html#statistical-tests">statsmodels</a>, two popular Python libraries, have implemented hundreds of hypothesis tests for all types of use cases.</p><p>This article is your quick reference guide to the most common types of hypothesis tests you’ll need to analyse your A/B(/C) experiments. I use these tests regularly as a Data Scientist at <a href="http://movember.com/">Movember</a>.</p><p>We will cover parametric and non-parametric tests for continuous and categorical variables in two or more samples. I’ve included a flowchart below to help you determine what test to use. Read the documentation when implementing the test as each method has several different input parameters.</p><p>For further reading, check out my other articles to learn <a href="https://medium.com/@rtkilian/how-a-b-testing-helps-microsoft-and-why-you-should-consider-it-too-c975f2922ffe">why you should run A/B experiments</a> and <a href="https://medium.com/towards-data-science/a-quick-reference-checklist-for-a-b-testing-40f533cfb523">how to set up an A/B test</a>. You can also find in-depth explanations of the tests <a href="https://towardsdatascience.com/a-b-testing-a-complete-guide-to-statistical-testing-e3f1db140499">here</a>, <a href="https://towardsdatascience.com/the-ultimate-guide-to-a-b-testing-part-3-parametric-tests-2c629e8d98f8">here</a> and <a href="https://towardsdatascience.com/the-ultimate-guide-to-a-b-testing-part-4-non-parametric-tests-4db7b4b6a974">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjJlHuRemQNli-rqVEkuKA.png" /><figcaption>Image by the author</figcaption></figure><h3>Student’s t-test</h3><p>The t-test is a parametric test used to determine whether there is a significant difference between the means of two continuous samples.</p><p><strong>Assumptions</strong></p><ul><li>Observations in each sample are independent</li><li>Observations in each sample are approximately normally distributed</li><li>Observations in each sample have the same variance</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the means of the two samples are equal</li><li>H1: the means of the two samples are not equal</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Student%27s_t-test">Student’s t-test, Wikipedia</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html">scipy.stats.ttest_ind</a></li><li><a href="https://en.wikipedia.org/wiki/Welch%27s_t-test">Welch’s t-test for samples with unequal variance, Wikipedia</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c966f69745c789005e0f7f1741461b4a/href">https://medium.com/media/c966f69745c789005e0f7f1741461b4a/href</a></iframe><h3>Mann-Whitney U test</h3><p>The Mann-Whitney U test is a non-parametric test to determine whether the distributions of two continuous samples are the same. The Mann-Whitney U test is the non-parametric version of the Student’s t-test for independent samples.</p><p><strong>Assumptions</strong></p><ul><li>Observations in each sample are independent</li><li>Observations in each sample are continuous or ordinal and can be ranked</li><li>The distribution of each sample is approximately the same shape</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the distributions of each sample are the same</li><li>H1: the distributions of each sample are not the same</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test">Mann-Whitney U test, Wikipedia</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mannwhitneyu.html">scipy.stats.mannwhitneyu</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5591eaa5af7a11e7534b9d4bf33a76e/href">https://medium.com/media/f5591eaa5af7a11e7534b9d4bf33a76e/href</a></iframe><h3>Paired Student’s t-test</h3><p>The Paired Student’s t-test is a parametric test used to determine whether there is a significant difference between the means of two paired continuous samples.</p><p><strong>Assumptions</strong></p><ul><li>Observations in each sample are independent</li><li>Observations in each sample are approximately normally distributed</li><li>Observations in each sample have the same variance</li><li>Observations across each sample are paired</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the means of the two paired samples are equal</li><li>H1: the means of the two paired samples are not equal</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Student%27s_t-test#Dependent_t-test_for_paired_samples">Student’s t-test for paired samples, Wikipedia</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_rel.html">scipy.stats.ttest_rel</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df39c1a641944cae0bb38e2017cdf45a/href">https://medium.com/media/df39c1a641944cae0bb38e2017cdf45a/href</a></iframe><h3>Wilcoxon signed-rank test</h3><p>The Wilcoxon signed-rank test is a non-parametric test to determine whether the distributions of two paired continuous samples are the same. The Wilcoxon test is the non-parametric version of the Paired Student’s t-test.</p><p><strong>Assumptions</strong></p><ul><li>Observations in each sample are independent</li><li>Observations in each sample can be ranked</li><li>Observations across each sample are paired</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the distributions of the paired samples are the same</li><li>H1: the distributions of the paired samples are not the same</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test">Wilcoxon signed-rank test, Wikipedia</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.wilcoxon.html">scipy.stats.wilcoxon</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a07ee9a5f9260a0351b428851f5d0065/href">https://medium.com/media/a07ee9a5f9260a0351b428851f5d0065/href</a></iframe><h3>Analysis of Variance Test (ANOVA)</h3><p>The one-way ANOVA test is a parametric test used to determine whether there is a significant difference between the means of two or more continuous samples.</p><p><strong>Assumptions</strong></p><ul><li>Observations in each sample are independent</li><li>Observations in each sample are approximately normally distributed</li><li>Observations in each sample have the same variance</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the means of the two or more samples are equal</li><li>H1: one or more of the means of the samples are not equal</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Analysis_of_variance">Analysis of variance (ANOVA), Wikipedia</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.f_oneway.html">scipy.stats.f_oneway</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b734d4b87e3d00655db9940ed4b122d/href">https://medium.com/media/2b734d4b87e3d00655db9940ed4b122d/href</a></iframe><h3>Kruskal-Wallis H-test</h3><p>The Kruskal-Wallis H-test is a non-parametric test to determine whether there is a significant difference between the medians of two or more continuous samples. It is the non-parametric equivalent of the one-way ANOVA test.</p><p><strong>Assumptions</strong></p><ul><li>Observations in each sample are independent</li><li>Observations in each sample have the same variance</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the medians of the two or more samples are equal</li><li>H1: one or more of the medians of the samples are not equal</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Kruskal%E2%80%93Wallis_one-way_analysis_of_variance">Kuskal-Wallis one-way analysis test of variance, Wikipedia</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kruskal.html">scipy.stats.kruskal</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ade6be5c748b742c9e3b576037b92c2/href">https://medium.com/media/2ade6be5c748b742c9e3b576037b92c2/href</a></iframe><h3>Chi-squared Test</h3><p>The Chi-squared test tests the independence of two or more categorical variables in a contingency table.</p><p><strong>Assumptions</strong></p><ul><li>Observations in the sample are independent</li><li>The observed and expected frequencies in each cell in the contingency table are at least 5</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the variables are independent</li><li>H1: the variables are not independent</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Chi-squared_test">Chi-squared test, Wikipedia</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html">scipy.stats.chi2_contingency</a></li><li><a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html">pandas.crosstab</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86387e2709a21ace6bd3afe0590406a8/href">https://medium.com/media/86387e2709a21ace6bd3afe0590406a8/href</a></iframe><h3>Fisher’s exact test</h3><p>Like the Chi-squared test, Fisher’s exact test is used to test the independence of two categorical variables in a contingency table. Fisher’s exact test is used instead of a Chi-squared test when the sample sizes are small.</p><p><strong>Assumptions</strong></p><ul><li>Observations in the sample are independent</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the variables are independent</li><li>H1: the variables are not independent</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Fisher%27s_exact_test">Fisher’s test, Wikipedia</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.fisher_exact.html">scipy.stats.fisher_exact</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d5cd90f957176bc4b92f3e12d075954/href">https://medium.com/media/2d5cd90f957176bc4b92f3e12d075954/href</a></iframe><h3>Poisson E-test</h3><p>The Poisson exact test (E-test) tests whether there is a significant difference between two Poisson rates.</p><p><strong>Assumptions</strong></p><ul><li>Observations in the sample are independent</li></ul><p><strong>Hypotheses</strong></p><ul><li>H0: the Poisson rates are the same</li><li>H1: the Poisson rates are not the same</li></ul><p><strong>Resources</strong></p><ul><li><a href="https://onlinelibrary.wiley.com/doi/10.1002/bimj.200710403">Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates, Biometrical Journal 50 (2008) 2, 2008</a></li><li><a href="https://www.statsmodels.org/dev/generated/statsmodels.stats.rates.test_poisson_2indep.html">statsmodels.stats.rates.test_poisson_2indep</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8af28f3fbaf8e07b240a63faadfe4cf/href">https://medium.com/media/c8af28f3fbaf8e07b240a63faadfe4cf/href</a></iframe><h3>Conclusion</h3><p>This article reviewed the hypothesis tests you will most likely use when analysing your A/B experiments. We covered what situations the tests are most suitable for, what assumptions need to be met, how to interpret the results, and provided the code and resources you will need to implement the tests.</p><p>Thank you to <a href="https://machinelearningmastery.com/statistical-hypothesis-tests-in-python-cheat-sheet/">Machine Learning Mastery</a> for inspiring this article.</p><p>Have I missed anything? Let me know, and I will update the list.</p><p>Liked what you read? Follow me on <a href="https://medium.com/@rtkilian"><strong>Medium</strong></a>. Otherwise, <a href="https://twitter.com/rtkilian"><strong>tweet me</strong></a><strong> </strong>or add me on <a href="https://www.linkedin.com/in/rtkilian/"><strong>LinkedIn</strong></a>.</p><p>You can find all the code used in this post on <a href="https://github.com/rtkilian/data-science-blogging/blob/main/what-hypothesis-test-ab.ipynb">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cfc7fd3537b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-hypothesis-test-should-i-use-for-my-a-b-experiment-2cfc7fd3537b">What Hypothesis Test Should I Use for My A/B Experiment?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick-Reference Checklist for A/B Testing]]></title>
            <link>https://medium.com/data-science/a-quick-reference-checklist-for-a-b-testing-40f533cfb523?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/40f533cfb523</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[experimentation]]></category>
            <category><![CDATA[experiment]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 13:51:23 GMT</pubDate>
            <atom:updated>2022-07-15T03:13:04.176Z</atom:updated>
            <content:encoded><![CDATA[<h4>Don’t miss any critical steps for your next experiment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PDcVLhkglFfHk3Ex" /><figcaption>Photo by <a href="https://unsplash.com/@thomasbormans?utm_source=medium&amp;utm_medium=referral">Thomas Bormans</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So you want to run an A/B test?</p><p>It’s easy to get bogged down in the details if you’ve never run a test before or if you haven’t run an experiment in a while. That’s why I use this checklist in my role as a Data Scientist when setting up experiments at <a href="http://movember.com/">Movember</a>.</p><p>This checklist isn’t meant to be a comprehensive guide to A/B testing (if that’s what you’re after, check out the resources <a href="https://towardsdatascience.com/ab-testing-with-python-e5964dd66143">here</a>, <a href="https://towardsdatascience.com/a-practical-guide-to-a-b-tests-in-python-66666f5c3b02">here</a> and <a href="https://towardsdatascience.com/how-to-conduct-a-b-testing-3076074a8458">here</a>). Instead, you can bookmark the checklist and reference it when required.</p><p>The A/B testing checklist is broken into twelve steps:</p><ol><li>Formulate your hypotheses</li><li>Choose the metrics you will track</li><li>Decide if you will test more than one variant</li><li>Pick your sampling process</li><li>Determine the sample size for each group (power analysis)</li><li>Calculate how long your experiment will run for</li><li>Ensure you can replicate your experiment</li><li>Don’t stop the test early</li><li>Monitor the quality of your experiment</li><li>Analyse the A/B test results</li><li>Check the validity of your results</li><li>Consider the difference between statistical and practical significance</li></ol><p>I’ve provided links to resources for a quick refresher on concepts and called out best practices.</p><h3>Before the test</h3><h4>1. Formulate your hypotheses</h4><ul><li>What are your null and alternative <a href="https://www.statisticshowto.com/probability-and-statistics/hypothesis-testing/#Hypothesis">hypotheses</a>?</li><li>Are you running a one-sided or a two-sided <a href="https://www.statisticshowto.com/probability-and-statistics/hypothesis-testing/one-tailed-test-or-two/#:~:text=A%20one%2Dtailed%20test%20has,the%20image%20to%20the%20left).&amp;text=Very%20simply%2C%20the%20hypothesis%20test,state%20that%20the%20mean%20%3D%20x.">test</a>?</li></ul><h4>2. Choose the metrics you will track</h4><ul><li>What is your <a href="https://www.linkedin.com/pulse/overall-evaluation-criterion-oec-ronny-kohavi/">Overall Evaluation Criteria (OEC)</a>? The OEC is the primary decision variable and can combine several metrics.</li><li>Have your stakeholders approved the OEC and the metrics you will track?</li></ul><h4>3. Decide if you will test more than one variant</h4><ul><li>Will you be analysing more than one variable with a multivariate <a href="https://towardsdatascience.com/a-b-c-tests-how-to-analyze-results-from-multi-group-experiments-ad5d5cee0b05">A/B/C test</a>? Be careful of the <a href="https://egap.org/resource/10-things-to-know-about-multiple-comparisons/">multiple comparisons problem</a>.</li><li>Will you be running an <a href="https://towardsdatascience.com/an-a-b-test-loses-its-luster-if-a-a-tests-fail-2dd11fa6d241">A/A test</a> to check for sampling issues, including sample ratio mismatch?</li></ul><h4>4. Pick your sampling process</h4><ul><li>Will the Stable Unit Treatment Value Assumption (SUTVA) be violated (e.g. <a href="https://towardsdatascience.com/ab-testing-challenges-in-social-networks-e67611c92916">network data</a>)?</li><li>Will your sample have distinct subpopulations (e.g. heavy vs. light users) that need to be controlled using <a href="https://en.wikipedia.org/wiki/Stratified_sampling">stratified sampling</a>?</li></ul><h4>5. Determine the sample size for each group (power analysis)</h4><ul><li>What is the <a href="https://towardsdatascience.com/finding-the-right-significance-level-for-an-ab-test-26d907ca91c9">significance level</a> (<em>α</em>) of the test? The significance level is the probability of rejecting the null hypothesis when it’s true (Type I error, false positive) and is commonly set as 0.05.</li><li>What is the <a href="https://towardsdatascience.com/finding-the-right-significance-level-for-an-ab-test-26d907ca91c9">power</a> (1-<em>β</em>) of the test? The power is the probability of correctly rejecting the null hypothesis when the alternative is true and is commonly set as 0.8.</li><li>What is the <a href="https://dimewiki.worldbank.org/Minimum_Detectable_Effect#:~:text=The%20minimum%20detectable%20effect%20is,and%20survey%20and%20project%20budgets.">minimum detectable effect</a> (<em>δ</em>) of the test? The minimum detectable effect is the smallest improvement by which the experiment would be deemed successful and is commonly set by stakeholders.</li><li>What is the sample size required for your test and control group? The size can be calculated using <a href="https://towardsdatascience.com/introduction-to-power-analysis-in-python-e7b748dfa26">Python</a>.</li></ul><h4>6. Calculate how long your experiment will run for</h4><ul><li>How many days will it take to meet the minimum sample requirements calculated above? For example, if you need n=10,000 participants in each group and your website receives 1,000 unique visitors per day, you will need 20 days to fill the two samples.</li><li>Are you going to be running your experiment across multiple seasons, holidays or <a href="https://www.widerfunnel.com/blog/ab-testing-during-the-holidays/">promotional cycles</a>? A commonly cited rule of thumb is to run your experiment for at least <a href="https://cxl.com/blog/12-ab-split-testing-mistakes-i-see-businesses-make-all-the-time/#:~:text=You%20must%20run%20tests%20for,minimum%20of%20two%20weeks%20anyway.">two weeks</a>.</li></ul><h4>7. Ensure you can replicate your experiment</h4><ul><li>Have you set up a repository for your code (e.g. <a href="https://resources.github.com/webcasts/GitHub-for-data-scientists-thankyou/#:~:text=Data%20science%20and%20machine%20learning,team%20and%20across%20the%20organization.)">GitHub</a>)?</li><li>How will you document your process and results (e.g. a wiki)?</li><li>Have you set a random seed?</li></ul><h3>During the test</h3><h4>8. Don’t stop the test early</h4><ul><li>Are you ‘<a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3204791">p-hacking</a>’ by stopping your experiment early because you’ve observed a positive effect? Instead, you should wait until you’ve collected your full sample or have previously agreed on an <a href="https://netflixtechblog.com/improving-experimentation-efficiency-at-netflix-with-meta-analysis-and-optimal-stopping-d8ec290ae5be">early stopping criterion</a>.</li></ul><h4>9. Monitor the quality of your experiment</h4><ul><li>Have you checked for <a href="https://towardsdatascience.com/the-essential-guide-to-sample-ratio-mismatch-for-your-a-b-tests-96a4db81d7a4">sample ratio mismatch</a> (i.e. where the sample sizes don’t match)? A Chi-Squared test of independence can be used on your sample to check if there is a mismatch.</li><li>Are there any other quality issues that may threaten the validity of your experiment? E.g. <a href="https://www.kameleoon.com/en/blog/ab-testing-flicker-effect#:~:text=During%20A%2FB%20tests%2C%20the,and%20overall%20engagement%20with%20consumers.">flicker effect</a>, <a href="https://web.pdx.edu/~stipakb/download/PA555/ResearchDesign.html">instrumentation effect</a>.</li></ul><h3>After the test</h3><h4>10. Analyse the A/B test results</h4><ul><li>What is the appropriate statistical test? Your choice of test will be dependent on <a href="https://towardsdatascience.com/simple-and-complet-guide-to-a-b-testing-c34154d0ce5a">several factors</a>, including the probability distribution function for your primary metric (continuous, binary, etc.), the size of your sample, and whether you are using a one-sided or two-sided test. For example, you may use a 2-sample T-Test when comparing the average revenue per user or the Chi-Squared Test for the number of conversions.</li><li>What is the value of the test statistic and p-value? See <a href="https://towardsdatascience.com/what-hypothesis-test-should-i-use-for-my-a-b-experiment-2cfc7fd3537b">this article </a>for a cheat sheet of statistical tests and how to apply them in Python.</li><li>Do you reject, or fail to reject, the statistical hypothesis based on your selected significant level?</li><li>What is the standard error and confidence interval? For non-parametric statistical tests, you will need to use a resampling technique such as <a href="https://elizavetalebedeva.com/bootstrapping-confidence-intervals-the-basics/">bootstrapping</a>.</li></ul><h4>11. Check the validity of your results</h4><ul><li>Have you checked whether the experiment is <a href="https://www.verywellmind.com/internal-and-external-validity-4584479">internally valid</a> (i.e. the extent to which the investigation establishes a trustworthy causal relationship)? For example, you should check for <a href="https://odsc.medium.com/mastering-a-b-testing-from-design-to-analysis-f0ab3974aee0">confounding variables</a>, <a href="https://towardsdatascience.com/online-controlled-experiment-8-common-pitfalls-and-solutions-ea4488e5a82e">cross-contamination</a> between test and control groups, etc.</li><li>Have you checked whether the experiment is <a href="https://www.verywellmind.com/internal-and-external-validity-4584479">externally valid</a> (i.e. how well the investigation can be generalised to the broader population)? For example, you should check for any <a href="https://medium.com/airbnb-engineering/selection-bias-in-online-experimentation-c3d67795cceb">selection bias</a>, unexpected events through your experiment, and how easily your test can be replicated.</li></ul><h4>12. Consider the difference between statistical and practical significance</h4><ul><li>Is the measured effect greater than the minimum detectable effect set in the power analysis (i.e. practically significant)? This is different from getting a p-value lower than your significance level (i.e. statistically significant) which can be achieved even with a low effect size.</li><li>Are you Hypothesising After the Results are Known (<a href="https://pubmed.ncbi.nlm.nih.gov/15647155/">HARK</a>)?</li></ul><h3>Conclusion</h3><p>This article described the various items to check before, during, and after an A/B test. The checklist is written as a quick-reference guide based on my experiences running experiments at Movember.</p><p>Have I missed anything? Please let me know, and I will update the checklist.</p><p>Liked what you read? Follow me on <a href="https://medium.com/@rtkilian"><strong>Medium</strong></a>. Otherwise, <a href="https://twitter.com/rtkilian"><strong>tweet me</strong></a> or add me on <a href="https://www.linkedin.com/in/rtkilian/"><strong>LinkedIn</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40f533cfb523" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-quick-reference-checklist-for-a-b-testing-40f533cfb523">A Quick-Reference Checklist for A/B Testing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How A/B Testing Helps Microsoft and Why You Should Consider It Too]]></title>
            <link>https://medium.com/@rtkilian/how-a-b-testing-helps-microsoft-and-why-you-should-consider-it-too-c975f2922ffe?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c975f2922ffe</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[experimentation]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 12:03:23 GMT</pubDate>
            <atom:updated>2022-02-16T06:33:24.347Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use A/B testing wisely to maximise results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hqfg6bpLpi-QT1ls" /><figcaption>Photo by <a href="https://unsplash.com/@impelling?utm_source=medium&amp;utm_medium=referral">Ed Hardie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A/B testing is an experimental approach to decision-making that could generate significant value for your organisation. Microsoft has been using it <a href="https://www.microsoft.com/en-us/research/publication/online-experimentation-at-microsoft/">since 2006</a> and now their <a href="https://www.microsoft.com/en-us/research/group/experimentation-platform-exp/">Experimentation Platform (ExP)</a> is embedded across all their major products.</p><p>A/B testing is a controlled experiment where two versions of a variable (e.g. button, algorithm, marketing content) are shown to users who have randomly been split into two groups. Once a sufficient number of observations are recorded in each group they are compared to determine if there is a statistically significant difference. This form of experimentation was popularised by online companies, such as Google’s now-famous experiment of <a href="https://stopdesign.com/archive/2009/03/20/goodbye-google.html">testing 41 shades of blue to see which one performs best</a>.</p><p>After reading this article you will understand the benefits of A/B testing, how Microsoft uses it, and some potential pitfalls.</p><h3>The benefits of A/B testing</h3><p>A/B testing is a form of causal inference. <a href="https://hdsr.mitpress.mit.edu/pub/wjhth9tr/release/1#:~:text=Causal%20inference%20is%20the%20study,treatments%20affect%20outcomes%20of%20interest.&amp;text=In%20such%20settings%2C%20statisticians%20and,(i.e.%2C%20nonexperimental)%20data.">Causal inference</a> is the study of how treatments affect outcomes of interest. For example, does a change to my recommendation algorithm increase the click-through rate of my product?</p><p>Using data to drive decision-making is a big step for many organisations, with as many as <a href="https://www.alation.com/resource-center/reports/state-data-culture-report-2020-q3">two-thirds of CEOs still relying on gut instincts when making decisions</a>. Even if this isn’t the case at your organisation, you could see large benefits from moving beyond correlational analysis.</p><p>A study conducted with Microsoft, <a href="https://ieeexplore.ieee.org/abstract/document/8051322">The Benefits of Controlled Experimentation at Scale</a>, outlined the following advantages of experimentation:</p><ol><li><strong>Value discovery:</strong> a business can learn what its customers value by experimenting with its product and marketing platform</li><li><strong>Lowering product complexity:</strong> only one-third of new product features tested on Microsoft’s experimentation system showed noticeable improvement in key metrics, allowing them to avoid wasting resources implementing non-value-adding features</li><li><strong>Team activity planning</strong>: learnings from experiments can be used to prioritise the strategic direction of personnel</li><li><strong>Ensuring quality and capacity:</strong> implementing a new feature to a subset of the total user base limits the impact of problems caused by bugs and underestimated resource allocation</li></ol><p>With these benefits, it is unsurprising to find that many organisations, not just Microsoft, have embraced A/B testing as part of their core culture.</p><h3>What organisations are using A/B testing?</h3><p>Experimentation has become ubiquitous in the technology industry. Software and the internet have facilitated an environment where A/B testing is relatively inexpensive and can be run with millions of users. Everything is now tested, from front-end user-interface changes to back-end algorithms and marketing content and media.</p><p>Over one hundred thousand experiments are run annually by thirteen organisations present at the <a href="https://dl.acm.org/doi/10.1145/3331651.3331655">Practical Online Controlled Experiments Summit</a>, including:</p><ul><li><strong>Search:</strong> <a href="https://research.google/pubs/pub36500/">Google</a>, <a href="https://dl.acm.org/doi/10.1145/2487575.2488217">Bing</a>, <a href="https://research.yandex.com/tutorials/online-evaluation/sigir-2019">Yandex</a></li><li><strong>Retail:</strong> <a href="https://www.awa-digital.com/blog/truth-about-amazon-booking-experimentation-culture/">Amazon</a>, <a href="https://tech.ebayinc.com/research/measuring-success-with-experimentation/">eBay</a>, <a href="https://www.etsy.com/seller-handbook/article/building-better-tools-with-experiments/128628130971">Etsy</a></li><li><strong>Media</strong>: <a href="https://netflixtechblog.com/its-all-a-bout-testing-the-netflix-experimentation-platform-4e1ca458c15">Netflix</a>, Amazon</li><li><strong>Social networking</strong>: <a href="https://www.degruyter.com/document/doi/10.1515/jci-2015-0021/html">Facebook</a>, <a href="https://engineering.linkedin.com/blog/2020/our-evolution-towards-t-rex--the-prehistory-of-experimentation-i">LinkedIn</a>, <a href="https://blog.twitter.com/engineering/en_us/a/2015/twitter-experimentation-technical-overview">Twitter</a></li><li><strong>Travel</strong>: <a href="https://eng.lyft.com/experimentation-in-a-ridesharing-marketplace-b39db027a66e">Lyft</a>, <a href="https://eng.uber.com/xp/">Uber</a>, <a href="https://medium.com/airbnb-engineering/https-medium-com-jonathan-parks-scaling-erf-23fd17c91166">Airbnb</a>, <a href="https://booking.ai/tagged/experimentation">Booking.com</a></li></ul><p>To help us understand what sort of experiments these companies are running, let’s look at two examples from Microsoft.</p><h3>A case study of experimentation at Microsoft</h3><p>Microsoft has a culture of experimentation. A/B testing is used across its suite of products including Office, Bing and Skype. Their involvement in the study of the <a href="https://ieeexplore.ieee.org/abstract/document/8051322">benefits of experimentation at scale</a> gives us an idea of the tests that Microsoft is running at any given time.</p><h4>Case study 1: MS Word contextual commands</h4><p>Designers at Microsoft hypothesised that adding contextual commands (i.e. the suggested actions shown on the <a href="https://i.ytimg.com/vi/zHvZlpm5neo/maxresdefault.jpg">bottom of the screen</a>) to the mobile app will result in more users editing documents on their phone and increase 2-week retention.</p><p>Initial results of the A/B test showed an unusual result. Further investigation found that there was a telemetry bug introduced with the release. Thankfully, this bug only affected a small group of users involved in the experiment and was fixed (and validated using <a href="https://towardsdatascience.com/an-a-b-test-loses-its-luster-if-a-a-tests-fail-2dd11fa6d241">A/A testing</a>).</p><p>Subsequent A/B testing over two weeks confirmed there was a significant increase in mobile edits but no significant increase in 2-week retention. Nevertheless, the experiment was deemed a success and the feature was prioritised for other MS Office products.</p><h4>Case study 2: OneNote sharing</h4><p>The OneNote team hypothesised that allowing users to share a single page of a OneNote notebook, rather than the whole notebook only, would increase the percentage of users sharing.</p><p>The A/B test showed that users with this change had a significantly higher share rate. However, further investigation showed that a subset of the treatment group didn’t share this improved rate. Similar to the previous case study, the feature caused a bug that impacted a subset of users on an older OS version. This bug was identified and fixed because of the controlled experiment.</p><h3>The potential pitfalls of A/B testing</h3><p>A/B testing can help your organisation generate value as shown by Microsoft. However, running experiments isn’t as simple as rolling out a change and measuring the difference in key metrics. A/B tests that are poorly designed and not analysed correctly could end up costing your organisation.</p><p>In general, <a href="https://www.braze.com/resources/articles/not-worth-ab-testing">you shouldn’t run an A/B test</a> when:</p><ul><li>You don’t have a large enough sample size</li><li>You can’t invest the time</li><li>You don’t have an informed hypothesis with key metrics to measure</li></ul><p>Even if you meet the above criteria, it’s easy to fail in your experiment if you make any of these <a href="https://towardsdatascience.com/online-controlled-experiment-8-common-pitfalls-and-solutions-ea4488e5a82e">eight common mistakes</a>, such as having cross-contamination between groups, and not holding non-treatment variables constant.</p><p>Given the complexity of A/B testing, you may be tempted to instead simply make a change and attempt to assess success by measuring your key metrics before and after. If only it was that easy. Without running a controlled experiment, it’s difficult to determine whether an improvement in your key metric was because of your change or some other external variable.</p><p>But it’s also possible to go too far with experimentation. Focussing on incremental changes may stifle innovation (think <a href="https://stopdesign.com/archive/2009/03/20/goodbye-google.html">Google’s 41 shades of blue)</a>.</p><h3>Conclusion</h3><p>Investing in A/B testing, like Microsoft, can benefit your organisation, provided you avoid the common pitfalls. A/B testing will allow you to identify high-value opportunities, plan strategic objectives and ensure a high-quality offering for your customers. Microsoft has benefited from A/B testing by incorporating contextual commands into the MS Word app and adding page sharing to OneNote. However, improperly designed A/B tests or focussing on incremental improvements as opposed to innovation may end up hurting your organisation. Nonetheless, A/B testing done right can help you unlock value by making more data-driven decisions.</p><p>Liked what you read? Follow me on <a href="https://medium.com/@rtkilian"><strong>Medium</strong></a>.</p><p>Otherwise, <a href="https://twitter.com/rtkilian"><strong>tweet me</strong></a> or add me on <a href="https://www.linkedin.com/in/rtkilian/"><strong>LinkedIn</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c975f2922ffe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Deployed a Sentiment Analyser API with spaCy, Flask and Heroku]]></title>
            <link>https://medium.com/data-science/how-i-deployed-a-sentiment-analyser-api-with-spacy-flask-and-heroku-bd9b8f9de6cf?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd9b8f9de6cf</guid>
            <category><![CDATA[spacy]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Wed, 27 Oct 2021 13:20:02 GMT</pubDate>
            <atom:updated>2021-10-27T13:20:02.666Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how you can develop RESTful APIs with the models you build</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2lOY5Lr0i3N20GWF" /><figcaption>Photo by <a href="https://unsplash.com/@artbyhybrid?utm_source=medium&amp;utm_medium=referral">Hybrid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>By completing this tutorial, you will learn to deploy a machine learning model to Heroku using Flask. Therefore, even if you don’t have access to Machine Learning Engineers or Software Engineers at your organisation, you will have the necessary skills to deploy machine learning REST APIs.</p><p>I will demonstrate by first creating a sentiment analysis model using spaCy. I will then show you how you turn this model into a REST API using Flask. Finally, the API will be deployed to Heroku and integrated into an existing web application.</p><h3>Creating a simple sentiment analyser with spaCy</h3><p>First, we build a basic sentiment analysis model that identifies whether the user input is positive or negative. We will use <a href="https://spacy.io/universe/project/spacy-textblob">spaCyTextBlob</a>, which extends <a href="https://spacy.io/">SpaCy</a> with additional text processing capabilities from <a href="https://textblob.readthedocs.io/en/dev/">TextBlob</a>, including sentiment analysis.</p><p>To begin, we import spaCy and TextBlob.</p><pre>import spacy</pre><pre>from spacytextblob.spacytextblob import SpacyTextBlob</pre><p>We also load the spaCy language model and extend our text processing pipeline using TextBlob.</p><pre>nlp = spacy.load(&#39;en_core_web_sm&#39;)</pre><pre>nlp.add_pipe(&#39;spacytextblob&#39;)</pre><p>We aim to build a sentiment analysis model that takes a user inputted string and scores the sentiment. The model should output its prediction in a dictionary which will simplify the development of our API.</p><pre># User input text<br>user_input = &#39;This is a wonderful campsite. I loved the serenity and the birds chirping in the morning.&#39;</pre><pre># Process user input<br>doc = nlp(user_input)</pre><pre># Convert the model output to a dictionary<br>input_polarity = doc._.polarity<br>sentiment = {<br>    &#39;score&#39;: input_polarity<br>}<br>print(sentiment)</pre><p>If we run this pipeline, we should get the following output:</p><pre>{&#39;score&#39;: 0.85}</pre><p>Our model outputs a score from -1 (negative sentiment) to 1 (positive sentiment).</p><p>To run this code yourself, please check out my <a href="https://github.com/rtkilian/data-science-blogging/blob/main/spaCy_sentiment.ipynb">Google Colab Notebook</a>.</p><h3>Flask RESTful API Concept Review</h3><p>Before we jump into developing our sentiment analysis Restful API, let’s first review a few concepts.</p><h4>What is Flask?</h4><p><a href="https://flask.palletsprojects.com/en/2.0.x/">Flask</a> is a Python micro web framework that gives you the tools required to develop and build a web application. ‘Micro’ refers to the fact that Flask does not enforce particular libraries or structures like other frameworks do (e.g. <a href="https://www.djangoproject.com/">Django</a>). Flask’s lightweight design makes the framework flexible and easy to use, making it popular with Data Scientists familiar with Python.</p><h4>What is an API?</h4><p>An Application Programming Interface (API) allows products and services to communicate with each other based on a set of rules. As a Data Scientist, you don’t need to understand how an API is implemented, however, you can use its interface to interact with it. For example, here is a list of simple APIs:</p><ul><li><a href="https://api.cryptonator.com/api/ticker/btc-usd">Cryptonator</a>: cryptocurrency exchange rates</li><li><a href="https://open-meteo.com/en">Open-Meteo</a>: weather forecasts</li><li><a href="https://icanhazdadjoke.com/">icanhazdadjoke</a>: random dad jokes</li></ul><h4>What is a RESTful API?</h4><p>REST stands for <strong>RE</strong>presentational <strong>S</strong>tate <strong>T</strong>ransfer. An API is RESTful when it is developed with particular constraints in mind. The constraints make it easier for others to use and communicate with your API.</p><p>In the REST architecture, a client (e.g. your browser) requests to create, read, update or delete (otherwise known as ‘CRUD’) data on a server. The server will then respond based on the request you have made.</p><h3>A simple ‘Hello World’ API using Flask</h3><p>We will start by developing a simple API to demonstrate the main building blocks of Flask.</p><p><em>Note: I recommend that you use a Python IDE or code editor, such as </em><a href="https://code.visualstudio.com/"><em>Visual Studio Code</em></a><em>, to write your scripts. My application is developed on a Windows machine so your commands may vary on Unix or macOS.</em></p><h4>Virtual environments and installing libraries</h4><p>Using the terminal, create a virtual environment called <strong>env </strong>in a new directory called <strong>flask-hello-world</strong>:</p><pre>$ py -m venv env</pre><p><em>If you’re on Unix or macOS the command is:</em></p><pre>$ python3 -m venv env</pre><p>Before we start installing Flask and the other libraries we need, activate your virtual environment:</p><pre>$ .\env\Scripts\activate</pre><p><em>If you’re on Unix or macOS the command is:</em></p><pre>$ source env/bin/activate</pre><p>Now, let’s install the <a href="https://flask.palletsprojects.com/en/2.0.x/installation/">Flask</a> and <a href="https://flask-restful.readthedocs.io/en/latest/installation.html">Flask-RESTful</a>:</p><pre>$ pip install Flask<br>$ pip install flask-restful</pre><p>Finally, let’s install <a href="https://pypi.org/project/gunicorn/">gunicorn </a>for our server:</p><pre>$ pip install gunicorn</pre><h4>Writing our app.py</h4><p>With everything set up, we can move onto our <strong>app.py </strong>file. Start by importing Flask and Flask-RESTful:</p><pre>from flask import Flask<br>from flask_restful import Resource, Api</pre><p>We then initialise the Flask application and assign it as an API:</p><pre>app = Flask(__name__)<br>api = Api(app)</pre><p>Flask-RESTful provides building blocks known as resources that allow us to access HTTP methods such as POST, GET, PUT and DELETE. These correspond to our Create, Read, Update and Delete (CRUD) operations respectively. Let’s define a simple GET route:</p><pre>class HelloWorld(Resource):<br>    def get(self):<br>        return {&#39;hello&#39;: &#39;world&#39;}</pre><p>When it comes time to create our sentiment analysis app, we will return to this block of code and adjust as required.</p><p>Next, we add our HelloWorld resource with a URL of ‘/’ to our API:</p><pre>api.add_resource(HelloWorld, &#39;/&#39;)</pre><p>Finally, we want to run the application if the current filename is the same as the main filename. We also run with debug mode on which will be turned off when deploying:</p><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>If you’ve been following along, your <strong>app.py</strong> should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b11e50e32a6b441e9ccc14d44d894c7b/href">https://medium.com/media/b11e50e32a6b441e9ccc14d44d894c7b/href</a></iframe><p>To start our simple web application, we run our <strong>app.py</strong> file in our terminal:</p><pre>$ python app.py</pre><p>You should see the following messages in your terminal if everything has gone to plan:</p><figure><img alt="Flask hello world terminal after running" src="https://cdn-images-1.medium.com/max/1024/1*6GrIsExWh2Y2TYoPJam-zw.png" /><figcaption>Image by author</figcaption></figure><p>To test our API, we have a few different options. The simplest is using curl in a new terminal window by using the following command:</p><pre>$ curl http://127.0.0.1:5000/</pre><p>You should get the following output:</p><pre>{<br>    &quot;hello&quot;: &quot;world&quot;<br>}</pre><p>Alternatively, you could use a tool like <a href="https://www.postman.com/">Postman</a> which is designed for building and testing APIs. For example, the image below demonstrates a GET request to our server and the response we receive back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjSyF4eoNTJj0ABlvCDwgA.png" /><figcaption>Image by author</figcaption></figure><p>Finally, you could use the Python <a href="https://docs.python-requests.org/en/latest/">Requests</a> library that allows you to send HTTP requests. However, this tutorial doesn’t cover the Requests library and I encourage you to read the documentation instead.</p><p>That’s it! By this point, you should have your first ‘hello world’ Flask API running now. For reference, you can find all my code in this <a href="https://github.com/rtkilian/flask-hello-world">GitHub repository</a>.</p><h3>Adding sentiment analysis to our API with spaCy</h3><p>Between our spaCy sentiment analyser notebook and ‘hello world’ Flask API, you should have everything you need to create the sentiment analysis API.</p><p>Start by creating a new directory (mine is called <strong>sentiment-analyser-yelpcamp</strong>), setting up your virtual environment and installing the libraries you require. Don’t forget to include spaCy and spaCyTextBlob:</p><pre>$ pip install -U pip setuptools wheel<br>$ pip install -U spacy<br>$ python -m spacy download en_core_web_sm<br>$ pip install spacytextblob</pre><p>Then, we begin our <strong>app.py</strong> file by importing and initialising our libraries:</p><pre>from flask import Flask, request<br>from flask_restful import Resource, Api, reqparse</pre><pre>import spacy<br>from spacytextblob.spacytextblob import SpacyTextBlob</pre><pre>nlp = spacy.load(&#39;en_core_web_sm&#39;)<br>nlp.add_pipe(&#39;spacytextblob&#39;)</pre><pre>app = Flask(__name__)<br>api = Api(app)</pre><p>You may notice that we’re importing the <a href="https://flask-restful.readthedocs.io/en/latest/api.html#module-reqparse">reqparse</a> module from Flask-RESTful. The reqparse module simplifies form validation, allowing us to check the user’s input before passing it onto our sentiment analysis model.</p><p>My API will be deployed to my website, <a href="https://github.com/rtkilian/YelpCamp">YelpCamp</a>, to classify the sentiment of campground reviews. I’ll set up reqparse to check that the form (or request from a tool such as Postman) includes a field called ‘review’:</p><pre>parser = reqparse.RequestParser()<br>parser.add_argument(&#39;review&#39;, required=True,<br>                    help=&#39;Review cannot be blank!&#39;)</pre><p>Now, let’s define a POST route that takes the ‘review’ field from the request body, converts it into a spaCy Doc object via the nlp object, and extracts the sentiment score using spaCyTextBlob:</p><pre>class PredictSentiment(Resource):<br>    def post(self):<br>        args = parser.parse_args()<br>        review = args[&#39;review&#39;]<br>        doc = nlp(review)<br>        score = doc._.polarity<br>        return {&#39;score&#39;: score}</pre><p>Then we add our PredictSentiment resource with a URL of ‘/predict’ to our API:</p><pre>api.add_resource(PredictSentiment, &#39;/predict&#39;)</pre><p>Finally, we want to run the application if the current filename is the same as the main filename. This time, however, we do not run our API in debug mode as we will be deploying our application to Heroku in the next step.</p><pre>if __name__ == &#39;__main__&#39;:<br>    app.run()</pre><p>Once complete, your <strong>app.py</strong> should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e65e44d204014206016592ba1f7214d/href">https://medium.com/media/1e65e44d204014206016592ba1f7214d/href</a></iframe><p>We can now start our Flask application and test our API using Postman to see if we receive the expected response. This time, we will be making our POST request to ‘http://127.0.0.1:5000/predict’ and we include our ‘review’ in the request body:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmogdhIHsn4Ei3atRIVThg.png" /><figcaption>Image by author</figcaption></figure><p>Our model responds with a JSON indicating the sentiment score is 0.60 (on a scale of -1 to 1) meaning the sentiment of our review was very positive.</p><p>Now that our API is running in our local environment, we can deploy our application to Heroku.</p><p>For reference, you can access my code on my <a href="https://github.com/rtkilian/sentiment-analyser-yelpcamp">GitHub</a>.</p><h3>Deploying the API to Heroku</h3><p>In your application directory, add a file called <strong>Procfile </strong>and include the following:</p><pre>web: gunicorn app:app</pre><p>According to the Heroku <a href="https://devcenter.heroku.com/articles/procfile">documentation</a>, the Procfile “specifies the commands that are executed by the app on startup”.</p><p>We also need to create a <strong>requirements.txt</strong> file to be included in our directory:</p><pre>pip freeze &gt; requirements.txt</pre><p>Before we deploy our application to Heroku, we’re going to initialise a Git repository:</p><pre>$ git init</pre><p>However, we don’t want to include all our packages in our virtual environment so we’re going to create a <strong>.gitignore</strong> with the following contents:</p><pre>env/<br>__pycache__/</pre><p>We can then add our application files and commit our changes:</p><pre>$ git add .gitignore app.py requirements.txt Procfile<br>$ git commit -m &quot;Initialize Git repository&quot;</pre><p>By now, you should have a directory similar to <a href="https://github.com/rtkilian/sentiment-analyser-yelpcamp">mine</a>.</p><p>To deploy our API to Heroku, you will need to register for a free Heroku account and install the <a href="https://devcenter.heroku.com/articles/getting-started-with-python#set-up">Heroku CLI</a>. After this, you can log into the Heroku CLI using the terminal:</p><pre>$ heroku login</pre><p>We’re now going to link our code to the Heroku servers which can be achieved with a Git <a href="https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes">remote</a>. This is achieved by running the following command from the CLI which will create a Heroku application:</p><pre>$ heroku create</pre><p>Finally, we push our code to the Git remote repository that triggers the build process. After you run the below command, you’ll see the information about the deployment process and (hopefully) a success message once complete:</p><pre>$ git push heroku main</pre><p>You made it! The output will display the URL for your API (mine is <a href="https://sentiment-analyser-yelpcamp.herokuapp.com/">https://sentiment-analyser-yelpcamp.herokuapp.com/</a>). Alternatively, you can access the application through the Heroku dashboard here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxiNte2MwpvLkWuCJui9ag.png" /><figcaption>Image by author</figcaption></figure><p>To test that our API has been properly deployed, we can use Postman. Using the same review, we get the same response from our deployed API as when it was on our local machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*He73_4iodIAOSfG1kswabA.png" /><figcaption>Image by author</figcaption></figure><h3>(Bonus) Integrating the API with an existing web application</h3><p>Most of the time, you’ll have a specific use case for the APIs you build. You may want to call the API during some batch ETL processing jobs or demonstrate a prototype on <a href="https://streamlit.io/">Streamlit</a>. In my case, my goal is to classify the sentiment on campsite reviews on my website, <a href="https://github.com/rtkilian/YelpCamp">YelpCamp</a>.</p><p>YelpCamp is developed using NodeJS. Therefore, I use the <a href="https://github.com/axios/axios">Axios</a> library to call my API, passing on the review body and returning the sentiment score which is stored in <a href="https://www.mongodb.com/">MongoDB</a>. The code below demonstrates this process, however, the explanation is beyond the scope of this tutorial:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/163dac1aa816f3a7e4636372e5c9ed1d/href">https://medium.com/media/163dac1aa816f3a7e4636372e5c9ed1d/href</a></iframe><h3>Conclusion</h3><p>By following this tutorial you should now have an understanding of:</p><ul><li>Using spaCy and spaCyTextBlob to classify the sentiment of text</li><li>Developing a simple REST API with Flask and Flask-RESTful</li><li>Deploying your application to Heroku</li></ul><p>The models you develop no longer have to live in your local Jupyter Notebooks. Use this tutorial as a guide and start sharing your models with the world.</p><p>Do you have any questions? <a href="https://twitter.com/rtkilian"><strong>Tweet me</strong></a> or add me on <a href="https://www.linkedin.com/in/rtkilian/"><strong>LinkedIn</strong></a>.</p><p>You can find all the code used in this post on <a href="https://github.com/rtkilian/sentiment-analyser-yelpcamp"><strong>GitHub</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd9b8f9de6cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-i-deployed-a-sentiment-analyser-api-with-spacy-flask-and-heroku-bd9b8f9de6cf">How I Deployed a Sentiment Analyser API with spaCy, Flask and Heroku</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anonymise Sensitive Data in a Pandas DataFrame Column with hashlib]]></title>
            <link>https://medium.com/data-science/anonymise-sensitive-data-in-a-pandas-dataframe-column-with-hashlib-8e7ef397d91f?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7ef397d91f</guid>
            <category><![CDATA[anonymization]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[sensitive-data]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Wed, 01 Sep 2021 05:19:46 GMT</pubDate>
            <atom:updated>2021-09-01T05:19:46.283Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop sharing personally identifiable information in your DataFrames</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d44HOeIsnQCrj39q" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A common scenario encountered by Data Scientists is sharing data with others. But what should you do if that data contains personally identifiable information (PII) such as email addresses, customer IDs or phone numbers?</p><p>A simple solution is to remove these fields before sharing the data. However, your analysis may rely on having the PII data. For example, customer IDs in an e-commerce transactional dataset are necessary to know which customer bought which product.</p><p>Instead, you can anonymise the PII fields in your data using <strong>hashing</strong>.</p><h3>What is hashing?</h3><p>Hashing is a one-way process of transforming a string of plaintext characters into a unique string of fixed length. The hashing process has two important characteristics:</p><ol><li>It is very difficult to convert a hashed string into its original form</li><li>The same plaintext string will produce the same hashed output</li></ol><p>For these reasons, developers will store your hashed password in the website’s database.</p><h3>A simple example using hashlib</h3><p><a href="https://docs.python.org/3/library/hashlib.html">haslib</a> is a built-in module in Python that contains many popular hash algorithms. In our tutorial, we’re going to be using SHA-256 which is part of the <a href="https://en.wikipedia.org/wiki/SHA-2">SHA-2</a> (<strong>S</strong>ecure <strong>H</strong>ash <strong>A</strong>lgorithm 2) family of algorithms.</p><p>Before we can convert our string, in this example an email address, to a hashed value, we must first convert it into bytes using UTF-8 encoding:</p><pre>import hashlib</pre><pre># Encode our string using UTF-8 default <br>stringToHash = &#39;example@email.com&#39;.encode()</pre><p>We can now hash it using SHA-256:</p><pre># Hash using SHA-256 and print<br>print(&#39;Email (SHA-256): &#39;, hashlib.sha256(stringToHash).hexdigest())</pre><p>Output:</p><pre>Email (SHA-256): 36e96648c5410d00a7da7206c01237139f950bed21d8c729aae019dbe07964e7</pre><p>That’s it! Our fake email address has been successfully hashed.</p><h3>A complete example using pandas and hashlib</h3><p>Now that we can apply hashlib to a single string, it’s fairly straightforward to scale this example to a pandas DataFrame. We’re going to use credit card customer data, available on <a href="https://www.kaggle.com/sakshigoyal7/credit-card-customers">Kaggle</a>, which was originally made available by <a href="https://leaps.analyttica.com/">Analyttica TreasureHunt LEAPS</a>.</p><p><strong>Scenario:</strong> you need to share a list of credit card customers. You want to retain the field ‘CLIENTNUM’ as a customer can have multiple credit cards and you want to be able to uniquely identify them.</p><pre>import pandas as pd</pre><pre># Read only select columns using pandas<br>df = pd.read_csv(&#39;data/BankChurners.csv&#39;, usecols=[&#39;CLIENTNUM&#39;, &#39;Customer_Age&#39;, &#39;Gender&#39;, &#39;Attrition_Flag&#39;, &#39;Total_Trans_Amt&#39;])</pre><pre>df.head()</pre><figure><img alt="Sample data output" src="https://cdn-images-1.medium.com/max/1024/1*sHHLQOXmoqGfF3es2jc91A.png" /><figcaption>Image by author</figcaption></figure><p>After converting our ‘CLIENTNUM’ column to a string data type, we can then use pandas .apply() to hash all the strings in the column:</p><pre># Convert column to string<br>df[&#39;CLIENTNUM&#39;] = df[&#39;CLIENTNUM&#39;].astype(str)</pre><pre># Apply hashing function to the column<br>df[&#39;CLIENTNUM_HASH&#39;] = df[&#39;CLIENTNUM&#39;].apply(<br>    lambda x: <br>        hashlib.sha256(x.encode()).hexdigest()<br>)</pre><p>Good luck trying to crack our newly created column.</p><figure><img alt="Output of hashed pandas column" src="https://cdn-images-1.medium.com/max/1019/1*2u_qNZeiY2KGJPQpCiqkBw.png" /><figcaption>Image by author</figcaption></figure><h3>Conclusion</h3><p>After completing this tutorial you should have a basic understanding of what a hash algorithm is. We saw how to use <strong>hashlib</strong> to hash a single string and how this can be applied to a pandas DataFrame column to anonymise sensitive information.</p><p>Do you have any questions? <a href="https://twitter.com/rtkilian"><strong>Tweet me</strong></a> or add me on <a href="https://www.linkedin.com/in/rtkilian/"><strong>LinkedIn</strong></a>.</p><p>You can find all the code used in this post on <a href="https://github.com/rtkilian/data-science-blogging/blob/main/hashlib_pandas.ipynb"><strong>GitHub</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7ef397d91f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/anonymise-sensitive-data-in-a-pandas-dataframe-column-with-hashlib-8e7ef397d91f">Anonymise Sensitive Data in a Pandas DataFrame Column with hashlib</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy and share your sentiment analysis app using Streamlit Sharing]]></title>
            <link>https://medium.com/@rtkilian/deploy-and-share-your-sentiment-analysis-app-using-streamlit-sharing-2ba3ca6a3ead?source=rss-40e98576066e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ba3ca6a3ead</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Rhys Kilian]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 06:52:13 GMT</pubDate>
            <atom:updated>2021-08-15T07:25:33.362Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial on creating a sentiment analysis application in under 30-minutes.</h4><figure><img alt="Streamlit logo" src="https://cdn-images-1.medium.com/max/1024/1*srQdUu5yPUu6msmYr_-eQw.jpeg" /><figcaption>Source: <a href="https://streamlit.io/">Streamlit</a></figcaption></figure><p>Imagine this, you’ve spent the last two weeks developing a killer sentiment analysis model on your local machine. You’ve experimented with five different models, tuned your hyperparameters to perfection and tested the performance on a range of scenarios.</p><p>But now a non-technical Product Manager wants to review your model. What do you do?</p><p>You could run a live demo? Your calendars don’t line up for weeks.<br>You could share your virtual environment? They don’t know how to code.<br>You could get a developer to deploy the model? Their task list is two weeks long.</p><p>Unfortunately, this is a scenario that many Data Scientists find themselves in. <strong>But thanks to </strong><a href="https://streamlit.io/sharing"><strong>Streamlit Sharing</strong></a><strong> you can now deploy and share your model in less than 30-minutes without help from a developer.</strong></p><h3>The Goal of this Tutorial</h3><p>In this tutorial, I will show you how to deploy a <a href="https://en.wikipedia.org/wiki/Sentiment_analysis">sentiment analysis</a> model using Streamlit Sharing. A user will be able to enter their text and the model will classify it as ‘POSITIVE’ or ‘NEGATIVE’ sentiment, along with a confidence score.</p><p>To see a <strong>live demo</strong> of my application on Streamlit Sharing: <a href="https://share.streamlit.io/rtkilian/streamlit-huggingface/main/sentiment_analyser.py">click here</a>.<br>To view my <strong>source code</strong> on GitHub: <a href="https://github.com/rtkilian/streamlit-huggingface">click here</a>.</p><figure><img alt="A screenshot of the app you will develop in this tutorial" src="https://cdn-images-1.medium.com/max/1024/1*lUrhmga0ySFiEdPSvyR2Dw.png" /><figcaption>A screenshot of the app you will build in this tutorial</figcaption></figure><h3>Step 1: Installing Libraries</h3><p>The first step is to ensure you have all installed the required libraries.</p><h4>Streamlit</h4><p><a href="https://streamlit.io/">Streamlit</a> is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science.</p><p>To install:</p><pre>pip install streamlit</pre><p>You should also request an invitation for <a href="https://streamlit.io/sharing"><strong>Streamlit Sharing</strong></a><strong> </strong>which allows you to deploy, manage, and share your apps with the world, directly from Streamlit.</p><p>It may take up to 2-days to receive your invitation. However, I received my invitation within 24-hours, even after requesting it on the weekend.</p><h4>🤗 Transformers by Hugging Face</h4><p><a href="https://huggingface.co/transformers/">🤗 Transformers</a> provides general-purpose architectures (BERT, GPT-2, etc.) for Natural Language Understanding (NLU) and Natural Language Generation (NLG) with over 32+ pre-trained models in 100+ languages. In only a few lines of code, you can have a state of the art sentiment analysis model downloaded and ready to go.</p><p>First, you need to install one of, or both, TensorFlow 2.0 and PyTorch. Please refer to the <a href="https://www.tensorflow.org/install/pip#tensorflow-2.0-rc-is-available">TensorFlow installation page</a> and <a href="https://pytorch.org/get-started/locally/#start-locally">PyTorch installation page</a> regarding the specific install command for your platform.</p><p>When installed, run the following command:</p><pre>pip install transformers</pre><h3>Step 2: Project Set-Up</h3><p>All your code will need to be contained within a Python file (.py). I personally use Visual Studio Code that comes installed in Anaconda, however, you can also download your Jupyter Notebook as a .py file.</p><p>I’ve called my file <strong>sentiment_analyser.py</strong>.</p><p>Now, import the libraries you downloaded in Step 1:</p><pre>import streamlit as st<br>from transformers import pipeline</pre><p>In the same directory, create a text file called <strong>requirements.txt </strong>and copy the version of the libraries you installed in Step 1. When it comes time to deploy your app, Streamlit Sharing will install the libraries in this file.</p><pre>streamlit==0.86<br>transformers==4.8.1<br>torch==1.9.0</pre><p>At this point, you should also create a <strong>GitHub repo</strong>. If you’ve never used GitHub before, I recommend checking out their <a href="https://docs.github.com/en/get-started/quickstart/create-a-repo">documentation</a> to set up your first repo.</p><h3>Step 3: Create the User Interface Using Streamlit</h3><p>Finally, something fun! We will now start by creating the structure of your Streamlit web application.</p><p>First, let’s add a title and some descriptive text by adding the following code to your <strong>sentiment_analyser.py<em> </em></strong>file:</p><pre>st.title(&#39;Sentiment Analyser App&#39;)<br>st.write(&#39;Welcome to my sentiment analysis app!&#39;)</pre><p>To run your app locally (before we deploy it), navigate to your development directory in your terminal and run the following command:</p><pre>streamlit run sentiment_analyser.py</pre><p>If all goes to plan, you should have your Streamlit app popping up in a new browser window.</p><figure><img alt="First Streamlit application output" src="https://cdn-images-1.medium.com/max/1024/1*iGZ6t758PLMNb1a1AnzYiQ.png" /><figcaption>Your first Streamlit application</figcaption></figure><p>We will now build a simple form that contains a text area for user input and a submit button. Our ‘<em>user_input</em>’ variable will be passed into our sentiment analysis model in Step 4.</p><pre>form = st.form(key=&#39;sentiment-form&#39;)<br>user_input = form.text_area(&#39;Enter your text&#39;)<br>submit = form.form_submit_button(&#39;Submit&#39;)</pre><p>After refreshing your application, it should now look like this:</p><figure><img alt="Streamlit application with user input form" src="https://cdn-images-1.medium.com/max/1024/1*Wt7Q2RARUnFoDTeJw2AJXg.png" /><figcaption>Streamlit application with user input form</figcaption></figure><h3>Step 4: Classify User Input Using 🤗 Transformers</h3><p>Hugging Face has an <a href="https://huggingface.co/course/chapter1/3?fw=pt">excellent tutorial</a> on their 🤗 Transformer library. For this tutorial, we will be using the <strong>pipeline </strong>object that will connect the default sentiment analysis model with its necessary preprocessing and postprocessing steps.</p><p>If you were to run the following code in a Jupyter Notebook or .py file:</p><pre>classifier = pipeline(&quot;sentiment-analysis&quot;)<br>classifier(&quot;I&#39;ve been waiting for a HuggingFace course my whole life.&quot;)</pre><p>It would output the classified sentiment label (‘POSITIVE or ‘NEGATIVE’), along with a confidence score.</p><pre>[{&#39;label&#39;: &#39;POSITIVE&#39;, &#39;score&#39;: 0.9598047137260437}]</pre><h3>Step 5: Linking Streamlit and the Sentiment Analysis Model</h3><p>By now, you should see that we already have the basic building blocks of our application. To finish our app, let’s classify our ‘<em>user_input</em>’ variable using the 🤗 Transformer library to give our sentiment label and confidence score:</p><pre>classifier = pipeline(&quot;sentiment-analysis&quot;)    <br>result = classifier(user_input)[0]    <br>label = result[&#39;label&#39;]    <br>score = result[&#39;score&#39;]</pre><p>However, we only want to run out model after the user submitted the form. We can also display the result in a green banner (st.success) for ‘POSITIVE’ sentiment and in a red banner (st.error) for ‘NEGATIVE’ sentiment:</p><pre>if submit:<br>    classifier = pipeline(&quot;sentiment-analysis&quot;)<br>    result = classifier(user_input)[0]<br>    label = result[&#39;label&#39;]<br>    score = result[&#39;score&#39;]</pre><pre>if label == &#39;POSITIVE&#39;:<br>        st.success(f&#39;{label} sentiment (score: {score})&#39;)<br>    else:<br>        st.error(f&#39;{label} sentiment (score: {score})&#39;)</pre><p>Once complete, <strong>push your changes to your GitHub repo</strong>.</p><p>If you want to see all the code in my <strong>sentiment_analyser.py</strong> file, please check out my <a href="https://github.com/rtkilian/streamlit-huggingface/blob/main/sentiment_analyser.py">GitHub repo</a>.</p><h3>Step 6: Deploy Your App to Streamlit Sharing</h3><p>You should now have a functioning application on your local machine. But we want to be able to share our application just by sharing a single URL using Streamlit Sharing.</p><p>Once you have received your invitation to register for Streamlit Sharing, you can create a ‘New app’ on your <a href="https://share.streamlit.io/">app dashboard</a>. Enter your GitHub username/repo, the name of your branch and the name of the Python file that contains your code. It should look something like this:</p><figure><img alt="Streamlit sharing configuration" src="https://cdn-images-1.medium.com/max/1024/1*ptnB0Rv3nL7HIau17tyWRw.png" /><figcaption>Streamlit Sharing configuration</figcaption></figure><p>Once you hit ‘Deploy!’, Streamlit will look for your <strong>requirements.txt</strong> file in your repo and install all the required libraries. After it has finished installing, you should receive a message that your application has been deployed successfully and you should be provided with a URL. For example, you can find my app <a href="https://share.streamlit.io/rtkilian/streamlit-huggingface/main/sentiment_analyser.py">here</a>.</p><p>Congratulations! You have just deployed your sentiment analysis application that you can now share.</p><h3>Conclusion</h3><p>In this tutorial, I have shown you how you can build a simple interface using Streamlit to capture user input, classify the sentiment using Hugging Face’s 🤗 Transformer library, and deploy your application using Streamlit Sharing. We have only scratched the surface of what is possible using Streamlit (and Hugging Face). But now you should have the basic tools to share your prototypes with your colleagues, friends and family.</p><p>I encourage you to experiment. How can you make this app faster? What other NLP models can you deploy?</p><p>Share your apps with me on <a href="https://twitter.com/rtkilian"><strong>Twitter</strong></a><strong> </strong>or add me on <a href="https://www.linkedin.com/in/rtkilian/"><strong>LinkedIn</strong></a>. More than happy to answer any questions you may have!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ba3ca6a3ead" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>