MaxRelativeError

MaxRelativeError#

import numpy as np

def max_relative_error(y_true: np.ndarray | list, y_pred: np.ndarray | list) -> float:
    """
    Calculate the Maximum Relative Error (MRE) between true values and predicted values.

    Parameters:
    y_true (np.ndarray | list): Array or list of true values.
    y_pred (np.ndarray | list): Array or list of predicted values.

    Returns:
    float: The mean relative error.
    """
    # Convert inputs to numpy arrays if they are not already
    y_true = np.asarray(y_true, dtype=np.float64)
    y_pred = np.asarray(y_pred, dtype=np.float64)
    
    # Calculate the absolute differences
    d = np.abs(y_true - y_pred)
    
    # Avoid division by zero by adding a small epsilon value
    epsilon = np.finfo(float).eps
    denominator = np.abs(y_true) + epsilon
    
    # Calculate relative errors and find the maximum
    relative_error = np.max(d / denominator)
    return relative_error