## Forecast time series using k-nearest neighbors
f <- forecast(AirPassengers, h = 12, method = "knn")
f$pred
library(ggplot2)
autoplot(f)
## Using k-nearest neighbors changing the default k value
forecast(AirPassengers, h = 12, method = "knn", param = list(k = 5))$pred
## Using your own regression model
# Function to build the regression model
my_knn_model <- function(X, y) {
structure(list(X = X, y = y), class = "my_knn")
}
# Function to predict a new example
predict.my_knn <- function(object, new_value) {
FNN::knn.reg(train = object$X, test = new_value, y = object$y)$pred
}
forecast(AirPassengers, h = 12, method = my_knn_model)$pred
## Estimating forecast accuracy of the model
f <- forecast(UKgas, h = 4, lags = 1:4, method = "rf", efa = evaluation("minimum"))
f$efa
## Estimating forecast accuracy of different tuning parameters
f <- forecast(UKgas, h = 4, lags = 1:4, method = "knn", tuneGrid = expand.grid(k = 1:5))
f$tuneGrid
## Forecasting a trending series
# Without any preprocessing or transformation
f <- forecast(airmiles, h = 4, method = "knn", preProcess = list(trend("none")))
autoplot(f)
# Applying the additive transformation (default)
f <- forecast(airmiles, h = 4, method = "knn")
autoplot(f)
Run the code above in your browser using DataLab