本文介绍了python中的MAPE计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算预测值和真实值的平均绝对百分比误差 (MAPE).我从这里找到了一个解决方案,但这给出了错误并显示无效mask = a <> 行中的语法0
def mape_vectorized_v2(a, b):掩码 = a <>0返回 (np.fabs(a - b)/a)[mask].mean()def mape_vectorized_v2(a, b):文件<ipython-input-5-afa5c1162e83>",第 1 行def mape_vectorized_v2(a, b):^SyntaxError:解析时出现意外的 EOF
我正在使用 spyder3.我的预测值是 np.array 类型,真实值是数据框
类型(预测)出[7]:numpy.ndarray类型(y_test)出[8]:pandas.core.frame.DataFrame
如何清除此错误并继续进行 MAPE 计算?
predicted.head()出[22]:Total_kWh0 7.1636271 6.5849602 6.6380573 7.7854874 6.994427y_test.head()出[23]:Total_kWh79 7.2148 6.7143 6.7189 7.217 6.4np.abs(y_test[['Total_kWh']] - 预测[['Total_kWh']]).head()出[24]:Total_kWh0 南1 纳米2 南3 南4 0.094427
解决方案
在python中进行不等比较需要!=
,而不是.
>
所以需要:
def mape_vectorized_v2(a, b):掩码 = a != 0返回 (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)返回 np.mean(np.abs((y_true - y_pred)/y_true)) * 100
I want to calculate Mean Absolute percentage error (MAPE) of predicted and true values. I found a solution from here, but this gives error and shows invalid syntax in the line 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
I am using spyder3. My predicted value is a type np.array and true value is dataframe
type(predicted)
Out[7]: numpy.ndarray
type(y_test)
Out[8]: pandas.core.frame.DataFrame
How do i clear this error and proceed with MAPE Calculation ?
Edit :
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
解决方案
In python for compare by not equal need !=
, not <>
.
So need:
def mape_vectorized_v2(a, b):
mask = a != 0
return (np.fabs(a - b)/a)[mask].mean()
Another solution from 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
这篇关于python中的MAPE计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!