训练集和测试集的长度与实际集的长度不同

The length of the train and test sets are different from the length of the actual set

我正在使用 test_forecast 并且我的代码设置如下

df_train <- df[1:20] 
df_test <- df[21:nrow(df)] 

test_forecast(actual = df, 
              forecast.obj = forecast,
              train = df_train, 
              test = df_test)

df 中的每一行都包含在 df train 和 df test 中。

但是,它给了我这个错误

Error in test_forecast(actual = df, forecast.obj = forecast,  : 
  The length of the train and test sets are different from the length of the actual set

df 是一个数据 table,但我也尝试过将所有对象转换为数据帧,但没有用

我尝试了一个数据框和一个数据 table 并得到了完全相同的错误消息。

仔细阅读后test_forecastdocumentation,我发现:

actual: The full time series object (supports "ts", "zoo" and "xts" formats).

结论是 test_forecast 不应该与 data.frames / data.tables 一起使用。

由于您没有提供您正在使用的数据,我尝试了 this example 并且有效:

library(TSstudio)
ts <- USgas
ts_par <- ts_split(ts, sample.out = 20)

train <- ts_par$train

test <- ts_par$test

ts_info(train)
ts_info(test)

library(forecast)

md <- tslm(train ~ season + trend)

fc <- forecast(md, h = 20)
test_forecast(actual = ts,
              forecast.obj = fc,
              test = test)

另一个重要的一点是,您不应该像使用 data.table 那样对时间序列进行子集化,因为它会变成 numeric,这样它就无法使用 test_forecast ]:

class(USgas[1:20])
[1] "numeric"