python中的MAPE计算

2024-05-16 01:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算预测值和真值的平均绝对百分比误差(MAPE)。我从here找到了一个解决方案,但这会产生错误,并在mask = a <> 0行中显示无效语法

    def mape_vectorized_v2(a, b): 
    mask = a <> 0
    return (np.fabs(a - b)/a)[mask].mean() 

   def mape_vectorized_v2(a, b): 
       File "<ipython-input-5-afa5c1162e83>", line 1
         def mape_vectorized_v2(a, b):
                                       ^
     SyntaxError: unexpected EOF while parsing

我在用spyder3。我的预测值是np.array类型,真正的值是dataframe

type(predicted)
Out[7]: numpy.ndarray
type(y_test)
Out[8]: pandas.core.frame.DataFrame

如何清除此错误并继续MAPE计算?

编辑:

predicted.head()
Out[22]: 
   Total_kWh
0   7.163627
1   6.584960
2   6.638057
3   7.785487
4   6.994427

y_test.head()
Out[23]: 
     Total_kWh
79         7.2
148        6.7
143        6.7
189        7.2
17         6.4

np.abs(y_test[['Total_kWh']] - predicted[['Total_kWh']]).head()
Out[24]: 
   Total_kWh
0        NaN
1        NaN
2        NaN
3        NaN
4   0.094427

Tags: testdefnpmasknanoutheadv2
2条回答

在python中用于比较的不等于需要!=,而不是<>

所以需要:

def mape_vectorized_v2(a, b): 
    mask = a != 0
    return (np.fabs(a - b)/a)[mask].mean()

来自stats.stackexchange的另一个解决方案:

def mean_absolute_percentage_error(y_true, y_pred): 
    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100

这两种解决方案都不能使用零值。这是我的工作方式:

def percentage_error(actual, predicted):
    res = np.empty(actual.shape)
    for j in range(actual.shape[0]):
        if actual[j] != 0:
            res[j] = (actual[j] - predicted[j]) / actual[j]
        else:
            res[j] = predicted[j] / np.mean(actual)
    return res

def mean_absolute_percentage_error(y_true, y_pred): 
    return np.mean(np.abs(percentage_error(np.asarray(y_true), np.asarray(y_pred)))) * 100

我希望有帮助。

相关问题 更多 >