# Mean Absolute percentage error getting infinity?

i have written a function for calculating mape using python here i am mentioning the function :

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

except Exception as inst:
self.log.info('<------------- mean_absolute_percentage_error ---------------> ')
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)
self.log.info(str(exc_type)+' '+str(fname)+' '+str(exc_tb.tb_lineno))


Some times i am getting infinity value as mape ,please suggest on this how to avoid this problem not to get this infinity value as mape. Thanks in advance .

• Does y_true have zero values?
– Sycorax
Jun 24, 2020 at 13:03
• yes some datasets getting zero values ,how to overcome this infinity value in mape. Jun 24, 2020 at 13:05

MAPE doesn't make sense when y_true can be zero, because division by zero is not defined. You'll have to use a different measurement.

Excluding values where y_true is zero is not good practice; sometimes your data is zero, and you need to model that. In other words, the choice of MAPE is the problem, not the data.

MAE will behave similarly, except that it is expressed in terms of the original units, instead of as a percentage. On the other hand, MAE is not differentiable at zero. If differentiability is important, log-cosh loss could be useful as a smooth approximation to MAE, and it's everywhere differentiable.

You may find these answers helpful. What are the shortcomings of the Mean Absolute Percentage Error (MAPE)?

• Thanks for the answer , we need to check y_true is zero or not then only we can use mape as metrics. Jun 24, 2020 at 13:45

What you are calculating is the absolute relative error. This can go to infinity for y_true = 0.

• i am calculating mean absolute percentage error ,some times i am getting mape as infinity,how to overcome this value . Jun 24, 2020 at 13:06
• if you have y_true = 0, then you cannot use the relative error. One workaround is to add a small value $\epsilon$ to the denominator.
– user289381
Jun 24, 2020 at 13:11
• If y_true can take on values of $-\epsilon$, adding $\epsilon$ doesn't solve the problem.
– Sycorax
Jun 24, 2020 at 13:17
• True. You can add $\epsilon$ to y_true=0 if y_true are observations with some degree of error. If not, you cannot use the MAPE.
– user289381
Jun 24, 2020 at 13:20
• Thanks you for all suggestions. Jun 24, 2020 at 13:44