PyTorch torch.var_mean Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.var_meanIt is a function in PyTorch that returns both the variance and mean of a tensor simultaneously. It is an efficient function that can compute the variance and mean in a single operation.

Function Definition

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

Usage Example

Example

import torch

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

# Return both variance and mean simultaneously
var, mean = torch.var_mean(x)
print("Variance:", var)
print("Mean:", mean)

# Return both variance and mean along dim=0
y = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
var0, mean0 = torch.var_mean(y, dim=0)
print("dim=0 variance:", var0)
print("dim=0 mean:", mean0)

The output is:

方差: tensor(2.5000)
均值: tensor(3.)
dim=0 方差: tensor([2.2500, 2.2500, 2.2500])
dim=0 均值: tensor([2.5000, 3.5000, 4.5000])

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions