Skip to content

← Classifiers from Scratch step 1 of 5

Easy End-to-End

Binary Classifier

Evaluate a binary classifier using supplied weights and bias. Its linear score, called a logit, becomes a probability for class 1 after applying sigmoid. This exercise computes predictions and a loss; it does not train or update the parameters.

Your task

Implement binary_classifier(x, W, b, y):

  • x has shape (N, features), with N >= 1.
  • W has shape (features, 1) and b has shape (1,).
  • y has shape (N, 1) and contains labels 0 or 1.

Compute z = x @ W + b, then p = sigmoid(z). Return a dictionary with "prediction" holding p of shape (N, 1) and "loss" holding a Python float. Keep probabilities as probabilities; do not threshold them into class labels. Preserve the inputs.

Loss convention

Use this epsilon-adjusted binary cross-entropy formula, with natural logs:

eps = 1e-7
loss = -mean(y * log(p + eps) + (1 - y) * log(1 - p + eps))

Average over the N examples. Add epsilon inside both logarithms; do not clamp the probabilities or add epsilon to the sigmoid. This convention keeps the logarithms finite when a probability rounds to zero or one. It slightly changes ordinary BCE: a confidently wrong prediction has a loss capped near -log(eps), and a perfectly confident correct prediction can have a tiny negative loss. Do not clip that loss to zero.

Example

For x = [[0], [1]], W = [[2]], b = [0] and y = [[1], [0]], the logits are [[0], [2]] and predictions are approximately [[0.5], [0.880797]]. The second prediction is confidently wrong. The mean adjusted loss is approximately 1.410037.

Keep y as a column. A label vector of shape (N,) would broadcast against p to form an unwanted (N, N) matrix.