Sigmoid Activation & Binary Thresholding

Basics
BasicsPyTorchClassificationGoogleMetaAmazon

Problem

Given raw binary classification logits logits and a decision threshold threshold=0.5, implement sigmoid_predict(logits, threshold=0.5) returning (probs, preds) where probs = torch.sigmoid(logits) and preds is an integer (long) tensor with 1 wherever probs >= threshold and 0 otherwise.

Why It Matters: Binary classifiers trained with BCEWithLogitsLoss output unbounded logits; converting them to calibrated probabilities and tuning the decision threshold is essential for precision/recall tradeoffs in production.

Function Signature

import torch

def sigmoid_predict(logits: torch.Tensor, threshold: float = 0.5):
    """Return (sigmoid_probabilities, binary_0_1_predictions)."""

Sample Input & Output

Example 1: Default Threshold 0.5

Input:

logits = torch.tensor([-2.0, 0.0, 2.0]), threshold = 0.5

Expected Output:

probs = tensor([0.1192, 0.5000, 0.8808])
preds = tensor([0, 1, 1])

Explanation: sigmoid(0.0) = 0.5, which satisfies probs >= 0.5 and predicts class 1.

Example 2: Stricter High-Precision Threshold 0.8

Input:

logits = torch.tensor([-2.0, 0.0, 2.0]), threshold = 0.8

Expected Output:

probs = tensor([0.1192, 0.5000, 0.8808])
preds = tensor([0, 0, 1])

Explanation: Raising the threshold to 0.8 flips the 0.5000 sample from 1 to 0.

Constraints & Edge Cases

  • Return (probs, preds) where preds has integer dtype (0 or 1).
  • Use >= threshold (inclusive) when computing preds.
  • Cast boolean predictions to torch.long via .long().

Constraints & Evaluation Criteria

  • Return `(probs, preds)` where `preds` has integer dtype (`0` or `1`).

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[-2.0, 0.0, 2.0]
Expected Output / Criteria
preds=[0, 1, 1]