plenoptic.process.variance#

plenoptic.process.variance(x, mean=None, dim=None, keepdim=False)[source]#

Calculate sample variance.

Note that this is the uncorrected, or sample, variance, corresponding to torch.var(*, correction=0).

Parameters:
  • x (Tensor) – The input tensor.

  • mean (float | Tensor | None (default: None)) – Reuse a precomputed mean.

  • dim (int | list[int] | None (default: None)) – The dimension or dimensions to reduce.

  • keepdim (bool (default: False)) – Whether to retain the reduced dimensions (as singletons) or not.

Return type:

Tensor

Returns:

out – The variance tensor.

See also

skew

Calculate sample skewness.

kurtosis

Calculate sample kurtosis.

Examples

>>> import plenoptic as po
>>> import matplotlib.pyplot as plt
>>> import torch
>>> po.set_seed(42)
>>> x = torch.randn(10000)
>>> v = po.process.variance(x)
>>> x_more = x * 3
>>> v_more = po.process.variance(x_more)
>>> x_less = x * 0.3
>>> v_less = po.process.variance(x_less)
>>> fig, (ax_less, ax, ax_more) = plt.subplots(
...     1, 3, sharex=True, sharey=True, figsize=(12, 4)
... )
>>> _ = ax_less.hist(x_less, bins=50)
>>> _ = ax_less.set(title=f"σ=0.3\nVariance: {v_less:.4f}", ylabel="Frequency")
>>> _ = ax.hist(x, bins=50)
>>> _ = ax.set(title=f"Standard Gaussian, σ=1\nVariance: {v:.4f}")
>>> _ = ax_more.hist(x_more, bins=50)
>>> _ = ax_more.set(title=f"σ=3\nVariance: {v_more:.4f}")

(png, hires.png, pdf)

../../_images/plenoptic-process-variance-1.png

If you have precomputed the mean, you can pass it and avoid recomputing it:

>>> precomputed_mean = torch.mean(x)
>>> v = po.process.variance(x, mean=precomputed_mean)
>>> v
tensor(1.0088)

If you want to compute along a specific dimension, you can specify it:

>>> x = torch.randn(10000, 2)
>>> v = po.process.variance(x, dim=0)
>>> v
tensor([1.0127, 1.0045])

This function differs from torch.var in that it does not apply a correction:

>>> plenoptic_v_corrected = v * x.shape[0] / (x.shape[0] - 1)
>>> torch_v = torch.var(x, dim=0)
>>> torch.isclose(plenoptic_v_corrected, torch_v)
tensor([True, True])