|
| 1 | +/** |
| 2 | + * BinaryCrossEntropyLoss calculates the binary cross-entropy loss between predictions and target values. |
| 3 | + * This loss is commonly used for binary classification tasks. |
| 4 | + * |
| 5 | + * Formula: |
| 6 | + * `L = -Σ(y_true * log(y_pred) + (1 - y_true) * log(1 - y_pred))` |
| 7 | + * |
| 8 | + * @example |
| 9 | + * ```typescript |
| 10 | + * const binaryCrossEntropy = new BinaryCrossEntropyLoss(); |
| 11 | + * const predictions = [0.9, 0.2, 0.8]; |
| 12 | + * const targets = [1, 0, 1]; |
| 13 | + * const loss = binaryCrossEntropy.calculate(predictions, targets); |
| 14 | + * console.log("Binary CrossEntropy Loss:", loss); // Output: ~0.1839 |
| 15 | + * ``` |
| 16 | + */ |
| 17 | +export class BinaryCrossEntropyLoss { |
| 18 | + /** |
| 19 | + * Calculates the binary cross-entropy loss. |
| 20 | + * @param predictions An array of predicted probabilities (values between 0 and 1). |
| 21 | + * @param targets An array of binary target values (0 or 1). |
| 22 | + * @returns The calculated binary cross-entropy loss. |
| 23 | + * @throws Error if the predictions and targets arrays do not have the same length. |
| 24 | + */ |
| 25 | + calculate(predictions: number[], targets: number[]): number { |
| 26 | + if (predictions.length !== targets.length) { |
| 27 | + throw new Error("Predictions and targets must have the same length."); |
| 28 | + } |
| 29 | + |
| 30 | + if (predictions.length === 0 || targets.length === 0) { |
| 31 | + return 0; // Return 0 for empty arrays |
| 32 | + } |
| 33 | + |
| 34 | + const epsilon = 1e-12; // To avoid log(0) |
| 35 | + let loss = 0; |
| 36 | + |
| 37 | + for (let i = 0; i < predictions.length; i++) { |
| 38 | + const yTrue = targets[i]; |
| 39 | + const yPred = Math.min(Math.max(predictions[i], epsilon), 1 - epsilon); // Clamp predictions to avoid log(0) |
| 40 | + loss -= yTrue * Math.log(yPred) + (1 - yTrue) * Math.log(1 - yPred); |
| 41 | + } |
| 42 | + |
| 43 | + return loss / predictions.length; // Average loss |
| 44 | + } |
| 45 | +} |
0 commit comments