knn_forecasting function

Time series forecasting using KNN regression

Time series forecasting using KNN regression

It applies KNN regression to forecast the future values of a time series. The lags used as autoregressive variables are set with the lags

parameter. If the user does not set the number of nearest neighbors or the lags, these values are selected automatically.

knn_forecasting( timeS, h, lags = NULL, k = c(3, 5, 7), msas = c("recursive", "MIMO"), cf = c("mean", "median", "weighted"), transform = c("additive", "multiplicative", "none") )

Arguments

  • timeS: A numeric vector or time series of class ts.
  • h: A positive integer. Number of values to forecast.
  • lags: An integer vector in increasing order expressing the lags used as autoregressive variables.
  • k: A positive integer. The k parameter in KNN regression. A vector of k values can also be used. In that case, the forecast is the average of the forecasts produced by the different models with the different k parameters.
  • msas: A string indicating the Multiple-Step Ahead Strategy used when more than one value is predicted. It can be "recursive" or "MIMO" (the default).
  • cf: A string. It indicates the combination function used to aggregate the targets associated with the nearest neighbors. It can be "median", "weighted" or "mean" (the default).
  • transform: A character value indicating whether the training samples are transformed. If the time series has a trend it is recommended. By default is "multiplicative" (multiplicative transformation). It is also possible a multiplicative transformation or no transformation.

Returns

An object of class "knnForecast". The function summary can be used to obtain or print a summary of the results.

An object of class \code{"knnForecast"} is a list containing at least
the following components:
  • call: the matched call.

  • msas: the Multi-Step Ahead Strategy.

  • prediction: a time series with the forecast.

  • model: an object of class "knnModel" with the KNN model

Examples

pred <- knn_forecasting(USAccDeaths, h = 12, lags = 1:12, k = 2) pred$prediction # To see a time series with the forecasts plot(pred) # To see a plot with the forecast