Eigen:有一个内置的方法来计算样本协方差 [英] Eigen: Is there an inbuilt way to calculate sample covariance

查看:1717
本文介绍了Eigen:有一个内置的方法来计算样本协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C ++中的Eigen库:我目前正在计算协方差矩阵,如下:

I am using the Eigen library in C++: I am currently calculating the covariance matrix myself as follows:

Eigen::MatrixXd covariance_matrix = Eigen::MatrixXd::Constant(21, 21, 0);
data mean = calc_mean(all_data)
for(int j = 0; j < 21; j++){
    for(int k = 0; k < 21; k++){
        for(std::vector<data>::iterator it = all_data.begin(); it!= all_data.end(); it++){
            covariance_matrix(j,k) += ((*it)[j] - mean[j]) * ((*it)[k] - mean[k]);
        }
        covariance_matrix(j,k) /= all_data.size() - 1;
    }
}

是否有内置/更优化的方法与特征库?例如,如果我将数据存储在 MatrixXd 中,其中每行是观察值,每列都是功能?

Is there an inbuilt/more optimized way to do this with the Eigen library? For example if I store my data in a MatrixXd where each row is an observation and each column a feature?

感谢

推荐答案

当每一行都是观察值时,可以使用矩阵公式来表示样本协方差矩阵, a href =http://en.wikipedia.org/wiki/Sample_mean_and_sample_covariance#Sample_covariance> http://en.wikipedia.org/wiki/Sample_mean_and_sample_covariance#Sample_covariance )

When each row is an observation, you can use the matrix formulation for the sample covariance matrix as shown on wikipedia ( http://en.wikipedia.org/wiki/Sample_mean_and_sample_covariance#Sample_covariance )

这是相当容易写的特征矩阵乘法等。无论是更高性能对我来说不是很明显,我怀疑优化器将不得不做一个真正好的工作(一定要使用至少-O2)。它可能值得尝试和剖析它。

This is fairly easy to write in terms of Eigen matrix multiplications etc. Whether it will be more performant isn't obvious to me, I suspect the optimizer would have to do a really good job (be sure to use at least -O2). It may be worth trying and profiling it.

这篇关于Eigen:有一个内置的方法来计算样本协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆