Calculate the mean hinge loss for between true labels and predicted probabilities for training support vector machines (SVMs). Hinge loss = max(0, 1 - true * pred) Reference: https://en.wikipedia.org/wiki/Hinge_loss Args: - y_true: actual values (ground truth) encoded as
(y_true: np.ndarray, y_pred: np.ndarray)
| 251 | |
| 252 | |
| 253 | def hinge_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float: |
| 254 | """ |
| 255 | Calculate the mean hinge loss for between true labels and predicted probabilities |
| 256 | for training support vector machines (SVMs). |
| 257 | |
| 258 | Hinge loss = max(0, 1 - true * pred) |
| 259 | |
| 260 | Reference: https://en.wikipedia.org/wiki/Hinge_loss |
| 261 | |
| 262 | Args: |
| 263 | - y_true: actual values (ground truth) encoded as -1 or 1 |
| 264 | - y_pred: predicted values |
| 265 | |
| 266 | >>> true_labels = np.array([-1, 1, 1, -1, 1]) |
| 267 | >>> pred = np.array([-4, -0.3, 0.7, 5, 10]) |
| 268 | >>> float(hinge_loss(true_labels, pred)) |
| 269 | 1.52 |
| 270 | >>> true_labels = np.array([-1, 1, 1, -1, 1, 1]) |
| 271 | >>> pred = np.array([-4, -0.3, 0.7, 5, 10]) |
| 272 | >>> hinge_loss(true_labels, pred) |
| 273 | Traceback (most recent call last): |
| 274 | ... |
| 275 | ValueError: Length of predicted and actual array must be same. |
| 276 | >>> true_labels = np.array([-1, 1, 10, -1, 1]) |
| 277 | >>> pred = np.array([-4, -0.3, 0.7, 5, 10]) |
| 278 | >>> hinge_loss(true_labels, pred) |
| 279 | Traceback (most recent call last): |
| 280 | ... |
| 281 | ValueError: y_true can have values -1 or 1 only. |
| 282 | """ |
| 283 | if len(y_true) != len(y_pred): |
| 284 | raise ValueError("Length of predicted and actual array must be same.") |
| 285 | |
| 286 | if np.any((y_true != -1) & (y_true != 1)): |
| 287 | raise ValueError("y_true can have values -1 or 1 only.") |
| 288 | |
| 289 | hinge_losses = np.maximum(0, 1.0 - (y_true * y_pred)) |
| 290 | return np.mean(hinge_losses) |
| 291 | |
| 292 | |
| 293 | def huber_loss(y_true: np.ndarray, y_pred: np.ndarray, delta: float) -> float: |
nothing calls this directly
no outgoing calls
no test coverage detected