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.