Skip to content

Instantly share code, notes, and snippets.

@khalido
Created April 20, 2020 08:56
Show Gist options
  • Save khalido/4356f1e8357c88ed4317822448ff4483 to your computer and use it in GitHub Desktop.
Save khalido/4356f1e8357c88ed4317822448ff4483 to your computer and use it in GitHub Desktop.
# below code from
# https://alex.miller.im/posts/linear-model-custom-loss-function-regularization-python/
def mean_absolute_percentage_error(y_pred, y_true, sample_weights=None):
"""Mean absolute percentage error regression loss"""
y_true = np.array(y_true)
y_pred = np.array(y_pred)
assert len(y_true) == len(y_pred)
if np.any(y_true==0):
print("Found zeroes in y_true. MAPE undefined. Removing from set...")
idx = np.where(y_true==0)
y_true = np.delete(y_true, idx)
y_pred = np.delete(y_pred, idx)
if type(sample_weights) != type(None):
sample_weights = np.array(sample_weights)
sample_weights = np.delete(sample_weights, idx)
if type(sample_weights) == type(None):
return(np.mean(np.abs((y_true - y_pred) / y_true)) * 100)
else:
sample_weights = np.array(sample_weights)
assert len(sample_weights) == len(y_true)
return(100/sum(sample_weights)*np.dot(
sample_weights, (np.abs((y_true - y_pred) / y_true))
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment