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'))
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())
def predict_time_series(self, val: TimeSeries): super().predict(len(val)) x_test = val.time_index() # Reshape data x_test = np.array(x_test).reshape(x_test.shape[0], 1) forecast = self.model.predict(x_test) return self._build_forecast_series(forecast)
def fit(self, series: TimeSeries): super().fit(series) series = self.training_series # defined in super() x_train = series.time_index() y = series.univariate_values() self.last_tick = x_train[-1] # Reshape data x_train = np.array(x_train).reshape(x_train.shape[0], 1) self.model.fit(x_train, y)
def residuals(self, series: TimeSeries, forecast_horizon: int = 1, verbose: bool = False) -> TimeSeries: """ A function for computing the residuals produced by the current model on a univariate time series. This function computes the difference between the actual observations from `series` and the fitted values vector `p` obtained by training the model on `series`. For every index `i` in `series`, `p[i]` is computed by training the model on `series[:(i - forecast_horizon)]` and forecasting `forecast_horizon` into the future. (`p[i]` will be set to the last value of the predicted series.) The vector of residuals will be shorter than `series` due to the minimum training series length required by the model and the gap introduced by `forecast_horizon`. Most commonly, unless otherwise specified, the term "residuals" implies a value for `forecast_horizon` of 1. This method works only on univariate series and does not currently support covariates. Parameters ---------- series The univariate TimeSeries instance which the residuals will be computed for. forecast_horizon The forecasting horizon used to predict each fitted value. verbose Whether to print progress. Returns ------- TimeSeries The vector of residuals. """ series._assert_univariate() # get first index not contained in the first training set first_index = series.time_index()[self.min_train_series_length] # compute fitted values p = self.historical_forecasts(series=series, start=first_index, forecast_horizon=forecast_horizon, stride=1, retrain=True, last_points_only=True, verbose=verbose) # compute residuals series_trimmed = series.slice_intersect(p) residuals = series_trimmed - p return residuals
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())
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())
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())
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
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
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())
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())