Deep learning: Two loss functions

Measure how wrong a set of predictions is.

What to build

A program that computes the mean squared error and the binary cross-entropy of predictions.

Requirements

  • Targets are 0 or 1; predictions are strictly between 0 and 1.
  • Print MSE X and cross-entropy Y, each with four decimal places.

Input

Line 1: the targets. Line 2: the predictions.

Output

Two lines.

Constraints

At most 1,000 values.

Example

Input:

1 0
0.8 0.2

Output:

MSE 0.0400
cross-entropy 0.2231

Why it works

Both losses are small when predictions are close to the targets; cross-entropy grows sharply when a prediction is confidently wrong.

Examples

Example 1 · Input
1 0
0.8 0.2
Expected output
MSE 0.0400
cross-entropy 0.2231
Example 2 · Input
1
0.5
Expected output
MSE 0.2500
cross-entropy 0.6931

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

MSE is the mean of (p − y)².

Hint 2

Cross-entropy is the mean of −(y log p + (1 − y) log(1 − p)), using math.log.

Solution

Show one correct solution (try it yourself first)
import math

ys = list(map(float, input().split()))
ps = list(map(float, input().split()))
n = len(ys)
mse = sum((p - y) ** 2 for p, y in zip(ps, ys)) / n
ce = -sum(y * math.log(p) + (1 - y) * math.log(1 - p) for p, y in zip(ps, ys)) / n
print(f"MSE {mse:.4f}")
print(f"cross-entropy {ce:.4f}")

Lesson: Loss functions and gradient descent →