<?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 Sam Mourad on Medium]]></title>
        <description><![CDATA[Stories by Sam Mourad on Medium]]></description>
        <link>https://medium.com/@vadoverde?source=rss-229e8aa5bbbe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*uaOJ-8YeVhHAX7sau5vWkA.png</url>
            <title>Stories by Sam Mourad on Medium</title>
            <link>https://medium.com/@vadoverde?source=rss-229e8aa5bbbe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:49:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vadoverde/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[to .apply or not to .apply…]]></title>
            <link>https://medium.com/analytics-vidhya/to-apply-or-not-to-apply-13271d10f892?source=rss-229e8aa5bbbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/13271d10f892</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[pandas-series]]></category>
            <category><![CDATA[vectorization]]></category>
            <dc:creator><![CDATA[Sam Mourad]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 19:03:48 GMT</pubDate>
            <atom:updated>2021-11-30T06:21:10.285Z</atom:updated>
            <content:encoded><![CDATA[<h3>to .apply or not to .apply…</h3><p><em>This post is in collaboration with </em><a href="https://medium.com/@jacobdodd94"><em>Jacob Dodd</em></a></p><blockquote>pandas sucks</blockquote><blockquote>if you don’t use it correctly</blockquote><blockquote>it’s a million bucks</blockquote><blockquote>worth more than a Bentley</blockquote><p>Not really, we love pandas.</p><p>In this post, we’ll show you how to speed up your pandas code for date-related calculation by more than 10,000 times!</p><h3>Intro</h3><p>And we’re not talking about <a href="https://nationalzoo.si.edu/animals/news/pandastory-bubble-bath-wrestling-match">these</a> pandas (adorable), but the <a href="https://pandas.pydata.org/">python library</a> we all data scientists out there use on a daily basis to do anything data-related.</p><p>Pandas look familiar to new users coming from many different backgrounds.</p><p>If you’re an Excel user, <a href="https://towardsdatascience.com/intro-to-pandas-for-excel-super-users-dac1b38f12b0">operations such as</a> finding the sum or the cumulative sum of all columns in an array can be done in pandas by calling the DataFrame.sum or DataFrame.cumsum methods.</p><pre>import pandas as pd<br>df = pd.DataFrame({&quot;a&quot;: [1,2,3], &quot;b&quot;: [4,5,6]})<br>print(df.sum())<br>print(df.cumsum())</pre><p>If you’re a SQL user, <a href="https://pandas.pydata.org/docs/getting_started/comparison/comparison_with_sql.html">operations like</a> select or join statements can be done by calling the DataFrame.query or DataFrame.merge methods.</p><pre>import pandas as pd<br>df = pd.DataFrame({&quot;a&quot;: [1,2,3], &quot;b&quot;: [4,5,6]})<br>bf = pd.DataFrame({&quot;a&quot;: [6,5,4], &quot;b&quot;: [3,2,1]})<br>print(df.query(&quot;a == 1&quot;))<br>print(df.merge(bf, how=&quot;inner&quot;, left_on=&#39;a&#39;, right_on=&#39;b&#39;))</pre><p>If you’re an R, Stata, SAS, SPSS, or other statistical language user, operations like finding the correlation, standard deviation, or even an exponential weighted function can be done by calling the DataFrame.corr, DataFrame.std, or DataFrame.ewm methods.</p><pre>import pandas as pd<br>df = pd.DataFrame({&quot;a&quot;: [1,2,3], &quot;b&quot;: [4,5,6]})<br>print(df.ewm(com=0.8))</pre><p>Last but not least, matrix multiplication can be done by using the DataFrame.dot method.</p><pre>import pandas as pd<br>df = pd.DataFrame({&quot;a&quot;: [1,2], &quot;b&quot;: [3,4]})<br>bf = pd.DataFrame({&quot;a&quot;: [5,6], &quot;b&quot;: [7,8]})<br>print(df.dot(bf.T))</pre><p>Or really any of <a href="https://numpy.org/doc/stable/reference/ufuncs.html">NumPy&#39;s universal functions</a> a.k.a <em>ufunc</em> can be used by pandas to make use of vectorized operations as much as <em>possible</em>.</p><p>Though you’re on a roll and you want to use pandas for everything.</p><h3>Such as date-time operations</h3><p>A common operation is calculating the interval between 2 dates, let’s say in years. First, let&#39;s create a simple function and some global variables:</p><pre>import pandas as pd<br>from datetime import date, timedelta</pre><pre>def calc_age_function(start_date: date, end_date: date):<br>		&quot;&quot;&quot;Calculate difference between 2 dates in years.&quot;&quot;&quot;<br>		return (end_date - start_date)/timedelta(days=365.25)</pre><p>And now let’s define some example dates and calculate the age between them:</p><pre>[In]:<br>start = date(<br>    year=1930,<br>    day=10,<br>    month=5<br>)<br>end = date(<br>    year=2020,<br>    day=10,<br>    month=8<br>)<br>print(calc_age_function(start, end))</pre><pre>[Out]: 90.2532511978097</pre><p>In practice though, it&#39;s likely you have a list of more than one date that needs this operation done. Let&#39;s create a series with the number of examples listed above to use for timing, as well as a DataFrame:</p><pre>from datetime import datetime, timedelta<br>from random import randint, seed</pre><pre>import pandas as pd</pre><pre>seed(42)<br>N_SAMPLES = 1_000_000<br>start_date_list = [<br>	datetime.fromisoformat(&quot;2019-01-01&quot;) + timedelta(days=randint(0,365))<br>	for _ in range(N_SAMPLES )<br>]<br>end_date_list = [<br>	datetime.fromisoformat(&quot;2020-01-01&quot;) + timedelta(days=randint(0,365))<br>	for _ in range(N_SAMPLES )<br>]<br>start_dates = pd.Series(start_date_list, name=&quot;start&quot;, dtype=&quot;datetime64[ns]&quot;)<br>end_dates = pd.Series(end_date_list, name=&quot;end&quot;, dtype=&quot;datetime64[ns]&quot;)</pre><pre>age_df = pd.DataFrame(<br>  {<br>    &quot;start_date&quot;:start_dates,<br>    &quot;end_date&quot;: end_dates<br>	}<br>)</pre><p>Now let&#39;s calculate the age using our function on the columns in the DataFrame using apply with a lambda function (not best)</p><pre>%%timeit<br># slow, for loop apply<br>age_df[&quot;age&quot;] = age_df.apply(<br>	lambda x: calc_age_function(x[&quot;start_date&quot;], x[&quot;end_date&quot;]),<br>	axis=1,<br>)</pre><pre>20.6 s ± 63.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</pre><p>As a python newbie, <em>apply</em> might be an easy thing to use. All you need to remember is an <em>apply</em> method and how to write a python function.</p><p>This works, though is not fast enough for us.</p><p>With pandas we can use arithmetic operations on Series objects which are significantly faster than for loops (usually what apply does, with exceptions which we’ll get to later).</p><p>What if we passed the series through our function instead?</p><pre>%%timeit<br># with date series, vectorized<br>ages = calc_age_function(start_dates, end_dates)</pre><pre>10.3 ms ± 104 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)</pre><p>Running the calculation directly on the series made this operation <strong>2,000x</strong> faster!</p><p>But can we make it even faster?</p><p>In the code snippets above we’re using pandas date-time operations to get the number of days between two dates and divide it by a timedelta object representing the number of days in a year.</p><p>What if we try the same calculation using integer operations by representing the start and end dates as <a href="https://en.wikipedia.org/wiki/Epoch_(computing)">epoch</a> integers rather than DateTime objects?</p><pre>%%timeit<br>SECONDS_TO_YEARS = 60*60*24*365.25*1_000_000_000<br>(end_dates.astype(int) - start_dates.astype(int))/SECONDS_TO_YEARS</pre><pre>2.22 ms ± 32.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)</pre><p>Did that make our calculation <strong>10,000x</strong> times faster than apply?</p><p>You bet it did!</p><h3>Stress testing</h3><p>Using sample sizes: 100, 1,000, 10,000, 100,000, 500,000, 1,000,000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*eOkgsOm7o52b3GcVwyDQxQ.png" /><figcaption>apply vs vectorized datetime64[ns] vs vectorized epoch operations</figcaption></figure><p>What is (and isn’t surprising) is how linear is the performance of the apply method relative to the data size, which appears to be O(n) in the graph above. Also, it&#39;s on a much higher scale than the datetime64[ns] and epoch vectorized calculations. We can’t really compare the performance of all three calculations. Let’s zoom into the datetime64[ns] and epoch (vectorized) calculations here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*rZKt4b2aUor_uMtwsIshug.png" /><figcaption>vectorized datetime64[ns] vs vectorized epoch operations</figcaption></figure><p>The Benefits of using epochs really kick in at 100k samples or so, as the datetime64[ns] performance is O(log n) while the epoch calculation is <em>almost</em> O(1).</p><h3>Note on Series instantiation with DateTime dtype</h3><pre>%%timeit<br># format series WITHOUT numpy dates<br>start_dates = pd.Series([start]*N_SAMPLES, name=&quot;start&quot;)<br>end_dates = pd.Series([end]*N_SAMPLES, name=&quot;end&quot;)</pre><pre>1.59 s ± 6.91 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</pre><p>With specifying Numpy datetime64:</p><pre>%%timeit<br># format series WITH numpy datetime<br>start_dates = pd.Series([start]*N_SAMPLES, name=&quot;start&quot;, dtype=&quot;datetime64[ns]&quot;)<br>end_dates = pd.Series([end]*N_SAMPLES, name=&quot;end&quot;, dtype=&quot;datetime64[ns]&quot;)</pre><pre>1.73 s ± 4.04 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</pre><p>Difference of 140 ms, but these costs are especially worth it if you are going to be doing more than one operation with these columns.</p><p>You can also use pandas’ built-in to_datetime function if you prefer, with similar performance:</p><pre>%%timeit<br># format series WITH pandas datetime<br>start_dates = pd.to_datetime(pd.Series([start]*N_SAMPLES, name=&quot;start&quot;))<br>end_dates = pd.to_datetime(pd.Series([end]*N_SAMPLES, name=&quot;end&quot;))</pre><pre>1.76 s ± 4.57 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</pre><h3>Conclusion</h3><ol><li>Running arithmetic operations on pandas series (or dataframes) makes use of vectorization when available in pandas, and is significantly faster than a row-wise apply of that same operation</li><li>Using pandas native dtypes (in this case datetime64[ns]) could make your operations go significantly faster</li><li>Arithmetic operations on epoch date-time are less expensive than DateTime objects</li><li>This is true for the case of 1,000,000 data points. The gains do not scale linearly with the number of data points so don’t expect them to do so. The performance gains of pandas’ vectorized operations start at 10,000 points as pointed by Travis Oliphant in <a href="https://www.youtube.com/watch?v=gFEE3w7F0ww&amp;ab_channel=LexFridman">this podcast</a> with Lex Friedman</li><li>Pandas gains are not limited by its performance. The ease of use for data pipelines is a tremendous plus for using pandas. If performance is not highly important for your production processes, using pandas at any capacity would save you days or weeks of development of your data pipelines, analysis, or manipulation</li></ol><h3>What’s next</h3><p>Look out for our next pandas’ blog post. We’ll be looking deeper into NumPy&#39;s <em>ufunc</em> and analyzing Andrej Karpathy&#39;s <a href="https://twitter.com/karpathy/status/1430316576016793600?ref_src=twsrc%5Etfw%7Ctwcamp%5Etweetembed&amp;ref_url=https%3A%2F%2Fwww.notion.so%2Fprestonventures%2FProjects-54ba0256df63447cbc9f7de5821da879%3Fp%3D0fc8f1ed6b1b41d0ad22ae229529ad3a">infamous tweet</a> about NumPy&#39;s <em>sqrt</em> function!</p><h3>Andrej Karpathy on Twitter: &quot;TIL 😳😵‍💫😱. This single line change sped up our data loader 10% pic.twitter.com/9gIzscrgTQ / Twitter&quot;</h3><p>TIL 😳😵‍💫😱. This single line change sped up our data loader 10% pic.twitter.com/9gIzscrgTQ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13271d10f892" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/to-apply-or-not-to-apply-13271d10f892">to .apply or not to .apply…</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Brief History of Forecasting in the Food Industry]]></title>
            <link>https://medium.com/@vadoverde/a-brief-history-of-forecasting-in-the-food-industry-26b8c8f50bb2?source=rss-229e8aa5bbbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/26b8c8f50bb2</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sam Mourad]]></dc:creator>
            <pubDate>Sun, 08 Dec 2019 22:13:47 GMT</pubDate>
            <atom:updated>2019-12-08T22:13:47.189Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was originally published on </em><a href="https://www.gocrisp.com/blog/forecasting-history-food-supply-chain"><em>Crisp’s blog</em></a><em> on Nov 7, 2019</em></p><p>Forecasting in the food industry still faces many of the same challenges it faced half a century ago, including the following:</p><ul><li>Forecasts are often made with insufficient consideration of external factors, such as campaigns and promotions, moving holidays, weather, and other events. These factors are often either stored in separate, siloed systems or not collected at all.</li><li>Algorithms currently in use present high uncertainty for long-term forecasts, as well as slow reaction to change.</li><li>The existence of an abundance of forecasting techniques that are suitable for specific demand patterns, thus requiring high domain expertise.</li><li>The realities of traditional forecasting algorithms, such as inherent deficiencies where long daily or weekly time series are concerned.</li><li>Scattered data sources and <em>ad hoc</em> solutions, with an overall lack of data centralization</li><li>A general lack of capabilities to consider and account for retailer data when generating forecasts.</li></ul><p>We believe the solution is to bridge the data gap across the supply chain by 1.) centralizing all data sources in one platform, and 2.) applying cutting-edge machine learning algorithms that can account for a wide range of external factors. This will then allow for accurate forecasts and more informed decision-making, thus leading to reduced waste throughout the supply chain.</p><p>To dissect the problem — and thus understand the solution — let’s delve into the history of forecasting in the food supply chain.</p><h3>Forecasting in the Food Supply Chain</h3><blockquote><strong><em>FACT:</em></strong><em> </em><strong>Forecasting is a century-old field of study, which makes it one of the oldest areas of predictive analytics.</strong></blockquote><p><strong>Where We Began:</strong> The concept of “<a href="https://www.encyclopediaofmath.org/index.php/Yule,_George_Udny">stochasticity in time series</a>” was introduced by the Scottish statistician Udny Yule in the late nineteenth century: put succinctly, he postulated that every time series can be regarded as the realization of a stochastic — or random — process. This one simple idea led to the development of autoregressive and moving average models, which are still being used in many forecasting models today.</p><h3>Forecasting Techniques Through the Decades</h3><p><strong>Fast-forward about half a century:</strong> academic journals began publishing regularly about statistical approaches to forecasting since the late 1950s, and the first companies to integrate forecasting in their processes reported increased economic gains. Quantitative forecasting methods have been used in multiple industries since the 1960s, leading the Harvard Business Review to publish a <a href="https://hbr.org/1971/07/how-to-choose-the-right-forecasting-technique">guide for selecting among forecasting techniques</a> in 1971.</p><p>Another of the most popular forecasting techniques, <a href="https://www.vividcortex.com/blog/exponential-smoothing-for-time-series-forecasting">exponential smoothing</a> (a more advanced variant of this being the <a href="https://www.sciencedirect.com/science/article/abs/pii/S0360544216305357">Holt-Winters method</a>), originated in the 1960s and was developed further until the 1980s. In the midst of this, the <a href="https://machinelearningmastery.com/gentle-introduction-box-jenkins-method-time-series-forecasting/">Box-Jenkins methodology</a> for time-series estimation was developed in mid-1970, which then led to the development of the associated computerized version — <a href="https://towardsdatascience.com/time-series-forecasting-arima-models-7f221e9eee06">ARIMA or Auto-Regressive Integrated Moving Average</a> — after the advent of adequate computer technology.</p><h3>Food Supply Chain Forecasting Challenges: 2000 and Beyond</h3><p>The early 2000s wrought significant advances that include the development and publishing of state-space approaches to the same forecasting models. However, while these methodologies are coherent and fairly versatile, they still face challenges related to forecasting accuracy, given high-frequency time series with multiple seasonalities with high correlation to external factors. Furthermore, over the past decade, the artificial intelligence (AI) community has compiled a wealth of knowledge and undergone significant development, neither of which the industry has thus far put to good use.</p><p>As early as 2001, multiple research papers reported performance gains by using <a href="https://www.analyticsvidhya.com/blog/2017/12/fundamentals-of-deep-learning-introduction-to-lstm/">Long-Short Term Memory</a> <a href="https://www.analyticsvidhya.com/blog/2017/12/fundamentals-of-deep-learning-introduction-to-lstm/">Networks</a>, and in 2013, <a href="https://towardsdatascience.com/recurrent-neural-networks-d4642c9bc7ce">Recurrent Neural Networks</a> were proven useful for generating sequences (such as time-series). Since then, multiple deep-learning approaches have been tested and demonstrated to be helpful for time-series, including probabilistic forecasting with autoregressive recurrent networks, the basis of the <a href="https://aws.amazon.com/blogs/machine-learning/creating-neural-time-series-models-with-gluon-time-series/">recently announced Amazon forecast.</a></p><p>We developed the Crisp forecasting technology because we believed there was still a large gap to fill — a gap that is in large part represented by existing tools’ difficulty in dealing with the following complexities:</p><ul><li>Drifting holidays</li><li>Multiple coinciding seasonalities</li><li>Non-periodic change-points such as irregularly high demand before an expected winter storm</li><li>Effects of a wide range of external variables such as promotion variables and number and size of customers</li><li>A lack of centralized data, which makes it impossible to reap the benefits of cutting-edge AI and machine learning algorithms</li><li>Existing tools’ inability to account for user feedback and improve forecasting models’ performance over time</li></ul><p>Here is an example forecast for one of our clients’ products that highlights the above points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RJe-2ItT7rYWeUw4.png" /></figure><p>Working with daily time series requires complex seasonalities; in this case, yearly and weekly are shown, as are the sales patterns for each day of the year.</p><p>Points to note:</p><ul><li>The upward trend in December, modeled in the annual seasonality component</li><li>The demand spikes before Christmas 2018 and Easter 2019 were both accurately predicted, even though:</li><li>Christmas 2018 spike is 20% lower than Christmas 2017.</li><li>Easter is a drifting holiday.</li><li>A slight demand increase in February 2019 related to another local holiday was accurately predicted because of the aforementioned seasonalities, in addition to campaigns. In this case, the conclusion of one of the campaigns provided a signal to the model that demand would be slightly lower, which is also demonstrated on the graph.</li></ul><blockquote><strong>For reference: </strong><a href="https://robjhyndman.com/hyndsight/dailydata/">Here is a blog post</a> by Professor Rob Hyndman, a pioneer in the area of forecasting, that explains the <a href="https://robjhyndman.com/hyndsight/dailydata/">difficulties traditional models have in forecasting such complexities</a>.</blockquote><p>Why is the history so important? Put simply: as with most other pursuits when generating solutions to complex problems, context is key! A thorough investigation of the industry — past and present — led to our belief that there <strong><em>had</em></strong> to be a better solution for forecasting. Modeling numerous complex, shifting components to generate accurate forecasts is challenging (to say the least) when using traditional forecasting techniques, but with <a href="https://www.gocrisp.com/crisp-video">Crisp’s forecasting solution</a>, they are done — and done <em>reliably</em> — in the blink of an eye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26b8c8f50bb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prophet vs DeepAR: Forecasting Food Demand]]></title>
            <link>https://medium.com/data-science/prophet-vs-deepar-forecasting-food-demand-2fdebfb8d282?source=rss-229e8aa5bbbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fdebfb8d282</guid>
            <category><![CDATA[ar-deep]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[facebook-prophet]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Sam Mourad]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 18:06:17 GMT</pubDate>
            <atom:updated>2020-09-01T21:23:34.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*JvoN0h70JwphhXekRdzvCQ.png" /></figure><p><em>In collaboration with </em><a href="https://medium.com/u/d3aeda500a4a"><em>Christian Aalby Svalesen</em></a></p><p>The global food industry faces significant sustainability challenges, and the UN estimates that “approximately <a href="https://www.researchgate.net/publication/267919405_Global_Food_Losses_and_Food_Waste">one-third of the global food</a> production is wasted or lost annually”. About<em> </em><a href="https://www.ers.usda.gov/webdocs/publications/43833/43680_eib121.pdf">66% of the losses</a> are in food groups where freshness is an important criterion for consumption. In addition, spoilage often occurs due to over-ordering and overstocking, which in most cases is a result of forecasting difficulties. The problem is amplified as one moves upstream in the supply chain and away from consumer purchasing behavior, a phenomenon known as the <a href="https://hbr.org/product/bullwhip-effect-in-supply-chains/SMR029-PDF-ENG">bullwhip effect</a>, which results in higher inaccuracies and exacerbates the waste problem.</p><p>Until now, most if not all, forecasting solutions in the market have been based on traditional decades-old methodologies such as ARIMA and Exponential Smoothing. While these methodologies generate stable forecasts, they have difficulties forecasting quick changes in time-series, especially when these changes are due to multiple seasonalities or moving holidays.</p><p>However, with the advance of machine learning, several techniques were developed in the last few years that made addressing these challenges easier.</p><p><a href="https://www.gocrisp.com/">Crisp</a> is offering a comprehensive and fully automatic forecasting solution to the food industry by combining cutting-edge machine learning techniques along with a novel methodology to model economic losses and freshness of inventory.</p><p>In this post, we are examining two forecasting models: Facebook Prophet and Amazon forecast’s DeepAR. We found these to be promising as Amazon research claimed DeepAR resulted in forecasting improvements of around 15% compared to the current state-of-the-art methods, while Prophet allows for a quick and tremendously flexible modeling experience.</p><p><strong>Facebook Prophet</strong></p><p>The <a href="https://peerj.com/preprints/3190.pdf">Facebook Prophet</a> model is a combination of multiple functions such as trend, multiple seasonalities, holidays, and user injected regressors estimated with LOESS. It is therefore conceptually similar to a <a href="https://projecteuclid.org/download/pdf_1/euclid.ss/1177013604">Generalized Additive Model</a>.</p><p>Here is the general formula for Prophet showing all different components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ghTHwruT5QxQ_g_2rvu-3w.png" /></figure><p><em>Trend:</em></p><p>The trend component can be a linear or logistic function of time. To model non-periodic changes in the trend, the term <em>a(t)^T</em>, namely <em>changepoints</em>, was introduced into the equation to allow for changes in the growth factor. The logistic function introduces the term <em>C(t)</em> to prevent infinite growth or negative growth in the trend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*X0Zo0_QK7Ac-87HKM6xZFQ.png" /></figure><p><em>Seasonality:</em></p><p>Multiple seasonalities can be modeled with Fourier series with a smoothing prior and a low-pass filter. In Prophet, this is represented by the formula below. The higher the number of terms (N) is, the higher the risk of overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUfM9AEGR95QrpvigN-zKw.png" /></figure><p><em>Holidays and Events:</em></p><p>Holidays are modeled as independent dummy external regressors allowing the inclusion of a window of days around the holidays to model their effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*CsX11dyaINMjcc1LxRg4dw.png" /></figure><p>The priors for all model components’ parameters are drawn from a normal distribution with hyper-parameterized standard deviation to allow for its flexibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*-AOHHOfP_1QxK-50.png" /></figure><p>Pros</p><ul><li>Ability to easily model any number of seasonalities</li><li>Ability to work with missing dates in time-series</li><li>Easily integrates holidays in the model</li><li>Built-in uncertainty modeling with full Bayesian sampling allows for model transparency</li><li>Allowing flexible step-wise linear or logistic trend modeling with user-specified change points</li></ul><p>Cons</p><ul><li>Can be volatile with a low number of observations</li><li>Long-horizon forecasting can be volatile with automatic changepoint selection</li></ul><p><strong>Amazon’s DeepAR</strong></p><p>The <a href="https://arxiv.org/pdf/1704.04110.pdf">DeepAR Algorithm</a> (or the evolved version, DeepAR+, referred to as DeepAR in this article for simplicity) developed by Amazon Research tailors a similar LSTM-based recurrent neural network architecture to the probabilistic forecasting problem. <a href="https://arxiv.org/pdf/1308.0850.pdf">Long Short-Term Memory (LSTM)</a> is known for its ability to learn dependencies between items in a sequence, which makes it suitable for a time-series forecasting problem. It implements a series of gates in which information is either passed on or forgotten. Instead of just passing on a hidden state <em>h</em>, it also passes on a long term state <em>c</em>. This allows it to learn both short and long term time-series patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*9xUS6MMxz3hCz2f7.png" /></figure><p>The <a href="https://arxiv.org/pdf/1704.04110.pdf">DeepAR </a>model implements such LSTM cells in an architecture that allows for simultaneous training of many related time-series and implements an encoder-decoder setup common in sequence-to-sequence models. This entails first training an encoder network on the whole conditioning data range, then outputting an initial state <em>h</em>. This state is then used to transfer information about the conditioning range to the prediction range through a decoder network. In the DeepAR model, the encoder and decoder networks have the same architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*uhDxGJ1oxZMk_lkV" /></figure><p>The DeepAR model also takes a set of covariates <em>X</em>, which are time series related to the target time series. In addition, a single categorical variable is supplied to the model which is used as information on the groupings of related time series. The models train an embedding vector that learns the common properties of all the time series in the group. Another feature of the model is that DeepAR automatically creates additional feature time series depending on the granularity of the target time series. These can, for instance, be time-series created for “day of the month” or “day of the year”, and allow the model to learn time-dependent patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*olFNgRtA6LzeTW6k.png" /></figure><p>The DeepAR interface expects a <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/deepar_hyperparameters.html">fair number of hyperparameters to be set</a>, including the context length for training, number of epochs, dropout rate, and learning rate among others.</p><p><strong>Pros and Cons</strong></p><p>DeepAR has the advantage of training several hundred or thousands of time-series simultaneously, potentially offering significant model scalability. It also has the following technical benefits:</p><ul><li>Minimal Feature Engineering: The model requires minimal feature engineering, as it learns seasonal behaviour on given covariates across time series.</li><li>Monte Carlo Sampling: It is also possible to compute consistent quantile estimates for the sub-ranges of the function, as DeepAR implements Monte Carlo sampling. This could, for instance, be useful when deciding on safety stock.</li><li>Built-in item supersession: It can predict on items with little history items by learning from similar items</li><li>Variety of likelihood functions: DeepAR does not assume Gaussian noise, and likelihood functions can be adapted to the statistical properties of the data allowing for data flexibility.</li></ul><h3>Model Evaluation</h3><p>Common practice in data science is to use <a href="https://otexts.com/fpp3/accuracy.html">statistical measures </a>to facilitate model selection and tuning towards attaining desirable model prediction accuracies. However, these measures fail to capture the actual business impacts of forecasting errors. We developed a custom measure that quantified these errors, differentiating between errors due to over-forecasting and under-forecasting. Our approach to developing the evaluation will be explained in a future article, but the measure allows us to evaluate the two models on whether they caught daily trends when this was important (e.g. fresh products) or performed more towards average accuracies the suitable products for this (e.g. dried food).</p><p>For model comparison, we used the time-series for 1000 food retail products that ranged anywhere between 3 months and 3 years of data. In the case of DeepAR, the data included the Holidays data as well as product grouping by retail product category. We set the number of epochs to 500, a context length and a prediction length of 90 days while leaving the default values for all other hyperparameters. In the case of Prophet, a model was trained for each time-series on its own including Holidays. The hyperparameters used tuned on the most popular food item and included multiplicative weekly seasonality, additive annual seasonality, and a high variance for the prior distribution of both seasonalities.</p><p>Using an expanded window cross-validation methodology with a 7-days horizon and a moving origin of 12 origins and 7-days step size, the MAPE of almost the majority of products was significantly higher for DeepAR than Prophet. However, this is not a stable metric especially that several of the products had zero or near-zero entries, so we visually investigated the time-plots to compare both forecasts. Our custom metric also revealed that the forecasting errors from DeepAR would cause somewhat higher business costs than those of Prophet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*Ac_GC0jONI94H7Om00FEbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*cEeR8In42yVqc_Hsrq2aAA.png" /></figure><ul><li><em>Total losses with a Prophet forecast: 890,013.29 units</em></li><li><em>Total losses with a DeepAR forecast: 1,502,708.56 units</em></li><li><em>Prophet losses are 41% better than DeepAR.</em></li></ul><p>Below are two time-plots comparing the actual and forecast signals for the product DeepAR predicted at its best performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*8VTXTcrtCNMj1xmUz4WJpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*EdYd6F_z462Nw3vVGyGXeQ.png" /></figure><p>On visual analysis of the results, it is clear that DeepAR had problems picking up the intensity of a few highs and lows while missing some of the drops in the signal. Prophet was generally more flexible, had a better performance, and was able to match the magnitude of the variation in the actual demand. A possible explanation for the performance of DeepAR might be the need for better groupings. The category groupings included products with very different demand characteristics, and the model might, therefore, benefit from groupings where product demand is analytically inferred rather than set by retail category (e.g. dairy). Although beyond the scope of our current investigation, future experiments should examine whether the performance of DeepAR improves with grouping products by clustering methods or spectral analysis.</p><p>We conclude that Prophet wins in this forecasting exercise for the following reasons:</p><ul><li>Better forecasting performance with the food demand patterns</li><li>The flexibility of the model and ease of setup</li><li>No need for a large number of products to reach a good performance</li><li>No need for product grouping</li><li>Allows deployment to any cloud platform</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fdebfb8d282" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/prophet-vs-deepar-forecasting-food-demand-2fdebfb8d282">Prophet vs DeepAR: Forecasting Food Demand</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>
    </channel>
</rss>