torch.distributions.probs_to_logits
function probs_to_logits(probs: Tensor, options?: ProbsToLogitsOptions): Tensorfunction probs_to_logits(probs: Tensor, is_binary: boolean, options?: ProbsToLogitsOptions): TensorConverts probabilities to logits (log-odds).
Transforms probability values into their logarithmic odds representation, which is the natural parameterization for many probability distributions. Useful for:
- Distribution parameterization: Converting probabilities to logit form for numerical stability
- Numerical stability: Avoiding underflow/overflow in probability space
- Loss functions: Computing cross-entropy and KL divergence in numerically stable way
- Optimization: Working in logit space for better gradient behavior
- Model outputs: Converting network outputs (often in logit space) to probabilities
For binary distributions: logits = log(probs / (1 - probs)) For categorical distributions: logits = log(probs)
Clamps probabilities to avoid numerical issues (1e-7 to 1-1e-7 for binary, 1e-7 to 1 for categorical).
- Clamping: Automatically clamps probabilities to avoid log(0)
- Binary vs Categorical: Different formulas used based on is_binary flag
- Unconstrained output: Logits can take any real value (-∞ to ∞)
- Inverse of logits_to_probs: Use logits_to_probs() to convert back
- Invalid probabilities: Input values must be in [0, 1] range
- Extreme values: Probabilities close to 0 or 1 produce extreme logits
- NaN/Inf: Invalid inputs may produce NaN or infinite values
Parameters
probsTensor- Probability tensor with values in [0, 1]
optionsProbsToLogitsOptionsoptional
Returns
Tensor– Logits tensor with unconstrained values (-∞ to ∞)Examples
// Binary probability to logits
const probs = torch.tensor([0.1, 0.5, 0.9]);
const logits = torch.distributions.probs_to_logits(probs, true);
// logits ≈ [-2.197, 0, 2.197]// Categorical probabilities to logits
const probs = torch.tensor([0.1, 0.6, 0.3]);
const logits = torch.distributions.probs_to_logits(probs, false);
// logits = log(probs) ≈ [-2.303, -0.511, -1.204]// Use in distribution construction
const probs = torch.tensor([[0.3, 0.7], [0.5, 0.5]]);
const logits = torch.distributions.probs_to_logits(probs, true);
// Can now use logits to create Binary/Bernoulli distributionSee Also
- PyTorch torch.logit() (inverse of sigmoid)
- logits_to_probs - Convert logits back to probabilities
- torch.log - Logarithm operation