PyTorch torch.corrcoef Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.corrcoefIt is a function in PyTorch used to compute the Pearson correlation coefficient matrix. It returns the correlation coefficient matrix of the input tensor, which is used to measure the linear correlation between variables.

Function Definition

torch.corrcoef(input)

Usage Example

Example

import torch

# Compute the correlation coefficient matrix
x = torch.tensor([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]])
print(Input matrix shape:, x.shape)
print(Input:)
print(x)

# Compute the correlation coefficient matrix
corr = torch.corrcoef(x)
print(Correlation coefficient matrix:)
print(corr)

# Correlation between two variables
a = torch.tensor([1, 2, 3, 4, 5])
b = torch.tensor([2, 4, 6, 8, 10])
# Shape needs to be (2, n)
data = torch.stack([a, b])
corr2 = torch.corrcoef(data)
print(Correlation coefficient of a and b:, corr2[0, 1])
# The output is close to 1, indicating a strong positive correlation

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions