Forecasting Temperature with Outliers Imputation#

Main goal of the project:

Forecasting temperature in a accurate way using a Machine Learning general approach.

This part of the project will be focused in the following forecasting approaches:

  • Forecasting with outliers imputation.

For each approach the best model will be found, applying ML evaluation techniques like cross Validation and hyper-parameter optimization.

Author: Fabio Scielzo Ortiz

Requirements#

import polars as pl 
import pandas as pd 
import numpy as np
import sys
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
from statsmodels.tsa.seasonal import STL
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from datetime import timedelta
from sklearn.metrics import mean_absolute_error
import datetime
import warnings
warnings.filterwarnings("ignore")
import optuna
from PIL import Image
import pickle
import re

from skforecast.ForecasterAutoreg import ForecasterAutoreg 
from skforecast.ForecasterAutoregDirect import ForecasterAutoregDirect
from skforecast.ForecasterAutoregMultiVariate import ForecasterAutoregMultiVariate
from skforecast.ForecasterAutoregMultiSeries import ForecasterAutoregMultiSeries
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import LinearSVR
from sklearn.linear_model import ElasticNet
sys.path.insert(0, r'C:\Users\fscielzo\Documents\DataScience-GitHub\Time Series')
from PyTS import MakeLags, SARIMA, SimpleExpSmooth, VAR, LinearRegressionTS, KNeighborsRegressorTS, wape, absolute_r2, train_test_split_time_series, OptunaSearchTSCV, time_series_multi_plot, get_prediction_dates, predictive_time_series_plot, KFold_split_time_series, KFold_score_time_series, KFold_time_series_plot, autoSARIMA, DecisionTreeRegressorTS, ExtraTreesRegressorTS, RandomForestRegressorTS, HistGradientBoostingRegressorTS,  MLPRegressorTS, LinearSVRTS, XGBRegressorTS, RidgeTS, LassoTS, ElasticNetTS, StackingRegressorTS, BaggingRegressorTS, OutliersImputer, outliers_time_series_plot
sys.path.insert(0, 'C:/Users/fscielzo/Documents/DataScience-GitHub/EDA')
from EDA import prop_cols_nulls

Data#

Conceptual description#

Jena Climate is weather time series dataset recorded at the Weather Station of the Max Planck Institute for Biogeochemistry in Jena, Germany.

This dataset is made up of 14 different quantities (such air temperature, atmospheric pressure, humidity, wind direction, and so on) were recorded every 10 minutes, over several years. This dataset covers data from January 1st 2009 to December 31st 2016.

The dataset can be found in Kaggle: https://www.kaggle.com/datasets/mnassrib/jena-climate

Variable Name

Description

Type

Date Time

Date-time reference

Date

p (mbar)

The pascal SI derived unit of pressure used to quantify internal pressure. Meteorological reports typically state atmospheric pressure in millibars.

quantitative

T (degC)

Temperature in Celsius

quantitative

Tpot (K)

Temperature in Kelvin

quantitative

Tdew (degC)

Temperature in Celsius relative to humidity. Dew Point is a measure of the absolute amount of water in the air, the DP is the temperature at which the air cannot hold all the moisture in it and water condenses.

quantitative

rh (%)

Relative Humidity is a measure of how saturated the air is with water vapor, the %RH determines the amount of water contained within collection objects.

quantitative

VPmax (mbar)

Saturation vapor pressure

quantitative

VPact (mbar)

Vapor pressure

quantitative

VPdef (mbar)

Vapor pressure deficit

quantitative

sh (g/kg)

Specific humidity

quantitative

H2OC (mmol/mol)

Water vapor concentration

quantitative

rho (g/m ** 3)

Airtight

quantitative

wv (m/s)

Wind speed

quantitative

max. wv (m/s)

Maximum wind speed

quantitative

wd (deg)

Wind direction in degrees

quantitative

Preprocessing the data#

The next piece of code read the data, rename their columns, change the date column to an appropriate date format, ad columns with the day, week, month, quarter and year of each observation and remove the last row which is the only point related with 2017.

climate_df = pl.read_csv(r'C:\Users\fscielzo\Documents\DataScience-GitHub\Time Series\Temperature Prediction\Second Project\Data\jena_climate_2009_2016.csv')

climate_df.columns = ['date', 'p', 'T', 'Tpot', 'Tdew', 'rh', 'VPmax', 'VPact', 'VPdef', 
                      'sh', 'H2OC', 'rho', 'wv', 'max_wv', 'wd']

climate_df = climate_df.with_columns(pl.col("date").str.to_date("%d.%m.%Y %H:%M:%S").name.keep())

climate_df = climate_df.with_columns(climate_df['date'].dt.day().alias('day'),
                        climate_df['date'].dt.month().alias('month'),
                        climate_df['date'].dt.year().alias('year'),
                        climate_df['date'].dt.week().alias('week'),
                        climate_df['date'].dt.quarter().alias('quarter'))

climate_df = climate_df[:-1,:] # removing last row, just because is the only data point regarding 2017

The data has 420550 rows and 20 columns.

climate_df.shape
(420550, 20)

We print a head and tail of the data.

climate_df.head()
shape: (5, 20)
datepTTpotTdewrhVPmaxVPactVPdefshH2OCrhowvmax_wvwddaymonthyearweekquarter
datef64f64f64f64f64f64f64f64f64f64f64f64f64f64i8i8i32i8i8
2009-01-01996.52-8.02265.4-8.993.33.333.110.221.943.121307.751.031.75152.311200911
2009-01-01996.57-8.41265.01-9.2893.43.233.020.211.893.031309.80.721.5136.111200911
2009-01-01996.53-8.51264.91-9.3193.93.213.010.21.883.021310.240.190.63171.611200911
2009-01-01996.51-8.31265.12-9.0794.23.263.070.191.923.081309.190.340.5198.011200911
2009-01-01996.51-8.27265.15-9.0494.13.273.080.191.923.091309.00.320.63214.311200911
climate_df.tail()
shape: (5, 20)
datepTTpotTdewrhVPmaxVPactVPdefshH2OCrhowvmax_wvwddaymonthyearweekquarter
datef64f64f64f64f64f64f64f64f64f64f64f64f64f64i8i8i32i8i8
2016-12-311000.11-3.93269.23-8.0972.64.563.311.252.063.311292.410.561.0202.631122016524
2016-12-311000.07-4.05269.1-8.1373.14.523.31.222.063.31292.980.671.52240.031122016524
2016-12-31999.93-3.35269.81-8.0669.714.773.321.442.073.321289.441.141.92234.331122016524
2016-12-31999.82-3.16270.01-8.2167.914.843.281.552.053.281288.391.082.0215.231122016524
2016-12-31999.81-4.23268.94-8.5371.84.463.21.261.993.21293.561.492.16225.831122016524

We make a fast descriptive summary of the data.

climate_df.describe()
shape: (9, 21)
describedatepTTpotTdewrhVPmaxVPactVPdefshH2OCrhowvmax_wvwddaymonthyearweekquarter
strstrf64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64
"count""420550"420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0420550.0
"null_count""0"0.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.0
"mean"null989.2127519.450181283.4927794.95588676.0082613.5762739.5337714.0424196.0224189.6402381216.0625571.7022253.056558174.74371415.7133596.517322012.49680226.6177292.506375
"std"null8.3584758.4233468.5044496.73065116.4761957.7390164.1841584.8968552.6561354.23538839.97506465.44679269.01701486.6817948.7990743.4483152.28975215.0606591.116766
"min""2009-01-01"913.6-23.01250.6-25.0112.950.950.790.00.50.81059.45-9999.0-9999.00.01.01.02009.01.01.0
"25%"null984.23.36277.430.2465.217.786.210.873.926.291187.490.991.76124.98.04.02010.014.02.0
"50%"null989.589.42283.475.2279.311.828.862.195.598.961213.791.762.96198.116.07.02012.027.03.0
"75%"null994.7215.47289.5310.0789.417.612.355.37.812.491242.772.864.74234.123.010.02014.040.04.0
"max""2016-12-31"1015.3537.28311.3423.11100.063.7728.3246.0118.1328.821393.5428.4923.5360.031.012.02016.053.04.0

There is an anomaly in the variable wv, since the minimum value of it is -9999 when it should be a positive variable since is measure in m/s. We are going to clean this anomaly (error) substituting this value by the mean of the variable.

Naturally, this anomaly has been transmitted to max_wv, so, we will clean this variable as well.

climate_df = climate_df.with_columns(
                        pl.when(pl.col('wv') == pl.col('wv').min())
                        .then(pl.col('wv').mean())  # The replacement value for when the condition is True
                        .otherwise(pl.col('wv'))  # Keeps original value when condition is False
                        .alias('wv')  # Rename the resulting column back to 'variable'
                    )

climate_df = climate_df.with_columns(
                        pl.when(pl.col('max_wv') == pl.col('max_wv').min())
                        .then(pl.col('max_wv').mean())  # The replacement value for when the condition is True
                        .otherwise(pl.col('max_wv'))  # Keeps original value when condition is False
                        .alias('max_wv')  # Rename the resulting column back to 'variable'
                    )
# climate_df.write_csv(r'C:\Users\fscielzo\Documents\DataScience-GitHub\Time Series\Temperature Prediction\Second Project\Data\jena_climate_cleaned.csv')

Checking if the last transformation has solved the anomaly completely.

climate_df.min()
shape: (1, 20)
datepTTpotTdewrhVPmaxVPactVPdefshH2OCrhowvmax_wvwddaymonthyearweekquarter
datef64f64f64f64f64f64f64f64f64f64f64f64f64f64i8i8i32i8i8
2009-01-01913.6-23.01250.6-25.0112.950.950.790.00.50.81059.450.00.00.011200911

Checking if there are missing values.

prop_cols_nulls(climate_df)
shape: (1, 20)
datepTTpotTdewrhVPmaxVPactVPdefshH2OCrhowvmax_wvwddaymonthyearweekquarter
f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64
0.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.0

We can see that there are non missing values in the data, which is specially important.

''''
# If the data would have missing values, a way to fill them could be this:

climate_df = climate_df.fill_null(strategy="forward") # fill NaN's with the previous values 
climate_df = climate_df.fill_null(strategy="backward") # fill NaN's with the later values 
'''
'\'\n# If the data would have missing values, a way to fill them could be this:\n\nclimate_df = climate_df.fill_null(strategy="forward") # fill NaN\'s with the previous values \nclimate_df = climate_df.fill_null(strategy="backward") # fill NaN\'s with the later values \n'

Daily time series#

In this section we are going to compute the daily time series for the series with which we are going to work.

df = {}
variables_forecasting = ['T', 'rh', 'VPact', 'H2OC', 'wv', 'max_wv', 'wd', 'p']
for col in variables_forecasting:
    df[col] = climate_df.group_by(['year', 'month', 'day']).agg(pl.col(col).mean()).sort(['year', 'month', 'day'])
    df[col] = df[col].with_columns((pl.col("day").cast(str) + '-' + pl.col("month").cast(str) + '-' + pl.col("year").cast(str)).alias("date"))
    df[col] = df[col].with_columns(pl.col("date").str.to_date("%d-%m-%Y").name.keep())
for col in variables_forecasting:
    print('--------------------------------------')
    print(f'head-tail of {col}')

    display(df[col].head(3))
    display(df[col].tail(3))
--------------------------------------
head-tail of T
shape: (3, 5)
yearmonthdayTdate
i32i8i8f64date
200911-6.8106292009-01-01
200912-3.7281942009-01-02
200913-5.2717362009-01-03
shape: (3, 5)
yearmonthdayTdate
i32i8i8f64date
201612292.676252016-12-29
20161230-1.7065972016-12-30
20161231-2.49252016-12-31
--------------------------------------
head-tail of rh
shape: (3, 5)
yearmonthdayrhdate
i32i8i8f64date
20091191.0860142009-01-01
20091292.0868062009-01-02
20091376.4580562009-01-03
shape: (3, 5)
yearmonthdayrhdate
i32i8i8f64date
2016122990.3847222016-12-29
2016123092.9270832016-12-30
2016123174.3606942016-12-31
--------------------------------------
head-tail of VPact
shape: (3, 5)
yearmonthdayVPactdate
i32i8i8f64date
2009113.3555242009-01-01
2009124.2672922009-01-02
2009133.1077082009-01-03
shape: (3, 5)
yearmonthdayVPactdate
i32i8i8f64date
201612296.7058332016-12-29
201612305.0485422016-12-30
201612313.7650692016-12-31
--------------------------------------
head-tail of H2OC
shape: (3, 5)
yearmonthdayH2OCdate
i32i8i8f64date
2009113.3578322009-01-01
2009124.268752009-01-02
2009133.1119442009-01-03
shape: (3, 5)
yearmonthdayH2OCdate
i32i8i8f64date
201612296.6135422016-12-29
201612304.9968752016-12-30
201612313.7494442016-12-31
--------------------------------------
head-tail of wv
shape: (3, 5)
yearmonthdaywvdate
i32i8i8f64date
2009110.7786012009-01-01
2009121.4195142009-01-02
2009131.2509032009-01-03
shape: (3, 5)
yearmonthdaywvdate
i32i8i8f64date
201612290.8379862016-12-29
201612301.1381252016-12-30
201612310.8034032016-12-31
--------------------------------------
head-tail of max_wv
shape: (3, 5)
yearmonthdaymax_wvdate
i32i8i8f64date
2009111.3782522009-01-01
2009122.2273612009-01-02
2009132.0650692009-01-03
shape: (3, 5)
yearmonthdaymax_wvdate
i32i8i8f64date
201612291.3940282016-12-29
201612301.8393062016-12-30
201612311.4535422016-12-31
--------------------------------------
head-tail of wd
shape: (3, 5)
yearmonthdaywddate
i32i8i8f64date
200911181.8630772009-01-01
200912125.0720142009-01-02
200913190.3833332009-01-03
shape: (3, 5)
yearmonthdaywddate
i32i8i8f64date
20161229196.6426392016-12-29
20161230201.3590282016-12-30
20161231194.5921532016-12-31
--------------------------------------
head-tail of p
shape: (3, 5)
yearmonthdaypdate
i32i8i8f64date
200911999.1455942009-01-01
200912999.6006252009-01-02
200913998.5486112009-01-03
shape: (3, 5)
yearmonthdaypdate
i32i8i8f64date
201612291013.9575692016-12-29
201612301010.4602782016-12-30
201612311004.4761812016-12-31

Now we build a data frame with each one of the daily time series (just the values, not th dates).

df_multi = pl.concat([pl.DataFrame(df[col][col]) for col in variables_forecasting], how='horizontal')
df_multi
shape: (2_920, 8)
TrhVPactH2OCwvmax_wvwdp
f64f64f64f64f64f64f64f64
-6.81062991.0860143.3555243.3578320.7786011.378252181.863077999.145594
-3.72819492.0868064.2672924.268751.4195142.227361125.072014999.600625
-5.27173676.4580563.1077083.1119441.2509032.065069190.383333998.548611
-1.37520889.4173614.9389584.9970141.7204173.564861213.069861988.510694
-4.86715386.2604173.8067363.8477783.8002785.94118.287361990.405694
-15.48284783.7747221.54251.5470831.2268062.097708156.915486997.052986
-15.73437585.6597221.7209721.7314580.72251.483333161.920486993.506389
-9.60916787.5826392.6011812.5935420.8702081.443611182.9444441002.969653
-12.30145883.976252.0196532.0138190.6638191.237778166.9479171003.113333
-10.72826482.3408332.2392362.2328470.6664581.306597161.7561811002.967569
-8.68166783.4093062.6531252.64251.2352.289861163.9998611004.0075
-5.38486172.4441672.9265282.9306942.4599313.696806190.859722998.494722
-0.61743186.8660425.0643755.0668751.4332642.237917166.400903999.409931
-1.66555683.2656944.4795834.4736811.4360422.364236184.0942361001.110556
-0.00736186.6319445.2872925.2718752.0625693.229583183.5055561002.849028
1.24506990.0298616.0140975.9777781.5660422.468681180.3116671005.972569
4.53951480.4708336.8042366.8204863.0306945.145972210.6925997.729375
7.79861178.5861118.3579178.3923612.6734725.390069222.744306995.797778
7.52743175.5227787.9591677.9771533.4288896.124236231.709028998.122569
5.24562572.5318066.4743066.4286113.0670836.255069258.1951391006.777708
4.88715384.0708337.2695837.1718752.5581944.726597254.4277081013.542986
2.6762590.3847226.7058336.6135420.8379861.394028196.6426391013.957569
-1.70659792.9270835.0485424.9968751.1381251.839306201.3590281010.460278
-2.492574.3606943.7650693.7494440.8034031.453542194.5921531004.476181

Plotting#

In this section we are going to plot all the considered time series as a multi-plot.

time_series_multi_plot(df=df, n_cols=2, figsize=(17, 15), title='Times Series Multi-Plot', 
                       titles_size=15, title_height=0.93, 
                       subtitles_size=12, hspace=0.4, wspace=0.2)
_images/846835279bffbf96f670bbae68a594e7f1441989b9f70144e9e7236d0972667a.png

Outlier detection and imputation#

PyTS incorporates tools for outliers detection and imputation in Time Series.

The idea of this methods is to detect extreme values in a given series (using the Tukey rule so far), and substitute (impute) them by mean of different strategies.

The current strategies available for imputing the outliers are:

  • Trend: the outliers are imputed using the trend of the original series.

  • Model: the outliers are imputed using the estimations of a given model for those points.

The main goals of this section are:

  • Illustrates how the outlier detection and imputation methods work visually.

  • Try outliers imputations as another alternative for forecasting the temperature in Jena 15 days ahead.

    • Basically, we are going to follow the schema of the above sections but applying outliers imputations as a first step in the pipeline.

    • We want to investigate if this preprocessing step could improve the predictive performance of some models.

Visualization#

Y, X_st, = {}, {}
X_sk, Y_sk, = {col: {} for col in variables_forecasting}, {col: {} for col in variables_forecasting}
# Defining a grid of lags to be considered as hyper-parameters
lags_grid = [5, 10, 15, 20, 30, 40, 50]

############################################################################
# For univariate forecasting
############################################################################

for col in variables_forecasting:
    # Original series 
    Y[col] = df[col][col].to_numpy()
    # Fake X for statsmodels based implementations
    X_st[col] = np.zeros((len(Y[col]), 4))
                            
    # Lagged X and Y for sklearn based implementations
    for lag in lags_grid:
        make_lags = MakeLags(n_lags=lag, ascending=True)
        make_lags.fit()
        X_sk[col][lag], Y_sk[col][lag] = make_lags.transform(y=Y[col])
outliers_time_series_plot(figsize=(12,9), 
                          outliers_imputer=OutliersImputer(method='trend', period=7, h=1),
                          y=Y['T'], dates=df['T']['date'], 
                          title='Outlier detection and imputation - Daily Avg. Temperature',
                          titles_size=14, subtitles_size=12, hspace=0.4, bbox_to_anchor=(0.5,0.01),
                          legend_size=11)
_images/4548996c43c0b97749a7f76df3104f8001ee8ed27098774eeed39f3e00580d68.png
outliers_time_series_plot(figsize=(12,9), 
                          outliers_imputer=OutliersImputer(method='trend', period=7, h=1),
                          y=Y['T'], dates=df['T']['date'], 
                          title='Outlier detection and imputation - Daily Avg. Temperature',
                          titles_size=14, subtitles_size=12, hspace=0.4, bbox_to_anchor=(0.5,0),
                          zoom_start_date='2008-12-15', zoom_end_date='2011-3-30', title_height=0.97)
_images/01d13fa6d5ba0f074f44b7b1112f6bdb1ac324fda5be98e956de869a470ac5bf.png
outliers_time_series_plot(figsize=(12,9), 
                          outliers_imputer=OutliersImputer(method='model', estimator=SimpleExpSmooth(smoothing_level=0.05), h=1),
                          y=Y['T'], dates=df['T']['date'], X=X_st['T'],
                          title='Outlier detection and imputation - Daily Avg. Temperature',
                          titles_size=14, subtitles_size=12, hspace=0.4, bbox_to_anchor=(0.5,0.01),
                          legend_size=11)
_images/de80383eb1dbe770e7de4871ccfb474b6fc521c9512aedbbfd6c2ca5904fb974.png
outliers_time_series_plot(figsize=(12,9), 
                          outliers_imputer=OutliersImputer(method='model', estimator=SimpleExpSmooth(smoothing_level=0.01), h=1),
                          y=Y['T'], dates=df['T']['date'], X=X_st['T'],
                          title='Outlier detection and imputation - Daily Avg. Temperature',
                          titles_size=14, subtitles_size=12, hspace=0.4, bbox_to_anchor=(0.5,0.01),
                          legend_size=11)
_images/8498d20f09b946c792e7e0d5ff2d14abce215fc014cb6f0223b8479fc44f135c.png
outliers_time_series_plot(figsize=(12,9), 
                          outliers_imputer=OutliersImputer(method='model', 
                                                           estimator=SARIMA(p=0, d=0, q=1, P=0, D=0, Q=0, s=0), h=1),
                          y=Y['T'], dates=df['T']['date'], X=X_st['T'],
                          title='Outlier detection and imputation - Daily Avg. Temperature',
                          titles_size=14, subtitles_size=12, hspace=0.4, bbox_to_anchor=(0.5,0.01),
                          legend_size=11)
_images/d406efc8c6d9fa8eab80690af98880b831737d35caa351775d5d6159e3b9fdd7.png
outliers_time_series_plot(figsize=(12,9), 
                          outliers_imputer=OutliersImputer(method='model', 
                                                           estimator=SARIMA(p=0, d=0, q=1, P=0, D=0, Q=0, s=0), h=1),
                          y=Y['T'], dates=df['T']['date'], X=X_st['T'],
                          title='Outlier detection and imputation - Daily Avg. Temperature',
                          titles_size=14, subtitles_size=12, hspace=0.4, bbox_to_anchor=(0.5,0.01),
                          zoom_start_date='2009-11-01', zoom_end_date='2011-04-01', title_height=0.97, legend_size=11)
_images/b6a19bfd5cf0c73bf6119e69fe99ec6129f8472c6ae881b357a8b217a63bc9eb.png
outliers_time_series_plot(figsize=(12,9), 
                          outliers_imputer=OutliersImputer(method='model', 
                                                           estimator=SARIMA(p=0, d=0, q=1, P=0, D=1, Q=1, s=14), h=0.70),
                          y=Y['T'], dates=df['T']['date'], X=X_st['T'],
                          title='Outlier detection and imputation - Daily Avg. Temperature',
                          titles_size=14, subtitles_size=12, hspace=0.4, bbox_to_anchor=(0.5,0.01),
                          legend_size=11)
_images/3c22d7f4dec7db1d054befc8692873d0661893ef57b152b7e70c8e7d88f3376e.png

Inner evaluation#

outer_test_window = 15
inner_test_window = 15
n_splits = 10

Defining the data#

# For Sklearn implementations
X_train_sk, X_test_sk, Y_train_sk, Y_test_sk = {col: {} for col in variables_forecasting}, {col: {} for col in variables_forecasting}, {col: {} for col in variables_forecasting}, {col: {} for col in variables_forecasting}

# Train-Test split for univariate forecasting with Sklearn based implementations
for col in variables_forecasting:
    for lag in lags_grid:

        X_train_sk[col][lag], X_test_sk[col][lag], Y_train_sk[col][lag], Y_test_sk[col][lag] = train_test_split_time_series(X=X_sk[col][lag], 
                                                                                                                            y=Y_sk[col][lag], 
                                                                                                                            test_window=outer_test_window)
# For Statmodels implementations
X_train_st, X_test_st, Y_train_st, Y_test_st, = {}, {}, {}, {}

# Train-Test split for univariate forecasting with Statsmodels based implementations
for col in variables_forecasting:
    
    X_train_st[col], X_test_st[col], Y_train_st[col], Y_test_st[col] = train_test_split_time_series(X=X_st[col], y=Y[col], test_window=outer_test_window)

Defining outliers methods#

outliers_imputer = {'trend(h=1)': OutliersImputer(method='trend', period=7, h=1),
                    'trend(h=1.5)': OutliersImputer(method='trend', period=7, h=1.5),
                    'trend(h=0.75)': OutliersImputer(method='trend', period=7, h=0.75),
                    'SARIMA1(h=1)': OutliersImputer(method='model', h=1, estimator=SARIMA(p=0, d=0, q=1, P=0, D=0, Q=0, s=0)),
                    'ExpSmooth1(h=1)': OutliersImputer(method='model', h=1, estimator=SimpleExpSmooth(smoothing_level=0.05)),
                    'SARIMA1(h=1.5)': OutliersImputer(method='model', h=1.5, estimator=SARIMA(p=0, d=0, q=1, P=0, D=0, Q=0, s=0)),
                    'ExpSmooth1(h=1.5)': OutliersImputer(method='model', h=1.5, estimator=SimpleExpSmooth(smoothing_level=0.05)),
                    'ExpSmooth1(h=0.75)': OutliersImputer(method='model', h=0.75, estimator=SimpleExpSmooth(smoothing_level=0.05)),
                    'SARIMA1(h=0.80)': OutliersImputer(method='model', h=0.80, estimator=SARIMA(p=0, d=0, q=1, P=0, D=0, Q=0, s=0)),
                    'SARIMA2(h=0.70)': OutliersImputer(method='model', estimator=SARIMA(p=0, d=0, q=1, P=0, D=1, Q=1, s=14), h=0.70),
                    'SARIMA2(h=1)': OutliersImputer(method='model', estimator=SARIMA(p=0, d=0, q=1, P=0, D=1, Q=1, s=14), h=1),
                    'ExpSmooth2(h=1)': OutliersImputer(method='model', h=1, estimator=SimpleExpSmooth(smoothing_level=0.01)),
                    'ExpSmooth2(h=0.80)': OutliersImputer(method='model', h=0.80, estimator=SimpleExpSmooth(smoothing_level=0.01))
                    }
X_train_imputed_sk = {col: {lag: {} for lag in lags_grid} for col in variables_forecasting}

for col in variables_forecasting:
    for lag in lags_grid:
        for method in outliers_imputer.keys(): 
             
            outliers_imputer[method].fit(y=Y_train_st[col], X=X_train_st[col])
            Y_train_imputed = outliers_imputer[method].transform(y=Y_train_st['T'])

            make_lags = MakeLags(n_lags=lag, ascending=True)
            make_lags.fit()
            X_train_imputed_sk[col][lag][method] , _ = make_lags.transform(y=Y_train_imputed)

Applying inner evaluation to the top-5 models obtained in PyTS chapter#

with open(r'C:\Users\fscielzo\Documents\DataScience-GitHub\Time Series\Temperature Prediction\Second Project\results\best_params', 'rb') as file:
        best_params = pickle.load(file)
best_score = {}
lag = 30
estimator = RandomForestRegressorTS(random_state=123).set_params(**best_params[f'RF(lag={lag})'])
series_name = 'T'

for method in outliers_imputer.keys():

    name = f'RF(lag={lag}, imputation={method})'

    best_score[name] = KFold_score_time_series(estimator=estimator, 
                                               X=X_train_imputed_sk[series_name][lag][method], 
                                               y=Y_train_sk[series_name][lag], 
                                               n_splits=n_splits, test_window=inner_test_window, 
                                               n_lags=lag, scoring=wape, framework='PyTS')
lag = 40
estimator = ElasticNetTS(random_state=123).set_params(**best_params[f'ElasticNet(lag={lag})'])
series_name = 'T'

for method in outliers_imputer.keys():

    name = f'ElasticNet(lag={lag}, imputation={method})'

    best_score[name] = KFold_score_time_series(estimator=estimator, 
                                               X=X_train_imputed_sk[series_name][lag][method], 
                                               y=Y_train_sk[series_name][lag], 
                                               n_splits=n_splits, test_window=inner_test_window, 
                                               n_lags=lag, scoring=wape, framework='PyTS')
lag = 30
estimator = DecisionTreeRegressorTS(random_state=123).set_params(**best_params[f'Trees(lag={lag})'])
series_name = 'T'

for method in outliers_imputer.keys():

    name = f'Trees(lag={lag}, imputation={method})'

    best_score[name] = KFold_score_time_series(estimator=estimator, 
                                               X=X_train_imputed_sk[series_name][lag][method], 
                                               y=Y_train_sk[series_name][lag], 
                                               n_splits=n_splits, test_window=inner_test_window, 
                                               n_lags=lag, scoring=wape, framework='PyTS')
lag = 30
estimator = LinearSVRTS(random_state=123).set_params(**best_params[f'SVM(lag={lag})'])
series_name = 'T'

for method in outliers_imputer.keys():

    name = f'SVM(lag={lag}, imputation={method})'

    best_score[name] = KFold_score_time_series(estimator=estimator, 
                                               X=X_train_imputed_sk[series_name][lag][method], 
                                               y=Y_train_sk[series_name][lag], 
                                               n_splits=n_splits, test_window=inner_test_window, 
                                               n_lags=lag, scoring=wape, framework='PyTS')
lag = 40
estimator = MLPRegressorTS(random_state=123).set_params(**best_params[f'MLP(lag={lag})'])
series_name = 'T'

for method in outliers_imputer.keys():

    name = f'MLP(lag={lag}, imputation={method})'

    best_score[name] = KFold_score_time_series(estimator=estimator, 
                                               X=X_train_imputed_sk[series_name][lag][method], 
                                               y=Y_train_sk[series_name][lag], 
                                               n_splits=n_splits, test_window=inner_test_window, 
                                               n_lags=lag, scoring=wape, framework='PyTS')

Saving the results:

'''
with open(r'C:\Users\fscielzo\Documents\DataScience-GitHub\Time Series\Temperature Prediction\Second Project\results\best_score_outlier_imputation', 'wb') as file:
    pickle.dump(best_score, file)
'''

Opening the results:

with open(r'C:\Users\fscielzo\Documents\DataScience-GitHub\Time Series\Temperature Prediction\Second Project\results\best_score_outlier_imputation', 'rb') as file:
        best_score = pickle.load(file)

Selecting the best model#

model_names = np.array(list(best_score.keys()))
inner_scores_values = np.array(list(best_score.values()))
best_model = model_names[np.argmin(inner_scores_values)]
score_best_model = np.min(inner_scores_values)

combined_models_score = list(zip(model_names, inner_scores_values))
sorted_combined_models_score= sorted(combined_models_score, key=lambda x: x[1], reverse=False)  # Sort from lower to greater
sorted_models, sorted_scores = zip(*sorted_combined_models_score)
sorted_models, sorted_scores = list(sorted_models), list(sorted_scores)
top = 30 

fig, axes = plt.subplots(figsize=(8,9))

ax = sns.barplot(y=sorted_models[0:top], x=sorted_scores[0:top], color='blue', width=0.45, alpha=0.9)
ax = sns.barplot(y=[best_model], x=[score_best_model], color='red', width=0.45, alpha=0.9)

ax.set_ylabel('Models', size=13)
ax.set_xlabel('WAPE', size=12)
ax.set_xticks(np.round(np.linspace(0, np.max(sorted_scores[0:top]), 7),3)) 
ax.tick_params(axis='y', labelsize=10)    
plt.title(f'Model Selection (Top {top}) - Daily Temperature (ºC) \n \n {n_splits} Fold CV - Test window {inner_test_window} days', size=14, weight='bold', y=1.02)

for label in ax.get_yticklabels():
        label.set_weight('bold')
        label.set_color('black') 

plt.show()
_images/467f4bfeaf44f9011d007ae41a1ed61fe33b83a215a8f2640c125daec0e40238.png