|
|
|
|
|
import numpy as np |
|
import torch |
|
import torch.nn.functional as F |
|
|
|
|
|
def masked_mape_np(y_true, y_pred, null_val=np.nan): |
|
with np.errstate(divide='ignore', invalid='ignore'): |
|
if np.isnan(null_val): |
|
mask = ~np.isnan(y_true) |
|
else: |
|
mask = np.not_equal(y_true, null_val) |
|
mask = mask.astype('float32') |
|
mask /= np.mean(mask) |
|
mape = np.abs(np.divide(np.subtract(y_pred, y_true).astype('float32'), |
|
y_true)) |
|
mape = np.nan_to_num(mask * mape) |
|
return np.mean(mape) |
|
|
|
|
|
def masked_mse(preds, labels, null_val=np.nan): |
|
if np.isnan(null_val): |
|
mask = ~torch.isnan(labels) |
|
else: |
|
mask = (labels != null_val) |
|
mask = mask.float() |
|
|
|
|
|
mask /= torch.mean((mask)) |
|
mask = torch.where(torch.isnan(mask), torch.zeros_like(mask), mask) |
|
loss = (preds - labels) ** 2 |
|
loss = loss * mask |
|
loss = torch.where(torch.isnan(loss), torch.zeros_like(loss), loss) |
|
return torch.mean(loss) |
|
|
|
|
|
def masked_rmse(preds, labels, null_val=np.nan): |
|
return torch.sqrt(masked_mse(preds=preds, labels=labels, |
|
null_val=null_val)) |
|
|
|
|
|
def masked_mae(preds, labels, null_val=np.nan): |
|
if np.isnan(null_val): |
|
mask = ~torch.isnan(labels) |
|
else: |
|
mask = (labels != null_val) |
|
mask = mask.float() |
|
mask /= torch.mean((mask)) |
|
mask = torch.where(torch.isnan(mask), torch.zeros_like(mask), mask) |
|
loss = torch.abs(preds - labels) |
|
loss = loss * mask |
|
loss = torch.where(torch.isnan(loss), torch.zeros_like(loss), loss) |
|
return torch.mean(loss) |
|
|
|
|
|
def masked_mae_test(y_true, y_pred, null_val=np.nan): |
|
with np.errstate(divide='ignore', invalid='ignore'): |
|
if np.isnan(null_val): |
|
mask = ~np.isnan(y_true) |
|
else: |
|
mask = np.not_equal(y_true, null_val) |
|
mask = mask.astype('float32') |
|
mask /= np.mean(mask) |
|
mae = np.abs(np.subtract(y_pred, y_true).astype('float32'), |
|
) |
|
mae = np.nan_to_num(mask * mae) |
|
return np.mean(mae) |
|
|
|
|
|
def masked_rmse_test(y_true, y_pred, null_val=np.nan): |
|
with np.errstate(divide='ignore', invalid='ignore'): |
|
if np.isnan(null_val): |
|
mask = ~np.isnan(y_true) |
|
else: |
|
|
|
mask = np.not_equal(y_true, null_val) |
|
mask = mask.astype('float32') |
|
mask /= np.mean(mask) |
|
mse = ((y_pred - y_true) ** 2) |
|
mse = np.nan_to_num(mask * mse) |
|
return np.sqrt(np.mean(mse)) |
|
|
|
|
|
def sce_loss(x, y, alpha=3): |
|
x = F.normalize(x, p=2, dim=-1) |
|
y = F.normalize(y, p=2, dim=-1) |
|
|
|
|
|
|
|
|
|
loss = (1 - (x * y).sum(dim=-1)).pow_(alpha) |
|
|
|
loss = loss.mean() |
|
return loss |
|
|