Binary classification with logistic regressionEasy

Binary classification with logistic regression

Background

Once logistic regression is trained, prediction is a single forward pass: score each example with the linear combination z=Xw+bz = Xw + b, squash it through the sigmoid into a probability, and threshold at 0.50.5 to read off a class label. Predicting class 1 when the probability is at least one-half is equivalent to predicting class 1 whenever z0z \ge 0 — i.e. on the positive side of the model's linear decision boundary.

Problem statement

Implement predict_logistic(X, weights, bias) that returns the binary class predictions of a trained logistic-regression model. For each row xix_i:

zi=xiw+b,pi=σ(zi)=11+eziz_i = x_i \cdot w + b, \qquad p_i = \sigma(z_i) = \frac{1}{1 + e^{-z_i}} y^i={1pi0.50pi<0.5\hat{y}_i = \begin{cases} 1 & p_i \ge 0.5 \\ 0 & p_i < 0.5 \end{cases}

Input

  • Xnp.ndarray of shape (N, D): N samples with D features each.
  • weightsnp.ndarray of shape (D,): the trained weight vector ww.
  • biasfloat: the trained bias bb.

Output

Returns an np.ndarray of shape (N,) with integer labels in {0,1}\{0, 1\} — one prediction per sample.

Examples

Example 1

Input:  X = [[1, 1], [2, 2], [-1, -1], [-2, -2]], weights = [1, 1], bias = 0
Output: [1, 1, 0, 0]

Explanation: the scores are z=[2,4,2,4]z = [2, 4, -2, -4]. The sigmoid maps the two positive scores above 0.50.5 (class 1) and the two negative scores below 0.50.5 (class 0).

Constraints

  • Threshold at exactly 0.50.5: a probability of exactly 0.50.5 (i.e. z=0z = 0) predicts class 1.
  • Clip zz into a safe range (e.g. [500,500][-500, 500]) before exp to avoid overflow.
  • Return integer labels (0/1) as an array of shape (N,).
  • Vectorise with numpy — no Python loop over samples.

Notes

  • Thresholding the probability at 0.50.5 is identical to thresholding the raw score zz at 00, so you don't strictly need the sigmoid to make the decision — only if you want calibrated probabilities.
  • The decision boundary {x:xw+b=0}\{x : x \cdot w + b = 0\} is a hyperplane, which is why logistic regression is a linear classifier.
Python
Loading...

This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.

  • Reference example: scores [2,4,-2,-4] -> [1,1,0,0]
  • Probability exactly 0.5 (z = 0) predicts class 1
  • Bias shifts the decision boundary
  • Returns integer labels, one per sample