PyTorch torch.var Function


Pytorch torch 参考手册PyTorch torch Reference Manual

torch.varis a function in PyTorch used to return the variance of a tensor. Variance is the average of the squared differences between each data point and the mean, measuring the dispersion of the data.

Function Definition

torch.var(input, dim, unbiased, keepdim=False)

Usage Example

Example

import torch

x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])

# Return the variance of all elements
print("Variance:", torch.var(x))

# Variance along dim=0
y = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print("dim=0 variance:", torch.var(y, dim=0))
print("dim=1 variance:", torch.var(y, dim=1))

The output result is:

方差: tensor(2.5000)
dim=0 方差: tensor([2.2500, 2.2500, 2.2500])
dim=1 方差: tensor([1., 1.])

Pytorch torch 参考手册PyTorch torch Reference Manual

Other Extensions