簡體   English   中英

嘗試在預測對象上應用預測方法時出錯

[英]Error when trying to apply forecasting methods on forecast object

我想編寫自己的預測函數,分配forecast對象並在該對象上使用預測包中的使用函數。 我嘗試通過以下方式復制meanf函數(使用此方法如何在R中創建預測對象 ):

myfun <- function(x, h, ...)
{
  # Compute some forecasts
  fc <- rep(mean(x), h)
  # Construct output list
  output <- list(mean=fc, x=x, ...)
  # Return with forecasting class
  return(structure(output, class='forecast'))
}

但是當我應用精度函數時:

# sample dataset
price <- c(351.75, 347, 348, 342, 339, 339.86, 342.61, 345, 340, 336.11, 
           331, 333.94, 330.01, 317, 313, 313.98, 315, 319.45, 313, 316, 
           316.5, 315, 320, 315, 311.23, 305.55, 298.02, 291.8, 294.98, 
           296.44, 296, 294, 290.65, 288, 291.99, 295, 310, 303.1, 306.11, 
           309.51, 312.51, 328.1, 328.1, 324.8, 329.23, 337.01, 333.6, 333, 
           327.23, 328.5, 328.54, 324.5, 322, 317.01, 318, 319.98, 329.8, 
           323, 317, 318.55, 319.98, 323.99, 316.09, 315.01, 317.5, 315.03, 
           312.55, 312, 315, 312.89, 308.5, 295.53, 308, 315, 285.12, 284.34, 
           285, 281.39, 282.92, 285.94, 284.96, 282.9, 273.5, 273.5, 273.21, 
           281.14, 286.99, 283, 280.39, 283, 280, 285, 285.02, 289, 288, 
           284.5, 280.83, 278.3, 274.1, 276)
price <- ts(price, start = 1, frequency = 1)
train <- subset(price, end = length(price) - 10)
test <- subset(price, start = (length(price) + 1) - 10)

# my forecast function
myfun <- function(x, h, ...)
{
  # Compute some forecasts
  fc <- rep(mean(x), h)
  # Construct output list
  output <- list(mean=fc, x=x, ...)
  # Return with forecasting class
  return(structure(output, class='forecast'))
}

# aplpy function and accuracy
myMean <- myfun(train, 10)
accuracy(myMean, test)

它返回一個錯誤:

NextMethod(.Generic)中的錯誤:無法將“ tsp”分配給零長度向量

我不明白這個錯誤?

問題是您的output沒有適合的值元素。 這很重要,因為forecast:::accuracy.default()調用forecast:::trainingaccuracy() ,后者又調用fitted()並嘗試從時間序列對象中減去結果。 fitted()的結果為NULL ,您將收到該錯誤。 我們可以通過修改myMean()來解決它:

myfun <- function(x, h, ...)
{
    # Compute some forecasts
    xmean <- mean(x)
    fc <- rep(xmean, h)
    fitted.values <- rep(xmean, length(x))
    # Construct output list
    output <- list(mean=fc, x=x, fitted.values=fitted.values, ...)
    # Return with forecasting class
    return(structure(output, class='forecast'))
}

# aplpy function and accuracy
myMean <- myfun(train, 10)
accuracy(myMean, test)

#                         ME     RMSE      MAE         MPE      MAPE     MASE
# Training set -1.388816e-14 19.61672 15.93970  -0.4032892  5.180507 3.718275
# Test set     -2.989633e+01 30.27324 29.89633 -10.6303518 10.630352 6.973957
#                   ACF1 Theil's U
# Training set 0.9181787        NA
# Test set     0.6992239  9.267271

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM