class MissingValuesFillerTestCase(unittest.TestCase):

    time = pd.date_range('20130101', '20130130')

    const_series = TimeSeries.from_times_and_values(
        time, np.array([2.0] * len(time)))
    const_series_with_holes = TimeSeries.from_times_and_values(
        time, np.array([2.0] * 10 + [np.nan] * 5 + [2.0] * 10 + [np.nan] * 5))

    lin = [float(i) for i in range(len(time))]
    lin_series = TimeSeries.from_times_and_values(time, np.array(lin))
    lin_series_with_holes = TimeSeries.from_times_and_values(
        time,
        np.array(lin[0:10] + [np.nan] * 5 + lin[15:24] + [np.nan] * 5 +
                 [lin[29]]))

    def test_fill_const_series_with_const_value(self):
        const_transformer = MissingValuesFiller(fill=2.0)
        transformed = const_transformer.transform(self.const_series_with_holes)

        self.assertEqual(self.const_series, transformed)

    def test_fill_const_series_with_auto_value(self):
        auto_transformer = MissingValuesFiller()
        transformed = auto_transformer.transform(self.const_series_with_holes)

        self.assertEqual(self.const_series, transformed)

    def test_fill_lin_series_with_auto_value(self):
        auto_transformer = MissingValuesFiller()
        transformed = auto_transformer.transform(self.lin_series_with_holes)

        self.assertEqual(self.lin_series, transformed)
Пример #2
0
    def helper_test_shift(test_case, test_series: TimeSeries):
        seriesA = test_case.series1.shift(0)
        test_case.assertTrue(seriesA == test_case.series1)

        seriesB = test_series.shift(1)
        test_case.assertTrue(seriesB.time_index().equals(
            test_series.time_index()[1:].append(
                pd.DatetimeIndex(
                    [test_series.time_index()[-1] + test_series.freq()]))))

        seriesC = test_series.shift(-1)
        test_case.assertTrue(seriesC.time_index().equals(
            pd.DatetimeIndex([
                test_series.time_index()[0] - test_series.freq()
            ]).append(test_series.time_index()[:-1])))

        with test_case.assertRaises(OverflowError):
            test_series.shift(1e+6)

        seriesM = TimeSeries.from_times_and_values(
            pd.date_range('20130101', '20130601', freq='m'), range(5))
        with test_case.assertRaises(OverflowError):
            seriesM.shift(1e+4)

        seriesD = TimeSeries.from_times_and_values(pd.date_range(
            '20130101', '20130101'),
                                                   range(1),
                                                   freq='D')
        seriesE = seriesD.shift(1)
        test_case.assertEqual(seriesE.time_index()[0],
                              pd.Timestamp('20130102'))
Пример #3
0
    def test_update(self):
        seriesA: TimeSeries = TimeSeries.from_times_and_values(
            self.times, [0, 1, 1, 3, 4, 5, 6, 2, 8, 0])
        seriesB: TimeSeries = TimeSeries.from_times_and_values(
            self.times, range(10))

        # change nothing
        seriesC = self.series1.copy()
        with self.assertRaises(ValueError):
            seriesA.update(self.times)
        seriesC = seriesC.update(self.times, range(10))
        self.assertEqual(seriesC, self.series1)

        # different len
        with self.assertRaises(ValueError):
            seriesA.update(self.times, [])
        with self.assertRaises(ValueError):
            seriesA.update(self.times, np.arange(3))
        with self.assertRaises(ValueError):
            seriesA.update(self.times, np.arange(4))

        # change outside
        seriesC = seriesA.copy()
        with self.assertRaises(ValueError):
            seriesC.update(self.times + 100 * seriesC.freq(), range(10))
        seriesC = seriesC.update(
            self.times.append(pd.date_range('20140101', '20140110')),
            list(range(10)) + [0] * 10)
        self.assertEqual(seriesC, self.series1)

        # change random
        seriesC = seriesA.copy()
        seriesC = seriesC.update(
            pd.DatetimeIndex(['20130108', '20130110', '20130103']), [7, 9, 2])
        self.assertEqual(seriesC, self.series1)

        # change one of each series
        seriesD = seriesB.copy()
        seriesD = seriesD.update(self.times, seriesA.pd_series().values)
        seriesA = seriesA.update(
            pd.DatetimeIndex(['20130103', '20130108', '20130110']), [2, 7, 9])
        self.assertEqual(seriesA, self.series1)
        seriesB = seriesB.update(self.times[::2], range(5))
        self.assertNotEqual(seriesB, self.series2)

        # use nan
        new_series = np.empty(10)
        new_series[:] = np.nan
        new_series[[2, 7, 9]] = [2, 7, 9]
        seriesD = seriesD.update(self.times, new_series)
        self.assertEqual(seriesD, self.series1)
Пример #4
0
    def test_exogenous_variables_support(self):
        # test case with pd.DatetimeIndex
        target_dt_idx = self.ts_gaussian
        fc_dt_idx = self.ts_gaussian_long

        # test case with numerical pd.RangeIndex
        target_num_idx = TimeSeries.from_times_and_values(
            times=tg._generate_index(start=0, length=len(self.ts_gaussian)),
            values=self.ts_gaussian.all_values(copy=False),
        )
        fc_num_idx = TimeSeries.from_times_and_values(
            times=tg._generate_index(start=0,
                                     length=len(self.ts_gaussian_long)),
            values=self.ts_gaussian_long.all_values(copy=False),
        )

        for target, future_covariates in zip([target_dt_idx, target_num_idx],
                                             [fc_dt_idx, fc_num_idx]):
            for model in dual_models:
                # skip models which do not support RangeIndex
                if isinstance(target.time_index, pd.RangeIndex):
                    try:
                        # _supports_range_index raises a ValueError if model does not support RangeIndex
                        model._supports_range_index()
                    except ValueError:
                        continue

                # Test models runnability - proper future covariates slicing
                model.fit(target, future_covariates=future_covariates)
                prediction = model.predict(self.forecasting_horizon,
                                           future_covariates=future_covariates)

                self.assertTrue(len(prediction) == self.forecasting_horizon)

                # Test mismatch in length between exogenous variables and forecasting horizon
                with self.assertRaises(ValueError):
                    model.predict(
                        self.forecasting_horizon,
                        future_covariates=tg.gaussian_timeseries(
                            start=future_covariates.start_time(),
                            length=self.forecasting_horizon - 1,
                        ),
                    )

                # Test mismatch in time-index/length between series and exogenous variables
                with self.assertRaises(ValueError):
                    model.fit(target, future_covariates=target[:-1])
                with self.assertRaises(ValueError):
                    model.fit(target[1:], future_covariates=target[:-1])
Пример #5
0
 def ts_inverse_transform(series: TimeSeries, transformer, *args,
                          **kwargs) -> TimeSeries:
     return TimeSeries.from_times_and_values(
         times=series.time_index,
         values=transformer.inverse_transform(series.values().reshape(
             (-1, series.width))),
         fill_missing_dates=False)
Пример #6
0
def _auto_fill(series: TimeSeries, **interpolate_kwargs) -> TimeSeries:
    """
    This function fills the missing values in the TimeSeries `series`,
    using the `pandas.Dataframe.interpolate()` method.

    Parameters
    ----------
    series
        The time series
    interpolate_kwargs
        Keyword arguments for `pandas.Dataframe.interpolate()`.
        See `the documentation
        <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html>`_
        for the list of supported parameters.
    Returns
    -------
    TimeSeries
        A new TimeSeries with all missing values filled according to the rules above.
    """

    series_temp = series.pd_dataframe()

    # pandas interpolate wrapper, with chosen `method`
    if 'limit_direction' not in interpolate_kwargs:
        interpolate_kwargs['limit_direction'] = 'both'
    interpolate_kwargs['inplace'] = True
    series_temp.interpolate(**interpolate_kwargs)

    return TimeSeries.from_times_and_values(series.time_index(), series_temp.values, series.freq())
Пример #7
0
    def test_map(self):
        fn = np.sin  # noqa: E731
        series = TimeSeries.from_times_and_values(
            pd.date_range('20000101', '20000110'), np.random.randn(10, 3))

        df_0 = series.pd_dataframe()
        df_2 = series.pd_dataframe()
        df_01 = series.pd_dataframe()
        df_012 = series.pd_dataframe()

        df_0[["0"]] = df_0[["0"]].applymap(fn)
        df_2[["2"]] = df_2[["2"]].applymap(fn)
        df_01[["0", "1"]] = df_01[["0", "1"]].applymap(fn)
        df_012 = df_012.applymap(fn)

        series_0 = TimeSeries(df_0, 'D')
        series_2 = TimeSeries(df_2, 'D')
        series_01 = TimeSeries(df_01, 'D')
        series_012 = TimeSeries(df_012, 'D')

        self.assertEqual(series_0['0'], series['0'].map(fn))
        self.assertEqual(series_2['2'], series['2'].map(fn))
        self.assertEqual(series_01[['0', '1']], series[['0', '1']].map(fn))
        self.assertEqual(series_012, series[['0', '1', '2']].map(fn))
        self.assertEqual(series_012, series.map(fn))

        self.assertNotEqual(series_01, series[['0', '1']].map(fn))
Пример #8
0
 def test_short_series_creation(self):
     # test missing freq argument error
     with self.assertRaises(ValueError):
         TimeSeries.from_times_and_values(
             pd.date_range('20130101', '20130102'), range(2))
     # test empty pandas series error
     with self.assertRaises(ValueError):
         TimeSeries.from_series(pd.Series(), freq='D')
     # test frequency mismatch case
     seriesA = TimeSeries.from_times_and_values(pd.date_range(
         '20130101', '20130105'),
                                                range(5),
                                                freq='M')
     self.assertEqual(seriesA.freq(), 'D')
     # test successful instantiation of TimeSeries with length 2
     TimeSeries.from_times_and_values(pd.date_range('20130101', '20130102'),
                                      range(2),
                                      freq='D')
Пример #9
0
    def fit(self, series: TimeSeries):
        series = fill_missing_values(series)
        super().fit(series)
        series = self.training_series

        # determine trend
        if self.trend == "poly":
            trend_coefficients = np.polyfit(range(len(series)),
                                            series.univariate_values(),
                                            self.trend_poly_degree)
            self.trend_function = np.poly1d(trend_coefficients)
        elif self.trend == "exp":
            trend_coefficients = np.polyfit(range(len(series)),
                                            np.log(series.univariate_values()),
                                            1)
            self.trend_function = lambda x: np.exp(trend_coefficients[
                1]) * np.exp(trend_coefficients[0] * x)
        else:
            self.trend_function = lambda x: 0

        # subtract trend
        detrended_values = series.univariate_values() - self.trend_function(
            range(len(series)))
        detrended_series = TimeSeries.from_times_and_values(
            series.time_index, detrended_values)

        # crop training set to match the seasonality of the first prediction point
        if self.required_matches is None:
            curr_required_matches = _find_relevant_timestamp_attributes(
                detrended_series)
        else:
            curr_required_matches = self.required_matches
        cropped_series = _crop_to_match_seasons(
            detrended_series, required_matches=curr_required_matches)

        # perform dft
        self.fft_values = np.fft.fft(cropped_series.univariate_values())

        # get indices of `nr_freqs_to_keep` (if a correct value was provied) frequencies with the highest amplitudes
        # by partitioning around the element with sorted index -nr_freqs_to_keep instead of sorting the whole array
        first_n = self.nr_freqs_to_keep
        if first_n is None or first_n < 1 or first_n > len(self.fft_values):
            first_n = len(self.fft_values)
        self.filtered_indices = np.argpartition(abs(self.fft_values),
                                                -first_n)[-first_n:]

        # set all other values in the frequency domain to 0
        self.fft_values_filtered = np.zeros(len(self.fft_values),
                                            dtype=np.complex_)
        self.fft_values_filtered[self.filtered_indices] = self.fft_values[
            self.filtered_indices]

        # precompute all possible predicted values using inverse dft
        self.predicted_values = np.fft.ifft(self.fft_values_filtered).real

        return self
Пример #10
0
    def test_alt_creation(self):
        with self.assertRaises(ValueError):
            # Series cannot be lower than three without passing frequency as argument to constructor
            index = pd.date_range('20130101', '20130102')
            TimeSeries.from_times_and_values(index, self.pd_series1.values[:2])
        with self.assertRaises(ValueError):
            # all arrays must have same length
            TimeSeries.from_times_and_values(self.pd_series1.index,
                                             self.pd_series1.values[:-1])

        # test if reordering is correct
        rand_perm = np.random.permutation(range(1, 11))
        index = pd.to_datetime(['201301{:02d}'.format(i) for i in rand_perm])
        series_test = TimeSeries.from_times_and_values(
            index, self.pd_series1.values[rand_perm - 1])

        self.assertTrue(series_test.start_time() == pd.to_datetime('20130101'))
        self.assertTrue(series_test.end_time() == pd.to_datetime('20130110'))
        self.assertTrue(series_test.pd_series().equals(self.pd_series1))
        self.assertTrue(series_test.freq() == self.series1.freq())
Пример #11
0
 def _build_forecast_series(
         self,
         points_preds: np.ndarray,
         input_series: Optional[TimeSeries] = None) -> TimeSeries:
     """
     Builds a forecast time series starting after the end of the training time series, with the
     correct time index (or after the end of the input series, if specified).
     """
     input_series = input_series if input_series is not None else self.training_series
     time_index = self._generate_new_dates(len(points_preds),
                                           input_series=input_series)
     return TimeSeries.from_times_and_values(time_index,
                                             points_preds,
                                             freq=input_series.freq_str())
Пример #12
0
    def helper_test_append(test_case, test_series: TimeSeries):
        # reconstruct series
        seriesA, seriesB = test_series.split_after(pd.Timestamp('20130106'))
        test_case.assertEqual(seriesA.append(seriesB), test_series)
        test_case.assertEqual(
            seriesA.append(seriesB).freq(), test_series.freq())

        # Creating a gap is not allowed
        seriesC = test_series.drop_before(pd.Timestamp('20130107'))
        with test_case.assertRaises(ValueError):
            seriesA.append(seriesC)

        # Changing frequence is not allowed
        seriesM = TimeSeries.from_times_and_values(
            pd.date_range('20130107', '20130507', freq='30D'), range(5))
        with test_case.assertRaises(ValueError):
            seriesA.append(seriesM)
Пример #13
0
    def filter(self,
               series: TimeSeries,
               num_samples: int = 1) -> TimeSeries:
        """
        Fits the Gaussian Process on the observations and returns samples from the Gaussian Process,
        or its mean values if `num_samples` is set to 1.

        Parameters
        ----------
        series : TimeSeries
            The series of observations used to infer the values according to the specified Gaussian Process.
            This must be a deterministic series (containing one sample).
        num_samples: int, default: 1
            Number of times a prediction is sampled from the Gaussian Process. If set to 1,
            instead the mean values will be returned.

        Returns
        -------
        TimeSeries
            A stochastic `TimeSeries` sampled from the Gaussian Process, or its mean
            if `num_samples` is set to 1.
        """
        raise_if_not(series.is_deterministic, 'The input series for the Gaussian Process filter must be '
                                              'deterministic (observations).')
        super().filter(series)

        values = series.values(copy=False)
        if series.has_datetime_index:
            times = np.arange(series.n_timesteps).reshape(-1, 1)
        else:
            times = series.time_index.values.reshape(-1, 1)

        not_nan_mask = np.all(~np.isnan(values), axis=1)

        self.model.fit(times[not_nan_mask, :], values[not_nan_mask, :])

        if num_samples == 1:
            filtered_values = self.model.predict(times)
        else:
            filtered_values = self.model.sample_y(times, n_samples=num_samples)
        
        return TimeSeries.from_times_and_values(series.time_index, filtered_values)
Пример #14
0
def _const_fill(series: TimeSeries, fill: float = 0) -> TimeSeries:
    """
    Fills the missing values of `series` with only the value provided (default zeroes).

    Parameters
    ----------
    series
        The TimeSeries to check for missing values.
    fill
        The value used to replace the missing values.

    Returns
    -------
    TimeSeries
        A TimeSeries, `series` with all missing values set to `fill`.
    """

    return TimeSeries.from_times_and_values(series.time_index(),
                                            series.pd_dataframe().fillna(value=fill),
                                            series.freq())
Пример #15
0
    def inverse_transform(self, series: TimeSeries, *args,
                          **kwargs) -> TimeSeries:
        """
        Performs the inverse transformation on a time series

        Parameters
        ----------
        series
            The time series to inverse transform

        Returns
        -------
        TimeSeries
            The inverse transform
        """
        super().inverse_transform(series, *args, **kwargs)
        return TimeSeries.from_times_and_values(
            series.time_index(),
            self.transformer.inverse_transform(series.values().reshape(
                (-1, series.width))), series.freq())
Пример #16
0
    def transform(self, series: TimeSeries, *args, **kwargs) -> TimeSeries:
        """
        Returns a new time series, transformed with this (fitted) scaler.
        This does not handle series with confidence intervals - the intervals are discarded.

        Parameters
        ----------
        series
            The time series to transform

        Returns
        -------
        TimeSeries
            A new time series, transformed with this (fitted) scaler.
        """
        super().transform(series, *args, **kwargs)
        return TimeSeries.from_times_and_values(
            series.time_index(),
            self.transformer.transform(series.values().reshape(
                (-1, series.width))), series.freq())
Пример #17
0
    def _predict(
        self,
        n: int,
        future_covariates: Optional[TimeSeries] = None,
        num_samples: int = 1,
    ) -> TimeSeries:

        super()._predict(n, future_covariates, num_samples)

        time_index = self._generate_new_dates(n)
        placeholder_vals = np.zeros((n, self.training_series.width)) * np.nan
        series_future = TimeSeries.from_times_and_values(
            time_index,
            placeholder_vals,
            columns=self.training_series.columns,
            static_covariates=self.training_series.static_covariates,
            hierarchy=self.training_series.hierarchy,
        )
        whole_series = self.training_series.append(series_future)
        filtered_series = self.darts_kf.filter(
            whole_series, covariates=future_covariates, num_samples=num_samples
        )

        return filtered_series[-n:]
Пример #18
0
    def historical_forecasts(
            self,
            series: TimeSeries,
            covariates: Optional[TimeSeries] = None,
            start: Union[pd.Timestamp, float, int] = 0.5,
            forecast_horizon: int = 1,
            stride: int = 1,
            retrain: bool = True,
            overlap_end: bool = False,
            last_points_only: bool = True,
            verbose: bool = False) -> Union[TimeSeries, List[TimeSeries]]:
        """
        Computes the historical forecasts the model would have produced with an expanding training window
        and (by default) returns a time series created from the last point of each of these individual forecasts.
        To this end, it repeatedly builds a training set from the beginning of `series`. It trains the
        current model on the training set, emits a forecast of length equal to forecast_horizon, and then moves
        the end of the training set forward by `stride` time steps.

        By default, this method will return a single time series made up of the last point of each
        historical forecast. This time series will thus have a frequency of `series.freq() * stride`.
        If `last_points_only` is set to False, it will instead return a list of the historical forecasts.

        By default, this method always re-trains the models on the entire available history,
        corresponding to an expanding window strategy.
        If `retrain` is set to False (useful for models for which training might be time-consuming, such as
        deep learning models), the model will only be trained on the initial training window
        (up to `start` time stamp), and only if it has not been trained before. Then, at every iteration, the
        newly expanded input sequence will be fed to the model to produce the new output.

        Parameters
        ----------
        series
            The target time series to use to successively train and evaluate the historical forecasts
        covariates
            An optional covariate series. This applies only if the model supports covariates.
        start
            The first point of time at which a prediction is computed for a future time.
            This parameter supports 3 different data types: `float`, `int` and `pandas.Timestamp`.
            In the case of `float`, the parameter will be treated as the proportion of the time series
            that should lie before the first prediction point.
            In the case of `int`, the parameter will be treated as an integer index to the time index of
            `series` that will be used as first prediction time.
            In case of `pandas.Timestamp`, this time stamp will be used to determine the first prediction time
            directly.
        forecast_horizon
            The forecast horizon for the predictions
        stride
            The number of time steps between two consecutive predictions.
        retrain
            Whether to retrain the model for every prediction or not. Currently only `TorchForecastingModel`
            instances such as `RNNModel`, `TCNModel`, `NBEATSModel` and `TransformerModel` support
            setting `retrain` to `False`.
        overlap_end
            Whether the returned forecasts can go beyond the series' end or not
        last_points_only
            Whether to retain only the last point of each historical forecast.
            If set to True, the method returns a single `TimeSeries` containing the successive point forecasts.
            Otherwise returns a list of historical `TimeSeries` forecasts.
        verbose
            Whether to print progress
        Returns
        -------
        TimeSeries or List[TimeSeries]
            By default, a single TimeSeries instance created from the last point of each individual forecast.
            If `last_points_only` is set to False, a list of the historical forecasts.
        """

        if covariates is not None:
            raise_if_not(
                series.has_same_time_as(covariates),
                'The provided series and covariates must have the same time index.'
            )

        # prepare the start parameter -> pd.Timestamp
        start = get_timestamp_at_point(start, series)

        # build the prediction times in advance (to be able to use tqdm)
        if not overlap_end:
            last_valid_pred_time = series.time_index()[-1 - forecast_horizon]
        else:
            last_valid_pred_time = series.time_index()[-2]

        pred_times = [start]
        while pred_times[-1] < last_valid_pred_time:
            # compute the next prediction time and add it to pred times
            pred_times.append(pred_times[-1] + series.freq() * stride)

        # the last prediction time computed might have overshot last_valid_pred_time
        if pred_times[-1] > last_valid_pred_time:
            pred_times.pop(-1)

        iterator = _build_tqdm_iterator(pred_times, verbose)

        # Either store the whole forecasts or only the last points of each forecast, depending on last_points_only
        forecasts = []

        last_points_times = []
        last_points_values = []

        # TODO: We should find a better object oriented way of handling covariates in GlobalForecastingModel
        fit_signature = signature(self.fit)
        predict_signature = signature(self.predict)

        # iterate and forecast
        for pred_time in iterator:
            train = series.drop_after(pred_time)  # build the training series
            if covariates is not None:
                train_cov = covariates.drop_after(pred_time)

            if retrain:
                if covariates is not None and 'covariates' in fit_signature.parameters:
                    self.fit(series=train, covariates=train_cov)
                else:
                    self.fit(series=train)

            if covariates is not None and 'covariates' in predict_signature.parameters:
                forecast = self.predict(n=forecast_horizon,
                                        series=train,
                                        covariates=train_cov)
            else:
                if 'series' in predict_signature.parameters:
                    forecast = self.predict(n=forecast_horizon, series=train)
                else:
                    forecast = self.predict(n=forecast_horizon)

            if last_points_only:
                last_points_values.append(forecast.values()[-1])
                last_points_times.append(forecast.end_time())
            else:
                forecasts.append(forecast)

        if last_points_only:
            return TimeSeries.from_times_and_values(
                pd.DatetimeIndex(last_points_times),
                np.array(last_points_values),
                freq=series.freq() * stride)
        return forecasts
Пример #19
0
 def ts_transform(series: TimeSeries, transformer) -> TimeSeries:
     return TimeSeries.from_times_and_values(
         series.time_index(),
         transformer.transform(series.values().reshape((-1, series.width))),
         series.freq())
Пример #20
0
 def ts_inverse_transform(series: TimeSeries, transformer, *args,
                          **kwargs) -> TimeSeries:
     return TimeSeries.from_times_and_values(
         series.time_index(),
         transformer.inverse_transform(series.values().reshape(
             (-1, series.width))), series.freq())
Пример #21
0
    def gridsearch(model_class,
                   parameters: dict,
                   series: TimeSeries,
                   covariates: Optional[TimeSeries] = None,
                   forecast_horizon: Optional[int] = None,
                   start: Union[pd.Timestamp, float, int] = 0.5,
                   last_points_only: bool = False,
                   val_series: Optional[TimeSeries] = None,
                   use_fitted_values: bool = False,
                   metric: Callable[[TimeSeries, TimeSeries],
                                    float] = metrics.mape,
                   reduction: Callable[[np.ndarray], float] = np.mean,
                   verbose=False) -> Tuple['ForecastingModel', Dict]:
        """
        A function for finding the best hyper-parameters among a given set.
        This function has 3 modes of operation: Expanding window mode, split mode and fitted value mode.
        The three modes of operation evaluate every possible combination of hyper-parameter values
        provided in the `parameters` dictionary by instantiating the `model_class` subclass
        of ForecastingModel with each combination, and returning the best-performing model with regards
        to the `metric` function. The `metric` function is expected to return an error value,
        thus the model resulting in the smallest `metric` output will be chosen.

        The relationship of the training data and test data depends on the mode of operation.

        Expanding window mode (activated when `forecast_horizon` is passed):
        For every hyperparameter combination, the model is repeatedly trained and evaluated on different
        splits of `training_series` and `target_series`. This process is accomplished by using
        the `backtest` function as a subroutine to produce historic forecasts starting from `start`
        that are compared against the ground truth values of `training_series` or `target_series`, if
        specified. Note that the model is retrained for every single prediction, thus this mode is slower.

        Split window mode (activated when `val_series` is passed):
        This mode will be used when the `val_series` argument is passed.
        For every hyper-parameter combination, the model is trained on `series` and
        evaluated on `val_series`.

        Fitted value mode (activated when `use_fitted_values` is set to `True`):
        For every hyper-parameter combination, the model is trained on `series`
        and evaluated on the resulting fitted values.
        Not all models have fitted values, and this method raises an error if the model doesn't have a `fitted_values`
        member. The fitted values are the result of the fit of the model on `series`. Comparing with the
        fitted values can be a quick way to assess the model, but one cannot see if the model is overfitting the series.

        Parameters
        ----------
        model_class
            The ForecastingModel subclass to be tuned for 'series'.
        parameters
            A dictionary containing as keys hyperparameter names, and as values lists of values for the
            respective hyperparameter.
        series
            The TimeSeries instance used as input and target for training.
        covariates
            An optional covariate series. This applies only if the model supports covariates.
        forecast_horizon
            The integer value of the forecasting horizon used in expanding window mode.
        start
            The `int`, `float` or `pandas.Timestamp` that represents the starting point in the time index
            of `training_series` from which predictions will be made to evaluate the model.
            For a detailed description of how the different data types are interpreted, please see the documentation
            for `ForecastingModel.backtest`.
        last_points_only
            Whether to use the whole forecasts or only the last point of each forecast to compute the error
        val_series
            The TimeSeries instance used for validation in split mode. If provided, this series must start right after
            the end of `series`; so that a proper comparison of the forecast can be made.
        use_fitted_values
            If `True`, uses the comparison with the fitted values.
            Raises an error if `fitted_values` is not an attribute of `model_class`.
        metric
            A function that takes two TimeSeries instances as inputs and returns a float error value.
        reduction
            A reduction function (mapping array to float) describing how to aggregate the errors obtained
            on the different validation series when backtesting. By default it'll compute the mean of errors.
        verbose
            Whether to print progress.

        Returns
        -------
        ForecastingModel, Dict
            A tuple containing an untrained 'model_class' instance created from the best-performing hyper-parameters,
            along with a dictionary containing these best hyper-parameters.
        """
        raise_if_not(
            (forecast_horizon is not None) + (val_series is not None) +
            use_fitted_values == 1,
            "Please pass exactly one of the arguments 'forecast_horizon', "
            "'val_target_series' or 'use_fitted_values'.", logger)

        if use_fitted_values:
            raise_if_not(
                hasattr(model_class(), "fitted_values"),
                "The model must have a fitted_values attribute to compare with the train TimeSeries",
                logger)

        elif val_series is not None:
            raise_if_not(
                series.width == val_series.width,
                "Training and validation series require the same number of components.",
                logger)

        if covariates is not None:
            raise_if_not(
                series.has_same_time_as(covariates),
                'The provided series and covariates must have the '
                'same time axes.')

        min_error = float('inf')
        best_param_combination = {}

        # compute all hyperparameter combinations from selection
        params_cross_product = list(product(*parameters.values()))

        # TODO: We should find a better object oriented way of handling covariates in GlobalForecastingModel
        fit_signature = signature(model_class.fit)
        predict_signature = signature(model_class.predict)

        # iterate through all combinations of the provided parameters and choose the best one
        iterator = _build_tqdm_iterator(params_cross_product, verbose)
        for param_combination in iterator:
            param_combination_dict = dict(
                list(zip(parameters.keys(), param_combination)))
            model = model_class(**param_combination_dict)
            if use_fitted_values:  # fitted value mode
                if covariates is not None and 'covariates' in fit_signature.parameters:
                    model.fit(series, covariates=covariates)
                else:
                    model.fit(series)
                fitted_values = TimeSeries.from_times_and_values(
                    series.time_index(), model.fitted_values)
                error = metric(fitted_values, series)
            elif val_series is None:  # expanding window mode
                error = model.backtest(series,
                                       covariates,
                                       start,
                                       forecast_horizon,
                                       metric=metric,
                                       reduction=reduction,
                                       last_points_only=last_points_only)
            else:  # split mode
                if covariates is not None and 'covariates' in fit_signature.parameters:
                    model.fit(series, covariates=covariates)
                else:
                    model.fit(series)

                if covariates is not None and 'covariates' in predict_signature.parameters:
                    pred = model.predict(n=len(val_series),
                                         covariates=covariates)
                else:
                    pred = model.predict(n=len(val_series))
                error = metric(pred, val_series)
            if error < min_error:
                min_error = error
                best_param_combination = param_combination_dict
        logger.info('Chosen parameters: ' + str(best_param_combination))

        return model_class(**best_param_combination), best_param_combination