Logistic regression — binary cross-entropy loss
Background
Taking the log of the dataset likelihood turns the product into a sum, and negating + averaging it gives the loss logistic regression actually minimises — binary cross-entropy (log loss):
For this is convex, so gradient descent reaches the single global optimum. It also punishes confident-and-wrong predictions hard: if but , .
Problem statement
Implement binary_cross_entropy(y, y_hat) returning the mean BCE over all examples.
Input
y— array-like of true labels, each0or1.y_hat— array-like of predicted probabilities in , same length.
Output
Returns a Python float: the mean binary cross-entropy.
Examples
Example 1
Input: y = [1], y_hat = [0.5]
Output: 0.6931471805...
Explanation: — the loss of a coin-flip prediction.
Example 2
Input: y = [1, 0], y_hat = [0.9, 0.1]
Output: 0.1053605156...
Explanation: both predictions are confident and correct, so each term is and the mean is .
Constraints
- Average over the examples (the factor).
- Assume
y_hatis strictly in — no clipping required here. - Return a plain
float.
Notes
- Lower is better; a perfect, confident model drives . This is the negative log-likelihood of a Bernoulli model — minimising it maximises the likelihood of the labels.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference coin-flip prediction
- •Sample confident and correct
- •Example mixed batch averages correctly