Binary Cross-Entropy Loss

~12 mincode completion

Implement binary_cross_entropy(y_true, y_pred) that returns the mean BCE loss over the batch.

Examples

Mixed correct predictions

Input
binary_cross_entropy([1, 0, 1], [0.9, 0.1, 0.8])
Output
0.14462

High-confidence correct predictions: low loss

Input
binary_cross_entropy([1, 1, 1], [0.9, 0.9, 0.9])
Output
0.10536

Completely wrong predictions: high loss

Input
binary_cross_entropy([1, 0], [0.1, 0.9])
Output
2.30259

Hints

Hint 1

bounds an array in one call.

Hint 2

Do not forget to clip causing log zero. That step is easy to skip.

Requirements

  • y_true: Ground-truth labels, 0 or 1, shape (m,)

  • y_pred: Predicted probabilities in [0, 1], shape (m,)

  • Return Scalar mean BCE loss.

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~12 min

8 employers weight this skill

3 frontier labs, 2 big tech firms, 2 autonomy companies, 1 enterprise vendor. Top match scores 68.

Python
import numpy as np

def binary_cross_entropy(y_true: np.ndarray, y_pred: np.ndarray) -> float:
    """
    Compute mean binary cross-entropy loss.

    Args:
        y_true: Ground-truth labels, 0 or 1, shape (m,)
        y_pred: Predicted probabilities in [0, 1], shape (m,)

    Returns:
        Scalar mean BCE loss.
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.