|
| 1 | +import typing as t |
| 2 | +from abc import ABC, abstractmethod |
| 3 | + |
| 4 | + |
| 5 | +class Loss(ABC): |
| 6 | + """ |
| 7 | + Abstract base class for all loss functions. |
| 8 | + """ |
| 9 | + |
| 10 | + @abstractmethod |
| 11 | + def __call__(self, predicted: t.List, actual: t.List) -> float: |
| 12 | + raise NotImplementedError |
| 13 | + |
| 14 | + |
| 15 | +class MSELoss(Loss): |
| 16 | + """ |
| 17 | + Mean Squared Error loss function. |
| 18 | + """ |
| 19 | + |
| 20 | + reduction: t.Literal["mean", "sum"] = "mean" |
| 21 | + |
| 22 | + def __call__(self, predicted: t.List[float], actual: t.List[float]) -> float: |
| 23 | + |
| 24 | + errors = [(p - a) ** 2 for p, a in zip(predicted, actual)] |
| 25 | + if self.reduction == "mean": |
| 26 | + return sum(errors) / len(errors) |
| 27 | + elif self.reduction == "sum": |
| 28 | + return sum(errors) |
| 29 | + else: |
| 30 | + raise ValueError(f"Invalid reduction method: {self.reduction}") |
| 31 | + |
| 32 | + |
| 33 | +class BinaryMetricLoss(Loss): |
| 34 | + """ |
| 35 | + Computes the loss for binary metrics. |
| 36 | + Supports accuracy and F1-score. |
| 37 | + """ |
| 38 | + |
| 39 | + metric: t.Literal["accuracy", "f1_score"] = "accuracy" |
| 40 | + |
| 41 | + def __call__(self, predicted: t.List[int], actual: t.List[int]) -> float: |
| 42 | + """ |
| 43 | + Computes the loss using the specified reduction. |
| 44 | +
|
| 45 | + Parameters |
| 46 | + ---------- |
| 47 | + predicted : list[int] |
| 48 | + List of predicted binary values (0 or 1). |
| 49 | + actual : list[int] |
| 50 | + List of actual binary values (0 or 1). |
| 51 | +
|
| 52 | + Returns |
| 53 | + ------- |
| 54 | + float |
| 55 | + The computed loss based on the reduction type. |
| 56 | + """ |
| 57 | + if len(predicted) != len(actual): |
| 58 | + raise ValueError("Predicted and actual lists must have the same length.") |
| 59 | + |
| 60 | + if self.metric == "accuracy": |
| 61 | + return self._accuracy(predicted, actual) |
| 62 | + elif self.metric == "f1_score": |
| 63 | + return self._f1_score(predicted, actual) |
| 64 | + else: |
| 65 | + raise ValueError(f"Unsupported reduction type: {self.metric}") |
| 66 | + |
| 67 | + def _accuracy(self, predicted: list[int], actual: t.List[int]) -> float: |
| 68 | + """ |
| 69 | + Computes accuracy as the reduction operation. |
| 70 | +
|
| 71 | + Returns |
| 72 | + ------- |
| 73 | + float |
| 74 | + Accuracy (proportion of correct predictions). |
| 75 | + """ |
| 76 | + correct = sum(p == a for p, a in zip(predicted, actual)) |
| 77 | + return correct / len(actual) |
| 78 | + |
| 79 | + def _f1_score(self, predicted: t.List[int], actual: t.List[int]) -> float: |
| 80 | + """ |
| 81 | + Computes F1-score as the reduction operation. |
| 82 | +
|
| 83 | + Returns |
| 84 | + ------- |
| 85 | + float |
| 86 | + The F1-score. |
| 87 | + """ |
| 88 | + tp = sum(p == 1 and a == 1 for p, a in zip(predicted, actual)) |
| 89 | + fp = sum(p == 1 and a == 0 for p, a in zip(predicted, actual)) |
| 90 | + fn = sum(p == 0 and a == 1 for p, a in zip(predicted, actual)) |
| 91 | + |
| 92 | + precision = tp / (tp + fp) if tp + fp > 0 else 0 |
| 93 | + recall = tp / (tp + fn) if tp + fn > 0 else 0 |
| 94 | + f1 = ( |
| 95 | + (2 * precision * recall) / (precision + recall) |
| 96 | + if precision + recall > 0 |
| 97 | + else 0 |
| 98 | + ) |
| 99 | + return f1 |
0 commit comments