PyTorch torch.cov Function
PyTorch torch Reference Manual
torch.covis a function in PyTorch used to compute the covariance matrix. It calculates the covariance matrix of the input tensor to measure the covariance between variables.
Function Definition
torch.cov(input, correction=1, fweights=None, aweights=None)
Usage Example
Example
import torch
# Calculate the covariance matrix
x = torch.tensor([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]], dtype=torch.float32)
print("Input matrix:")
print(x)
# Calculate the covariance matrix (Bessel's correction used by default)
cov = torch.cov(x)
print("Covariance matrix:")
print(cov)
# Without correction (correction=0)
cov_no_correction = torch.cov(x, correction=0)
print("Covariance matrix without correction:")
print(cov_no_correction)
# Two variables
a = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float32)
b = torch.tensor([2, 4, 6, 8, 10], dtype=torch.float32)
data = torch.stack([a, b])
cov2 = torch.cov(data)
print("Covariance matrix of a and b:")
print(cov2)
# Calculate the covariance matrix
x = torch.tensor([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]], dtype=torch.float32)
print("Input matrix:")
print(x)
# Calculate the covariance matrix (Bessel's correction used by default)
cov = torch.cov(x)
print("Covariance matrix:")
print(cov)
# Without correction (correction=0)
cov_no_correction = torch.cov(x, correction=0)
print("Covariance matrix without correction:")
print(cov_no_correction)
# Two variables
a = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float32)
b = torch.tensor([2, 4, 6, 8, 10], dtype=torch.float32)
data = torch.stack([a, b])
cov2 = torch.cov(data)
print("Covariance matrix of a and b:")
print(cov2)
Other Extensions