Calculate the mean Huber loss between the given ground truth and predicted values. The Huber loss describes the penalty incurred by an estimation procedure, and it serves as a measure of accuracy for regression models. Huber loss = 0.5 * (y_true - y_pred)^2
(y_true: np.ndarray, y_pred: np.ndarray, delta: float)
| 291 | |
| 292 | |
| 293 | def huber_loss(y_true: np.ndarray, y_pred: np.ndarray, delta: float) -> float: |
| 294 | """ |
| 295 | Calculate the mean Huber loss between the given ground truth and predicted values. |
| 296 | |
| 297 | The Huber loss describes the penalty incurred by an estimation procedure, and it |
| 298 | serves as a measure of accuracy for regression models. |
| 299 | |
| 300 | Huber loss = |
| 301 | 0.5 * (y_true - y_pred)^2 if |y_true - y_pred| <= delta |
| 302 | delta * |y_true - y_pred| - 0.5 * delta^2 otherwise |
| 303 | |
| 304 | Reference: https://en.wikipedia.org/wiki/Huber_loss |
| 305 | |
| 306 | Parameters: |
| 307 | - y_true: The true values (ground truth) |
| 308 | - y_pred: The predicted values |
| 309 | |
| 310 | >>> true_values = np.array([0.9, 10.0, 2.0, 1.0, 5.2]) |
| 311 | >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2]) |
| 312 | >>> bool(np.isclose(huber_loss(true_values, predicted_values, 1.0), 2.102)) |
| 313 | True |
| 314 | >>> true_labels = np.array([11.0, 21.0, 3.32, 4.0, 5.0]) |
| 315 | >>> predicted_probs = np.array([8.3, 20.8, 2.9, 11.2, 5.0]) |
| 316 | >>> bool(np.isclose(huber_loss(true_labels, predicted_probs, 1.0), 1.80164)) |
| 317 | True |
| 318 | >>> true_labels = np.array([11.0, 21.0, 3.32, 4.0]) |
| 319 | >>> predicted_probs = np.array([8.3, 20.8, 2.9, 11.2, 5.0]) |
| 320 | >>> huber_loss(true_labels, predicted_probs, 1.0) |
| 321 | Traceback (most recent call last): |
| 322 | ... |
| 323 | ValueError: Input arrays must have the same length. |
| 324 | """ |
| 325 | if len(y_true) != len(y_pred): |
| 326 | raise ValueError("Input arrays must have the same length.") |
| 327 | |
| 328 | huber_mse = 0.5 * (y_true - y_pred) ** 2 |
| 329 | huber_mae = delta * (np.abs(y_true - y_pred) - 0.5 * delta) |
| 330 | return np.where(np.abs(y_true - y_pred) <= delta, huber_mse, huber_mae).mean() |
| 331 | |
| 332 | |
| 333 | def mean_squared_error(y_true: np.ndarray, y_pred: np.ndarray) -> float: |
nothing calls this directly
no outgoing calls
no test coverage detected