Local variable referenced before assignment in If statement when calculating mean absolute error

Question:

I’m trying to add a weight to not penalize as much if prediction is greater than the actual in a forecast. Here’s my code, however, I keep getting:

UnboundLocalError: local variable ‘under’ referenced before assignment

import numpy as np

def mae(y, y_hat):
    if np.where(y_hat >= y):
        over = np.mean(0.5*(np.abs(y - y_hat)))
    elif np.where(y_hat < y):
        under = np.mean(np.abs(y - y_hat))
    return (over + under) / 2

I’ve tried setting ‘under’ to global but that doesn’t work either. This is probably an easy fix though I’m more of an R user.

Asked By: theduker

||

Answers:

So because of the if and elif statement, when you return np.mean(over,under), either under or over isn’t going to be defined. Therefore, you either need to initialize under and over with initial values or rework it because with you current logic only one of those variables will be defined.

EDIT

So you changed it to (over + under) / 2 as the return statement. Still one of them isn’t going to be defined. So you should initialize them as 0. Such as:

import numpy as np

def mae(y, y_hat):
    under = 0
    over = 0
    if np.where(y_hat >= y):
        over = np.mean(0.5*(np.abs(y - y_hat)))
    elif np.where(y_hat < y):
        under = np.mean(np.abs(y - y_hat))
    return (over + under) / 2

Then they won’t affect the output at all when not in use.

Answered By: Benjamin W.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.