Measure dispersion along a feature or batch dimension.
Feature scaling
PyTorch · Function
Calculates standard deviation over selected tensor dimensions. By default it uses Bessel’s correction; choose correction=0 for population standard deviation and keepdim=True to retain reduced axes.
torch.std reduces the selected dimensions by computing standard deviation with a denominator based on the number of values minus correction. Set dim to an integer or tuple, use correction to choose sample or population behavior, and use keepdim to preserve reduced axes as size-one dimensions.
torch.std(input, dim=None, *, correction=1, keepdim=False, out=None) → Tensor| Name | Type | Description |
|---|---|---|
input | Tensor | Input tensor whose standard deviation is calculated. |
dim | int or tuple of ints, optional | Dimension or dimensions to reduce; None reduces all dimensions. |
correction | int | Difference between sample size and sample degrees of freedom; defaults to 1. |
keepdim | bool, optional | Whether reduced dimensions are retained as size-one dimensions. |
out | Tensor, optional | Optional tensor in which to write the result. |
Tensor containing the standard deviation over the selected dimensions.
import torch
x = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
row_std = torch.std(x, dim=1, correction=0, keepdim=True)
print(row_std)Computes each row's population standard deviation while retaining the reduced dimension.
Feature scaling
Tensor reduction
Broadcasting
Statistical convention
torch.std computes standard deviation across the dimensions selected by dim. If dim is None, it reduces all dimensions.
Follow-up: How would you preserve the reduced axes for broadcasting? Set keepdim=True, which leaves each reduced axis with size 1.
correction is subtracted from the number of reduced elements in the denominator. Its default is 1, Bessel’s correction, so correction=0 gives population standard deviation.
Follow-up: What happens when the reduced count is no greater than correction? The denominator is clamped through max(0, N - correction), as shown by the documented formula.
dim may be one dimension, a tuple of dimensions, or None. keepdim=True retains reduced dimensions as size-one axes; otherwise those axes are squeezed.
Follow-up: How can the result remain aligned with the input rank? Use keepdim=True when subsequent tensor operations rely on broadcasting or positional dimensions.
torch.Tensor.stdtorch.std_meantorch.squeeze