fabletools::autoplot()报错:数据与预测键结构不匹配及绘图咨询
问题描述
刚接触交叉验证预测,使用tsibble库的global_economy数据集预测美国GDP时,无法正确使用autoplot()函数实现需求:仅展示最后4年的预测结果,并叠加在全量数据集(仅美国)之上。
- 留空
autoplot()参数时,会生成全时间段的预测图表,但不符合需求; - 尝试在
autoplot()中嵌套filter_index(. ~ "2014")、filter(Country=="United States")均无效; - 报错信息:
Error in
fabletools::autoplot(): ! Provided data contains a different key structure to the forecasts
原代码如下:
econ <- global_economy model <- econ %>% filter(Country=="United States") %>% stretch_tsibble(.init=15, .step=1) %>% model(NAIVE(GDP),NNETAR(GDP)) %>% fabletools::forecast(h="1 year") model %>% group_by(.id,.model) %>% mutate(h = row_number()) %>% ungroup() %>% as_fable(response = "GDP", distribution = GDP) %>% filter(h==1) %>% as_fable(key=c(.model)) %>% fabletools::autoplot(econ)
解决方案
报错原因
原代码中传给autoplot()的econ是全量数据集(包含所有国家),而预测结果仅针对美国,两者的key结构不匹配(全量数据的key是Country,预测结果的key是.model+Country),导致报错。同时,预测结果的处理步骤存在冗余,且未正确筛选最后4年的预测数据。
修正代码
library(fabletools) library(tsibble) library(dplyr) # 1. 提前筛选美国的经济数据,保证后续key结构匹配 us_econ <- global_economy %>% filter(Country == "United States") # 2. 交叉验证建模+预测 model <- us_econ %>% stretch_tsibble(.init=15, .step=1) %>% model(NAIVE(GDP), NNETAR(GDP)) %>% forecast(h="1 year") # 3. 筛选最后4年的预测结果(假设最后4年为2014-2017,可根据数据动态调整) last_4_forecasts <- model %>% filter_index("2014" ~ .) # 筛选2014年及以后的预测 # 4. 绘制预测结果+原始数据 last_4_forecasts %>% autoplot(us_econ)
关键说明
- 提前生成
us_econ:仅保留美国的数据,确保和预测结果的key(Country="United States"+.model)结构匹配,解决autoplot的key不兼容问题; - 筛选最后4年的预测:使用
filter_index("2014" ~ .)直接按时间筛选,若要动态适配数据的最后4年,可替换为:last_year <- year(last(us_econ$Year)) last_4_forecasts <- model %>% filter(year(Year) >= last_year - 3) - 简化预测结果处理:无需重复调用
as_fable(),forecast()输出的结果本身就是fable格式,可直接筛选和绘图。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

