Search code examples
pythonnumpydimension

Implicit handling of dimensions?


I have the following function to do Mean Average Percentage Error :

def mape(ys,yhat):
    if yhat.ndim == 1 :
        return np.sum(np.abs(ys - yhat)) / float(np.sum(ys))
    else :
        return np.sum(np.abs(ys - yhat), axis=1) / float(np.sum(ys))

The problem I have to explicitly check for the number of dimensions of the second operand. is there a way for numpy to handle this internally OR if I can call the function in different way, so I dont need to check dims explicitly.


Solution

  • Negative axis numbers count from the last axis, so to unconditionally sum along the last axis, you can specify axis=-1:

    return np.sum(np.abs(ys - yhat), axis=-1) / float(np.sum(ys))