我正在尝试预测每小时去医院急诊室的次数。几个小时的实际值是0,这在我为每个模型计算MAPE时是一个真正的问题。我看到了此question,在这里建议使用MASE(平均绝对标度误差),这也是由功能精度(预测包)给出的度量。但是,在我的情况下,这是不可能的,因为MASE提供了NaN。
因此,我尝试更改MAPE函数的原始代码,并仅使用我的项目所需的函数:首先,我为MAPE尝试了此代码,但是由于.resid
和.actual
是向量,因此它不起作用。
root_squared_error <- function(.resid, na.rm = TRUE, ...){sqrt(MSE(.resid, na.rm = na.rm))}
Mean_Abs_error <- function(.resid, na.rm = TRUE, ...){ mean(abs(.resid), na.rm = na.rm)}
Mean_Abs_percentage_error <- function(.resid, .actual, na.rm = TRUE, ...){
if(.resid == 0){
if(.actual == 0){
mean(abs(0), na.rm = na.rm)
} else{
mean(abs(100), na.rm = na.rm)
}
}
mean(abs(.resid / .actual * 100), na.rm = na.rm)
}
> accuracy(demand_fc_test,test, measures = list(RMSE = root_squared_error, MAE = Mean_Abs_error, MAPE = Mean_Abs_percentage_error))
# A tibble: 6 x 6
.model MTS .type RMSE MAE MAPE
<chr> <chr> <chr> <dbl> <dbl> <dbl>
1 Benchmark Blue Test 0.459 0.192 Inf
2 Benchmark Green Test 3.07 2.16 Inf
3 Benchmark Orange Test 0.579 0.280 Inf
4 Benchmark Red Test 0.0673 0.00453 100
5 Benchmark White Test 0.229 0.0516 Inf
6 Benchmark Yellow Test 2.38 1.74 Inf
Warning messages:
1: In if (.resid == 0) { :
the condition has length > 1 and only the first element will be used
此错误消息出现10次。经过一些研究,我看到了ifelse
函数解决类似问题的示例。但是,这不能完全起作用,因为它正在为每个值计算每个错误,并且不显示摘要表。
Mean_Abs_percentage_error <- function(.resid, .actual, na.rm = TRUE, ...){
ifelse(.resid == 0,
ifelse(.actual == 0, 0, 100),
abs(.resid / .actual * 100)
)}
> accuracy(demand_fc_test,test,
+ measures = list(RMSE = root_squared_error, MAE = Mean_Abs_error, MAPE = Mean_Abs_percentage_error))
# A tibble: 13,248 x 6
.model MTS .type RMSE MAE MAPE
<chr> <chr> <chr> <dbl> <dbl> <dbl>
1 Benchmark Blue Test 0.459 0.192 0
2 Benchmark Blue Test 0.459 0.192 0
3 Benchmark Blue Test 0.459 0.192 0
4 Benchmark Blue Test 0.459 0.192 0
5 Benchmark Blue Test 0.459 0.192 0
6 Benchmark Blue Test 0.459 0.192 0
7 Benchmark Blue Test 0.459 0.192 0
8 Benchmark Blue Test 0.459 0.192 0
9 Benchmark Blue Test 0.459 0.192 0
10 Benchmark Blue Test 0.459 0.192 0
# ... with 13,238 more rows
我认为问题出在我使用ifelse
函数的方式上。我需要将该条件应用于每个预测的每个值(在我有多个模型的情况下),并且它应该返回每个模型的平均值。我正在尝试获得与应用精度函数而未作任何更改一样的输出,这是我需要一个具有n行和6列的tsiblle,其中n是模型数。
关于如何解决我的问题的任何建议?预先谢谢你。
我的数据示例:
library(fpp3)
library(fasster)
> dados
# A tsibble: 140,400 x 7 [1h] <UTC>
# Key: MTS [6]
Date Weekday MTS Demand Temperature DaysToHoliday DaysAfterHoliday
<dttm> <int> <chr> <int> <dbl> <int> <int>
1 2017-05-01 00:00:00 1 Blue 0 11.4 0 0
2 2017-05-01 01:00:00 1 Blue 0 11.2 0 0
3 2017-05-01 02:00:00 1 Blue 1 11.2 0 0
4 2017-05-01 03:00:00 1 Blue 0 10.9 0 0
5 2017-05-01 04:00:00 1 Blue 1 10.9 0 0
基于在线快速搜索,这是MAPE在其中具有零值的时间序列方面的已知缺点。建议使用sMAPE。这是我查看的维基百科页面,当我搜索时还有另外两个博客文章:https://en.wikipedia.org/wiki/Mean_absolute_percentage_error
免责声明:尽管这不是完全的解决方案,但应作为评论,但由于我目前的排名低于50,因此我无法发表评论。希望对您有所帮助。