<?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 Ethan Potter on Medium]]></title>
        <description><![CDATA[Stories by Ethan Potter on Medium]]></description>
        <link>https://medium.com/@ethan.potter?source=rss-30d26d71e53f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Th4O5LPsk89XJBWd</url>
            <title>Stories by Ethan Potter on Medium</title>
            <link>https://medium.com/@ethan.potter?source=rss-30d26d71e53f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:36:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ethan.potter/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[Fully Customisable Hierarchical Forecasting]]></title>
            <link>https://medium.com/@ethan.potter/fully-customisable-hierarchical-forecasting-6682251db2d2?source=rss-30d26d71e53f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6682251db2d2</guid>
            <category><![CDATA[hierarchical-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[class-inheritance]]></category>
            <category><![CDATA[sktime]]></category>
            <dc:creator><![CDATA[Ethan Potter]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 11:27:46 GMT</pubDate>
            <atom:updated>2025-01-24T11:38:36.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*aL6TLPjs-TW1iI8yi8H6hg.jpeg" /></figure><p>As a data scientist, I often find myself torn between using purely plug-and-play algorithms or building bespoke solutions. I had a recent dilemma with a hierarchical forecasting problem I had to solve. I thought I would have to build a bespoke solution as I wanted to use different models for each base forecast in my hierarchy. But thanks to class inheritance, I could find a way to solve this problem! In this post, I’ll show you how I implemented a custom forecaster by extending BaseForecaster from sktime, enabling cohort-specific configurations for hierarchical forecasting.</p><p>Before I get into this though, I will be using terminology specific to hierarchical forecasting here, if you’re unfamiliar with terms like base-forecast, I’d recommend <a href="https://otexts.com/fpp3/hierarchical.html">starting here</a>.</p><h3>Why Extend BaseForecaster?</h3><p>The BaseForecaster class in sktime is a powerful abstraction for time-series forecasting. By inheriting from it, you can:</p><ol><li>Implement custom logic while leveraging sktime&#39;s core functionalities.</li><li>Define flexible workflows tailored to specific requirements.</li><li>Manage complex setups, such as cohort-specific models and exogenous features.</li></ol><p>My custom implementation, CohortSpecificModelForecaster, addresses a hierarchical forecasting scenario where each cohort has its own model and set of exogenous features.</p><h3>The CohortSpecificModelForecaster Class</h3><p>Here’s how the class is structured:</p><ol><li><strong>Initialisation:</strong> The model_lookup dictionary maps each cohort to its specific model and exogenous features.</li><li><strong>_fit Method:</strong> Ensures each call corresponds to one cohort. It extracts relevant exogenous features and fits the specified model.</li><li><strong>_predict Method:</strong> Uses the fitted model to generate predictions for the specified cohort.</li><li><strong>_update Method:</strong> Updates the fitted model with new data, maintaining the cohort-specific configurations.</li></ol><pre>from typing import Any, Dict, Optional<br>import pandas as pd<br>from sktime.forecasting.base import BaseForecaster, ForecastingHorizon<br><br>class CohortSpecificModelForecaster(BaseForecaster):<br>    def __init__(self, model_lookup: Dict[str, Dict[str, Any]]):<br>        self.model_lookup: Dict[str, Dict[str, Any]] = model_lookup<br>        self.forecaster_: Optional[BaseForecaster] = None<br>        super().__init__()<br>        self.set_tags(**{&quot;requires-fh-in-fit&quot;: False})<br><br>    def _fit(self, y: pd.Series, X: Optional[pd.DataFrame] = None, fh: Optional[ForecastingHorizon] = None):<br>        if X is None or &quot;base_forecast&quot; not in X.columns:<br>            raise ValueError(&quot;`X` must include a `base_forecast` column to identify configurations.&quot;)<br><br>        unique_base_forecasts = X[&quot;base_forecast&quot;].unique()<br>        if len(unique_base_forecasts) != 1:<br>            raise ValueError(&quot;Each call to `_fit` must correspond to exactly one `base_forecast`.&quot;)<br><br>        base_forecast = unique_base_forecasts[0]<br>        exogeneous_features = self.model_lookup[base_forecast][&quot;exogeneous_features&quot;]<br><br>        filtered_exog = X.drop(columns=[&quot;base_forecast&quot;])[[x for x in X.columns if x in exogeneous_features]]<br>        model: BaseForecaster = self.model_lookup[base_forecast][&quot;model&quot;]<br><br>        if not model:<br>            raise ValueError(f&quot;No model specified for base forecast: {base_forecast}&quot;)<br><br>        model.fit(y=y, X=filtered_exog, fh=fh)<br>        self.forecaster_ = model<br>        return self<br><br>    def _predict(self, fh: ForecastingHorizon, X: Optional[pd.DataFrame] = None) -&gt; pd.Series:<br>        if X is None or &quot;base_forecast&quot; not in X.columns:<br>            raise ValueError(&quot;`X` must include a `base_forecast` column to identify configurations.&quot;)<br><br>        unique_base_forecasts = X[&quot;base_forecast&quot;].unique()<br>        if len(unique_base_forecasts) != 1:<br>            raise ValueError(&quot;Each call to `_predict` must correspond to exactly one `base_forecast`.&quot;)<br><br>        base_forecast = unique_base_forecasts[0]<br>        exogeneous_features = self.model_lookup[base_forecast][&quot;exogeneous_features&quot;]<br>        filtered_exog = X.drop(columns=[&quot;base_forecast&quot;])[[x for x in X.columns if x in exogeneous_features]]<br><br>        if self.forecaster_ is None:<br>            raise ValueError(&quot;The model has not been fitted yet. Call `_fit` before `_predict`.&quot;)<br><br>        return self.forecaster_.predict(fh=fh, X=filtered_exog)<br><br>    def _update(self, y: pd.Series, X: Optional[pd.DataFrame] = None, update_params: bool = True):<br>        if X is None or &quot;base_forecast&quot; not in X.columns:<br>            raise ValueError(&quot;`X` must include a `base_forecast` column to identify configurations.&quot;)<br><br>        unique_base_forecasts = X[&quot;base_forecast&quot;].unique()<br>        if len(unique_base_forecasts) != 1:<br>            raise ValueError(&quot;Each call to `_update` must correspond to exactly one `base_forecast`.&quot;)<br><br>        base_forecast = unique_base_forecasts[0]<br>        exogeneous_features = self.model_lookup[base_forecast][&quot;exogeneous_features&quot;]<br>        filtered_exog = X[exogeneous_features]<br><br>        if self.forecaster_ is None:<br>            raise ValueError(&quot;The model has not been fitted yet. Call `_fit` before `_update`.&quot;)<br><br>        self.forecaster_.update(y=y, X=filtered_exog, update_params=update_params)</pre><p>Note that my custom class is inheriting BaseForecaster from sktime, this means that all of the validation and model vectorization for hierarchical forecasting will be used within class. The methods I created for CohortSpecificModelForecaster will now override the default _fit , _predict and _update methods of the BaseForecaster .</p><p>Below is an example on how this looks in code, we use a simple hierarchy like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NclPabTas_J0xvWpZTT7Cg.jpeg" /></figure><pre>import numpy as np<br>from sktime.forecasting.naive import NaiveForecaster<br>from sktime.forecasting.sarimax import SARIMAX<br>from sktime.forecasting.model_selection import temporal_train_test_split<br>from sktime.transformations.hierarchical.aggregate import Aggregator<br><br># Example dataset, arb. target y, arb. exogeneous features X_1 and X_2<br>data_a = {<br>    &quot;cohort&quot;: [&quot;A&quot;] * 100,<br>    &quot;date&quot;: pd.date_range(start=&quot;2020-01-01&quot;, periods=100, freq=&quot;D&quot;),<br>    &quot;y&quot;: np.sin(np.linspace(0, 20, 100)) + np.random.normal(0, 0.1, 100),<br>    &quot;X_1&quot;: np.random.normal(0, 1, 100),<br>    &quot;X_2&quot;: np.random.normal(1, 0.5, 100),<br>}<br><br>data_b = {<br>    &quot;cohort&quot;: [&quot;B&quot;] * 100,<br>    &quot;date&quot;: pd.date_range(start=&quot;2020-01-01&quot;, periods=100, freq=&quot;D&quot;),<br>    &quot;y&quot;: np.sin(np.linspace(0, 20, 100)) + np.random.normal(0, 0.1, 100),<br>    &quot;X_1&quot;: np.random.normal(0, 1, 100),<br>    &quot;X_2&quot;: np.random.normal(1, 0.5, 100),<br>}<br><br>df = pd.concat([pd.DataFrame(data_a), pd.DataFrame(data_b)])<br><br># Aggregate cohorts A and B so that we create the top level of our hierarchy<br>df_hier = pd.DataFrame(Aggregator().fit_transform(df.set_index([&#39;cohort&#39;, &#39;date&#39;])))<br><br># Model configuration, we create a model for each of our base forecasts<br>model_lookup = {<br>    0: {<br>        &quot;model&quot;: SARIMAX(order = [0,0,0]),<br>        &quot;exogeneous_features&quot;: [&quot;X_1&quot;]<br>    },<br>    1: {<br>        &quot;model&quot;: SARIMAX(order = [0,0,0]),<br>        &quot;exogeneous_features&quot;: []<br>    },<br>    2: {<br>        &quot;model&quot;: SARIMAX(order = [1,1,1]),<br>        &quot;exogeneous_features&quot;: [&quot;X_1&quot;, &quot;X_2&quot;]<br>    }<br>}<br><br># Model A uses model 0<br>df_hier.loc[(&#39;A&#39;, slice(None)), &#39;base_forecast&#39;] = 0<br># Model B uses model 1<br>df_hier.loc[(&#39;B&#39;, slice(None)), &#39;base_forecast&#39;] = 1<br># Model __total uses model 2<br>df_hier.loc[(&#39;__total&#39;, slice(None)), &#39;base_forecast&#39;] = 2<br>df_hier[&#39;base_forecast&#39;] = df_hier[&#39;base_forecast&#39;].astype(int)<br><br>train_df, predict_df = temporal_train_test_split(df_hier)<br><br># Using the custom forecaster<br>forecaster = CohortSpecificModelForecaster(model_lookup=model_lookup)<br>forecaster.fit(y=train_df[[&#39;y&#39;]], X=train_df[[&#39;X_1&#39;, &#39;X_2&#39;, &#39;base_forecast&#39;]])<br>predictions = forecaster.predict(fh=[1, 2, 3], X=predict_df[[&#39;X_1&#39;, &#39;X_2&#39;, &#39;base_forecast&#39;]])<br><br>print(forecaster.forecasters_.loc[&#39;A&#39;][0].forecaster_.summary())<br>print(forecaster.forecasters_.loc[&#39;B&#39;][0].forecaster_.summary())<br>print(forecaster.forecasters_.loc[&#39;__total&#39;][0].forecaster_.summary())</pre><p>From this we can see the 3 models parameters used for each base forecaster by printing the model summary, we have:</p><ul><li>The base forecaster for cohort A that uses X_1 as an exogenous feature</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*eRZRL_ujvBgcR2hMTWowrw.png" /></figure><ul><li>The base forecaster for cohort A that uses one AR component and differencing from ARIMA process</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*jGphrqVfogZzfcXAmCK8zA.png" /></figure><ul><li>The base forecaster for __total that uses one AR component, differencing, and one MA component from ARIMA process, and both exogenous features.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*pd439yA_w5NiQQhes9f4aQ.png" /></figure><h3>Summary</h3><p>In this blog post, we explored the implementation of a fully customisable hierarchical forecasting solution using the CohortSpecificModelForecaster class. By extending the BaseForecaster from sktime, this approach provides a robust framework for managing complex hierarchical forecasting scenarios with cohort-specific configurations.</p><p>Key takeaways from this solution include:</p><ul><li><strong>Flexibility and Modularity</strong>: By using a dictionary (model_lookup), each cohort in the hierarchy can have its own tailored forecasting model and set of exogenous variables. This makes the solution adaptable to diverse forecasting needs.</li><li><strong>Efficient Workflow Integration</strong>: Leveraging the BaseForecaster class allows us to inherit sktime&#39;s core functionalities, avoiding building a bespoke solution.</li></ul><p>This approach bridges the gap between plug-and-play algorithms and bespoke solutions. By utilising inheritance and abstraction, we created a scalable and reusable tool for hierarchical forecasting, while maintaining the flexibility to fine-tune individual components.</p><p>For practitioners working on hierarchical forecasting problems, this method provides a powerful template for building solutions that are both efficient and adaptable to unique data and modelling requirements. Whether working with simple hierarchies or complex multi-level structures, this approach can be a valuable addition to the data scientist’s toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6682251db2d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Problem with Gradient Boosting (Gradient Boosted Gremlins)]]></title>
            <link>https://medium.com/gousto-engineering-techbrunch/the-problem-with-gradient-boosting-gradient-boosted-gremlins-a69908dcea94?source=rss-30d26d71e53f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a69908dcea94</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <dc:creator><![CDATA[Ethan Potter]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 15:30:43 GMT</pubDate>
            <atom:updated>2022-04-04T15:30:43.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ztQfdwQ_F_mraY4b" /><figcaption>Photo by <a href="https://unsplash.com/@brisch27?utm_source=medium&amp;utm_medium=referral">Brigitta Schneiter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In the advent of gradient boosted (GB) decision trees (adaBoost, XGBoost, LGBM), such systems have gained notable popularity over other tree-based methods such as Random Forest (RF). Though both have their place in the data science roadmap, in my experience I tend to favour GB models over RF due to the incredibly fast training speed.</p><p>Though as the title might suggest, I have a problem with GB models, one which isn’t typically made clear to Data Scientists. There is a gremlin in the gradient boosting algorithm, one that, if not accounted for, may break a data science pipeline when it’s too late.</p><h3>The Problem</h3><p>First, let’s frame the problem with some code! now as a pre-warning, this article is to explain at a top-level how these algorithms work and where to be careful in their implementation. It is NOT a tutorial on how to effectively use these models, so get ready for some bad data science choices.</p><p>Now, what is the problem you might ask? well, the standard assumption I make (and I’m sure a lot of other data scientists make) when using tree-based regressors is:</p><blockquote><strong>A tree-based regressor will produce predictions in the range in which they’re trained on</strong></blockquote><p>Meaning if we have some training dataset with target y_t and features X_t, where y_t has a range [a, b]. Once we’ve fit a model to our dataset, we expect all our predictions y_p, from a new set of features X_p, regardless of what new values X_p contains, to be in the range [a, b]. BUT you see, unlike decision trees or RF algorithms, this isn’t the case with GBT models, GBT models can predict outside the range [a, b]!!</p><p>Now you might ask why this is an issue?</p><p>Well, here at Gousto DS, we were in the stages of releasing a new model for predicting the relative popularity of recipes for a given week that used LGBM. This problem space requires all predictions to be a <strong>positive</strong> float, as relative popularity can only be greater than 0.</p><p>You might think we’re safe using a tree-based regressor because if you only train on positive values, it can never be negative! right? Well fortunately before our new recipe popularity model hit production we saw something weird; a gradient boosted gremlin kicked our popularity predictions outside the training range and made a negative prediction!</p><p>Let’s demonstrate this happening with some public dataset, first let’s import some libraries and get some data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d7c5e2fd1a9cf948bd8e0a6221bd10a/href">https://medium.com/media/8d7c5e2fd1a9cf948bd8e0a6221bd10a/href</a></iframe><p>Now, select some arbitrary features to train on X_train and fit our models to y_train, here we’re just predicting the distance of a taxi journey, ie: must always be a positive float.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ef0483b565f5c4d79040bf48b255916/href">https://medium.com/media/7ef0483b565f5c4d79040bf48b255916/href</a></iframe><p>Now let’s look at what our target feature looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be61b15dbe2b936e23203c14924c8a98/href">https://medium.com/media/be61b15dbe2b936e23203c14924c8a98/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_O0zvnh8zccQ0yGNQIMILA.png" /></figure><p>So our range for y_train in our training dataset is [0, 36.7].</p><p>Now let’s create some models! for this example I’m going to compare:</p><ul><li>An RF model, the sklearn RandomForestRegressor</li><li>My personal favourite GBT model, lightgbm</li></ul><p>For fitting the random forest we run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e139fdacffdfde2d2e3369db98ccac1d/href">https://medium.com/media/e139fdacffdfde2d2e3369db98ccac1d/href</a></iframe><p>For our lightgbm model, it’s a bit different, we define most of our model parameters in a dictionary, create a Dataset class, then just pass the parameters and Dataset at the training stage to the lightgbm class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/737ecfecaee56193277dab75d9d17d94/href">https://medium.com/media/737ecfecaee56193277dab75d9d17d94/href</a></iframe><p>GREAT! now we have two models fitted to our dataset, regr and lgbmodel .</p><p>What we want to do next is create some toy data to predict on. It doesn’t matter if the data makes sense, we just want a lot of data with a variety of feature values X_predict to predict from.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bdf63d13588c8d9335a5c67f8a0ab9b/href">https://medium.com/media/4bdf63d13588c8d9335a5c67f8a0ab9b/href</a></iframe><p>If we plot our predictions y_predict, on top of our training values y_train, we can see how GB models can predict outside our y_train range of [0, 36.7]! whereas the RF model does what we expect and keeps inside the range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1fzXgrU6k14d20AbVyKcg.png" /></figure><h3>The Theory</h3><p>Okay, so I’ve proven to you that gremlins exist, but now you might ask, why does this happen?</p><p>Well before we dive into why this happens, let’s just refresh our memory on how tree-based methods work (for more reading on this see <a href="https://static1.squarespace.com/static/5ff2adbe3fe4fe33db902812/t/6062a083acbfe82c7195b27d/1617076404560/ISLR%2BSeventh%2BPrinting.pdf">Chapter 8 of An Introduction to Statistical Learning</a>).</p><h4>Decision Trees</h4><p>Before even training/fitting a model to our data, we need to define a loss function, a standard one is Mean Squared Error (MSE). This is simply:</p><ul><li>Given i observations with feature set X, and true values y_hat</li><li>When we train a model M</li><li>Then our model makes i predictions y</li></ul><p>The loss is the mean of the squared differences between the predictions y and the true values y_hat:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*zKyY3jxsTgwLHqIE" /></figure><p>The aim of training is to minimise MSE when growing the tree, we can evaluate MSE at each node that we split.</p><p>To grow a tree, we then recursively split the data into J regions R_j across our feature space X. The prediction value assigned to the region R_j is the value that minimises the MSE Loss function. This is visualised below for a tree that has grown into 5 regions across some 2D feature space X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nT33PwDnzLtGqnE-SuIn4Q.png" /><figcaption><a href="https://static1.squarespace.com/static/5ff2adbe3fe4fe33db902812/t/6062a083acbfe82c7195b27d/1617076404560/ISLR%2BSeventh%2BPrinting.pdf">Chapter 8 of An Introduction to Statistical Learning</a></figcaption></figure><p>This kind of predictor can’t make predictions outside of the range [a, b] the model was trained on. This is because, for any new observation with features X_p that are outside the training range of our feature set X_t, the prediction value for X_p, y_hat, will just fall on a flat plane. aka. a region R, which is a plane perpendicular to y and within the bounds [a, b] (see figure above).</p><p>We can generalise our model f(X) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*L7IGnzdA9f3CfauF" /><figcaption>Where R_1 ….. R_J represents a partition of feature space, and c_j, represents the value adjustment for the jth feature space partition.</figcaption></figure><h4>Random Forests</h4><p>For random forests, we grow multiple trees B, each trained on a bootstrapped dataset, and grown on a random sample of features at each split. (for more reading on this see <a href="https://static1.squarespace.com/static/5ff2adbe3fe4fe33db902812/t/6062a083acbfe82c7195b27d/1617076404560/ISLR%2BSeventh%2BPrinting.pdf">Chapter 8 of An Introduction to Statistical Learning</a>).</p><p>When making a prediction, we get each tree from our set of trees B, to each make a prediction, we then average the results to get our final prediction y_t (like all good data science algorithms, just average it). Now each tree will be bound to the same logic we just defined:</p><blockquote><strong>the prediction value, y_hat, will just fall on a flat plane, ie: a region R, which is within the bounds [a,b]</strong></blockquote><p>The only difference is, we are averaging results across many trees, but an average of results within bounds [a, b] will still be a result within bounds [a, b].</p><p>We can generalise our model for RF as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*BoINES-rAnDSXH_U" /><figcaption>Where f*b(x*) is the tree grown for the bth bootstrapped dataset on the x* randomly sampled features.</figcaption></figure><h4>Gradient Boosted Trees</h4><p>For GB methods, it gets a bit more complicated, so grab a coffee and get ready to join me on this rabbit hole.</p><p>In GB models, we grow our trees in a similar way to how we grow our decision tree above (albeit there are numerous differences in reality, ie: pre-sort-based algorithms, histogram-based algorithms, level vs leaf-wise growth etc, see the <a href="https://proceedings.neurips.cc/paper/2017/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf">original LightGBM paper for more details</a> on these).</p><p>The main difference between RF and GB models is that where RF takes the average of many models, GB trees are additive, meaning we sum the predictions between all trees. The way the GB model f_GBT(X) fits to a dataset (X, y) is:</p><ol><li>Set f_GBT(X) = 0, giving residuals r_i = y_i for all i data points.</li><li>For b = 1, 2, …. B trees, repeat:</li></ol><p>a) Fit tree f^b with d splits to the training data (X, r)</p><p>b) Update f_GBT(X) by adding in a shrunken version of the new tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/0*KeF_li3khxMzXdNG" /><figcaption>where lambda is the learning rate or shrinkage parameter typically in the range {0, 1}</figcaption></figure><p>c) Update the residuals that will be used for the next tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*uuoVWlNoHgYlscsV" /></figure><p>This gives our boosted model in the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*T9Q26xoqTdTjnFZp" /></figure><p>The main takeaway from this is that (in point (a) above) we fit our tree f^b to the <strong>residuals</strong> of our model at that boosting round! aka. the residuals of each tree we grow do not start at r_i = y_i</p><blockquote><strong>In gradient boosted trees, new trees are created to correct the residual errors in the predictions from the existing sequence of trees</strong></blockquote><p>Though it isn’t glaringly obvious that this is the reason why we can make predictions outside our target range [a, b], I’ll do my best to demonstrate this. But before this, let’s just briefly touch on how GBT methods calculate loss.</p><p>Now, with this additive model in mind, and knowing that when we grow our trees, we need to keep track of our loss function, something like MSE loss becomes a bit more complicated and computationally expensive from this kind of additive model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*4_xQOw0QGVZohtHzsSWBwQ.png" /><figcaption>taken from <a href="https://everdark.github.io/k9/notebooks/ml/gradient_boosting/gbt.nb.html">Demystifying modern gradient boosted trees</a> section 4.2</figcaption></figure><p>This is surprisingly one of the simpler loss function derivations for GB models! To make loss functions simpler for GB models, we take a 2nd order Taylor series expansion of our loss function to approximate it at a given boosting round in our model training phase, (note this is a bit of a pain if you ever want to use linear loss functions as there’s no 2nd order Tayor series of a linear function).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Udv3wQDdGqlxkYxQK-6dtQ.png" /><figcaption>taken from <a href="https://everdark.github.io/k9/notebooks/ml/gradient_boosting/gbt.nb.html">Demystifying modern gradient boosted trees</a> section 4.3</figcaption></figure><p>Doing this makes our loss function far less computationally expensive as our first order Taylor term, g_i (gradient) and second-order term h_i (hessian) become constant for each boosting round. This is one of the main benefits of GB models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*ex-aQY9ipkN0CgPE_dLlfw.png" /><figcaption>taken from <a href="https://xgboost.readthedocs.io/en/latest/tutorials/model.html">Introduction to Boosted Trees, XGBoost documentation</a></figcaption></figure><blockquote><strong>Gradient boosted trees are used to minimise an approximate loss function, not to respect the bounds of initial inputs. It sees only the gradient statistics, which is the couple (gradient, hessian) for each trained observation.</strong></blockquote><p>Now that we have a bit of a better understanding of the inner mechanics of GBT models, let’s smoke out the gremlin!</p><h4>Gradient Boosted Trees (smoking out the gremlin)</h4><p>The primary cause to predicting outside a training range is due to the additive nature of gradient boosted models.</p><p>Now, to find these gremlins, I’m going to do two things to demonstrate how using an additive model can create a gremlin:</p><ul><li>Use a very simple training dataset so we don’t get lost in numbers</li><li>Burn and cut down most of the GB forest (metaphorically of course)</li></ul><p>For my model, I’m only going to:</p><ul><li>grow stumps (max_depth = 1)</li><li>increase the learning rate to 1 to get rid of that troublesome lambda/shrinkage parameter</li><li>Grow only 2 stumps (boosting_rounds = 2).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/916bbdbfd4652c2a343ee95a46f46a1e/href">https://medium.com/media/916bbdbfd4652c2a343ee95a46f46a1e/href</a></iframe><p>This should help me smoke out those gremlins. With these parameters, my fitted model is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*a_K_Fljl9SqUFTvzt8nCZQ.png" /></figure><p>So simple that we can calculate the results with pandas:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25acf4cd7e0891125cdab17d6589e93e/href">https://medium.com/media/25acf4cd7e0891125cdab17d6589e93e/href</a></iframe><p>Giving:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZqnulFON2dhPO13bW0Kmg.png" /></figure><p>Here we can see how our residuals r_i get reduced at each step. The end predictions are relatively sensible from the albeit, terrible training data. There’s a super interesting point to make here, see how for row index 2 we:</p><ul><li>have y = 0.5 and a residual r_0 = 0.5.</li><li>Our first fitted stump makes it so our prediction is f_1(X) = 0.75, now our residual is r_1 = 0.5 – 0.75 = -0.25</li><li>when fitting our second stump, our model sees r_1 = -0.25 and says “hey! I can reduce this residual to 0! I just need to make a split so that if feature_1 &gt; 0 I add 0.25”</li><li>And we get a y_pred that equals our true y value, 0.5</li></ul><p>This seems fine, but what happens if we add an extra row with feature_0 = 0 and feature_1 = 1 ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*bRA-AeMGyNIToI40ocQWVw.png" /></figure><p>We got a prediction of -0.25! which is outside our training range of [0, 1]! And thus, the additive nature of our model has created a gremlin capable of kicking our predictions outside our training range.</p><h3>The Solution</h3><p>Okay, so we understand how these gremlins work, but now you might ask, what can we do about it?</p><p>My favourite suggestion that I’ve come across so far is from <a href="https://github.com/dmlc/xgboost/issues/1581">this</a> closed Github issue for XGBoost, where we simply bound all negative samples to the minimum of our initial predictions. This is what we decided to do for our recipe popularity predictor.</p><p>Another suggestion is to create a large loss on negative samples in a custom loss function, though this might be harder to implement.</p><p>Though personally, I’m not satisfied with these solutions as they feel like band-aids. If there’s a better solution out there, I’ll be sure to write about it soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a69908dcea94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gousto-engineering-techbrunch/the-problem-with-gradient-boosting-gradient-boosted-gremlins-a69908dcea94">The Problem with Gradient Boosting (Gradient Boosted Gremlins)</a> was originally published in <a href="https://medium.com/gousto-engineering-techbrunch">Gousto Engineering &amp; Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>