gpt4 book ai didi

python - 使用 np.matmul(data.T, data) 的协方差矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:55 25 4
gpt4 key购买 nike

这是我在网上找到的代码

d0 = pd.read_csv('./mnist_train.csv')
labels = d0.label.head(15000)
data = d0.drop('label').head(15000)

from sklearn.preprocessing import StandardScaler
standardized_data = StandardScaler().fit_transform(data)

#find the co-variance matrix which is : (A^T * A)/n
sample_data = standardized_data

# matrix multiplication using numpy
covar_matrix = np.matmul(sample_data.T , sample_data) / len(sample_data)

如何将相同的数据相乘得到 np.matmul(sample_data.T, sample_data) 协方差矩阵?根据我在网上找到的这个教程,协方差矩阵是什么?最后一步是我不明白的。

最佳答案

对于数学或统计堆栈交换来说,这可能是一个更好的问题,但我现在会在这里回答。

这来自definition of covariance .维基百科页面(链接)提供了大量细节,但协方差定义为(伪代码)

cov = E[dot((x - E[x]), (x - E[x]).T)]

对于列向量,但在你的情况下你可能有行向量,这就是为什么你的点积中的第一个元素被转置,而不是第二个。 E[...] 表示期望值,which is the mean for Gaussian-distributed data .当您执行 StandardScaler().fit_transform(data) ,您基本上是在减去数据的均值,所以这就是为什么您没有在点积中明确这样做的原因。

请注意,StandardScaler() 也除以方差,因此它将所有内容归一化为单位方差。 这会影响您的协方差!因此,如果您需要未经归一化的数据的实际协方差,只需使用类似 np.cov() 的方法进行计算即可。来自 numpy 模块。

关于python - 使用 np.matmul(data.T, data) 的协方差矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54464444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com