无法正确计算 np.cov()

Can't calculate np.cov() correctly

这个问题可能很愚蠢,但我找不到解释。

我正在从头开始编写多元概率密度函数(用于研究目的),我需要计算的其中一件事是数据的协方差矩阵。我正在使用 Iris 数据集(150 个样本,4 个特征),当我编码时:


cov_matrix = np.cov(X)
print(cov_matrix.shape) // (150,150)

我不明白为什么它返回一个 150x150 矩阵,这是一个“逐元素协方差矩阵”吗?不应该是4x4的协方差矩阵吗?

提前致谢。

numpy.cov的参考页中,有一个名为rowvar的参数,默认设置为True。下面一段是它的解释:

If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.

因此,它假定给定矩阵的列中有观测值。因此,您需要输入 $X^T$(通过 X.T)或使用 rowvar=False.

调用此函数

默认情况下 Numpy assumes 变量在行中,而观察值在列中:

rowvar : bool, optional
If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.