<?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 Jean-Baptiste Scellier on Medium]]></title>
        <description><![CDATA[Stories by Jean-Baptiste Scellier on Medium]]></description>
        <link>https://medium.com/@scellier_76084?source=rss-bc7689ac637d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RtHNeH3mmsO2W2rJWeseOQ.jpeg</url>
            <title>Stories by Jean-Baptiste Scellier on Medium</title>
            <link>https://medium.com/@scellier_76084?source=rss-bc7689ac637d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:59:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scellier_76084/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[Methodology to evaluate a forecasting model]]></title>
            <link>https://medium.com/enefitit/methodology-to-evaluate-a-forecasting-model-356a97786173?source=rss-bc7689ac637d------2</link>
            <guid isPermaLink="false">https://medium.com/p/356a97786173</guid>
            <category><![CDATA[model-validation]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jean-Baptiste Scellier]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 13:10:43 GMT</pubDate>
            <atom:updated>2024-01-18T12:53:06.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>To data scientists training a forecasting model that will go to production.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X_87QMCwnoB79zj7" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data scientists are used to train models in a notebook with some datasets. But they might be less experienced to evaluate them in live and even more in case of time series. This leads to false assumptions during the training, evaluation, and selection of a model.</p><p>So how to rigorously evaluate a machine learning model trained on time series data? And how to select the one that will do the best predictions when deployed in production?</p><p>For that, I use one guiding principle: <strong>evaluation of a model should adhere to the same conditions as those encountered in production. </strong>It is our best chance to get accurate predictions when going live.</p><p>Based on that I will enumerate below 4 implications.</p><h3>A model should be evaluated on data posterior to the training data</h3><p>In live, we do not know what will happen in the future. That is exactly why we need a forecasting model. So, when training and evaluating a model, let us assume the same!</p><p>A practical implication is that default K-folds cross-validation do not suit, as only the final fold for time ordered K-folds resembles reality.</p><p>Be aware that K-fold cross-validation assumes the data to be independent and identically distributed. This is usually not the case for time series. Inertia is inherent to them, which means that models could do predictions by looking at the context instead of finding the underlying relations between the variables.</p><p>With K-fold, the model will learn on future data and may use context of this data to guess real value. As such information will not be available in live, the model will have low performance compared to the one measured on validation test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eHDy8FJY-PKBOmW5FhqxuA.png" /></figure><p>For time-series, cross-validation techniques that fulfill our guiding principle involves training only on past data. There are two classical options:</p><p>Expanding window means that we take all available past data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EeOR5sBE7dYy5whYdJUO3g.png" /></figure><p>Rolling / sliding window means that we take a fixed length for training data. A combination of both can work. In the example below, first training fold was not long enough, so only available data was taken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QMRY6l4cI1BwlLL-23y7jg.png" /></figure><h3>Length of validation data should be equal to the retraining frequency of the model</h3><p>The test set(s) has a certain length, so when evaluating models, the chosen one is based on this time length. There is no certainty that the model would be performing as well on longer periods and it may exist a more performing one on shorter periods.</p><p>In production, the trained model will be used during a certain time, and at some point, retrained. So, this frequency of retraining and the length of validation data are intimately linked.</p><p>As time series may suffer a drift, it is expected for the model to see its performances to decrease across the time. The length of the validation data should not be a random value. It should be set to the frequency of the retraining, i.e. the length between two retrainings.</p><p>As it may lead to short length of test set compared to the size of data available for training, a reliable evaluation requires to use several folds. It means cross validation is mandatory and the number of folds must be adapted so that the test folds altogether cover a significant part of the data.</p><p>But the frequency of retraining itself is often not yet decided. Then how to set it? What I suggest is to measure the relation between validation data length and performances. Then the final decision of the retraining frequency will be a trade-off between the drop of performance of the model and the computational cost of retraining frequently.</p><p>Below is an example of increasing error of a model, when the length of the test sets is also increasing. This is the result based on a PV production forecast model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WGwC3Zy4X-sDWUrvm2o9g.png" /></figure><h3>Length of training data is a hyperparameter of the model</h3><p>A machine learning model is the combination of different transformations: data cleaning, feature engineering and the core model itself. Each one will affect the performance of the model.</p><p>The selection of the training data is part of these transformations. There exists different kind of training selection (selection based on distance between vectors for example), as long as they take only data from the past, there are all valid for time series forecasting. This selection is part of the whole prediction model. And criteria of choice should be the final score of the model.</p><p>One important parameter will be the length of history to take to train the model. It should be treated on the same level as hyperparameters of the core model. Especially, during the tuning of the model, length of the training set should be chosen at the same time as for other hyperparameters. Not before, not after, because they are dependent one to each other.</p><p>Let’s take the example of min_samples_split of scikit-learn’s RandomForestRegressor, it is obvious that the optimal value will depend on the total number of samples in the training set.</p><p>This length is a key hyperparameter for time series forecasting model due to the drift inherent to such problems. Relation between variables change a bit with the time so old samples may not be relevant anymore.</p><p>Below is some code that defines a class wrapping any scikit-learn’s model and that can work with any of their hyperparameter-tuning CV classes (here GridSearchCV). Its added value is that the length of the train size becomes a hyperparameter like any other one. RandomForestRegressor can be replaced by any other model.</p><pre>from sklearn.model_selection import TimeSeriesSplit, GridSearchCV<br>from sklearn.ensemble import RandomForestRegressor<br><br>class WrapModelHPSearch:<br>    def __init__(self, model=None, train_length=None, **kwargs):<br>        self.train_length = train_length<br>        self.model = model<br>        self.kwargs = kwargs<br>        if model:<br>            self.model_instance = model(**kwargs)<br>        else:<br>            self.model_instance = None<br><br>    def get_params(self, deep=True):<br>        if self.model_instance != None:<br>            params = self.model_instance.get_params(deep=deep)<br>        else:<br>            params = self.kwargs<br>        params[&quot;train_length&quot;] = self.train_length<br>        params[&quot;model&quot;] = self.model<br>        return params<br><br>    def set_params(self, **params):<br>        self.train_length = params[&quot;train_length&quot;]<br>        params.pop(&quot;train_length&quot;)<br>        if not self.model:<br>            self.model = params[&quot;model&quot;]<br>            params.pop(&quot;model&quot;)<br>        self.model_instance = self.model()<br>        self.model_instance.set_params(**params)<br>        return self<br><br>    def fit(self, X, y):<br>        first_idx = max(0, len(X) - self.train_length)<br>        X_used = X[first_idx:]<br>        y_used = y[first_idx:]<br>        self.model_instance.fit(X_used, y_used)<br>        return self<br>    <br>    def predict(self, X):<br>        return self.model_instance.predict(X)<br>    <br>    def score(self, X, y):<br>        return self.model_instance.score(X, y)<br><br><br>params = {<br>    &quot;train_length&quot;: range(100, 1000, 100),<br>    &quot;n_estimators&quot;: [5, 20, 50, 200, 500],<br>    &quot;max_depth&quot;: range(2, 8)<br>}<br>ts_split = TimeSeriesSplit(test_size=test_size)<br>grid_search = GridSearchCV(WrapModelHPSearch(RandomForestRegressor),<br>                           params, cv=ts_split)<br>grid_search.fit(X, y)</pre><h3>Test data should be similar to production data</h3><p>It looks obvious to use similar data encountered in production to evaluate the model. But the devil is in the details, so let us see some concrete examples:</p><p>A common feature added to the dataset for time series forecasting is the target lagged by some time. When working with all the historical data, it is tempting to use the target value of previous row as an input to predict the next one. But is it realistic in production to have this data? I suggest asking to the data engineer about it before training a model with such a feature. Because it could end up with a high performing model using last hour data whereas in production, the last available data dates 3 hours back.</p><p>Another common situation is a model that, in production, uses a forecast of another variable as an input. Whether this forecast comes from another machine learning model, whether it is an external data. Why not using the real value for the training instead of the forecast value? The real value is more accurate obviously. Once again, let us be careful. What does a score of a model mean on this actual values? Will it still be the best one when used on forecasted ones?<br>In this situation I suggest having different datasets for the training sets and the validation sets. Because it is a valid practice to train on actual values and it may indeed improve the model, however the validation should take place exactly like it will be in production, i.e. with the forecast values.</p><pre>from sklearn.model_selection import TimeSeriesSplit<br><br>ts_split = TimeSeriesSplit(test_size=test_size)<br>for train_indices, test_indices in ts_split.split(df_forecast, target):<br>    # Both forecast and actual values can be used for training<br>    X_train_forecast = df_forecast[train_indices]<br>    X_train_actual = df_actual[train_indices]<br>    y_train = target[train_indices]<br>    # But only the forecast should be used for validation<br>    X_test = df_forecast[test_indices]<br>    y_test = target[test_indices]</pre><h3>Conclusion</h3><p>Brief recap: to train a forecasting model that will run in production:</p><ul><li>put data in a test set posterior to the data in its relative train set<br>so use cross-validation with expanding / rolling window</li><li>set the same value for length of a test set and retraining frequency</li><li>tune the length of the training set as any other hyperparameter</li><li>ask what data is available in production and use the same when evaluating</li></ul><p>This way, the evaluation takes place in the same conditions encountered in production. The best performing one has the biggest chance to be the best one in production as well.</p><p><em>Thanks to Amine Lemaizi and Jan Timko for the proofreading.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=356a97786173" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enefitit/methodology-to-evaluate-a-forecasting-model-356a97786173">Methodology to evaluate a forecasting model</a> was originally published in <a href="https://medium.com/enefitit">enefitit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>