You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R语言hts包计算分层时间序列准确率出现non-conformable arrays报错

问题原因排查及解决方法

Error in x - fcasts : non-conformable arrays报错的核心原因是测试集test的时间序列长度和预测结果fcasts的步长不匹配,hts包的accuracy()函数要求预测结果的时间长度和测试集的时间长度完全一致才能逐点计算误差。
具体存在两个问题:

  • 你使用的周度频率为365.25/7 ≈ 52.17857,手动设置的data结束位置2021.166和test开始位置2021.185换算为周数后,最终test的长度不等于设定的预测步长h=20,两个数组维度不一致触发报错。
  • 你写的accuracy(fcasts test, levels = 1)存在语法错误,两个参数之间漏了逗号,正确写法为accuracy(fcasts, test, levels = 1)。

修正后的可运行代码

library(hts)
abc <- matrix(sample(1:100, 32*140, replace=TRUE), ncol=32)
colnames(abc) <- c(
  paste0("A0",1:5), 
  paste0("B0",1:9),"B10",
  paste0("C0",1:8),
  paste0("D0",1:5),
  paste0("E0",1:4)
)
abc <- ts(abc, start=2019, frequency=365.25/7)
x <- hts(abc, characters = c(1,2))

# 按索引拆分训练集和测试集,保证测试集长度等于预测步长20
total_obs <- nrow(x)
train_end <- total_obs - 20
data <- window(x, end = time(x)[train_end])
test <- window(x, start = time(x)[train_end + 1])

fcasts <- forecast(data, h = 20, method = "bu")
# 计算准确率
accuracy(fcasts, test)
accuracy(fcasts, test, levels = 1)

额外注意事项

  • 预测时出现的32条警告是默认基础预测模型(ETS)对部分序列拟合的常规提示,不影响准确率计算,无需特殊处理。
  • 周度频率下手动输入浮点型时间起止点很容易出现计算偏差,用索引定位训练集、测试集的起止位置更稳妥。

内容的提问来源于stack exchange,提问作者Aureon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:06:03