#307Logistic regression — classify at a thresholdEasy

Logistic regression — classify at a threshold

Background

A logistic-regression model outputs a probability p=P(y=1x)(0,1)p = \mathbb{P}(y=1 \mid \mathbf{x}) \in (0, 1). To turn that into a hard class label you compare it to a threshold — by default 0.50.5:

y^={1pt0p<t\hat{y} = \begin{cases} 1 & p \ge t \\ 0 & p < t \end{cases}

The default t=0.5t = 0.5 is the neutral choice; raising or lowering it trades precision against recall.

Problem statement

Implement classify(probs, threshold=0.5) that converts predicted probabilities into 0/1 labels, predicting class 1 when ptp \ge t.

Input

  • probs — array-like of probabilities in [0,1][0, 1].
  • thresholdfloat, default 0.5. Predict class 1 when pthresholdp \ge \text{threshold}.

Output

Returns an np.ndarray of integer labels (0 or 1), the same length as probs.

Examples

Example 1 — default 0.5 threshold

Input:  probs = [0.2, 0.5, 0.8, 0.49, 0.51]
Output: [0 1 1 0 1]

Explanation: 0.50.50.5 \ge 0.5 so it rounds up to class 1; 0.49<0.50.49 < 0.5 stays class 0.

Example 2 — stricter threshold

Input:  probs = [0.2, 0.5, 0.8, 0.49, 0.51], threshold = 0.7
Output: [0 0 1 0 0]

Explanation: only 0.80.8 clears the higher bar of 0.70.7.

Constraints

  • Use >= so a probability exactly at the threshold is class 1.
  • Return integer labels (0/1), not booleans or floats.

Notes

  • The threshold is a decision knob, separate from the model. Shifting it changes which mistakes you make (false positives vs false negatives) without retraining.
Python
Loading...

▶ 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.

  • Example — default 0.5 threshold (>= rounds up)
  • Reference — stricter threshold 0.7
  • Sample — three probabilities at default threshold