首页 > 解决方案 > R 中的 forecast() 函数的默认训练集和测试集大小是多少?

问题描述

我在我的数据上使用了 TBATS 模型,当我应用 forecast() 函数时,它会自动预测未来两年。我没有指定任何训练集或测试集,那么我怎么知道它使用了多少数据来预测未来两年呢?

我正在处理的数据是 2016 年 1 月至 2020 年 1 月的 Uber 出行时间数据。我有 18 个城市的每日数据(采样频率 = 1),每个城市都有不同的样本量(范围从 1422 天到 1459 天) .

这就是阿姆斯特丹旅行时间数据的样子

我已将旅行时间向量设置为一个msts对象,因为它具有多个季节性,由 TBATS 模型使用。

当我计算 RMSE、MAE、MAPE 和 MSE 时,我通常会得到非常低的值,那么我如何知道 TBATS 正在训练哪些数据?

这是我的代码:

data <- read.csv('C:/users/Datasets/Final Datasets/final_a.csv', TRUE, ",")
y <- msts(data$MeanTravelTimeSeconds, start=c(2016,1), seasonal.periods=c(7.009615384615385, 30.5, 91.3, 365.25))

fit <- tbats(y)
plot(fit)
fc <- forecast(fit)
autoplot(fc, ylab = "Travel Time in Seconds")

# Check residuals (ACF and histogram)
checkresiduals(fc)

# RMSE
rmse <- sqrt(fit$variance)

# MAE
res <- residuals(fit)
mae <- mean(abs(res))

# MAPE
pt <- (res)/y
mape <- mean(abs(pt))

# MSE (Mean Squared Error)
mse <- mean(res^2)

这就是预测的样子

阿姆斯特丹的 TBATS 模型的性能结果是:

RMSE: 0.06056063
MAE: 0.04592825
MAPE: 6.474616e-05
MSE: 0.00366759

如果我必须手动选择测试集和训练集,我应该如何修改我的代码才能这样做?

标签: rtime-seriesdatasettraining-dataforecast

解决方案


如果你forecast(fit)像你一样使用 ,你得到的是训练数据中的拟合值。

如果您还想使用测试集,请参见下面的示例。您使用拟合模型预测到水平 h 并与已知数据集进行比较。

library(forecast)

# Training Data
n_train <- round(length(USAccDeaths) * 0.8)
train <- head(USAccDeaths, n_train)

# Test Data
n_test <- length(USAccDeaths) - n_train
test <- tail(USAccDeaths, n_test)

# Model Fit
fit <- tbats(train)

# Forecast for the same horizion as the test data
fc <- forecast(fit, n_test)

# Point Forecasts 
fc$mean
#            Jan       Feb       Mar       Apr       May       Jun       Jul
# 1977                      7767.513  7943.791  8777.425  9358.863 10034.996
# 1978  7711.478  7004.621  7767.513  7943.791  8777.425  9358.863 10034.996
#            Aug       Sep       Oct       Nov       Dec
# 1977  9517.860  8370.509  8706.441  8190.262  8320.606
# 1978  9517.860  8370.509  8706.441  8190.262  8320.606

test # for comparison with the point forecasts
#        Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
# 1977              7726  8106  8890  9299 10625  9302  8314  8850  8265  8796
# 1978  7836  6892  7791  8192  9115  9434 10484  9827  9110  9070  8633  9240

看看像下面这样的情节如何表现也会很有趣。

autoplot(USAccDeaths) + autolayer(fc) + autolayer(fitted(fit))
#autoplot(USAccDeaths) +  autolayer(fitted(fit))

在此处输入图像描述


推荐阅读