<?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 Manu Joseph on Medium]]></title>
        <description><![CDATA[Stories by Manu Joseph on Medium]]></description>
        <link>https://medium.com/@manujosephv?source=rss-c8dcc7fb5ce5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*eVvYVSkqyFwiuwJGfpCduw.png</url>
            <title>Stories by Manu Joseph on Medium</title>
            <link>https://medium.com/@manujosephv?source=rss-c8dcc7fb5ce5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:12:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manujosephv/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[Mixture Density Networks: Probabilistic Regression for Uncertainty Estimation]]></title>
            <link>https://medium.com/data-science/mixture-density-networks-probabilistic-regression-for-uncertainty-estimation-5f7250207431?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f7250207431</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch-tabular]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 00:55:59 GMT</pubDate>
            <atom:updated>2021-06-08T01:44:29.123Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Uncertainty </strong>is all around us. It is present in every decision we make, every action we take. And this is especially true in business decisions where we plan for the future. But in spite of that, all of our predictive models that we use in business ignore uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YPD0cyp6tiJ8fv7_" /><figcaption>Photo by <a href="https://unsplash.com/@ingle_jake?utm_source=medium&amp;utm_medium=referral">Jake Ingle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Suppose you are the manager of the Google Play Store and Google Pixel 5a launch is coming up. HQ sends you a forecast from their ML model and says that they expect 100 units to be sold in the first week of launch. But you know, from you experience, that the HQ predictions are not always right and want to hedge against a stock out by procuring more than 100. <em>But how much more?</em> How do you know how wrong the prediction from the ML model will be? In other words, how <strong>confident</strong> this prediction of a 100 units is? This additional information of the confidence of the model is crucial in making this decision and the ML model from HQ does not give you that. But what if in addition to this forecast of 100 units, the model also gives you <strong>a measure of uncertainty</strong> — like the standard deviation of the expected probability distribution? Now you can make an informed decision based on your risk appetite on how much to over-stock.</p><p>But how do we do that? Usually, classification problems have an added advantage because of the logistic function we slap on at the top which gives us some idea about the confidence of the model(although it is not technically the same thing). When it comes to regression, our traditional models give us a point estimate.</p><h3>Types of Uncertainty</h3><p>There are two major kinds of uncertainty — Epistemic and Aleatoric Uncertainty (phew, that was quite a mouthful).</p><ul><li>Epistemic Uncertainty describes what the model doesn’t know. It is attributed to inadequate knowledge of the model. This is the uncertainty which can be reduced by having more data or increasing the model complexity.</li><li>Aleatoric Uncertainty is the inherent uncertainty which is part of the data generating process. For example, a paper plane which is launched by high precision equipment, which maintains the same degree of release, speed of release and a thousand other parameters will still not fall in the same place each trial. This inherent variability is Aleatoric Uncertainty.</li></ul><p>A typical supervised machine learning problem can be written as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/0*vjLqABSCMJ9HbU7f" /></figure><p>Here the epistemic uncertainty is derived from θ and the aleatoric from <strong>x</strong>. Typically high epistemic uncertainty is found in the part of the feature space which is sparsely populated with data examples. In such an n-dimensional space, there might be many parameters which can explain the given data points and this leads to uncertainty.</p><h3>The Core Idea</h3><p>The key innovation here is like this:</p><p>In a vanilla Neural Network regression, we will have a single neuron at the last layer which is trained to predict the value that we are interested in. What if we predict the<strong> parameters of a probability distribution</strong> instead? For example, a Gaussian distribution is parametrized by its mean( μ) and its standard deviation(σ). So instead of having a single neuron in the last layer, we have two which predicts the mean and the standard deviation of the Gaussian Distribution.</p><p>Awesome! When properly trained, we have the <strong>mean and the standard deviation,</strong> which means we have the entire probability distribution and therefore by extension as <strong>estimate of the uncertainty</strong>.</p><p>But, there is a problem. When we train the model to predict the parameters of the distribution, we are slapping on a huge inductive bias onto the model. for all we know, the target variable that we are trying to model might not even follow any parametric distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*X8NcCs8yMvsEJ3Aw.png" /><figcaption>A Bimodal Distribution (Source: <a href="https://en.wikipedia.org/wiki/Multimodal_distribution">Wiki</a>)</figcaption></figure><p>Let’s look at the bimodal example. It looks like there are two gaussian distributions, squished together. And if we do a though experiment, and extend this “ <em>squishing of two gaussian distributions</em>” to “ <em>squishing of N gaussian distributions</em> “, this resultant mixture can model a wide variety of probability distributions. This is exactly the code idea of a Mixture Density network is. You have a number of gaussian components(mean and standard deviation) which comprises the last layer in the network. And have another learned parameter(a latent representation) which decides how to mix these gaussian components.</p><h3>Mixture Density Networks</h3><p>Mixture Density Networks are built from two components — a Neural Network and a Mixture Model.</p><p>The Neural Network can be any valid architecture which takes in the input <strong>X </strong>and converts into a set of learned features(we can think of it as an encoder or backbone).</p><p>Now, let’s take a look at the Mixture Model. The Mixture Model, like we discussed before, is a model of probability distributions built up with a weighted sum of more simple distributions. More formally, it models a probability density function( <em>pdf</em>) <em>p(x) </em>as a mixture of <em>m</em> pdfs indexed by <em>j pⱼ(x)</em>, with weights</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*CocwelWbmp9u0uX5" /></figure><p>by the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/0*wkUs0iBZzivZqDd1" /></figure><p>, where θⱼ are the parameters of the distribution describing the shape and location of the distribution.</p><p>In his paper[1], Bishop uses the Gaussian kernel and explains that any probability density function can be approximated to arbitrary accuracy, provided the mixing coefficients and the Gaussian parameters are correctly chosen. By using the Gaussian kernel in the above equation. it becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*d9tkx7kaaa2DNY-n" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*RBP5p9MrEgdDufh2.png" /><figcaption>Mixture Density Network: The output of a neural network parametrizes a Gaussian mixture model. <a href="https://www.researchgate.net/publication/325194613_Probabilistic_Forecasting_of_Household_Electrical_Load_Using_Artificial_Neural_Networks">Source[2]</a></figcaption></figure><h3>Sufficient Conditions</h3><p>Bishop proposed a few restrictions and ways to implement the MDNs as well.</p><ol><li>The mixing coefficients ( π or α) are probabilities and have to be less than zero and sum to unity. This can be easily achieved by passing the outputs of the mixing coefficients through a <em>Softmax</em> layer.</li><li>The variance (σ) should be strictly positive. Bishop[1] suggested that we use the exponential function to the raw logits of the sigma neuron. He suggested that this had the same effect as assuming an uninformative prior and avoids the pathological configurations in which one or more of the variances goes to zero.</li><li>The center parameters (μ) represent location parameters and this should be the raw logits of the mean neuron.</li></ol><h3>Loss Function</h3><p>The network is trained end-to-end using standard backpropagation. And for that the loss function we are minimizing is the Negative Log Likelihood, which is equivalent to the Maximum Likelihood Estimation.</p><p>We already know what <em>P(x) </em>is and it’s just the matter of calculating it and minimizing the negative log-likelihood.</p><h3>Implementation &amp; Tricks to Ensure Stability</h3><p>Now that we know the theory behind the model, let’s look at how we can implement it(and a few tricks and failure modes). Implementing and training an MDN is notoriously hard because there are just a lot of things that could go wrong. But through adopting prior research and a lot of experimentation, I have fixed on a few tricks which makes the training relatively stable. The implementation will be in PyTorch using a library that I developed — <a href="https://deep-and-shallow.com/2021/01/27/pytorch-tabular-a-framework-for-deep-learning-for-tabular-data/">Pytorch Tabular</a>(which is a highly flexible framework to work with deep learning and tabular data).</p><h3>Avoiding Numerical Underflow</h3><p>If you remember the <em>pdf</em> formula for the Gaussian mixture, it involves the summation of all the <em>pdf</em> ‘s weighted by the mixing coefficients. So the Negative Log-Likelihood would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*WlAYhW_Mv83LKySu" /></figure><p>and we know that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/0*QOycUeUWlG_kZwG4" /></figure><p>If you examine the equation, we see an exponential function which is then multiplied with the mixing coefficients and then take the log of it. This exponential and the subsequent log can lead to very small numbers leading to numerical underflow. So we as suggested by Axel Brando Guillaumes [3] use the <a href="https://en.wikipedia.org/wiki/LogSumExp">LogsumExp</a> trick and carry out the calculations in log domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*9XCGkOAL7IhdtuXB" /></figure><p>So the negative log likelihood becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*e0_2q5Z7WjCs1bgW" /></figure><p>Now using the torch.logsumexp we calculate the negative log-likelihood of all the samples in the batch and then compute the mean. This helps us avoid a lot of numerical instabilities in training.</p><h3>The Activation Function for Variance Parameter</h3><p>Bishop[1] suggested to use an Exponential activation function for the variance parameter. The choice has its strengths. The exponential function tends to a positive output and on the lower side, it never really reaches zero. But practically, it has some problems. The exponential function grows very large very fast and in case of datasets with high variance, the training becomes unstable.</p><p>Axel Brando Guillaumes [3] proposes an alternative, which is what we have used in our implementation. A modified version of an ELU activation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*syrOePyA0vCHKEO5" /><figcaption>The ELU activation function (Source: <a href="https://ml-cheatsheet.readthedocs.io/en/latest/activation_functions.html#elu">ML cheatsheet</a>)</figcaption></figure><p>The ELU function retains the exponential behavior and reverts to a linear behavior for higher values. The only problem is that the exponential behavior is when x is negative. But if we move this function upwards by 1, we have a function which approximates the exponential behavior. So Axel Brando Guillaumes [3] proposed to use</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/0*83mQ343p3oKiikKR" /></figure><p>as the activation function for the variance parameter. Since technically this also can become zero, we have added an epsilon also to the modified ELU to ensure stability. So the final activation used is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*6zPRp5KfGxyWxphF" /></figure><h3>Multiple Gaussians and Mode Collapse</h3><p>When we are using multiple Gaussian components and training the model using backpropagation, there is a tendency for the network to ignore all but one of the components and train a single component to explain the data. For eg. if we are using two components, while training one component will tend to zero and the other to 1 and the mean and variance components corresponding to the mixing component which became 1 will be trained to explain the data.</p><p>Axel Brando Guillaumes [3] suggests to clip the π value to a lower limit. But there was a problem with this approach.</p><ul><li>Because of the softmax applied, you can’t clip the π after applying softmax; otherwise it won’t add up to one. And before softmax, you have to apply the clipping on the raw logit value, which is highly unintuitive.</li></ul><p>So, through experimentation, we found out another set of tricks to make the network behave(although not guaranteed, but certainly encourage the network away from mode collapse).</p><ol><li><strong>Weight Regularization</strong> — Applying L1 or L2 regularization to the weights of the neurons which compute the mean, variances and mixing components.</li><li><strong>Bias Initialization</strong> — If we precompute the possible centers of the two gaussians, we can initialize the bias of the μ layers to these centers. This has shown to have a strong effect in the separation of the two gaussian kernels/components during training.</li></ol><h3>Alternative for Softmax for Mixing Coefficients</h3><p>Bishop[1] suggested to use a Softmax layer to convert the raw logits of the mixing coefficients(π) to probabilities. But we have used a <a href="https://towardsdatascience.com/what-is-gumbel-softmax-7f6d9cdcb90e">Gumbel Softmax</a>, which provides a much more sharper probability distribution. This is desirable because we want our model to be able to efficiently factor out one or more components when it is not needed. Softmax would still assign a small probability to those, while Gumbel Softmax makes that probability even smaller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P-xWBF6UqP8vBPWr.png" /><figcaption>Source [4]</figcaption></figure><h3>Code</h3><p>Below is a sample code for the implementation in <a href="https://github.com/manujosephv/pytorch_tabular">PyTorch Tabular</a>. Head over to the repo to see the full implementation(as a bonus also have access to implementations to other models like NODE, AutoInt, etc as well).</p><p>The code for the MDN Head</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9d66414a9412d6fc291e1e784fdd23c/href">https://medium.com/media/f9d66414a9412d6fc291e1e784fdd23c/href</a></iframe><p>An abstract class which takes in a backbone network and makes it an MDN</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb7fad206cdf405a2c710c0a73456e0f/href">https://medium.com/media/fb7fad206cdf405a2c710c0a73456e0f/href</a></iframe><h3>Experiments</h3><p>Taking inspiration from this excellent <a href="https://colab.research.google.com/drive/1at5lIq0jYvA58AmJ0aVgn2aUVpzIbwS3#scrollTo=MEhwQgPbuZuC">Colab Notebook</a> by Dr. Oliver Borchers, I have designed my own set of experiments using the implementation. There is also a tutorial on how to use MDNs in PyTorch Tabular .</p><h3>Linear Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*QHrlDdfBKhOHXgQ7" /><figcaption>Image by Author</figcaption></figure><p>This is a simple linear function, but some gaussian noise added as a function of the input x. A regular feedforward network will be able to approximate this function with a straight line through the middle. But if we use an MDN with a single component, it will approximate both the mean and the uncertainty in the function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*mplAXxHWmAwJOQsv" /><figcaption>Image by Author</figcaption></figure><h3>Non-Linear Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*H01EmvhhwKiySsfe" /><figcaption>Image by Author</figcaption></figure><p>This is a non-linear function with a twist. For each value of x, there are two values of y — one of the positive side and another on the negative side. Let’s take a look at what happens if we fit a normal FeedForward network on this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*xVSnzAnlO7N4imvH" /><figcaption>Image by Author</figcaption></figure><p>Not very good isn’t it? Well, if you think of the maximum likelihood estimate, it will likely fail because both the positive and negative points are equally likely. But when you train an MDN on it, the two components are properly learned and if we plot out the two components, it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*pauH0xFXHDiXPZGJ" /><figcaption>Image by Author</figcaption></figure><h3>Gaussian Mixture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*QhOSdLgof3FsFeN2" /><figcaption>Image by Author</figcaption></figure><p>Here we have two gaussian components which are mixed in a ratio, all of which is parameterized by x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*JV8vX6FVjI05dc5m" /><figcaption>Image by Author</figcaption></figure><p>The histogram also shows two small bumps on the top instead of a single smooth on of a normal gaussian.</p><p>Let’s look at how the standard FeedForward network captures this function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/0*sF2WD48nKj4sLmig" /><figcaption>Image by Author</figcaption></figure><p>Pretty well, except for the part where there is a transition. And as always no information about the uncertainty. (note: Really awesome how the network bends itself to approximate the step function.</p><p>Now let’s train an MDN on this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*yiZXKFh_WV39MeP4" /><figcaption>Image by Author</figcaption></figure><p>Now, isn’t that something? The two components are well captured — one component captures the first part well and the other one does the second one. The uncertainty is also estimated pretty well. Let’s also take a look at the mixing coefficients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/0*FFecQl6uwgadyjf2" /><figcaption>Image by Author</figcaption></figure><p>Component 1(which is the pink one in the previous plot) has high mixing coefficients till the transition point and drops to zero pretty quickly after that.</p><h3>Summary</h3><p>We have seen how important uncertainty is important to business decisions and also explored one way of doing that using Mixture Density networks. The implementation with all the tricks discussed in the article is available to use in a very user friendly way at PyTorch Tabular, along with a few other State of the Art algorithms for Tabular data. Check it out here:</p><p><strong>As always for any query/questions reach out to me on </strong><a href="https://www.linkedin.com/in/manujosephv/"><strong>LinkedIn</strong></a><strong>.</strong> For any issues you face with the library, raise an issue at <a href="https://github.com/manujosephv/pytorch_tabular/issues"><strong>Github</strong></a>.</p><h3>References</h3><ol><li>C. M. Bishop, Mixture density networks, (1994)</li><li>Vossen, Julian &amp; Feron, Baptiste &amp; Monti, A.. (2018). Probabilistic Forecasting of Household Electrical Load Using Artificial Neural Networks. 10.1109/PMAPS.2018.8440559.</li><li>Guillaumes, A.B. (2017). <a href="https://www.semanticscholar.org/paper/Mixture-density-networks-for-distribution-and-Guillaumes/0c01928c685098d4be96c18c6243a0e8c6f66074">Mixture Density Networks for distribution and uncertainty estimatio</a>n. Master Thesis. University of Barcelona</li><li>Jang, E., Gu, S., &amp; Poole, B. (2017). Categorical Reparameterization with Gumbel-Softmax. <em>ArXiv, abs/1611.01144</em>.</li></ol><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2021/03/20/mixture-density-networks-probabilistic-regression-for-uncertainty-estimation/"><em>http://deep-and-shallow.com</em></a><em> on March 20, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f7250207431" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/mixture-density-networks-probabilistic-regression-for-uncertainty-estimation-5f7250207431">Mixture Density Networks: Probabilistic Regression for Uncertainty Estimation</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[Neural Oblivious Decision Ensembles(NODE) — A State-of-the-Art Deep Learning Algorithm for Tabular…]]></title>
            <link>https://medium.com/analytics-vidhya/neural-oblivious-decision-ensembles-node-a-state-of-the-art-deep-learning-algorithm-for-tabular-1cb6788c5212?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cb6788c5212</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tabular-data]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Thu, 25 Feb 2021 01:14:14 GMT</pubDate>
            <atom:updated>2021-02-26T16:40:26.096Z</atom:updated>
            <content:encoded><![CDATA[<h3>Neural Oblivious Decision Ensembles(NODE) — A State-of-the-Art Deep Learning Algorithm for Tabular Data</h3><p>Deep Learning brought about revolutions in many machine learning problems from the field of Computer Vision, Natural Language Processing, Reinforcement Learning, etc. But tabular data still remains firmly under classical machine learning algorithms, namely the gradient boosting algorithms(I have a whole series on different <a href="https://deep-and-shallow.com/2020/02/02/the-gradient-boosters-i-the-math-heavy-primer-to-gradient-boosting-algorithm/">Gradient Boosting algorithms</a>, if you are interested).</p><p>Intuitively, this is strange, isn’t it? Neural networks are universal approximators and ideally, they should be able to approximate the function even in the tabular data domain. Or may be they can, but need humungous amount of data to properly learn that function? But how does the Gradient Boosted Trees do it so well? May the inductive bias of a decision tree is well suited for tabular data domain?</p><p>If they are so good, why don’t we use decision trees in neural networks? Just like we have Convolution Operation for images, and Recurrent Networks for Text, why can’t we use Decision Trees as a basic building block for Tabular data?</p><p>The answer is pretty straightforward- Trees are not differentiable and without the gradients flowing through the network, back-prop bombs. But this is where researchers started to bang their heads. How do we make Decision Trees differentiable.</p><h3>Differentiable Decision Trees</h3><p>In 2015, Kontschieder et al., presented Deep Neural Decision Forests, which had a decision tree-like structure, but differentiable.</p><p>Let’s take a step back and think about a Decision Tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*CfpMllxWDF6PqLDb" /><figcaption>A Regular Decision Tree(Source [1])</figcaption></figure><p>A typical Decision Tree looks something like the picture above. Simplistically, it is a collection of decision nodes(dᵢ) and leaf nodes(πᵢ) which together acts as a function, y = <strong><em>F</em></strong>(θ, X), where <strong><em>F</em></strong> is the decision tree, parametrized by θ, which maps input X to output y.</p><p>Let’s look at the leaf nodes first, because it’s easier. In traditional Decision Trees, the leaf nodes is typically a distribution over the class labels. This is right up the alley of a Sigmoid or a Softmax activation. So we could really replace the leaf nodes with a SoftMax layer and make that node differentiable.</p><p>Now, let’s take a deeper look at a decision node. The core purpose of a decision node is to decide whether to route the sample to the left or right. Let’s call these decisions, <em>dᵢ and d¯ᵢ (read as d bar and blame medium from the lack of latex support)</em>. And for this decision, it uses a particular feature(<em>f</em>) and a threshold(<em>b</em>)- these are the parameters of the node.</p><p>In traditional Decision Trees, this decision is a binary decision; it’s either right or left, 0 or 1. But this is deterministic and not differentiable. Now, what if we relax this and make the routing stochastic. Instead of a sharp 1 or 0, it’s going to be a number between 0 and 1. This feels like familiar territory, doesn’t it? Sigmoid function?</p><p>That’s exactly what Kontschieder et al. proposed. If we relax the strict 0–1 decision to a stochastic one with a sigmoid function, the node becomes differentiable.</p><p>Now we know how a single node(decision or a leaf node) works. Let’s put them all together. The red path in the diagram above is one of the path in the decision tree. In the deterministic version, a sample either goes through this route or it doesn’t. If we think about the same process in probabilistic terms, we know that the probability of the sample to go in the path should be 1 for every node in that path for the sample to reach the leaf node at the end of the path.</p><p>In the probabilistic paradigm, we find the probability that a sample goes left or right(<em>dᵢ and d¯ᵢ</em>) and multiply all of those along the path to get the probability that a sample reaches the leaf node.</p><p>Probability of the sample reaching the highlighted leaf node would be (<em>d₁ x d¯₂ x d¯₅)</em>.</p><p>Now, we just need to take the expected value of all the leaf nodes using the probabilities of each of the decision paths to get the prediction for a sample.</p><p>Now that you’ve got an intuition about how Decision Tree-like structures were derived to be used in Neural Networks, let’s talk about the NODE model.</p><h3>Neural Oblivious Trees</h3><p>An Oblivious Tree is a decision tree which is grown symmetrically. These are trees the same features are responsible in splitting learning instances into the left and the right partitions for each level of the tree. <a href="https://deep-and-shallow.com/2020/02/29/the-gradient-boosters-v-catboost/">CatBoost</a>, a prominent gradient boosting implementation, uses oblivious trees. Oblivious Trees are particularly interesting because they can be reduced to a Decision Table with 2ᵈ cells, where d is the depth of the tree. This simplifies things up pretty neatly.</p><p>Each Oblivious Decision Tree(ODT) outputs one of 2ᵈ responses, where <em>d </em>is the depth of the tree. This is done by using <em>d</em> feature-threshold combinations, which are the parameters of the ODT.</p><p>Formally, the ODT can be defined as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*H6VspLA7A8jNgHdV" /></figure><p>, where <strong>I<em> </em></strong>denotes the Heaviside function(which is a step function which is 0 for negative or 1 for positive)</p><p>Now to make the tree output differentiable, we should replace the splitting feature choice(<em>f</em>) and the comparison operator using the threshold(<em>b</em>), but their continuous counterparts.</p><p>In Traditional Trees, the choice of a feature to split a node by is a deterministic decision. But for differentiability, we choose a softer approach, i.e. A weighted sum of the features, where the weights are learned. Normally, we would think of a Softmax choice over the features, but we want to have sparse feature selection, i.e. we want the decision to be made on only a handful(preferably 1) features. So, to that effect, NODE uses α-entmax transformation (Peters et al., 2019) over a learnable feature selection matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/0*yYgr1Sdf14QPx6Ph" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*RrdtNztL0vsM4z5v" /><figcaption>Source: [2]</figcaption></figure><p>Similarly, we relax the Heaviside function as a two-class entmax. As different features can have different characteristic scales, we scale the entmax with a parameter τ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/0*jyw0KywkOtEu3afX" /></figure><p>, where <em>bᵢ </em>and <em>τᵢ </em>are learnable parameters for thresholds and scales respectively.</p><p>We know that a tree has two sides and by <em>cᵢ</em>, we have only defined one side. So to complete the tree, we stack <em>cᵢ</em> and <em>(1-cᵢ) </em>one on top of the other. Now we define a “choice” tensor <strong><em>C </em></strong>as the outer product of all the trees:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*vSnCCj742YwyGaLU" /></figure><p>This gives us the choice weights, or intuitively the probabilities of each of the 2ᵈ outputs, which is in the Response tensor. So now it reduced into a weighted sum of Response tensor, weighted by the Choice tensor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/0*VstTY7ULGPt9o8Zn" /></figure><p>The entire setup looks like the below diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/0*k9VLchaQmX1oYM7N" /><figcaption>From the Paper [3]</figcaption></figure><h3>Neural Oblivious Decision Ensembles</h3><p>The jump from an individual tree to a “forest” is pretty simple. If we have <em>m </em>trees in the ensemble, the final output is the concatenation of m individual trees</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/0*ovRRrDoHW3O_JxCc" /></figure><h3>Going Deeper with NODE</h3><p>In addition to developing the core module(NODE layer), they also propose a deep version, where we stack multiple NODE layers on top of each other, but with residual connections. The input features and the outputs of all previous layers are concatenated and fed into the next NODE Layer and so on. And finally, the final output from all the layers are averaged(similar to the RandomForest).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cb_Fje3zNJUOsTpS" /><figcaption>From the Paper [3]</figcaption></figure><h3>Training and Experiments</h3><h3>Data Processing</h3><p>In all the experiments in the paper, they transformed each of the features to follow a normal distribution using a Quantile Transformation. This step was important for stable training and faster convergence.</p><h3>Initialization</h3><p>Before training the network, they propose to do data-aware initialization to get good initial parameters. They initialize the Feature Selection matrix(<em>F</em>) uniformly, while the thresholds(<em>b</em>) are initialize with random feature values <em>fᵢ(x)</em>. The scales <em>τᵢ </em>are initialize in such a way that all the samples in he first batch fall in the linear region of the $latex two-sided entmax and hence receive non-zero gradients. And finally, the response tensor are initialized with a standard normal distribution.</p><h3>Experiments and Results</h3><p>The paper performs experiments with 6 datasets — Epsilon, YearPrediction, Higgs, Microsoft, Yahoo, and Click. They compared NODE with CatBoost, XGBoost and FCNN.</p><p>First they compared with default hyperparameters across all the algorithms. the default architecture of NODE was set as below: Single layer of 2048 trees of depth 6. These parameters were inherited from CatBoost default parameters.</p><p>Then, they tuned all the algorithms and then compared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Nk2GVqzL0vJtN5x" /><figcaption>Comparison Table (Source: [3])</figcaption></figure><h3>Code and Implementation</h3><p>The authors have made the implementation available in a ready to use Module in PyTorch <a href="https://github.com/Qwicen/node">here</a>.</p><p>It is also implemented in the new library I released, PyTorch Tabular, along with a few other State of the Art algorithms for Tabular data. Check it out here:</p><ul><li><a href="https://pypi.org/project/pytorch-tabular/">PyPi</a></li><li><a href="https://github.com/manujosephv/pytorch_tabular">Github</a></li><li><a href="https://pytorch-tabular.readthedocs.io/en/latest/">Documentation</a></li></ul><h3>References</h3><ol><li>P. Kontschieder, M. Fiterau, A. Criminisi and S. R. Bulò, “Deep Neural Decision Forests,” <em>2015 IEEE International Conference on Computer Vision (ICCV)</em>, pp. 1467–1475, doi: 10.1109/ICCV.2015.172.</li><li>Ben Peters, Vlad Niculae, André F. T. Martins, “Sparse Sequence-to-Sequence Models,” <em>2019 Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics(ACL)</em>, pp. 1504–1519, doi: 10.18653/v1/P19–1146.</li><li>Sergei Popov, Stanislav Morozov, Artem Babenko, “<a href="https://arxiv.org/abs/1909.06312">Neural Oblivious Decision Ensembles for Deep Learning on Tabular Data</a>,” <a href="https://deep-and-shallow.com/2021/02/25/neural-oblivious-decision-ensemblesnode-a-state-of-the-art-deep-learning-algorithm-for-tabular-data/1909.06312%20[cs.LG]"><em>arXiv:1909.06312 [cs.LG]</em></a></li></ol><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2021/02/25/neural-oblivious-decision-ensemblesnode-a-state-of-the-art-deep-learning-algorithm-for-tabular-data/"><em>http://deep-and-shallow.com</em></a><em> on February 25, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cb6788c5212" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/neural-oblivious-decision-ensembles-node-a-state-of-the-art-deep-learning-algorithm-for-tabular-1cb6788c5212">Neural Oblivious Decision Ensembles(NODE) — A State-of-the-Art Deep Learning Algorithm for Tabular…</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[PyTorch Tabular — A Framework for Deep Learning for Tabular Data]]></title>
            <link>https://medium.com/data-science/pytorch-tabular-a-framework-for-deep-learning-for-tabular-data-bdde615fc581?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdde615fc581</guid>
            <category><![CDATA[tabular-data]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch-lightning]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Wed, 27 Jan 2021 18:10:53 GMT</pubDate>
            <atom:updated>2021-01-28T15:36:12.475Z</atom:updated>
            <content:encoded><![CDATA[<h3>PyTorch Tabular — A Framework for Deep Learning for Tabular Data</h3><p>It is common knowledge that <a href="https://deep-and-shallow.com/2020/02/02/the-gradient-boosters-i-the-math-heavy-primer-to-gradient-boosting-algorithm/">Gradient Boosting models</a>, more often than not, kick the asses of every other machine learning models when it comes to Tabular Data. I have written extensively about Gradient Boosting, <a href="https://deep-and-shallow.com/2020/02/02/the-gradient-boosters-i-the-math-heavy-primer-to-gradient-boosting-algorithm/">the theory</a> behind and covered the different implementations like <a href="https://deep-and-shallow.com/2020/02/12/the-gradient-boosters-iii-xgboost/">XGBoost</a>, <a href="https://deep-and-shallow.com/2020/02/21/the-gradient-boosters-iii-lightgbm/">LightGBM</a>, <a href="https://deep-and-shallow.com/2020/02/29/the-gradient-boosters-v-catboost/">CatBoost</a>, <a href="https://deep-and-shallow.com/2020/06/27/the-gradient-boosters-vib-ngboost/">NGBoost </a>etc. in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gsOZueMC6VhUafhU" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The unreasonable effectiveness of Deep Learning that was displayed in many other modalities — like text and image- haven not been demonstrated in tabular data. But lately, the deep learning revolution have shifted a little bit of focus to the tabular world and as a result, we are seeing new architectures and models which was designed specifically for tabular data modality. And many of them are coming up as an equivalent or even slightly better than well-tuned Gradient Boosting models.</p><h3>What is PyTorch Tabular?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*gQl9d-_SM4DAfyA7" /></figure><p>PyTorch Tabular is a framework/ wrapper library which aims to make Deep Learning with Tabular data easy and accessible to real-world cases and research alike. The core principles behind the design of the library are:</p><p>Instead of starting from scratch, the framework has been built on the shoulders of giants like <a href="https://pytorch.org/"><strong>PyTorch</strong></a>(obviously), and <a href="https://www.pytorchlightning.ai/"><strong>PyTorch Lightning</strong></a>.</p><p>It also comes with state-of-the-art deep learning models that can be easily trained using pandas dataframes.</p><ul><li>The high-level config driven API makes it very quick to use and iterate. You can just use a pandas dataframe and all of the heavy lifting for normalizing, standardizing, encoding categorical features, and preparing the dataloader is handled by the library.</li><li>The BaseModel class provides an easy to extend abstract class for implementing custom models and still leverage the rest of the machinery packaged with the library.</li><li>State-of-the-art networks like <a href="https://arxiv.org/abs/1909.06312">Neural Oblivious Decision Ensembles for Deep Learning on Tabular Data</a>, and <a href="https://arxiv.org/abs/1908.07442">TabNet: Attentive Interpretable Tabular Learning</a> are implemented. See examples from the documentation for how to use them.</li><li>By using PyTorch Lightning for the training, PyTorch Tabular inherits the flexibility and scalability that Pytorch Lightning provides</li></ul><h3>Why PyTorch Tabular?</h3><p>PyTorch Tabular aims to reduce the barrier for entry for both industry application and research of Deep Learning for Tabular data. As things stand now, working with Neural Networks is not that easy; at least not as easy as traditional ML models with Sci-kit Learn.</p><p>PyTorch Tabular attempts to make the “software engineering” part of working with Neural Networks as easy and effortless as possible and let you focus on the model. I also hopes to unify the different developments in the Tabular space into a single framework with an API that will work with different state-of-the-art models.</p><p>Right now, most of the developments in Tabular Deep Learning are scattered in individual Github repos. And apart from (which I love and hate), no framework has really paid attention to Tabular Data. And this is the need which led to PyTorch Tabular.</p><h3>How to use PyTorch Tabular?</h3><h3>Installation</h3><p>First things first — let’s look at how we can install the library.</p><p>Although the installation includes PyTorch, the best and recommended way is to first install PyTorch from <a href="https://pytorch.org/get-started/locally/">here</a>, picking up the right CUDA version for your machine. (PyTorch Version &gt;1.3)</p><p>Once, you have got Pytorch installed, just use:</p><pre>pip install pytorch_tabular[all]</pre><p>to install the complete library with extra dependencies( <a href="https://wandb.ai/">Weights &amp; Biases</a> for Experiment Tracking).</p><p>And :</p><pre>pip install pytorch_tabular</pre><p>for the bare essentials.</p><p>The sources for pytorch_tabular can be downloaded from the Github repo.</p><p>You can either clone the public repository:</p><pre>git clone git://github.com/manujosephv/pytorch_tabular</pre><p>Once you have a copy of the source, you can install it with:</p><pre>python setup.py install</pre><h3>Setting up the Configs</h3><p>There are four configs that you need to provide(most of them have intelligent default values), which will drive the rest of the process.</p><ul><li><strong>DataConfig </strong>— Define the target column names, categorical and numerical column names, any transformation you need to do, etc.</li><li><strong>ModelConfig </strong>— There is a specific config for each of the models. This determines which model we are going to train and also lets you define the hyperparameters of the model</li><li><strong>TrainerConfig</strong> — This let’s you configure the training process by setting things like batch_size, epochs, early stopping, etc. The vast majority of parameters are directly borrowed from PyTorch Lightning and is passed to the underlying Trainer object during training</li><li><strong>OptimizerConfig </strong>— This let’s you define and use different Optimizers and LearningRate Schedulers. Standard PyTorch Optimizers and Learning RateSchedulers are supported. For custom optimizers, you can use the parameter in the fit method to overwrite this. The custom optimizer should be PyTorch compatible</li><li><strong>ExperimentConfig</strong> — This is an optional parameter. If set, this defines the Experiment Tracking. Right now, only two experiment tracking frameworks are supported: Tensorboard and Weights&amp;Biases. W&amp;B experiment tracker has more features like tracking the gradients and logits across epochs.</li></ul><pre>data_config = DataConfig( target=[&#39;target&#39;], continuous_cols=num_col_names, categorical_cols=cat_col_names, ) </pre><pre>trainer_config = TrainerConfig( auto_lr_find=True, batch_size=1024, max_epochs=100, gpus=1) </pre><pre>ptimizer_config = OptimizerConfig() </pre><pre>model_config = CategoryEmbeddingModelConfig( task=&quot;classification&quot;, layers=&quot;1024-512-512&quot;, # Number of nodes in each layer activation=&quot;LeakyReLU&quot;, # Activation between each layers learning_rate = 1e-3 )</pre><h3>Initializing the Model and Training</h3><p>Now that we have the configs defined, we need to initialize the model using these configs and call the <em>fit</em> method.</p><pre>tabular_model = TabularModel( data_config=data_config, model_config=model_config, optimizer_config=optimizer_config, trainer_config=trainer_config, ) tabular_model.fit(train=train, validation=val)</pre><p>That’s it. The model will be trained for the specified number of epochs.</p><h4>Model List</h4><ul><li>FeedForward Network with Category Embedding is a simple FF network, but with and Embedding layers for the categorical columns. This is very similar to the <em>fastai </em>Tabular Model</li><li><a href="https://arxiv.org/abs/1909.06312">Neural Oblivious Decision Ensembles for Deep Learning on Tabular Data</a> is a model presented in ICLR 2020 and according to the authors have beaten well-tuned Gradient Boosting models on many datasets.</li><li><a href="https://arxiv.org/abs/1908.07442">TabNet: Attentive Interpretable Tabular Learning</a> is another model coming out of Google Research which uses Sparse Attention in multiple steps of decision making to model the output.</li></ul><p>To implement new models, see the <a href="https://github.com/manujosephv/pytorch_tabular/blob/main/docs/04-Implementing%20New%20Architectures.ipynb">How to implement new models tutorial</a>. It covers basic as well as advanced architectures.</p><h3>Evaluate Model on Unseen Data</h3><p>To evaluate the model on new data on the same metrics/loss that was used during training, we can use the method.</p><pre>result = tabular_model.evaluate(test)</pre><pre>-------------------------------------------------------------------------------- DATALOADER:0 TEST RESULTS <br>{<br>&#39;test_accuracy&#39;: tensor(0.6924, device=&#39;cuda:0&#39;), <br>&#39;train_accuracy&#39;: tensor(0.6051, device=&#39;cuda:0&#39;), <br>&#39;train_loss&#39;: tensor(0.6258, device=&#39;cuda:0&#39;), <br>&#39;valid_accuracy&#39;: tensor(0.7440, device=&#39;cuda:0&#39;), <br>&#39;valid_loss&#39;: tensor(0.5769, device=&#39;cuda:0&#39;)} <br>--------------------------------------------------------------------------------</pre><h3>Getting Predictions on Unseen Data</h3><p>To get the prediction as a dataframe, we can use the predict method. This will add predictions to the same dataframe that was passed in. For classification problems, we get both the probabilities and the final prediction taking 0.5 as the threshold</p><pre>pred_df = tabular_model.predict(test)</pre><h3>Saving and Loading Models</h3><p>We can also save a model and load it later for inferencing.</p><pre>tabular_model.save_model(&quot;examples/basic&quot;) </pre><pre>loaded_model = TabularModel.load_from_checkpoint(&quot;examples/basic&quot;) </pre><pre>result = loaded_model.evaluate(test)</pre><h3>Code, Documentation and How to Contribute</h3><p>The code for the framework is available at <a href="https://github.com/manujosephv/pytorch_tabular">PyTorch Tabular: A standard framework for modelling Deep Learning Models for tabular data (github.com)</a>.</p><p>Documentation and tutorials can be found at <a href="https://pytorch-tabular.readthedocs.io/en/latest/">PyTorch Tabular (pytorch-tabular.readthedocs.io)</a></p><p>Contributions are more than welcome and details about how to contribute is also laid out <a href="https://pytorch-tabular.readthedocs.io/en/latest/contributing/">here</a>.</p><h3>Related Work</h3><p><em>fastai </em>is the closest to PyTorch Tabular, both built on PyTorch. But where PyTorch Tabular differentiates from fastai is with it’s modular and decoupled nature and it’s usage of standard PyTorch and PyTorch Lightning components which makes adoption, including new models, and hacking the code much more easy than with <em>fastai</em>.</p><h3>References</h3><p>[1] Sergei Popov, Stanislav Morozov, Artem Babenko. <a href="https://arxiv.org/abs/1909.06312"><em>“Neural Oblivious Decision Ensembles for Deep Learning on Tabular Data”</em></a>. arXiv:1909.06312 [cs.LG] (2019)</p><p>[2] Sercan O. Arik, Tomas Pfister;. <a href="https://arxiv.org/abs/1908.07442"><em>“TabNet: Attentive Interpretable Tabular Learning”</em></a>. arXiv:1908.07442 (2019).</p><h3>What Next?</h3><p>I will be continuing to write separate blog posts to talk about the different models that have been implemented in PyTorch Tabular as of now. Watch out for them.</p><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2021/01/27/pytorch-tabular-a-framework-for-deep-learning-for-tabular-data/"><em>http://deep-and-shallow.com</em></a><em> on January 27, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdde615fc581" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/pytorch-tabular-a-framework-for-deep-learning-for-tabular-data-bdde615fc581">PyTorch Tabular — A Framework for Deep Learning for Tabular Data</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 to Train and Deploy Custom AI-Generated Quotes using GPT2, FastAPI, and ReactJS]]></title>
            <link>https://medium.com/data-science/how-to-train-and-deploy-custom-ai-generated-quotes-using-gpt2-fastapi-and-reactjs-9a6feb42d8b0?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a6feb42d8b0</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 23:46:27 GMT</pubDate>
            <atom:updated>2022-01-07T08:24:44.914Z</atom:updated>
            <content:encoded><![CDATA[<h4>Generate quotes at will</h4><h3>The Problem</h3><blockquote>Good quotes help make us stronger. What is truly inspiring about quotes is not their tone or contentedness but how those who share them reflect life experiences that really serve others.</blockquote><p>I didn’t write the above quote about quotes (<em>Quote-ception; bad pun?</em>), but an AI model I trained did. And it says it better than I would have. Quotes are something that means different things to different people. Sometimes they inspire us, motivate us. And some other times they make us think about life, religion, and sometimes they just make us laugh.</p><p>So, can we train an AI model to generate more quotes, and make us think, laugh, or inspired? That was the motivation behind me starting on this journey.</p><h3>TL;DR</h3><p>I have fine-tuned GPT2 model on quotes with personas like Motivational/Inspirational, Funny, and Serious/Philosophical and deployed in a ready-to-use website: AI Quotes Generator.</p><p>Edit 07–01–2022 — I have taken the app down. The link is no longer valid.</p><h3>The Model</h3><p>On June 3, 2020, OpenAI released GPT3, a mammoth language model trained on 570GB of internet text. People have put the multi-talented model to use in all kinds of applications ranging from creating app designs, to websites, to excel functions which do nothing short of magic. But there was just one problem — the model weights were never released. The only way we can access then was through a paywalled API.</p><p>So, let’s time travel to November 2019, when GPT-2 was released. GPT-2, although not as powerful as GPT-2, was a revolution when it came to text generation. I remember my jaw dropping to the floor while reading the demo text generated by the model- the coherence, and grammatical syntax, it was near perfect. What I want from the model was not to be a magician, but to be able to generate perfectly structured English sentences. And for that GPT2 was more than sufficient.</p><h3>Dataset</h3><p>First I needed a dataset. Scraping the web for quotes was one option, but before that I wanted to see if somebody had done that already. And bingo! <a href="https://github.com/ShivaliGoel/Quotes-500K">Quotes-500k</a> is a dataset of almost 500k quotes, all scraped from the web along with tags like knowledge, love, friendship, etc.</p><p>Now I wanted to have the model be able to generate quotes according to specific themes. Since I was planning to use a pretrained model, conditional text generation was not something that was easy to do. <a href="https://eng.uber.com/pplm/">PPLM</a> was a model, or rather a way of using pretrained models, that Uber released which attempts to do just this(A very interesting paper. Be sure to check that out), but in the end, I went another way. I decided to train three models, each fine-tuned to specific genre of quotes.</p><p>There were three genres I considered — Motivational, Serious, and Funny. I used the Quotes500k dataset and the tags to separate the quotes based on the tags into these three buckets. For <strong>Motivational</strong> dataset, I used tags such as <em>love, life, inspirational, motivational, life lessons, dreams, etc</em>. And for <strong>Serious</strong>, I went with tags like <em>philosophy, life, god, time, faith, fear, etc</em>. And finally, for <strong>Funny</strong>, I just took tags like <em>humour and funny</em>.</p><h3>Preprocessing</h3><p>Nothing fancy here; just the basic hygiene. Things like</p><ol><li>Converting to Lowercase</li><li>Replacing Contractions like wasn’t with the full form, i,e, was not.</li><li>Removing HTML special entities(because this was a corpus scraped from the web</li><li>Removing extra whitespaces</li><li>Inserting whitespaces between a word and punctuation.</li><li>Spellchecking and correction(using <a href="https://pypi.org/project/pyenchant/">pyenchant</a>)</li></ol><p>You might have questions like — <em>What about stop words? Lemmatization? Where are all of those?</em></p><p>Removal of stop words and lemmatization are not mandatory steps that you have to do in every single NLP task. It really depends on the task. If we were doing a text classification using a TF-IDF kind of a model, then yeah, it makes sense to do all of that. But text classification with a model which uses context, like a Neural Model or an N-Gram model, lesser so. And if you are doing Text Generation or Machine Translation, then removing the stop words and lemmatizing may actually hurt your performance as we are losing valuable context from the corpus.</p><h3>Beginning and End of Sentence Tokens and Maximum Length</h3><p>I also wanted to make the quotes not be too long. So I took a look at the dataset, plotted the frequencies of the length of the quote, and decided on an appropriate length where I should cut off. In the motivational corpus, I discarded all the quotes greater than 100 words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*emLt96tn3DtZ1VY8" /><figcaption>Image by Author</figcaption></figure><p>Another important aspect to making the quotes short was the ability of the model to predict an End-of-Sentence token. So, we wrap each quote with a beginning of sentence(bos) token and an end of sentence(eos) token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/903a10fd2e3fab59fd82288a70a785c8/href">https://medium.com/media/903a10fd2e3fab59fd82288a70a785c8/href</a></iframe><h3>Training</h3><p>Now that we have the dataset ready and prepared, let’s start training the model. <a href="https://huggingface.co/transformers/">Transformers from Hugging Face</a> is the obvious choice with its easy-to-use api and amazing collection of models with pretrained weights. Thanks to Hugging Face, training or fine-tuning a model is a breezy affair.</p><p>We start off by loading the model and the tokenizer for GPT2.</p><pre>tokenizer = AutoTokenizer.from_pretrained(&#39;gpt2&#39;) <br>model = AutoModelWithLMHead.from_pretrained(&#39;gpt2&#39;)</pre><p>That’s it. You have the entire power of the huge pretrained model behind your fingers while you code.</p><p>Now, let’s define a function to load the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f8131d595dd95299cb0d1402c1b3ba7/href">https://medium.com/media/2f8131d595dd95299cb0d1402c1b3ba7/href</a></iframe><p>Now that we have the datasets, let’s create the Trainer. This is the core class which handles all the training process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e10460028a5c8fddbdbcc39dacaa3ad/href">https://medium.com/media/2e10460028a5c8fddbdbcc39dacaa3ad/href</a></iframe><p>By this point of time, we have all the ingredients necessary to start training — the Model, Tokenizer, and the Trainer. All that is left is to do is train the model. And once the training is done, we just need to save the model and tokenizer for our use.</p><pre>trainer.train() trainer.save_model(&quot;./storage/gpt2-motivational_v6&quot;) tokenizer.save_pretrained(&quot;./storage/gpt2-motivational_v6&quot;)</pre><p>I trained each of the three models ~50 epochs on a single P5000 for a total of ~12 hours(excluding all the test runs, and runs which had some problems.)</p><h3>Inference</h3><p>We have trained the model and saved them. Now what? For inference, we take another brilliant feature from Hugging Face — pipelines. This awesome feature lets you put a model into production in as little as a few lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63435c4b251d1babd614bb4b53e89058/href">https://medium.com/media/63435c4b251d1babd614bb4b53e89058/href</a></iframe><p>The <em>gen_kwargs</em> configures the text generation. I have used a hybrid approach of <em>top_k sampling </em>with <em>k=50</em> and <em>top_p sampling </em>with <em>p=0.95</em>. To avoid repetitions in text generation, I have used <em>no_repeat_ngram_size = 3,</em> and <em>repetition_penalty=1.2</em>.</p><h3>User Interface</h3><p>Now that we have the core model trained, we need a way to interact with it. Writing code every time we need something from it is just not user friendly. So, we need a UI. And I chose to whip up a simple UI with ReactJS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LIN0hWH7iLVlndfS" /><figcaption>Image by Author</figcaption></figure><p><em>Although I can’t make the entire project available on Github, I’ll post the key parts as Github Gists.</em></p><p>For the purposes of the UI, I have dubbed the three models with a persona — <strong><em>Inspiratobot</em></strong>(Motivational), <strong><em>Aristobot</em></strong>(Serious), and <strong><em>FunnyBot</em></strong>.</p><p>The key features of the UI are:</p><ol><li>Ability to select between the three different personas</li><li>You can start off the quote or you can use one of the many random starting seeds which will be populated. If you don’t like a seed, hit the shuffle button to get another seed.</li><li>In the Advanced Setting, you get to play around with the minimum and maximum length of the quote. You can also play with the variety(or Temperature in sampling)</li><li>The UI also uses stock photos from Unsplash as backgrounds to the quote, because that is all the rave recently. It picks from a collection of photos which suit the persona for which the quotes are being generated</li><li>It also lets you rate the quote on a scale of 1 to 5.</li></ol><p>The folder structure of the UI Project is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*fLvgwT6b8FycVOA8FJjIFw.png" /></figure><p>The<a href="https://gist.github.com/manujosephv/e2beb755de858bcc906ef17a3e2cee59"> quotes.js </a>and <a href="https://gist.github.com/manujosephv/de27c203497bfacee4460c17afbff378">customRatings.js</a> can be found in my Github Gists.</p><h3>Backend API Server</h3><p>For hosting and serving the model, we need a server. And for this, I chose <a href="https://fastapi.tiangolo.com/">FastAPI</a>, a no-nonsense web framework, specifically designed to build APIs.</p><p>I highly recommend FastAPI because of the sheer simplicity. A very simple API example(from the docs) is below:</p><pre>from typing import Optional <br>from fastapi <br>import FastAPI </pre><pre>app = FastAPI() <br>@app.get(&quot;/&quot;) <br>def read_root(): <br>    return {&quot;Hello&quot;: &quot;World&quot;} </pre><pre>@app.get(&quot;/items/{item_id}&quot;) <br>def read_item(item_id: int, q: Optional[str] = None): <br>    return {&quot;item_id&quot;: item_id, &quot;q&quot;: q}</pre><p>Less than 10 lines of code to get a web server for your API sounds too good to be true, but that is just what it is.</p><p>Without going into details, the key part of the API is the generation of the quotes and below is the code for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/063e0f1c97698896d0d4c599b0480728/href">https://medium.com/media/063e0f1c97698896d0d4c599b0480728/href</a></iframe><p>The folder structure of the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*u2LBRqpVbJjcbjzWMIpnTA.png" /></figure><h3>Deployment</h3><p>It would have been all too easy to dockerize the application, spin up an EC2 instance, and host this. But I wanted an option which was cheap, if not free. Another challenge was that the models are about 500MB each and loading them into the memory made the RAM consumption to hover around 1GB. So an EC2 instance would have been costly. In addition to that, I also needed to store three models in the cloud which could cost storage. And to top it all, I also needed a DB to store the ratings that the user makes.</p><p>With these specifications, I went hunting for products/services. To make things easier, I had separated out the app into two — a backend API server and a frontend UI which calls the backend API internally.</p><p>During my search, I stumbled upon this awesome <a href="https://free-for.dev/#/">list of free services</a> that developers can avail. And after evaluating a few of those options, I finally zeroed in on the below options which would make the total cost of deployment as low as possible:</p><ul><li>Backend API Server — <a href="https://www.kintohub.com/">Kintohub</a></li><li>Frontend Hosting — <a href="https://firebase.google.com/">Firebase</a>(Free)</li><li>DB — <a href="https://www.mongodb.com/cloud/atlas">MongoDB Atlas</a>(Free)</li></ul><h3>KintoHub</h3><p>“KintoHub is an all-in-one deployment platform designed for full stack developers by full stack developers”, reads the home page. If cost was not a concern, I could have deployed the entire app on KintoHub because that is what their offering is — a backend Server which can scale well, a frontend server to server static HTML files, and a database. In the background, they containerize the app using a very easy to use web interface and deploy it on a machine of chosen specification. And the great thing is that all of this can be done from Github. You check-in your code to a Github repository(public or private) and deploy the app directly by pointing it to the repo.</p><p>As far as the bare minimum settings that has to be done does, it fits in a single page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*YdO2OBhS-4YWhBGw" /><figcaption>Image by Author</figcaption></figure><p>That’s it. Of course, there are more setting available, like the memory that should be available for the app to run, etc. Although KintoHub has a free tier, I soon realized because of the RAM consumption of the models, I need a minimum of 1.5GB to make it run without crashing. So I moved to a Pay-as-you-go tier, where they generously award you with a $5 credit each month. The cost calculator shows we the app hosting is going to cost $5.5 and I’m fine with that(Still waiting to see till the end of the month on the actual cost).</p><h3>Google Firebase</h3><p>Firebase is a lot of things. It says on the homepage that it is the complete app development platform, and it really is. But we are only interested in the Firebase Hosting, where they let you host single page websites for free. And it was a breeze to deploy the app. All you have to do is:</p><ol><li>Install the firebase CLI</li><li>Run <em>npm build</em> on your React project</li><li>Run <em>firebase init</em> from the root folder of your project and point the source from <em>public</em> to <em>build</em></li><li>Run <em>firebase deploy</em></li></ol><p>A very <a href="https://dzone.com/articles/react-apps-firebase">short tutorial</a> is all you need to get this done.</p><h3>MongoDB Atlas</h3><p>MongoDB Atlas is a cloud DBaaS which provides a MongoDB on the cloud and the good thing is that they offer a free tier with 512MB of storage. For our use-case, it is more than enough.</p><p>Creating a new <a href="https://docs.atlas.mongodb.com/tutorial/create-new-cluster/">cluster is straight-forward </a>and once you sort out the access issues, we can use a python wrapper like <a href="https://pymongo.readthedocs.io/en/stable/">pymongo </a>to implement our DB connection.</p><h3>Result</h3><p>The result of all this is a website where you can interact with the model, generate quotes and pass it off as yours :D.</p><blockquote><a href="https://aiquotesgenerator.com/"><strong><em>https://aiquotesgenerator.com</em></strong></a></blockquote><p>Edit — 07–01–2022 — The web-app is not up on the link anymore.</p><p>Although the model isn’t perfect, it still churns out some really good quotes that make you think. And that’s what you want from any quote, right? Have fun playing with the model.</p><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2020/11/28/how-to-train-and-deploy-custom-ai-generated-quotes-using-gpt2-fastapi-and-reactjs/"><em>http://deep-and-shallow.com</em></a><em> on November 27, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a6feb42d8b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-train-and-deploy-custom-ai-generated-quotes-using-gpt2-fastapi-and-reactjs-9a6feb42d8b0">How to Train and Deploy Custom AI-Generated Quotes using GPT2, FastAPI, and ReactJS</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[Intermittent Demand Forecasting with Deep Renewal Processes]]></title>
            <link>https://medium.com/data-science/intermittent-demand-forecasting-with-deep-renewal-processes-f152d3f59f35?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f152d3f59f35</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 06:09:58 GMT</pubDate>
            <atom:updated>2020-10-14T12:41:37.258Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s face it. anyone who has worked on Time Series Forecasting problems in the retail, logistics, e-commerce etc. would have definitely cursed that long tail which never behaves. The dreaded intermittent time series which makes the job of a forecaster difficult. This nuisance renders most of the standard forecasting techniques impractical, raises questions about the metrics, model selection, model ensembling, you name it. And to make things worse, there may be cases(like in the spare parts industry, where intermittent patterns appear is slow-moving but highly critical or high value items.</p><h3>Notation</h3><p>Y - <em>i</em> th element of the time series</p><p>n - The index of timeseries</p><p>i - The index of non-zero demand</p><p>Qi - The inter-demand interval, i.e. the gap between two non-zero demand.</p><p>Mi- The demand size at non-zero demand point.</p><h3>Traditional Approach</h3><p>Traditionally, there is a class of algorithms which take a slightly different path to forecasting the intermittent time series. This set of algorithms considered the intermittent demand in two parts — Demand Size and Inter-demand Interval — and modelled them separately.</p><h3>Croston</h3><p>Croston proposed to apply a single exponential smoothing seperately to both <em>M</em> and <em>Q</em>, as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*hgO_kj4_KsPzwyFx" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/0*6gxRFtBDy3nA8ZyW" /></figure><p>After getting these estimates, final forecast,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/0*HhQP9AMIdOQyt-1-" /></figure><p>And this is a one-step ahead forecast and if we have to extend to multiple timesteps, we are left with a flat forecast with the same value.</p><h3>Croston(SBA)</h3><p>Syntetos and Boylan, 2005, showed that Croston forecasting was biased on intermittent demand and proposed a correction with the β from inter demand interval estimation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/0*sh3Frf3PyQ9GKcTM" /></figure><h3>Croston(SBJ)</h3><p>Shale, Boylan, and Johnston (2006) derived the expected bias when the arrival follow a Poisson process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*RxmT_PvzFWoir1lO" /></figure><h3>Croston Forecasting as Renewal Process</h3><p>Renewal process is an arrival process in which the interarrival intervals are positive, independent and identically distributed (IID) random variables (rv’s). This formulation generalizes Poison process for arbitrary long times. Usually, in a Poisson process the inter-demand intervals are exponentially distributed. But renewal processes have an i.i.d. inter-demand time that have a finite mean.</p><p>Turkmen et al. 2019 casts Croston and its variants into a renewal process mold. The random variables, <em>M</em> and <em>Q</em>, both defined on positive integers fully define the Yn</p><h3>Deep Renewal Process</h3><p>Once Croston forecasting was cast as a renewal process, Turkmen et al. proposed to estimate them by using a separate RNN for each “Demand Size” and “Inter-demand Interval”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/0*VSLKLVlq4dQhXBFu" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/0*7ZZ-gYoBcIoAzkaP" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/0*mdQgRn8ApTxPEIzC" /></figure><p>This means that we have a single RNN, which takes in as input both <em>M</em> and <em>Q</em> and encodes that information into an encoder( <em>h</em>). And then we put two separate NN layers on top of this hidden layer to estimate the probability distribution of both <em>M</em> and <em>Q</em>. For both <em>M</em> and <em>Q</em>, Negative Binomial distribution is the choice suggested by the paper.</p><h3>Negative Binomial Distribution</h3><p>Negative Binomial Distribution is a discrete probability distribution which is commonly used to model count data. For example, the number of units of an SKU sold, number of people who visited a website, or number of service calls a call center receives.</p><p>The distribution derives from a sequence of <a href="https://en.wikipedia.org/wiki/Bernoulli_trial">Bernoulli Trials</a>, which says that there are only two outcomes for each experiment. A classic example is a coin toss, which can either be heads or tails. So the probability of success is <em>p</em> and failure is <em>1-p</em> (in a fair coin toss, this is 0.5 each). So now if we keep on performing this experiment until we have seen <em>r</em> successes, the number of failures we see will have a negative binomial distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/0*3t78oGEOS_NhkiSM" /></figure><p>The semantic meaning of success and failure need not hold true when we apply this, but what matters is that there are only two types of outcome.</p><h3>Network Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*bVyKLCRA3ygNlyHG" /><figcaption>Image by Author</figcaption></figure><h3>Our Contribution</h3><p>The paper just talks about one-step ahead forecasts, which is also what you will find in a lot of Intermittent Demand Forecast literature. But in a real world, we would need longer than that to plan properly. Whether it is Croston, or Deep Renewal Process, how we generate a n-step ahead forecast is the same — a flat forecast of Demand Size(M)/Inter-demand Time(Q).</p><p>We have introduced a two new method of decoding the output — Exact and Hybrid — in addition to the existing method Flat. Suppose we trained the model with a prediction length of 5.</p><p>The raw output from the mode would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*-NgIBVPjQQRwshCF" /></figure><p><strong>Flat</strong></p><p>Under flat decoding, we would just pick the first set of outputs (M=22 and Q=2) and generate a one-step ahead forecast and extend the same forecast for all 5 timesteps.</p><p><strong>Exact</strong></p><p>Exact decoding is more of a more confident version of decoding. Here we predict a demand of demand size M, every Inter demand time of Q and make the rest of the forecast zero.</p><p><strong>Hybrid</strong></p><p>In hybrid decoding, we combine these two to generate a forecast which is also taking into account long-term changes in the model’s expectation. We use the M/Q value for forecast, but we update the M/Q value based on the next steps. For eg, in the example we have, we will forecast 11(which is 22/3) for the first 2 timesteps, and then forecast 33(which is 33/1) for the next timestep, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/0*RlX8hc8WKWg5Dweh" /></figure><h3>Implementation</h3><p>I have implemented the algorithm using GluonTS, which is a framework for Neural Time Series forecasting, built on top of MXNet. AWS Labs is behind the open source project and some of the algorithms like DeepAR are used internally by Amazon to produce forecasts.</p><h3>Models Implemented</h3><p>The paper talks about two variants of the model — Discrete Time DRP(Deep Renewal Process) and Continuous Time DRP. In this library, we have only implemented the discrete time DRP, as it is the more popular use case.</p><h3>How to install?</h3><p>The package is uploaded on pypi and can be installed using:</p><pre>pip install deeprenewal</pre><p><strong>Recommended Python Version: 3.6</strong></p><p><strong>Source Code:</strong> <a href="https://github.com/manujosephv/deeprenewalprocess">https://github.com/manujosephv/deeprenewalprocess</a></p><p>If you are working Windows and need to use your GPU(which I recommend), you need to first install MXNet==1.6.0 version which supports GPU <a href="https://mxnet.apache.org/versions/1.6.0/get_started?platform=windows&amp;language=python&amp;processor=gpu&amp;environ=pip&amp;">MXNet Official Installation Page</a></p><p>And if you are facing difficulties installing the GPU version, you can try(depending on the CUDA version you have)</p><pre>pip install mxnet-cu101==1.6.0 -f <a href="https://dist.mxnet.io/python/all">https://dist.mxnet.io/python/all</a></pre><p>Relevant <a href="https://github.com/apache/incubator-mxnet/issues/17719">Github Issue</a></p><h3>Usage</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31c95f71a9ad6b8f3e4dd10072132c35/href">https://medium.com/media/31c95f71a9ad6b8f3e4dd10072132c35/href</a></iframe><p>There is also a notebook in examples folder which shows how to use the model. Relevant Excerpt is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/708949173c3bedd51f441ea1be983030/href">https://medium.com/media/708949173c3bedd51f441ea1be983030/href</a></iframe><h3>Experiment and Results from the Paper</h3><p>The paper evaluates the model on two datasets — Parts dataset and UCI Retail Dataset. And for evaluation of the probabilistic forecast, they use Quantile Loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*mGCOYrPhEGA9xgZN" /></figure><p>The authors used a single hidden layer with 10 hidden units and used the softplus activation to map the LSTM embedding to distribution parameters. They have used a global RNN, i.e. LSTM parameters are shared across all the timeseries. And they evaluated the one-step ahead forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*q3oYAN67_SK5wEx2" /></figure><h3>Our Experiments and Contribution</h3><h3>Experiment Setup</h3><p>We did not recreate the experiment, rather expanded the scope. The dataset chosen was the UCI Retail Dataset, and instead of one step ahead forecast, we took 39 days ahead forecast. This is more in line with a real world application where you need more than one-step ahead forecast to plan. And instead of just comparing with Croston and its variants, we do the comparison also with ARIMA, ETS, NPTS, and Deep AR (which is mentioned as the next steps in the paper).</p><h3>Dataset</h3><p><a href="https://archive.ics.uci.edu/ml/datasets/online+retail">UCI Retail dataset</a> is a transactional data set which contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered non-store online retail. The company mainly sells unique all-occasion gifts. Many customers of the company are wholesalers.</p><p><strong>Columns:</strong></p><ul><li><em>InvoiceNo</em>: Invoice number. Nominal, a 6-digit integral number uniquely assigned to each transaction. If this code starts with letter ‘c’, it indicates a cancellation.</li><li><em>StockCode</em>: Product (item) code. Nominal, a 5-digit integral number uniquely assigned to each distinct product.</li><li><em>Description</em>: Product (item) name. Nominal.</li><li><em>Quantity</em>: The quantities of each product (item) per transaction. Numeric.</li><li><em>InvoiceDate</em>: Invice Date and time. Numeric, the day and time when each transaction was generated.</li><li><em>UnitPrice</em>: Unit price. Numeric, Product price per unit in sterling.</li><li><em>CustomerID</em>: Customer number. Nominal, a 5-digit integral number uniquely assigned to each customer.</li><li><em>Country</em>: Country name. Nominal, the name of the country where each customer resides.</li></ul><p><strong>Preprocessing:</strong></p><ul><li>Group by at <em>StockCode</em>, <em>Country</em>, <em>InvoiceDate </em>-&gt; Sum of <em>Quantity</em>, and Mean of <em>UnitPrice</em></li><li>Filled in zeros to make timeseries continuous</li><li>Clip lower value of Quantity to 0(removing negatives)</li><li>Took only Time series which had length greater than 52 days.</li><li>Train Test Split Date: <em>2011–11–01</em></li></ul><p><strong>Stats:</strong></p><ul><li># of Timeseries: 3828. After filtering: 3671</li><li>Quantity: Mean = 3.76, Max = 12540, Min = 0, Median = 0</li></ul><p><strong>Time Series Segmentation</strong></p><p>Using the same segmentation — Intermittent, Lumpy, Smooth and Erratic- we discussed earlier, I’ve divided the dataset into four.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*DRYNI1nj_BRycSdN" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H8Cz0Fv2MXYcEQuP" /><figcaption>Image by Author</figcaption></figure><p>We can see that almost 98% of the timeseries in the dataset are either Intermittent or Lumpy, which is perfect for our use case.</p><h3>Results</h3><h4>Baseline Comparison</h4><p>The baseline we have chosen, as the paper, is Croston Forecast. We have also added slight modification to Croston, namely SBA and SBJ. So let’s first do a comparison against these baselines, for both one-step ahead and n-step ahead forecasts. We will also evaluate both point forecast(using MSE, MAPE, and MAAPE) and probabilistic forecast (using Quantile Loss)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*njivAD157y1tpYAM" /><figcaption>1 Step Ahead Point Estimates(Median)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/0*UrpHPSoqA6u1Vhon" /><figcaption>1 Step Ahead Probabilistic Forecast</figcaption></figure><p>We can see that the DRP models have considerably outperformed the baseline methods across both point as well as probabilistic forecasts.</p><p>Now let’s take a look at n-step ahead forecasts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*pK1UBZZJk84SfqRR" /><figcaption>N Step Ahead Point Estimates(Median)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*MBzdfzUO3iNLQbGm" /><figcaption>N Step Ahead Probabilistic Forecast</figcaption></figure><p>Here, we see a different picture. On the point forecasts, Croston is doing much better on MSE. DRPs are doing well on MAPE, but we know that MAPE favors under forecasting and not very reliable when we look at intermittent demand pattern. So from a point forecast standpoint, I wouldn’t say that DRPs outperformed Croston on long term forecast. What we do notice is that within the DRPs, the Hybrid decoding is working much better than flat decoding, in both MAPE and MSE.</p><h4>Extended Comparison</h4><p>For an extended comparison of the results, let’s also include results from other popular forecasting techniques as well. We have added ETS and ARIMA from the point estimation stable and DeepAR and NPTS from the probabilistic forecast stable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*s0oqTILhr1bpuGUF" /><figcaption>1 Step Ahead Point Estimates(Median)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/0*vzDcrjgv1KHEy9B3" /><figcaption>1 Step Ahead Probabilistic Forecast</figcaption></figure><p>On MSE, ETS takes the top spot, even though on MAPE and MAAPE DRPs retain their position. On the probabilistic forecast side, DeepAR has extraordinarily high Quantile losses, but when we look at a weighted Quantile Loss(weighted by volume) we see it emerging in the top position. This may be because DeepAR forecasting zero(or close to zero) in most of the time and only forecasting good numbers in high volume SKUs. Across all the three Quantile Losses, NPTS seems to be outperforming DRPs by a small margin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*tdhfR5Pn0tGK9Z7M" /><figcaption>N Step Ahead Point Estimates(Median)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*eiyhqhRDxMhNQYnN" /><figcaption>N Step Ahead Probabilistic Forecast</figcaption></figure><p>When we look at a long term forecast, we see that ARIMA and ETS is doing considerably better on the point estimates(MSE). And on the Probabilistic side, Deep AR turned it around and managed to become the best probabilistic model.</p><h4>A few example Forecasts</h4><p><strong>Intermittent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*uTOF1gxzj_PD2BBq" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*MlX1CphyEiDjyhCH" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*j8mvgeRYXrU2GfQG" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*JonH4iYl57z8UXev" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*sCtMgceuA5Dts6iB" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*Y2yMh1xEBvWVGKWH" /><figcaption>Image by Author</figcaption></figure><p><strong>Stable (less Intermittent)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*_msgyBUyNozDj7iP" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*h6ejS5D4-EvljkRb" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*svWFnisFqOiCeIhA" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*pXYKuPd2YyLYeFA9" /><figcaption>Image by Author</figcaption></figure><h3>References</h3><ol><li>Ali Caner Turkmen, Yuyang Wang, Tim Januschowski. <a href="https://arxiv.org/pdf/1911.10416.pdf">“Intermittent Demand Forecasting with Deep Renewal Processes”</a>. arXiv:1911.10416 [cs.LG] (2019)</li><li><a href="https://www.statisticshowto.com/contact/"><strong>Stephanie Glen</strong></a>. “Negative Binomial Experiment / Distribution: Definition, Examples” From <a href="https://www.statisticshowto.com/"><strong>StatisticsHowTo.com</strong></a>: Elementary Statistics for the rest of us! <a href="https://www.statisticshowto.com/negative-binomial-experiment/">https://www.statisticshowto.com/negative-binomial-experiment/</a></li></ol><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2020/10/13/intermittent-demand-forecasting-with-deep-renewal-processes/"><em>http://deep-and-shallow.com</em></a><em> on October 13, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f152d3f59f35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/intermittent-demand-forecasting-with-deep-renewal-processes-f152d3f59f35">Intermittent Demand Forecasting with Deep Renewal Processes</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[Forecast Error Measures: Intermittent Demand]]></title>
            <link>https://medium.com/data-science/forecast-error-measures-intermittent-demand-22617a733c9e?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/22617a733c9e</guid>
            <category><![CDATA[timeseries-forecasting]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Wed, 07 Oct 2020 12:35:10 GMT</pubDate>
            <atom:updated>2020-10-08T13:17:36.924Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous few blog posts, we’ve seen all the popular forecast measures used in practice. But all of them were really focused on smooth and steady time series. But there is a whole different breed of time series in real life — intermittent and lumpy demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jv_Rv35n0IopJLzZhK9OyQ.png" /><figcaption>Image by author</figcaption></figure><p>Casually, we call intermittent series as series with a lot of periods with no demand, i.e. sporadic demand. Syntetos and Boylan(2005) proposed a more formal way of categorizing time series. They used wo parameters of the time series for this classification — Average Demand Interval and Square of Coefficient of Variation.</p><p>Average Demand Interval is the average interval in time periods between two non-zero demand. i.e. if the ADI for a time series is 1.9, it means that on an average we see a non-zero demand every 1.9 time periods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/0*m6BHQOzBghN_n4AH" /></figure><p>ADI is a measure of intermittency; the higher it is, the ore intermittent the series is.</p><p>Coefficient of Variation is the standardized standard deviation. We calculate the standard deviation, but then scale it with the mean of the series to guard against scale dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*MCTajvD3_Qcg0bkm" /></figure><p>This shows the variability of a time series. If COV² is high, that means that the variability in the series is also high.</p><p>Based on these two demand characteristics, Syntetos and Boylan has theoretically derived cutoff values which defines a marked change in the type of behaviour. They have defined intermittency cutoff as 1.32 and COV² cutoff as 0.49. Using these cutoffs, they defined highs and lows and then putting both together a grid which classifies timeseries into Smooth, Erratic, Intermittent, and Lumpy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*BOX36Sfmk6VCvb_9.png" /><figcaption><a href="https://blog.griddynamics.com/safety-stock-optimization-for-ship-from-store/">Source</a></figcaption></figure><p>The Forecast measures we have discussed was all, predominantly, designed to handle Smooth and Erratic timeseries. But in the real world, there are a lot more Intermittent and Lumpy timeseries. Typical examples are Spare Parts sales, Long tail of Retail Sales, etc.</p><h3>Unsuitability of Traditional Error Measures</h3><p>The single defining characteristic of Intermittent and Lumpy series are the number of times there are zero demand. And this wreaks havoc with a lot of the measures we have seen so far. All the percent errors(for eg. <strong>MAPE</strong>) become unstable because of the division by zero, which now is an almost certainty. Similarly, the Relative Errors(for eg. <strong>MRAE</strong>), where we use a reference forecast to scale the errors, also becomes unstable, especially when using Naïve Forecast as a reference. This happens because there would be multiple periods with zero demand, and that would create zero reference error and hence undefined.</p><p><strong>sMAPE</strong> is designed against this division with zero, but even there sMAPE has problems when the number of zero demands increase. And we know from our previous explorations that sMAPE has problems when either forecast is much higher than actuals or vice versa. And in case of intermittent demand, such cases are galore. If there is zero demand and we have forecasted something, or the other way around, we have such a situation. For eg. for a zero demand, one method forecasts 1 and another forecasts 10, the outcome is 200% regardless.</p><h3>New and Recommended Error Measures</h3><p><strong>Cumulative Forecast Error</strong> <strong>(CFE, CFE Min, CFE Max)</strong></p><p>We have already seen Cumulative Forecast Error( a.k.a. Forecast Bias) earlier. It is just the signed error over the entire horizon, so that the negative and positive errors cancel out each other. This has direct implications to over or under stocking in a Supply Chain. Peter Wallstrom[1] also advocates the use of CFE Max and CFE Min. A CFE of zero can happen because of chance as well and over a large horizon, we miss out on a lot of detail in between. so he proposes to look at CFE in conjunction with CFE Max and CFE Min, which are the maximum and the minimum values of CFE in the horizon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/0*TmKRC4FydzSAZOmH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/0*XL1hxNlPoL2B8NFX" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/0*csEpQ9gePo4T53-N" /></figure><p><strong>Percent Better(PBMAE, PBRMSE, etc.)</strong></p><p>We have already seen Percent Better. This is also a pretty decent measure to use for Intermittent demand. This does not have the problem of numerical instability and is defined everywhere. But it does not measure the magnitude of errors, rather than the count of errors.</p><p><strong>Number of Shortages (NOS and NOSp)</strong></p><p>Generally, to trace whether a forecast is biased or not, we use tracking signal(which is CFE/MAD). But the limits that are set to trigger warnings(+/- 4) is derived on the assumption that the demand is normally distributed. In the case of intermittent demand, it is not normally distributed and because of that this trigger calls out a lot of false positives.</p><p>Another alternative to this is the Number of Shortages measure, more commonly represented as Percentage of Number of Shortages. It just counts the number of instances where forecast was lower than demand, resulting in a shortage. A very high number or a low number indicated bias in either direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*8rN7h1j-DrqWcMR6" /></figure><p><strong>Periods in Stock (PIS)</strong></p><p>NOS does not identify systematic errors because it doesn’t consider the temporal dimension of stock carry over. PIS goes one step ahead and measures the total number of periods the forecasted items has spent in stock or number of stock out periods.</p><p>To understand how PIS works, let’s take an example.</p><blockquote><em>Let’s say there is a forecast of one unit every day in a three day horizon. In the beginning of the first period the one item is delivered to the fictitious stock (this is a simplification compared to reality). If there has been no demand during the first day, the result is plus one PIS. When a demand occurs, the demand is subtracted from the forecast. A demand of one in period 1 results in zero PIS in period 1 and CFE of -1. If the demand is equal to zero during three periods, PIS in period 3 is equal to plus six. The item from day one has spent three days in stock, the item from the second day have spent two days in stock and the last item has spent one day in stock</em></blockquote><blockquote><em>Excerpt from </em><a href="https://www.diva-portal.org/smash/get/diva2:990519/FULLTEXT01.pdf"><em>Evaluation of Forecasting Techniques and Forecast Errors with a focus on Intermittent Demand</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/0*KwDlZfg0f-tijDle" /><figcaption><a href="https://www.diva-portal.org/smash/get/diva2:990519/FULLTEXT01.pdf">Evaluation of Forecasting Techniques and Forecast Errors with a focus on Intermittent Demand</a></figcaption></figure><p>A positive number indicates over forecast and a negative number shows under forecast of demand. It can easily be calculated as the cumulative sum of the CFE, i.e. the area under the bar chart in the diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/0*Xfee8qyGMhU0EpZF" /></figure><p><strong>Stock-keeping-oriented Prediction Error Costs(SPEC)</strong></p><p>SPEC is a newer metric(Martin et al. 2020[4]) which tries to take the same route as Periods in Stock, but slightly more sophisticated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z1bUbCsJpj0_Jksy" /></figure><p>Although it looks intimidating at first, we can understand it intuitively. The crux of the calculation is handled by two inner min terms — Opportunity cost and Stock Keeping costs. These are the two costs which we need to balance in a Supply Chain from an inventory management perspective.</p><p>The left term measures the opportunity cost which arises from under forecasting. This is the sales which we could have made if there was enough stock. For eg. if the demand was 10 and we only forecasted 5, we have an opportunity loss of 5. Now, let’s suppose we have been forecasting 5 for last three time periods and there were no demand and then a demand of 10 comes in. so we have 15 in stock and we fulfill 10. So here, there is no opportunity cost. And we can also say that an opportunity cost for a time period will not be greater than the demand at that time period. So combining these conditions, we get the first term of the equation, which measures the opportunity cost.</p><p>Using the same logic as before, but inverting it, we can derive the similar equation for Stock Keeping costs(where we over forecast). That is taken care by the right term in the equation.</p><p>SPEC for a timestep. actually, looks at all the previous timesteps, calculates the opportunity costs and stock keeping costs for each timestep, and adds them up to arrive at a single number. At any timestep, there will either be an opportunity cost or a stock keeping cost, which in turn looks at the cumulative forecast and actuals till that timestep.</p><p>And SPEC for a horizon of timeseries forecast is the average across all the timesteps.</p><p>Now there are two terms α1 and α2 which lets us apply different weightages to opportunity costs and stock keeping costs, and depending upon the strategy of the organization we can choose the right kind of weightages. The recommendation is to keep the summation of the weights to 1, and α1 = 0.75 and α2 = 0.25 is a common choice in a retail setting.</p><p>One disadvantage of this is the time complexity. We need nested loops to calculate this metric, which makes it slow to compute.</p><p>The implementation is available here — <a href="https://github.com/DominikMartin/spec_metric">https://github.com/DominikMartin/spec_metric</a></p><p><strong>Mean Arctangent Absolute Percent Error (MAAPE)</strong></p><p>This is a clever trick on the MAPE formula which avoids one of the main problems with it — undefined at zero. And while addressing this concern, this change also makes it symmetric.</p><p>the idea is simple. We know that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*fkGEAzLVaIIiI0Ms" /></figure><p>So, if we consider a triangle, with adjacent and opposite sides equal to A and |A-F| respectively, the Absolute Percent Error is nothing by the slope of the hypotenuse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*_0rimemi63zn5IC4" /><figcaption><a href="https://www.sciencedirect.com/science/article/pii/S0169207016000121">A new metric of absolute percentage error for intermittent demand forecasts</a></figcaption></figure><p>Slope can be measured as a ratio, ranging from 0 to infinity, and also as an angle, ranging from 0 to 90. The slope as a ratio is the traditional Absolute Percent Error that is quite popular. So the paper presents slope as an angle as a stable alternative. Those of you who remember your Trigonometry would remember that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/0*fF1UTnLweXQLoqAm" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*vlh0G4cmrowbpL4k" /></figure><p>The paper christens it as Arctangent Absolute Percent Error and defines Mean Arctangent Absolute Error as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/0*fu5tD9eKv4vhw8N1" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/0*S5yicltK9ZLRewM3" /></figure><p>arctan is defined at all real values from negative infinity to infinity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/0*dxSJEv_pLgaimvYD" /></figure><p>So by extension, while APE ranges from [0,∞], AAPE ranges from [0, π/2]. This makes it defined everywhere and robust that way.</p><p>The symmetricity test we saw earlier gives us the below results(from the paper)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*880CKXwTZnFlpt7w" /><figcaption><a href="https://www.sciencedirect.com/science/article/pii/S0169207016000121">A new metric of absolute percentage error for intermittent demand forecasts</a></figcaption></figure><p>We can see that the asymmetry that we saw in APE is not as evident here. The complementary plots that we saw earlier, if we compare AAPE to APE, we see it in a much better shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dOnM9Mtg4996r9Ha" /><figcaption><a href="https://www.sciencedirect.com/science/article/pii/S0169207016000121">A new metric of absolute percentage error for intermittent demand forecasts</a></figcaption></figure><p>We can see that AAPE still favours under forecasting, but not as much as APE and for that reason might be more useful.</p><p><strong>Relative Mean Absolute Error &amp; Relative Mean Squared Error (RelMAE &amp; RelMSE)</strong></p><p>There are relative measures which compare the error of the forecast with the error of a reference forecast, in most use cases a naïve forecast or more formally a random walk forecast.</p><p><strong>Scaled Error(MASE)</strong></p><p>We’ve seen MASE also earlier and know how it’s defined. We scale the error by the average MAE of the reference forecast. Davidenko and Fildes, 2013[3], have shows that the MASE is nothing but a weighted mean of Relative MAE, the weights being the number of error terms. This means that include both MASE and RelMAE may be redundant. But let’s check them out anyways.</p><h3>Experiment</h3><p>Let’s pick a real dataset, run ARIMA, ETS, and Crostons, with Zero Forecast as a baseline and calculate all these measures(using GluonTS).</p><h3>Dataset</h3><p>I’ve chosen the <a href="https://archive.ics.uci.edu/ml/datasets/online+retail">Retail Dataset</a> from UCI Machine Learning Repository. It is a transnational data set which contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered non-store online retail. The company mainly sells unique all-occasion gifts. Many customers of the company are wholesalers.</p><p><strong>Columns:</strong></p><ul><li><em>InvoiceNo</em>: Invoice number. Nominal, a 6-digit integral number uniquely assigned to each transaction. If this code starts with letter ‘c’, it indicates a cancellation.</li><li><em>StockCode</em>: Product (item) code. Nominal, a 5-digit integral number uniquely assigned to each distinct product.</li><li><em>Description</em>: Product (item) name. Nominal.</li><li><em>Quantity</em>: The quantities of each product (item) per transaction. Numeric.</li><li><em>InvoiceDate</em>: Invice Date and time. Numeric, the day and time when each transaction was generated.</li><li><em>UnitPrice</em>: Unit price. Numeric, Product price per unit in sterling.</li><li><em>CustomerID</em>: Customer number. Nominal, a 5-digit integral number uniquely assigned to each customer.</li><li><em>Country</em>: Country name. Nominal, the name of the country where each customer resides.</li></ul><p><strong>Preprocessing:</strong></p><ul><li>Group by at <em>StockCode</em>, <em>Country</em>, <em>InvoiceDate </em>-&gt; Sum of <em>Quantity</em>, and Mean of <em>UnitPrice</em></li><li>Filled in zeros to make timeseries continuous</li><li>Clip lower value of Quantity to 0(removing negatives)</li><li>Took only Time series which had length greater than 52 days.</li><li>Train Test Split Date: <em>2011–11–01</em></li></ul><p><strong>Stats:</strong></p><ul><li># of Timeseries: 3828. After filtering: 3671</li><li>Quantity: Mean = 3.76, Max = 12540, Min = 0, Median = 0</li></ul><p><strong>Time Series Segmentation</strong></p><p>Using the same segmentation — Intermittent, Lumpy, Smooth and Erratic- we discussed earlier, I’ve divided the dataset into four.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*TM-gO0h9_j2k6Aez" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7oK1uCnBuE7e98SG" /><figcaption>Image by author</figcaption></figure><p>We can see that almost 98% of the timeseries in the dataset are either Intermittent or Lumpy, which is perfect for our use case.</p><h3>Results</h3><h4>Forecast Method Ranking for each Metric</h4><p>We have included Zero Forecast as kind of a litmus test which will tell us which forecast metrics we should be wary of when using it with Intermittent Demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2pUVQH8HeH7FD2xX" /><figcaption>Image by author</figcaption></figure><p>We can see sMAPE, RelMAE, MAE, MAPE, MASE and ND(which is the volume weighted MAPE), all favors zero forecast and ranks it the best forecasting method. But when we look at the inventory related metrics(like CFE, PIS etc. which measure systematic bias in the forecast), Zero Forecast is the worst performing.</p><p>MASE, which was supposed to perform better in Intermittent Demand also falls flat and rates the Zero Forecast the best. The danger with choosing a forecasting methodology based on these measures is that we end up forecasting way loo low and that will wreak havoc in the downstream planning tasks.</p><p>Surprisingly, ETS and ARIMA fares quite well(over Croston) and ranks 1st and 2nd when we look at the metrics like PIS, MSE, CFE, NOSp etc.</p><p>Croston fares well only when we look at MAAPE, MRAE, and CFE_min.</p><h4>Rank Correlation (Aggregate)</h4><p>We have ranked the different forecast methods based on all these different metrics. And if a set of metrics are measuring the same thing, then these rankings would also show good correlation. So let’s calculate the Spearman’s Rank correlation for these ranks and see which metrics agree with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*-bvfJvB6Eb5P7s3L" /><figcaption>Image by author</figcaption></figure><p>We can see two large groups of metrics which are positively correlated among each other and negatively correlated between groups. MAE, MRAE, MASE, MAPE, RelMAPE, ND, and sMAPE falls into a group and MSE, RMSE, CFE, PIS, SPEC_0.75, SPEC_0.5, SPEC_0.25, NOSp, PBMAE, RelRMSE, and NRMSE in the other. MAAPE and CFE_min fall into the second group as well, but lightly correlated.</p><p>Are these two groups measuring different characteristics of the forecast?</p><h4>Ranking Correlation(Item Level)</h4><p>Let’s look at the same agreement between metrics at an item level now, instead of the aggregate one. For eg. for each item that we are forecasting we rank the forecasting methods based on these different metrics and run a Spearman’s Rank Correlation on those ranks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*FjhbNNLTX0O4DNta" /><figcaption>Image by author</figcaption></figure><p>Similar to the aggregate level view, here also we can find two groups of metrics, but contrary to the aggregate level, we cannot find a strong negative correlation across two groups. SPEC_0.5(where we give equal weightage to both opportunity cost and stock keeping cost) and PIS shows a high correlation, mostly because it is conceptually the same.</p><h4>Loading Plots</h4><p>Another way to visualize and understand the similarity of different metrics is to use the item level metrics and run a PCA with two dimensions. And plot the direction of the original features which point towards the two components we have extracted using PCA. It shows how the original variables contribute to creating the principal component. So if we assume the two PCA components are the main “attributes” that we measure when we talk about “accuracy” of a forecast, the Loading Plot shows you how these different features(metrics) contribute to it, both magnitude and direction wise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LY6rAV3iIieZlaqB" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-sm0REIRoU-u7F4T" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HIOlCuBo5UbIhOZc" /><figcaption>Image by author</figcaption></figure><p>Here, we can see the relationship more crystalized. Most of the metrics are clustered together around the two components. MAE, MSE, RMSE, CFE, CFE_max, and the SPEC metrics all occupy similar space in the loading plot, and it looks like it is the component for “forecast bias” as CFE and SPEC metrics dominate this component. PIS is on the other side, almost at 180 degrees to CFE, because of the sign of PIS.</p><p>The other component might be the “accuracy” component. This is dominated by RelRMSE, MASE, MAAPE, MRAE etc. MAPE seems to straddle between the two components, and so is MAAPE.</p><p>We can also see that sMAPE might be measuring something totally different, like NOSp and CFE_min.</p><p>PIS is at a 180 degrees from CFE, SPEC_0.5, and SPEC_0.75 because of the sign, but they are measuring the same thing. SPEC_0.25(where we give 0.25 weight to opportunity cost) shows more similarity to the other group, probably because it favors under forecasting because of the heavy penalty on stock keeping costs.</p><h3>Conclusion and Recommendations</h3><p>We’ve not done a lot of experiments in this short blog post(not as much as Peter Wallström’s thesis[1]), but whatever we have done have shown us quite a bit already. We know not to rely on metrics like sMAPE, RelMAE, MAE, MAPE, MASE because they were giving a zero forecast the best ranking. We also know that there is no single metric that would tell you the whole story. If we look at something like MAPE, we are not measuring the structural bias in the forecast. And if we just look at CFE, it might show a rosy picture, when it is not the case.</p><p>Let me quickly summarize the findings from Peter Wallström’s thesis(along with a few of my own conclusions.</p><ul><li>MSE and CFE, even though it appears in the same place in the loading plots, does not show that relationship consistently across different forecasting methods. The same we can see in our loading plots as well. CFE is away from the second component for Croston and ETS.</li><li>MAE and MSE are strongly related and they measure the same variability. And since MAE has shown an affinity to zero forecast, it is preferable to use MSE based error metrics.</li><li>CFE on its own is not very reliable to measure Forecast Bias. And it should be paired with metrics like PIS or SPEC to have a complete picture. CFE can conceal the bias tendency when a time in point is considered. If the CFE value is low in absolute terms the sign do not reveal any bias information. A positive CFE (underestimating) might just be a random figure for a method that is overestimating the demand when the other measures are checked. The low CFE is the result of fulfilling the demand afterwards the demand has occurred which is not traceable by CFE.</li><li>Peter also recommends not to use CFE_max and CFE_min in favor of metrics like PIS and NOSp.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*SSXqnsSpLrAUSmL5" /><figcaption><a href="https://www.diva-portal.org/smash/get/diva2:990519/FULLTEXT01.pdf">Evaluation of Forecasting Techniques and Forecast Errors with a focus on Intermittent Demand</a></figcaption></figure><ul><li>Apart from these, SPEC scores and MAAPE(which were not reviewed in the thesis) are also suitable measures.</li></ul><p>GitHub Repository — <a href="https://github.com/manujosephv/forecast_metrics">https://github.com/manujosephv/forecast_metrics</a></p><p><strong>Checkout the rest of the articles in the series</strong></p><ol><li><a href="https://deep-and-shallow.com/2020/09/26/forecast-error-measures-understanding-them-through-experiments/">Forecast Error Measures: Understanding them through experiments</a></li><li><a href="https://deep-and-shallow.com/2020/10/01/forecast-error-measures-scaled-relative-and-other-errors/">Forecast Error Measures: Scaled, Relative, and other Errors</a></li><li><a href="https://deep-and-shallow.com/2020/10/07/forecast-error-measures-intermittent-demand/">Forecast Error Measures: Intermittent Demand</a></li></ol><h3>References</h3><ol><li>Peter Wallström, 2009, <a href="https://www.diva-portal.org/smash/get/diva2:990519/FULLTEXT01.pdf">Evaluation of Forecasting Techniques and Forecast Errors with a focus on Intermittent Demand</a></li><li>Kim et al., 2016. <a href="https://www.sciencedirect.com/science/article/pii/S0169207016000121">A new metric of absolute percentage error for intermittent demand forecasts</a></li><li>Davidenko &amp; Fildes. 2013, <a href="https://www.sciencedirect.com/science/article/abs/pii/S0169207012001161?via%3Dihub">Measuring Forecast Accuracy: The Case Of Judgmental Adjustments To Sku-Level Demand Forecasts</a></li><li>Martin et al. 2013, <a href="https://arxiv.org/pdf/2004.10537.pdf">A New Metric for Lumpy and Intermittent Demand Forecasts: Stock-keeping-oriented Prediction Error Costs</a></li><li>Hyndman, R.J., &amp; Athanasopoulos, G. (2018) <em>Forecasting: principles and practice</em>, 2nd edition, OTexts: Melbourne, Australia. OTexts.com/fpp2. Accessed on 07–10–2020</li></ol><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2020/10/07/forecast-error-measures-intermittent-demand/"><em>http://deep-and-shallow.com</em></a><em> on October 7, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22617a733c9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/forecast-error-measures-intermittent-demand-22617a733c9e">Forecast Error Measures: Intermittent 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>
        <item>
            <title><![CDATA[Forecast Error Measures: Scaled, Relative, and other Errors]]></title>
            <link>https://medium.com/data-science/forecast-error-measures-scaled-relative-and-other-errors-c0645f794352?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0645f794352</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 01:49:15 GMT</pubDate>
            <atom:updated>2020-10-04T00:57:49.267Z</atom:updated>
            <content:encoded><![CDATA[<h4>Following through from my previous blog about the standard Absolute, Squared and Percent Errors, let’s take a look at the alternatives — Scaled, Relative and other Error measures for Time Series Forecasting.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*udtWmDuPWiIkovvP" /></figure><p>Both Scaled Error and Relative Error are extrinsic error measures. They depend on another reference forecast to evaluate itself, and more often than not, in practice, the reference forecast is a Naïve Forecast or a Seasonal Naïve Forecast. In addition to these errors, we will also look at measures like Percent better, cumulative Forecast Error, Tracking Signal etc.</p><h3>Relative Error</h3><p>When we say Relative Error, there are two main ways of calculating it and Shcherbakov et al. calls them Relative Errors and Relative Measures.</p><p>Relative Error is when we use the forecast from a reference model as a base to compare the errors and Relative Measures is when we use some forecast measure from a reference base model to calculate the errors.</p><p>Relative Error is calculated as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/54/0*dabvKe4uFzH_R2un" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*9prsS-U2aLML5ag9" /></figure><p>Similarly Relative Measures are calculated as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/51/0*t8m1RhlYTKK5hUtN" /></figure><p>where MAE is the Mean Absolute Error on the forecast and MAE* is the MAE of the reference forecast. This measure can be anything really, and not just MAE.</p><p>Relative Error is based on a reference forecast, although most commonly we use Naïve Forecast, not necessarily all the time. For instance, we can use the Relative measures if we have an existing forecast we are trying to better, or we can use the baseline forecast we define during the development cycle, etc.</p><p>One disadvantage we can see right away is that it will be undefined when the reference forecast is equal to ground truth. And this can be the case for either very stable time series or intermittent ones where we can have the same ground truth repeated, which makes the naïve forecast equal to the ground truth.</p><h3>Scaled Error</h3><p>Scaler Error was proposed by Hyndman and Koehler in 2006. They proposed to scale the errors based on the in-sample MAE from the naïve forecasting method. So instead of using the ground truth from the previous timestep as the scaling factor, we use the average absolute error across the entire series as the scaling factor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*DrGf_EzGmPIpBXV8" /></figure><p>where e is the error at timestep t, n is the length of the timeseries, a is the ground truth at timestep t, and l is the offset. l is 1 for naïve forecasting. Another alternative that is popularly used is l = seasonal period . For eg. l=12, for a seasonality of 12 months.</p><p>Here in-sample MAE is chosen because it is always available and more reliable to estimate the scale as opposed to the out of sample ones.</p><h3>Experiments</h3><p>In our previous blog, we checked Scale Dependency, Symmetricity, Loss Curves, Over and under Forecasting and Impact of outliers. But this time, we are dealing with relative errors. And therefore plotting loss curves are not easy anymore because there are three inputs, ground truth, forecast, and reference forecast and the value of the measure can vary with each of these. Over and Under Forecasting and Impact of Outliers we can still check.</p><h3>Loss Curves</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*UPZ6GzanIB-AZBxM" /></figure><p>The loss curves are plotted as a contour map to accommodate the three dimensions — Error, Reference Forecast and the measure value.</p><p>We can see that the errors are symmetric around the Error axis. If we keep the Reference Forecast constant and vary the error, the measures are symmetric on both sides of the errors. Not surprising since all these errors have their base in absolute error, which we saw was symmetric.</p><p>But the interesting thing here is the dependency on the reference forecast. The same error lead to different Relative Absolute Error values depending on the Reference Forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*hqRMwJ_Kt8pVJZWv" /></figure><p>We can see the same asymmetry in the 3D plot of the curve as well. But Scaled Error is different here because it is not directly dependent on the Reference Forecast, but rather on the mean absolute error of the reference forecast. And therefore it has the good symmetry of absolute error and very little dependency on the reference forecast.</p><h3>Over and Under Forecasting</h3><p>For the Over and Under Forecasting experiment, we repeated the same setup from last time<em>*</em>, but for these four error measures — Mean Relative Absolute Error(MRAE), Mean Absolute Scaled Error(MASE), Relative Mean Absolute Error(RMAE), and Relative Root Mean Squared Error(RRMSE)</p><p><em>* — With one small change, because we also add a random noise less than 1 to make sure consecutive actuals are not the same. In such cases the Relative Measures are undefined.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w97bJur5nd-v1uJm" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DdE9MizUB88LQSWH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U5NH3CMYvGvLzfYi" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y6tQbXGIRxes5X5e" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iNXf3UC6mxL4gbP5" /></figure><p>We can see that these scaled and relative errors do not have that problem of favoring over or under forecasting. Both the error bars of low forecast and high forecast are equally bad. Even in cases where the base error was favoring one of these,(for eg. MAPE), the relative error measure(RMAPE) reduces that “favor” and makes the error measure more robust.</p><p>One other thing we notice is that the Mean Relative Error has a huge spread(I’ve actually zoomed in to make the plot legible). For eg. The median <em>baseline_rmae </em>is 2.79 and the maximum <em>baseline_mrae </em>is 42k. This large spread shows us that the Mean Absolute Relative Error has low reliability. Depending on different samples, the errors vary wildly. this may be partly because of the way we use the Reference Forecast. If the Ground Truth is too close to Reference Forecast(in this case the Naïve Forecast), the errors are going to be much higher. This disadvantage is partly resolved by using Median Relative Absolute Error(MdRAE)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FdpuhEA-hhL-z3u9" /></figure><h3>Outlier Impact</h3><p>For checking the outlier impact also, we repeated the same experiment from previous blog post for MRAE, MASE, RMAE, and RRMSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*Ev031YGujTCoA-gh" /></figure><h3>Other Errors</h3><p>Apart from these standard error measures, there are a few more tailored to tackle a few aspects of the forecast which is not properly covered by the measures we have seen so far.</p><h3>Percent Better</h3><p>Out of all the measures we’ve seen so far, only MAPE is what I would call interpretable for non-technical folks. But as we saw, MAPE does not have the best of properties. All the other measures does not intuitively expound how good or bad the forecast is. Percent Better is another attempt at getting that kind of interpretability.</p><p>Percent Better(PB) also relies on a reference forecast and measures our forecast by counting the number of instances where our forecast error measure was better than reference forecast error.</p><p>For eg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/0*jtmMyiER397RZHbf" /></figure><p>where I = 0 when MAE&gt;MAE* and 1 when MAE&lt;MAE*, and N is the number of instances.</p><p>Similarly, we can extend this to any other error measure. This gives us an intuitive understand of how better are we doing as compared to reference forecast. This is also pretty resistant to outliers because it only counts the instances instead of measuring or quantifying the error.</p><p>That is also a key disadvantage. We are only measuring the count of the times we are better. But it doesn’t measure how better or how worse we are doing. If our error is 50% less than reference error or 1% less, the impact of that on the Percent better score is the same.</p><h3>Normalized RMSE (nRMSE)</h3><p>Normalized RMSE was proposed to neutralize the scale dependency of RMSE. The general idea is to divide RMSE with a scalar, like the maximum value in all the timeseries, or the difference between the maximum or minimum, or the mean value of all the ground truths etc.</p><p>Since dividing by maximum or the difference between maximum and minimum are prone to impact from outliers, popular use of nRMSE is by normalizing with the mean.</p><p>nRMSE =RMSE/ mean (y)</p><h3>Cumulative Forecast Error a.k.a. Forecast Bias</h3><p>All the errors we’ve seen so far focuses on penalizing errors, no matter positive or negative. We use an absolute or squared term to make sure the errors do not cancel each other out and paint a rosier picture than what it is.</p><p>But by doing this, we are also becoming blind to structural problems with the forecast. If we are consistently over forecasting or under forecasting, that is something we should be aware of and take corrective actions. But none of the measures we’ve seen so far looks at this perspective.</p><p>This is where Forecast Bias comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*IB4RaXM8pfPekty_" /></figure><p>Although it looks like the Percent Error formula, the key here is the absence of the absolute term. So without the absolute term, we are cumulating the actuals and forecast and measuring the difference between them as a percentage. This gives an intuitive explanation. If we see a bias of 5%, we can infer that overall, we are under-forecasting by 5%. Depending on whether we use Actuals — forecast or Forecast — Actuals, the interpretation is different, but in spirit the same.</p><p>If we are calculating across timeseries, then also we cumulate the actuals and forecast at whatever cut of the data we are measuring and calculate the Forecast Bias.</p><h3>Summary</h3><p>Let’s add the error measures we saw now to the summary table we made last time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i65JPk7qXqBIlh4t" /></figure><p>Again we see that there is <em>no one ring to rule them all</em>. There may be different choices depending on the situation and we need to pick and choose for specific purposes.</p><h3>Thumb-rules and Guide to choosing a Forecast Metric</h3><p>We have already seen that it is not easy to just pick one forecast metric and use it everywhere. Each of them has its own advantages and disadvantages and our choice should be cognizant of all of those.</p><p>That being said, there are thumb-rules you can apply to help you along the process:</p><ol><li>If every timeseries is on the same scale, use MAE, RMSE etc.</li><li>If there are large changes in the timeseries (i.e. in the horizon we are measuring, there is a huge shift is timeseries levels), then something like a Percent Better or Relative Absolute Error can be used.</li><li>When summarizing across timeseries, for metrics like Percent Better or APE, we can use Arithmetic Means (eg. MAPE). For relative errors, it has been empirically proven that Geometric Means have better properties. But at the same time, they are also vulnerable to outliers. A few ways we can control for outliers are:</li><li>Trimming the outliers or discarding them from the aggregate calculation</li><li>Using the Median for aggregation (MdAPE) is another extreme measure in controlling for outliers.</li><li>Winsorizing (replacing the outliers with the cutoff value) is another way to deal with such huge individual cases of errors.</li></ol><h3>Error Measures for Generalizing About Forecasting Methods: Empirical Comparisons[2]</h3><p>Armstrong et al. 1992, carried out an extensive study on these forecast metrics using the M competition to sample 5 subsamples totaling a set of 90 annual and 101 quarterly series, and its forecast. Then they went ahead and calculation the error measures on this sample and carried out a study to examine them.</p><p>The key dimensions they examined the different measures for were:</p><h4>Reliability</h4><p>Reliability talks about whether repeated application of the measure produce similar results. To measure this, they first calculated the error measures for different forecasting methods on all 5 subsamples(aggregate level), and ranked them in order of performance. They carried out this 1 step ahead and 6 steps ahead for Annual and Quarterly series.</p><p>So they calculated the Spearman’s rank-order correlation coefficients(pairwise) for each subsample and averaged them. e.g. We took the rankings from subsample 1 and compared them with subsample 2, and then subsample 1 with subsample 3, etc., until we covered all the pairs and then averaged them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*TnIhMF0MdXL50l1y" /><figcaption>Source: <a href="https://repository.upenn.edu/marketing_papers/69/">Armstrong et al.</a></figcaption></figure><p>The rankings based on RMSE was the least reliable with very low correlation coefficients. They state that the use of RMSE can overcome this reliability issue only when there is a high number of time series in the mix which might neutralize the effect.</p><p>They also found out that Relative Measures like the Percent Better and MdRAE has much higher reliability than their peers. They also tried to calculate the number of samples required to achieve the same statistical significance as Percent Better — 18 series for GMRAE, 19 using MdRAE, 49 using MAPE, 55 using MdAPE, and 170 using RMSE.</p><h4>Construct Validity</h4><p>While reliability was measuring the consistency, construct validity asks whether a measure does, in fact, measure what it intents to measure. This shows us the extent to which the various measures assess the “accuracy” of forecasting methods. To compare this they examined the rankings of the forecast methods as before, but this time they compared the rankings between pairs of error measures. For eg., how much agreement is there in ranking based on RMSE vs ranking based on MAPE?</p><p>These correlations are influenced by both Construct Validity as well as Reliability. To account for the change in Reliability, the authors derived the same table by using more number of samples and found that as expected the average correlations increased from 0.34 to 0.68 showing that these measures are, in fact, measuring what they are supposed to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*TShks63SBNWtnrgZ" /><figcaption>Source: <a href="https://repository.upenn.edu/marketing_papers/69/">Armstrong et al.</a></figcaption></figure><p>As a final test of validity, they constructed a consensus ranking by averaging the rankings from each of the error measures for the full sample of 90 annual series and 1010 quarterly series and then examined the correlations of each individual error measure ranking with the consensus ranking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/0*x4rwMimbrH5-prTT" /><figcaption>Source: <a href="https://repository.upenn.edu/marketing_papers/69/">Armstrong et al.</a></figcaption></figure><p>RMSE had the lowest correlation with the consensus. This is probably because of the low reliability. It can also be because of RMSE’s emphasis on higher errors.</p><p>Percent Better also shows low correlation(even though it had high reliability). This is probably because Percent better is the only measure which does not measure the magnitude of the error.</p><h4>Sensitivity</h4><p>It is desirable to have error measures which are sensitive to effects of changes, especially for parameter calibration or tuning. The measure should indicate the effect on “accuracy” when a change is made in the parameters of the model.</p><p>Median error measures are not sensitive and neither is Percent Better. Median aggregation hides the change by focusing on the middle value and will only change slowly. Percent Better is not sensitive because once the series is performing better than the reference, it stops making any more change in the metric. It also does not measure if we improve an extremely bad forecast to a point where it is almost as accurate as a naïve forecast.</p><h4>Relationship to Decision Making</h4><p>The paper makes it very clear that none of the measures they evaluated are ideal for decision making. They propose RMSE as a good enough measure and frown upon percent based errors under the argument that actual business impact occurs in dollars and not in percent errors. But I disagree with the point because when we are objectively evaluating a forecast to convey how good or bad it is doing, RMSE just does not make the cut. If I walk up to the top management and say that the financial forecast had an RMSE of 22343 that would fall flat. But instead if I say that the accuracy was 90% everybody is happy.</p><p>Both me and the paper agree on one thing, the relative error measures of not that relevant to decision making.</p><h4>Guidelines for choosing Error Measures</h4><p>To help with selection of errors, the paper also rates the different measures of the dimensions they identified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*fNf6dETvzVZghkaJ" /><figcaption>Source: <a href="https://repository.upenn.edu/marketing_papers/69/">Armstrong et al.</a></figcaption></figure><p><strong>For Parameter Tuning</strong></p><p>For calibration of parameter tuning, the paper suggests to use on of the measures which are rated high in sensitivity, — RMSE, MAPE, and <strong>GMRAE</strong>. And because of the low reliability of RMSE and the favoring low forecast issue of MAPE, they suggest to use GMRAE(Geometric Mean Relative Absolute Error). <strong>MASE </strong>was proposed way after the release of this paper and hence it does not actor in these analysis. But if you think about it MASE is also sensitive and immune to the problems that we see for RMSE or MAPE and can be a good candidate for calibration.</p><p><strong>For Forecast Method Selection</strong></p><p>To select between forecast methods, the primary criteria are reliability, construct validity, protection against outliers, and relationship to decision making. Sensitivity is not that important in this context.</p><p>The paper, right away, dismissed RMSE because of the low reliability and the lack of protection to outliers. When the number of series is low, they suggest MdRAE, which is as reliable as GMRAE, but offers additional protection from outliers.Given a moderate number of series, reliability becomes less of an issue and in such cases MdAPE would be an appropriate choice because of its closer relationship to decision making.</p><h3>Conclusion</h3><p>Over the two blogposts, we’ve seen a lot of forecast measures and understood what are the advantages and disadvantages for each of them. And finally arrived at a few thumb rules to go by when choosing forecast measures. although not conclusive, I hope it gives you a direction when going about these decisions.</p><p>But all this discussion was made under the assumption that the time-series that we are forecasting are stable and smooth. But in real-world business cases, there are also a lot of series which are intermittent or sporadic. We see long periods of zero demand before a non-zero demand. under such cases, almost all of the error measures(with an exception of may be MASE) fails. In the next blog post, let’s take a look at a few different measures which are suited to intermittent demand.</p><p>Github Link for the Experiments: <a href="https://github.com/manujosephv/forecast_metrics">https://github.com/manujosephv/forecast_metrics</a></p><h4><strong>Update(04–10–2020)</strong></h4><p>Upon further reading, stumbled upon a few criticism of MASE as well, and thought I should mention that as well here.</p><ol><li>There is some criticism on the fact that we use the average MAE of the reference forecast as the scaling error term. Davidenko and Fildes(2013)[3] claims that that introduces a bias towards overrating the accuracy of the reference forecast. In other words, the penalty for bad forecasting becomes larger than the reward for good forecasting.</li><li>Another criticism derives from the fact that mean is not a very stable estimate and can be swayed by a couple of large values.</li></ol><p>Another interesting fact that Davidenko and Fildes[3] shows is that MASE is equivalent to the weighted arithmetic mean of relative MAE, where number of available error values is the weight.</p><p><strong>Checkout the rest of the articles in the series</strong></p><ol><li><a href="https://deep-and-shallow.com/2020/09/26/forecast-error-measures-understanding-them-through-experiments/">Forecast Error Measures: Understanding them through experiments</a></li><li><a href="https://deep-and-shallow.com/2020/10/01/forecast-error-measures-scaled-relative-and-other-errors/">Forecast Error Measures: Scaled, Relative, and other Errors</a></li><li>Forecast Error Measures: Intermittent Demand</li></ol><h3>References</h3><ol><li>Shcherbakov et al. 2013, <a href="http://idosi.org/wasj/wasj(ITMIES)13/28.pdf">A Survey of Forecast Error Measures</a></li><li>Armstrong et al. 1992, <a href="https://repository.upenn.edu/cgi/viewcontent.cgi?article=1075&amp;context=marketing_papers">Error Measures for Generalizing About Forecasting Methods: Empirical Comparisons</a></li><li>Davidenko &amp; Fildes. 2013, <a href="https://www.sciencedirect.com/science/article/abs/pii/S0169207012001161?via%3Dihub">Measuring Forecast Accuracy: The Case Of Judgmental Adjustments To Sku-Level Demand Forecasts</a></li></ol><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2020/10/01/forecast-error-measures-scaled-relative-and-other-errors/"><em>http://deep-and-shallow.com</em></a><em> on October 1, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0645f794352" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/forecast-error-measures-scaled-relative-and-other-errors-c0645f794352">Forecast Error Measures: Scaled, Relative, and other Errors</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[Forecast Error Measures: Understanding them through experiments]]></title>
            <link>https://medium.com/data-science/forecast-error-measures-understanding-them-through-experiments-da7ddcb0b035?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/da7ddcb0b035</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[forecast]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 01:36:06 GMT</pubDate>
            <atom:updated>2020-10-01T03:36:16.450Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/getting-started">Getting Started</a></h4><blockquote>Measurement is the first step that leads to control and eventually improvement.</blockquote><blockquote>H. James Harrington</blockquote><p>In many business applications, the ability to plan ahead is paramount and in the majority of such scenarios, we use forecasts to help us plan ahead. For eg., If I run a retail store<em>, how many boxes of that shampoo should I order today?</em> Look at the Forecast. <em>Will I achieve my financial targets by the end of the year?</em> Let’s forecast and make adjustments if necessary. If I run a bike rental firm, <em>how many bikes do I need to keep at a metro station tomorrow at 4pm?</em></p><p>If for all of these scenarios, we are taking actions based on the forecast, we should also have an idea about how good those forecasts are. In classical statistics or machine learning, we have a few general loss functions, like the squared error or the absolute error. But because of the way Time Series Forecasting has evolved, there are a lot more ways to assess your performance.</p><p>In this blog post, let’s explore the different Forecast Error measures through experiments and understand the drawbacks and advantages of each of them.</p><h3>Metrics in Time Series Forecasting</h3><p>There are a few key points which makes the metrics in Time Series Forecasting stand out from the regular metrics in Machine Learning.</p><p>1. Temporal Relevance</p><p>As the name suggests, Time Series Forecasting have the temporal aspect built into it and there are metrics like Cumulative Forecast Error or Forecast Bias which takes this temporal aspect as well.</p><p>2. Aggregate Metrics</p><p>In most business use-cases, we would not be forecasting a single time series, rather a set of time series, related or unrelated. And the higher management would not want to look at each of these time series individually, but rather an aggregate measure which tells them directionally how well we are doing the forecasting job. Even for practitioners, this aggregate measure helps them to get an overall sense of the progress they make in modelling.</p><p>3. Over or Under Forecasting</p><p>Another key aspect in forecasting is the concept of over and under forecasting. We would not want the forecasting model to have structural biases which always over or under forecasts. And to combat these, we would want metrics which doesn’t favor either over-forecasting or under-forecasting.</p><p>4. Interpretability</p><p>The final aspect is interpretability. Because these metrics are also used by non-analytics business functions, it needs to be interpretable.</p><p>Because of these different use cases, there are a lot of metrics that is used in this space and here we try to unify it under some structure and also critically examine them.</p><h3>Taxonomy of Forecast Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7l4dcknJKwVqcEur" /></figure><p>We can classify the different forecast metrics. broadly,. into two buckets — <strong>Intrinsic and Extrinsic</strong>. Intrinsic measures are the measures which just take the generated forecast and ground truth to compute the metric. Extrinsic measures are measures which use an external reference forecast also in addition to the generated forecast and ground truth to compute the metric.</p><p>Let’s stick with the intrinsic measures for now(Extrinsic ones require a whole different take on these metrics). There are four major ways in which we calculate errors — Absolute Error, Squared Error, Percent Error and Symmetric Error. All the metrics that come under these are just different aggregations of these fundamental errors. So, without loss of generality, we can discuss about these broad sections and they would apply to all the metrics under these heads as well.</p><h4>Absolute Error</h4><p>This group of error measurement uses the absolute value of the error as the foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/0*2hFZdoSAk9wOTvam" /></figure><h4>Squared Error</h4><p>Instead of taking the absolute, we square the errors to make it positive, and this is the foundation for these metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*RTOiQXZVWUphQ2EE" /></figure><h4>Percent Error</h4><p>In this group of error measurement, we scale the absolute error by the ground truth to convert it into a percentage term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*hsLvV0VocAO23LGw" /></figure><h4>Symmetric Error</h4><p>Symmetric Error was proposed as an alternative to Percent Error, where we take the average of forecast and ground truth as the base on which to scale the absolute error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*rzbmnttnZS0HNLdY" /></figure><h3>Experiments</h3><p>Instead of just saying that these are the drawbacks and advantages of such and such metrics, let’s design a few experiments and see for ourselves what those advantages and disadvantages are.</p><h3>Scale Dependency</h3><p>In this experiment, we try and figure out the impact of the scale of timeseries in aggregated measures. For this experiment, we</p><ol><li>Generate 10000 synthetic time series at different scales, but with same error.</li><li>Split these series into 10 histogram bins</li><li>Sample Size = 5000; Iterate over each bin</li><li>Sample 50% from current bin and res, equally distributed, from other bins.</li><li>Calculate the aggregate measures on this set of time series</li><li>Record against the bin lower edge</li><li>Plot the aggregate measures against the bin edges.</li></ol><h3>Symmetricity</h3><p>The error measure should be symmetric to the inputs, i.e. Forecast and Ground Truth. If we interchange the forecast and actuals, ideally the error metric should return the same value.</p><p>To test this, let’s make a grid of 0 to 10 for both actuals and forecast and calculate the error metrics on that grid.</p><h3>Complementary Pairs</h3><p>In this experiment, we take complementary pairs of ground truths and forecasts which add up to a constant quantity and measure the performance at each point. Specifically, we use the same setup as we did the Symmetricity experiment, and calculate the points along the cross diagonal where ground truth + forecast always adds up to 10.</p><h3>Loss Curves</h3><p>Our metrics depend on two entities — forecast and ground truth. We can fix one and vary the other one using a symmetric range of errors((for eg. -10 to 10), then we expect the metric to behave the same way on both sides of that range. In our experiment, we chose to fix the Ground Truth because in reality, that is the fixed quantity, and we are measure the forecast against ground truth.</p><h3>Over &amp; Under Forecasting Experiment</h3><p>In this experiment, we generate 4 random time series — ground truth, baseline forecast, low forecast and high forecast. These are just random numbers generated within a range. Ground Truth and Baseline Forecast are random numbers generated between 2 and 4. Low forecast is a random number generated between 0 and 3 and High Forecast is a random number generated between 3 and 6. In this setup, the Baseline Forecast should act as a baseline for us, Low Forecast is a forecast where we continuously under-forecast, and High Forecast is a forecast where we continuously over-forecast. And now let’s calculate the MAPE for these three forecasts and repeat the experiment for 1000 times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*QvQFt80VFjcr9iz-" /></figure><h3>Outlier Impact</h3><p>To check the impact on outliers, we set up the below experiment.</p><p>We want to check the relative impact of outliers on two axes — number of outliers, scale of outliers. So we define a grid — number of outliers [0%-40%] and scale of outliers [0 to 2]. Then we picked a synthetic time series at random, and iteratively introduced outliers according to the parameters of the grid we defined earlier and recorded the error measures.</p><h3>Results and Discussion</h3><h3>Absolute Error</h3><h4>Symmetricity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*5qEpAofYMpGVdRrA" /></figure><p>That’s a nice symmetric heatmap. We see zero errors along the diagonal, and higher errors spanning away from it in a nice symmetric pattern.</p><h4>Loss Curves</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/0*f5lCzOrnHHlyuGsZ" /></figure><p>Again symmetric. MAE varies equally if we go on both sides of the curve.</p><h4>Complementary Pairs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/0*q_l8nJGrZzcYRU2p" /></figure><p>Again good news. If we vary forecast, keeping actuals constant, and vice versa the variation in the metric is also symmetric.</p><h4>Over and Under Forecasting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/0*vaaYstR5wVcaopjA" /></figure><p>As expected, over or under forecasting doesn’t make much of a difference in MAE. Both are equally penalized.</p><h4>Scale Dependency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*HYUrOewKCPvMmgCx" /></figure><p>This is the Achilles heel of MAE. here, as we increase the base level of the time-series, we can see that the MAE increases linearly. This means that when we are comparing performances across timeseries, this is not the measure you want to use. For eg., when comparing two timeseries, one with a level of 5 and another with a level of 100, using MAE would always assign a higher error to the timeseries with level 100. Another example is when you want to compare different sub-sections of your set of timeseries to see where the error is higher(for eg. different product categories, etc.), then using MAE would always tell you that the sub-section which has a higher average sales would also have a higher MAE, but that doesn’t mean that sub-section is not doing well.</p><h3>Squared Error</h3><h4>Symmetricity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*Ghw8PJk6S-f_eMZn" /></figure><p>Squared Error also shows the symmetry we are looking for. But one additional point we can see here is that the errors are skewed towards higher errors. The distribution of color from the diagonal is not as uniform as we saw in Absolute Error. <strong>This is because the squared error(because of the square term), assigns higher impact to higher errors that lower errors. </strong>This is also why Squared Errors are, typically, more prone to distortion due to outliers.</p><p><em>Side Note:</em> Since squared error and absolute error are also used as loss functions in many machine learning algorithms, this also has the implications on the training of such algorithms. If we choose squared error loss, we are less sensitive to smaller errors and more to higher ones. And if we choose absolute error, we penalize higher and lower errors equally and therefore a single outlier will not influence the total loss that much.</p><h4>Loss Curves</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/0*6KSGw_3UiXz024B7" /></figure><p>We can see the same pattern here as well. It is symmetric around the origin, but because of the quadratic form, higher errors are having disproportionately more error as compared to lower ones.</p><h4>Complementary Pairs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*JDJVDIE0dEbuyiZk" /></figure><h4>Over and Under Forecasting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/0*MGfiuUcA2adkCEMu" /></figure><p>Similar to MAE, because of the symmetry, Over and Under Forecasting has pretty much the same impact.</p><h4>Scale Dependency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/0*rm9j1EiBxhWz3jfW" /></figure><p>Similar to MAE, RMSE also has the scale dependency problem, which means that all the disadvantages we discussed for MAE, applied here as well, but worse. We can see that RMSE scales quadratically when we increase the scale.</p><h3>Percent Error</h3><p>Percent Error is <strong>the</strong> most popular error measure used in the industry. A couple of reasons why it is hugely popular are:</p><ol><li>Scale Independent — As we saw in the scale dependency plots earlier, the MAPE line is flat as we increase the scale of the timeseries.</li><li>Interpretability — Since the error is represented as a percentage term, which is quite popular and interpretable, the error measure also instantly becomes interpretable. If we say the RMSE is 32, it doesn’t mean anything in isolation. But on the other hand, if we say the MAPE is 20%, we instantly know ho good or bad the forecast is.</li></ol><h4>Symmetricity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*0OdmBEHYOEZItvK4" /></figure><p>Now that doesn’t look right, does it? Percent Error, the most popular of them all, doesn’t look symmetric at all. In fact, we can see that the errors peak when actuals is close to zero and tending to infinity when actuals is zero(the colorless band at the bottom is where the error is infinity because of division by zero).</p><p>We can see two shortcomings of the percent error here:</p><ol><li>It is undefined when ground truth is zero(because of division by zero)</li><li>It assigns higher error when ground truth value is lower(top right corner)</li></ol><p>Let’s look at the Loss Curves and Complementary Pairs plots to understand more.</p><h4>Loss Curves</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/0*8emEKoUdUXXp80q1" /></figure><p>Suddenly, the asymmetry we are seeing is no more. If we keep the ground truth fixed, Percent Error is symmetric around the origin.</p><h4>Complementary Pairs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*80ul5LPthfk4GIaq" /></figure><p>But when we look at complementary pairs, we see the asymmetry we were seeing earlier in the heatmap. When the actuals are low, the same error is having a much higher Percent Error than the same error when the forecast was low.</p><p>All of this is because of the base which we take for scaling it. Even if we have the same magnitude of error, if the ground truth is low, the percent error will be high and vice versa. For example, let’s review two cases:</p><ol><li>F = 8, A=2 -&gt; Absolute Percent Error =(8–2)/2 = 3</li><li>F=2, A=8 -&gt; Absolute Percent Error =(8–2)/8 = 0.75</li></ol><p>There are countless papers and blogs which claim the asymmetry of percent error to be a deal breaker. The popular claim is that absolute percent error penalizes over-forecasting more than under-forecasting, or in other words, it incentivizes under-forecasting.</p><p>One argument against this point is that this asymmetry is only there because we change the ground truth. An error of 6 for a time series which has an expected value of 2 is much more serious than an error of 2 for a time series which has an expected value of 6. So according to that intuition, the percent error is doing what it is supposed to do, isn’t it?</p><h4>Over and Under Forecasting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*o40iBihmw3aZMBdp" /></figure><p>Not exactly. On some levels the criticism of percent error is rightly justified. Here we see that the forecast where we were under-forecasting has a consistently lower MAPE than the ones where we were over-forecasting. The spread of the low MAPE is also considerably lower than the others. But does that mean that the forecast which always predicts on the lower side is the better forecast as far as the business is concerned? Absolutely not. In a Supply Chain, that leads to stock outs, which is not where you want to be if you want to stay competitive in the market.</p><h3>Symmetric Error</h3><p>Symmetric Error was proposed as a better alternative to Percent error. There were two key disadvantages for Percent Error — Undefined when Ground Truth is zero and Asymmetry. And Symmetric Error proposed to solve both by using the average of ground truth and forecast as the base over which we calculate the percent error.</p><h4>Symmetricity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*Wb96MvV-S4dUVQJy" /></figure><p>Right off the bat, we can see that this is symmetric around the diagonal, almost similar to Absolute Error in case of symmetry. And the bottom bar which was empty, now has colors(which means they are not undefined). But a closer look reveals something more. It is not symmetric around the second diagonal. We see the errors are higher when both actuals and forecast are low.</p><h4>Loss Curves</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*eb5cnoRqk60pBMvU" /></figure><p>This is further evident in the Loss Curves. We can see the asymmetry as we increase errors on both sides of the origin. And contrary to the name, Symmetric error penalizes under forecasting more than over forecasting.</p><h4>Complementary Pairs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*PMAY4cwthF86cWS_" /></figure><p>But when we look at complementary pairs, we can see it is perfectly symmetrical. This is probably because of the base, which we are keeping constant.</p><h4>Over and Under Forecasting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*baJvqvEhc65KkxGl" /></figure><p>We can see the same here as well. The over forecasting series has a consistently lower error as compared to the under forecasting series. So in the effort to normalize the bias towards under forecasting of Percent Error, Symmetric Error shot the other way and is biased towards over forecasting.</p><h3>Outlier Impact</h3><p>In addition to the above experiments, we had also run an experiment to check the impact of outliers(single predictions which are wildly off) on the aggregate metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/0*UZXJYjuLTSPP0cJT" /></figure><p>All four error measures have similar behavior, when coming to outliers. The number of outliers have a much higher impact than the scale of outliers.</p><p>Among the four, RMSE is having the biggest impact from outliers. We can see the contour lines are spaced far apart, showing the rate of change is high when we introduce outliers. On the other end of the spectrum, we have sMAPE which has the least impact from outliers. It is evident from the flat and closely spaced contour lines. MAE and MAPE are behaving almost similarly, probably MAPE a tad bit better.</p><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q5Aca-9lG_OHVTMr" /></figure><p>To close off, there is no one metric which satisfies all the <em>desiderata</em> of an error measure. And depending on the use case, we need to pick and choose. Out of the four intrinsic measures( and all its aggregations like MAPE, MAE, etc.), if we are not concerned by Interpretability and Scale Dependency, we should choose Absolute Error Measures. And when we are looking for scale independent measures, Percent Error is the best we have(even with all of its shortcomings). Extrinsic Error measures like Scaled Error offer a much better alternative in such cases (Maybe in another blog post I’ll cover those as well.)</p><p><strong>Code to recreate Experiments</strong></p><p><a href="https://github.com/manujosephv/forecast_metrics/tree/master">manujosephv/forecast_metrics</a></p><p><strong>Checkout the rest of the articles in the series</strong></p><ol><li><a href="https://deep-and-shallow.com/2020/09/26/forecast-error-measures-understanding-them-through-experiments/">Forecast Error Measures: Understanding them through experiments</a></li><li><a href="https://deep-and-shallow.com/2020/10/01/forecast-error-measures-scaled-relative-and-other-errors/">Forecast Error Measures: Scaled, Relative, and other Errors</a></li><li>Forecast Error Measures: Intermittent Demand</li></ol><p><strong>Further Reading</strong></p><ul><li>Shcherbakov et al. 2013, <a href="http://idosi.org/wasj/wasj(ITMIES)13/28.pdf">A Survey of Forecast Error Measures</a></li><li>Goodwin &amp; Lawton, 1999, <a href="https://doi.org/10.1016/S0169-2070(99)00007-2">On the asymmetry of symmetric MAPE</a></li></ul><p><strong><em>Edited(29–09–2020): Fixed a mislabeling issue in the contour map</em></strong></p><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2020/09/26/forecast-error-measures-understanding-them-through-experiments/"><em>http://deep-and-shallow.com</em></a><em> on September 26, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da7ddcb0b035" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/forecast-error-measures-understanding-them-through-experiments-da7ddcb0b035">Forecast Error Measures: Understanding them through experiments</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[Battle of the Boosters]]></title>
            <link>https://medium.com/data-science/battle-of-the-boosters-8ffd0671e56b?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ffd0671e56b</guid>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[the-gradient-boosters]]></category>
            <category><![CDATA[lightgbm]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 01:52:00 GMT</pubDate>
            <atom:updated>2020-07-05T01:36:42.934Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="http://towardsdatascience.com/tagged/the-gradient-boosters">GRADIENT BOOSTERS</a></h4><h4>The last booster standing in an all-out brawl match</h4><p>We have come a long way in the world of Gradient Boosting. If you have followed the whole series, you should have a much better understanding about the theory and practical aspects of the major algorithms in this space. After a grim walk through the math and theory behind these algorithms, I thought it would be a fun change to see all of them in action in a highly practical blog post.</p><p>So, I present to you, the Battle of the Boosters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZOfZOhtKo-KjkFdu" /><figcaption>Photo by <a href="https://unsplash.com/@attentieattentie?utm_source=medium&amp;utm_medium=referral">Attentie Attentie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Datasets</h3><p>I have chosen a few datasets for regression from Kaggle Datasets, mainly because it’s easy to setup and run in Google Colab. Another reason is that I do not need to spend a lot of time in data preprocessing, instead I can pick one of the public kernels and get cracking. I’ll also share one kernel for EDA of the datasets we choose. All notebooks will also be shared and links at the bottom of the blog.</p><ol><li><a href="https://www.kaggle.com/uciml/autompg-dataset">AutoMPG</a> — The data is technical spec of cars from UCI Machine Learning Repository.<br>Shape: (398,9) , <a href="https://www.kaggle.com/devanshbesain/exploration-and-analysis-auto-mpg">EDA Kernel</a>, Data Volume: Low</li><li><a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques/overview">House Prices: Advanced Regression Techniques</a> — The Ames Housing dataset was compiled by Dean De Cock for use in data science education. It’s an incredible alternative for data scientists looking for a modernized and expanded version of the often cited Boston Housing dataset. With 79 explanatory variables describing (almost) every aspect of residential homes in Ames, Iowa, this competition challenges you to predict the final price of each home. <br>Shape: (1460, 81), <a href="https://www.kaggle.com/erikbruin/house-prices-lasso-xgboost-and-a-detailed-eda">EDA kernel</a>, Data Volume: Medium</li><li><a href="https://www.kaggle.com/wkirgsn/electric-motor-temperature">Electric Motor Temperature</a> — The data set comprises several sensor data collected from a permanent magnet synchronous motor (PMSM) deployed on a test bench. The PMSM represents a German OEM’s prototype model.<br>Shape: (998k,13), <a href="https://www.kaggle.com/wkirgsn/eda-and-baseline-on-motor-temperature-estimation">EDA Kernel</a>, Data Volume: High</li></ol><h3>Experimental Setup</h3><h3>Algorithms in Contention</h3><ol><li>XGBoost</li><li>LightGBM</li><li>Regularized Greedy Forest</li><li>NGBoost</li></ol><h3>Data Preprocessing</h3><p>Nothing fancy here. Just did some basic data cleansing and scaling. Most of the code is from some random kernel. The only point is that the same preprocessing is applied to all algorithms</p><h3>Cross Validation Setup</h3><p>I have chosen cross validation to make sure the comparison between different algorithms is more generalized than specific to one particular split of the data. I have chosen a simple K-Fold with 5 folds for this exercise.</p><h3>Evaluation</h3><p><strong>Evaluation Metric :</strong> Mean Squared Error</p><p>To have standard evaluation for all the algorithms(thankfully all of them are Sci-kit Learn api), I defined a couple of functions.</p><p><strong>Default Parameters:</strong> First fit the CV splits with default parameters of the model. We record the mean and standard deviation of the CV scores and then fit the entire train split to predict on the test split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*MQcjOvODTWw2HEbyCa2X5A.png" /></figure><p><strong>With Hyperparameter Tuning</strong>: Very similar to the previous one, but with an additional step of GridSearch to find best parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqQk7n5xmCwu4meQpRwftg.png" /></figure><p>Hyperparameter tuning is in no way exhaustive, but is fairly decent.</p><p>The grids over which we run GridSearch for the different algorithms are</p><p><strong>XGBoost</strong>:</p><pre>{ &quot;learning_rate&quot;: [0.01, 0.1, 0.5], &quot;n_estimators&quot;: [100, 250, 500], &quot;max_depth&quot;: [3, 5, 7], &quot;min_child_weight&quot;: [1, 3, 5], &quot;colsample_bytree&quot;: [0.5, 0.7, 1], }</pre><p><strong>LightGBM</strong>:</p><pre>{ &quot;learning_rate&quot;: [0.01, 0.1, 0.5], &quot;n_estimators&quot;: [100, 250, 500], &quot;max_depth&quot;: [3, 5, 7], &quot;min_child_weight&quot;: [1, 3, 5], &quot;colsample_bytree&quot;: [0.5, 0.7, 1], }</pre><p><strong>RGF</strong>:</p><pre>{ &quot;learning_rate&quot;: [0.01, 0.1, 0.5], &quot;max_leaf&quot;: [1000, 2500, 5000], &quot;algorithm&quot;: [&quot;RGF&quot;, &quot;RGF_Opt&quot;, &quot;RGF_Sib&quot;], &quot;l2&quot;: [1.0, 0.1, 0.01], }</pre><p><strong>NGBoost</strong>:</p><p>Because NGBoost is kinda slow, instead of defining a standard grid for all experiments, I have done search along each parameter, independently, and decided a grid based on the intuitions from that experiment</p><h3>Results</h3><p>I’ve tabulated the Mean and Standard Deviations of RMSEs for the Train CV splits for all three datasets. For Electric-Motors, I did not tune the data, as it was computationally expensive.</p><h3>AutoMPG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/0*V7nsLAUx84V-XB-X" /><figcaption>Auto MPG Dataset Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bwl5nfCBL8gV4ZUS" /><figcaption>Auto MPG Mean vs SD (RMSE)Scatter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7HwhpmkXwAlHEGKV" /><figcaption>Execution Time for 4 CV splits and 1 Test split</figcaption></figure><h3>House Prices: Advanced Regression Techniques</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*7r5jOSadlLFqcT9g" /><figcaption>House Prices Dataset Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*laLAQEUjGiEn8ytb" /><figcaption>Housing Prices Mean vs SD (RMSE)Scatter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*762B5HOdixGLBIwp" /><figcaption>Execution Time for 4 CV splits and 1 Test split</figcaption></figure><h3>Electric Motor Temperature</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/0*9sYXEB72jp1RqCad" /><figcaption>Electric Motor Temperature Dataset Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oFa04gMcXrjF52Jm" /><figcaption>Electric Motor Temperature Mean vs SD (RMSE)Scatter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yq3qfKSDaWOCSFon" /><figcaption>Execution Time for 4 CV splits and 1 Test split</figcaption></figure><h3>Final Words</h3><blockquote><strong><em>Disclaimer</em></strong>: These experiments are in no way complete. One would need a much larger scale experiment to arrive at a conclusion on which algorithm is doing better. And then there is the No Free Lunch Theorem to keep in mind.</blockquote><p>Right off the bat, NGBoost seems like a strong contender in this space. In AutoMPG and Housing Prices datasets, NGBoost performs the best among all the other boosters, both on mean RMSE as well as the Standard Deviation in the CV scores, and by a large margin. NGBoost also shows quite a large gap between the default and tuned versions. This shows that either the default parameters are not well set, or that each tuning for dataset is a key element in getting good performance from NGBoost. But the Achilles heel of the algorithm is the run-time. With those huge bars towering over the others, we can see that the runtime, really, is in a different scale as compared to the other boosters. Especially on large datasets like Electric Motors Temperature dataset, the runtime is prohibitively large and because of that I didn’t tune the algorithm as well. It fares last among the other boosters in the competition.</p><p>Another standout algorithm is Regularized Greedy Forest, which is performing as good as or even better than XGBoost. In low and medium data setting, the runtime is also comparable to the reigning king, XGBoost.</p><p>In low data setting, popular algorithms like XGBoost and LightGBM are not performing well. And the standard deviation of the CV scores are higher, especially XGBoost, showing that it overfits. XGBoost has this problem in all three examples. In the matter of runtime, LightGBM reins king(although I haven’t tuned for computational performance), beating XGBoost in all three examples. In the high data setting, it blew everything else out of the water by having much lower RMSE and runtime than the rest of the competitors.</p><h4>Colab Notebooks with experiments</h4><ul><li><a href="https://colab.research.google.com/drive/1CRlVgzzjZQH7EN8YfSWr1bOGMfDZ_jFo?usp=sharing">Auto MPG</a></li><li><a href="https://colab.research.google.com/drive/1jtPpCcNpRCVE-BTEAR8irdbV1Qfo0Bax?usp=sharing">Housing Prices</a></li><li><a href="https://colab.research.google.com/drive/1J6vG4sMudRr1gKJ0nJvnHk6_JmxjCird?usp=sharing">Electric Motor Temperature</a></li></ul><h4><strong>Other Articles in </strong><a href="http://towardsdatascience.com/tagged/the-gradient-boosters"><strong><em>The Gradient Boosters</em></strong></a></h4><ul><li><a href="https://towardsdatascience.com/the-good-old-gradient-boosting-f4614b0e62b0">The Good Old Gradient Boosting</a></li><li><a href="https://towardsdatascience.com/regularized-greedy-forest-a17cd0c85f06">Regularized Greedy Forest</a></li><li><a href="https://towardsdatascience.com/xgboost-b736c2ab10ce">XGBoost</a></li><li><a href="https://towardsdatascience.com/lightgbm-800340f21415">LightGBM</a></li><li><a href="https://towardsdatascience.com/catboost-d1f1366aca34">CatBoost</a></li><li><a href="https://towardsdatascience.com/natural-gradient-ce454b3dcdfa">Natural Gradient</a></li><li><a href="https://towardsdatascience.com/ngboost-aca51711c8f5">NGBoost</a></li></ul><p>We have come far and wide in the world of gradient boosting and I hope that at least for some of you, Gradient Boosting does not mean XGBoost. There are so many algorithms with its own quirks in this world and lot of them perform at par or better than XGBoost. And another exciting area is Probabilistic Regression. I hope NGBoost become more efficient and step over that hurdle of computational efficiency. Once that happens, NGBoost is a very strong candidate in the probabilistic regression space.</p><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2020/07/01/the-gradient-boosters-vii-battle-of-the-boosters/"><em>http://deep-and-shallow.com</em></a><em> on July 1, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ffd0671e56b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/battle-of-the-boosters-8ffd0671e56b">Battle of the Boosters</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[NGBoost]]></title>
            <link>https://medium.com/data-science/ngboost-aca51711c8f5?source=rss-c8dcc7fb5ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/aca51711c8f5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ngboost]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[the-gradient-boosters]]></category>
            <dc:creator><![CDATA[Manu Joseph]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 14:57:23 GMT</pubDate>
            <atom:updated>2020-07-02T03:10:21.099Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="http://towardsdatascience.com/tagged/the-gradient-boosters">GRADIENT BOOSTERS</a></h4><h4>Natural Gradients in Gradient Boosting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSS-6OZLzIzchvvDK6v1gg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@paulgilmore_?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Paul Gilmore</a> on <a href="https://unsplash.com/s/photos/mountains?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The reign of the Gradient Boosters were almost complete in the land of tabular data. In most real world as well as competitions, there was hardly a solution which did not have at least one model from one of the gradient boosting algorithms. But as the machine learning community matured, and the machine learning applications started to be more in use, the need for uncertainty output became important. For classification, the output from Gradient Boosting was already in a form which lets you understand the confidence of the model in its prediction. But for regression problems, it wasn’t the case. The model spat out a number and told us this was its prediction. How do you get uncertainty estimates from a point prediction? And this problem was not just for Gradient Boosting algorithms. but was for almost all the major ML algorithms. This is the problem that the new kid on the block — NGBoost seeks to tackle.</p><blockquote>If you’ve not read the previous parts of the series, I strongly advise you to read up, at least the first one where I talk about the <a href="https://deep-and-shallow.com/2020/02/02/the-gradient-boosters-i-the-math-heavy-primer-to-gradient-boosting-algorithm/">Gradient Boosting algorithm</a>, because I am going to take it as a given that you already know what Gradient Boosting is. I would also strongly suggest to read the VI(A) <em>so that you have a better understanding of what </em><a href="https://deep-and-shallow.com/2020/04/01/the-gradient-boosters-via-natural-gradient/"><em>Natural Gradients</em></a><em> are.</em></blockquote><h3>Natural Gradient Boosting</h3><p>The key innovation in NGBoost is the use of Natural Gradients instead of regular gradients in the boosting algorithm. And by adopting this probabilistic route, it models a full probability distribution over the outcome space, conditioned on the covariates.</p><p>The paper modularizes their approach into three components -</p><ol><li>Base Learner</li><li>Parametric Distribution</li><li>Scoring Rule</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cpcttnm9guWYqmRR.png" /></figure><h3>Base Learners</h3><p>As in any boosting technique, there are base learners which are combined together to get a complete model. And the NGBoost doesn&#39;t make any assumptions and states that the base learners can be any simple model. The implementation supports a Decision Tree and ridge Regression as base learners out of the box. But you can replace them with any other sci-kit learn style models just as easily.</p><h3>Parametric Distribution</h3><p>Here, we are not training a model to predict the outcome as a point estimate, instead, we are predicting a full probability distribution. And every distribution is parametrized by a few parameters. For eg, the normal distribution is parametrized by its mean and standard deviation. You don’t need anything else to define a normal distribution. So, if we train the model to predict these parameters, instead of the point estimate, we will have a full probability distribution as the prediction.</p><h3>Scoring Rule</h3><p>Any machine learning system works on a learning objective, and more often than not, it is the task of minimizing some loss. In point prediction, the predictions are compared with data with a loss function. Scoring rule is the analogue from the probabilistic regression world. The scoring rule compares the estimated probability distribution with the observed data.</p><p>A proper scoring rule, <em>S</em>, takes as input a forecasted probability distribution, <em>P</em>, and one observation y<em>(outcome)</em>, and assigns a score <em>S(P,y) </em>to the forecast such that the true distribution of the outcomes gets the best score in expectation.</p><p>The most commonly used proper scoring rule is the logarithmic score <em>L</em>, which, when minimized we get the MLE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/0*vjbtaGTTZHZebsgu" /></figure><p>which is nothing but the log likelihood that we have seen in so many places. And the scoring rule is parametrized by θ because that is what we are predicting as part of the machine learning model.</p><p>Another example is CRPS(Continuous Ranked Probability Score). While the logarithmic score or the log likelihood generalizes Mean Squared Error to a probabilistic space, CRPS does the same to Mean Absolute Error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*Y6A0RGdZ3rIj1GV7" /></figure><h3>Generalized Natural Gradient</h3><p>In the last part of the series, we saw what Natural Gradient was. And in that discussion, we talked about KL Divergences, because traditionally, Natural Gradients were defined on the MLE scoring rule. But the paper proposes a generalization of the concept and provide a way to extend the concept to CRPS scoring rule as well. They generalized KL Divergence to a general Divergence and provided derivations for CRPS scoring rule.</p><h3>Putting it all together</h3><p>Now that we have seen the major components, let’s take a look at how all of this works together. NGBoost is a supervised learning method for probabilistic prediction that uses boosting to estimate the parameters of a conditional probability distribution <em>P(y|x)</em>. As we saw earlier, we need to choose three modular components upfront:</p><ol><li>Base learner (<em>f</em>)</li><li>Parametric Probability Distribution ( <em>P parameterized by θ</em>)</li><li>Proper scoring rule (<em>S</em>)</li></ol><p>A prediction <em>y|x </em>on a new input <em>x</em> is made in the form of a conditional distribution P, whose parameters θ are obtained by an additive combination of <em>M</em> base learners outputs and in initial θ₀. Let’s denote the combined function learned by the M base learners for all parameters by <em>f</em>⁽ᵐ⁾[2]. And there will be a separate set of base learners for each parameter in the chosen probability distribution. For eg. in the normal distribution, there will be <em>f</em>⁽ᵐ⁾ for μ and <em>f</em>⁽ᵐ⁾ for log σ. The predicted outputs are also scaled with a stage specific scaling factor (ρᵐ), and a common learning rate η:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*0LPkHBtA83ATuGeF" /></figure><p>One thing to note here is that even if you have <em>n</em> parameters for your probability distribution, ρ is still a single scalar.</p><h3>Algorithm</h3><p>Let’s look at the algorithm as explained in the paper[2].</p><p>Let us consider a Dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/0*s-ri616qnQDJnU8C" /></figure><p>Boosting Iterations <em>M</em>, Learning rate η, Probability Distribution with parameters θ, Proper scoring rule <em>S</em>, and Base learner <em>f</em></p><ol><li>Initialize θ₀ to the marginal. This is just estimating the parameters of the distribution without conditioning on any covariates; similar to initializing to mean. Mathematically, we solve this equation:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/0*tU0gKP-Oz3beesFO" /></figure><ol><li>For each iteration in M:</li><li>Calculate the Natural gradients gᵢᵐ of the Scoring rule S with respect to the parameters at previous stage θᵢᵐ⁻¹ for all <em>n</em> examples in dataset.</li><li>A set of base learners for that iteration <em>f</em>⁽ᵐ⁾ are fit to predict the corresponding components of the natural gradients, gᵢᵐ. This output can be thought of as the projection of the natural gradient on to the range of the base learner class, because we are training the base learners to predict the natural gradient at current stage.</li><li>This projected gradient is then scaled by a scaling factor ρᵐ. This is because Natural Gradients rely on local approximations(as we saw in the earlier post) and these local approximations won’t hold good far away from the current parameter position.<br>In practice, we use a line search to get the best scaling factor which minimizes the overall scoring rule. In the implementation, they have found out that reducing the scaling factor by half in the line search works well.</li><li>Once the scaling parameter is estimated, we update the parameters by adding the negative scaled projected gradient to the outputs of previous stage, after further scaling by a learning rate.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*urhq1unTnuBZU7mm" /></figure><h3>Implementation</h3><p>The algorithm has a ready use Sci-kit Learn style implementation at <a href="https://github.com/stanfordmlgroup/ngboost">https://github.com/stanfordmlgroup/ngboost</a>. Let’s take a look at the key parameters to tune in the model.</p><h3>Hyperparameters</h3><ul><li>Dist: This parameter sets the distribution of the output. Currently, the library supports <em>Normal, LogNormal, and Exponential </em>distributions for regression, <em>k_categorical and Bernoulli</em> for classification. <em>Default: Normal</em></li><li>Score: This specifies the scoring rule. Currently, the options are between <em>LogScore or CRPScore</em>. <em>Default: LogScore</em></li><li>Base: This specifies the base learner. This can be any Sci-kit Learn estimator. <em>Default is a 3-depth Decision Tree</em></li><li>n_estimators: The number of boosting iterations. <em>Default: 500</em></li><li><em>learning_rate</em>: The learning rate. <em>Default:0.01</em></li><li><em>minibatch_frac</em>: The percent subsample of rows to use in each boosting iteration. This is more of a performance hack than performance tuning. When the data set is huge, this parameter can considerably speed things up.</li></ul><h3>Interpretation</h3><p>Although there needs to be a <a href="https://deep-and-shallow.com/2019/11/13/interpretability-cracking-open-the-black-box-part-i/">considerable amount of caution before using the importances from machine learning models</a>, NGBoost also offers feature importances. It has separate set of importances for each parameter it estimates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*7i8p9rqtihJ3hR17" /><figcaption>Source: NGBoost Documentation[3]</figcaption></figure><p>But the best part is not just this, but that <a href="https://deep-and-shallow.com/2019/11/24/interpretability-cracking-open-the-black-box-part-iii/">SHAP</a>, is also readily available for the model. You just need to use TreeExplainer to get the values. (To know more about SHAP and other interpretable techniques, check out my other blog series — <a href="https://deep-and-shallow.com/2020/06/27/the-gradient-boosters-vib-ngboost/Cracking%20open%20the%20black%20box">Interpretability: Cracking open the black box</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*LogCP_qAOpWGDjiR" /><figcaption>Source: NGBoost Documentation[3]</figcaption></figure><h3>Experiments</h3><p>The paper also looks at how the algorithm performs when compared to other popular algorithms. There were two separate type of evaluation — Probabilistic, and Point Estimation</p><h3>Probabilistic Regression</h3><p>On a variety of datasets from the UCI Machine Learning Repository, NGBoost was compared with other major probabilistic regression algorithms, like <a href="http://proceedings.mlr.press/v48/gal16.pdf">Monte-Carlo Dropout</a>, <a href="https://papers.nips.cc/paper/7219-simple-and-scalable-predictive-uncertainty-estimation-using-deep-ensembles.pdf">Deep Ensembles</a>, <a href="http://papers.neurips.cc/paper/6949-concrete-dropout.pdf">Concrete Dropout</a>, Gaussian Process, <a href="https://www.jstatsoft.org/article/view/v023i07">Generalized Additive Model for Location, Scale and Shape(GAMLSS)</a>, <a href="https://arxiv.org/pdf/1804.02921.pdf">Distributional Forests</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w_xL8KqMEpxqDLh3" /></figure><h3>Point Estimate</h3><p>They also evaluated the algorithm on the point estimate use case against other regression algorithms like Elastic Net, Random Forest(Sci-kit Learn), Gradient Boosting(Sci-kit Learn).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GLgB5mbdVG_7Eczt" /></figure><h3>Conclusions</h3><p>NGBoost performs as well or better than the existing algorithms, but also has an additional advantage of providing us with a probabilistic forecast. And the formulation and implementation are flexible and modular enough to make it easy to use.</p><p>But one drawback here is with the performance of the algorithm. The time complexity linearly increases with each additional parameter we have to estimate. And all the efficiency hacks/changes which has made its way into popular Gradient Boosting packages like LightGBM, or XGBoost are not present in the current implementation. Maybe it would be ported over soon enough because I see the repo is under active development and see this as one of the action items they are targeting. But until that happens, this is quite slow, especially with large data. One way out is to use <em>minibatch_frac</em> parameter to make the calculation of natural gradients faster.</p><p>Now that we have seen all the major Gradient Boosters, let’s pick a sample dataset and see how these perform in the next part of the series.</p><p>Other Articles in <a href="http://towardsdatascience.com/tagged/the-gradient-boosters"><em>The Gradient Boosters</em></a></p><ul><li><a href="https://towardsdatascience.com/the-good-old-gradient-boosting-f4614b0e62b0">The Good Old Gradient Boosting</a></li><li><a href="https://towardsdatascience.com/regularized-greedy-forest-a17cd0c85f06">Regularized Greedy Forest</a></li><li><a href="https://towardsdatascience.com/xgboost-b736c2ab10ce">XGBoost</a></li><li><a href="https://towardsdatascience.com/lightgbm-800340f21415">LightGBM</a></li><li><a href="https://towardsdatascience.com/catboost-d1f1366aca34">CatBoost</a></li><li><a href="https://towardsdatascience.com/natural-gradient-ce454b3dcdfa">Natural Gradient</a></li><li>NGBoost (you are here)</li></ul><h3>References</h3><ol><li>Amari, Shun-ichi. Natural Gradient Works Efficiently in Learning. Neural Computation, Volume 10, Issue 2, p.251–276.</li><li>Duan, Tony. NGBoost: <a href="https://arxiv.org/pdf/1910.03225.pdf">Natural Gradient Boosting for Probabilistic Prediction</a>, arXiv:1910.03225v4 [cs.LG] 9 Jun 2020</li><li>NGBoost documentation, <a href="https://stanfordmlgroup.github.io/ngboost">https://stanfordmlgroup.github.io/ngboost</a></li></ol><p><em>Originally published at </em><a href="https://deep-and-shallow.com/2020/06/27/the-gradient-boosters-vib-ngboost/"><em>http://deep-and-shallow.com</em></a><em> on June 27, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca51711c8f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ngboost-aca51711c8f5">NGBoost</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>