Skip to main content

Write one training step of logistic regression in NumPy: given X, y, the weights and a learning rate, return the loss and the updated weights. For example, with all weights at zero, every predicted probability is 0.5 and the loss is ln 2, about 0.693.

Coding rounds · Intermediate 3

Short answer

Compute z = X @ w + b, pass it through the sigmoid to get probabilities, and measure the mean log loss. The gradient is simple: X.T @ (p - y) / n for the weights and the mean of p - y for the bias. Subtract the learning rate times each gradient. One step costs O(n d).

Deeper answer

Clarify the shapes first: X is n by d, y is a vector of 0 and 1 with length n, w has length d and b is one number.

The forward pass is z = X @ w + b and p = 1 / (1 + np.exp(-z)). The loss is the mean of -(y * log(p) + (1 - y) * log(1 - p)). The backward pass is short because the sigmoid and the log loss cancel: the gradient with respect to z is p - y. So grad_w = X.T @ (p - y) / n and grad_b = (p - y).mean(). Then w -= lr * grad_w and b -= lr * grad_b.

For stability, clip p away from 0 and 1 before the log, or compute the loss from z with np.logaddexp(0, z) - y * z. Test that zero weights give a loss of ln 2 and that one step lowers the loss. Interviewers watch for the sign of the update, for log of zero, and for forgetting to divide by n.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Classification

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.