gpt4 book ai didi

c++ - Armadillo 中的有效距离计算

转载 作者:行者123 更新时间:2023-11-30 05:12:29 25 4
gpt4 key购买 nike

我是 Armadillo 的新手。我有以下代码,我认为它效率低下。有什么建议可以提高内存效率和/或速度吗?关注armadillo docsRcpp gallery ,我无法获得 .colptr的,uvec的,或批量插入工作。但我认为它们中的任何一个都会有所改进。

输入 X (~100 x 30000),甚至我的大型工作 VM 也会崩溃。

Linux release 7.3.1611 (Core)
117GB RAM / 0GB SWAP
(24 x 2.494 GHz) processor(s)

R version 3.3.2 (2016-10-31)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

代码

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
sp_mat arma_distmat_LT(const arma::mat& x) { // input expected X_{n x p} n << p
int nr, nc;
Col<double> col0, col1;

nr = x.n_rows;
nc = x.n_cols;

sp_mat out(nc, nc);
for (int i = 0; i < nc; i++) {
col0 = x.col(i);
for (int j = i + 1; j < nc; j++) {
col1 = x.col(j);
out(j, i) = as_scalar(col0.t() * col1);
}
}
return out;
}

电话:sourceCpp("<file>"); dist_x <- arma_distmat_LT(X)

注意:这些是距离,因为我在计算余弦相似度时设置了 L2 范数 == 1。

最佳答案

在我看来,您好像只是在计算(上三角)矩阵乘积 t(X)%*%X。实际上,您可以使用未充分利用的 crossprod 函数直接在 R 中执行此操作。

X <- matrix(rnorm(100*30000), ncol=30000)
res <- crossprod(X, X)

这在我的笔记本电脑上需要几分钟时间。如果您更改代码以使用 Armadillo 库,那么您可以使用

sp_mat arma_distmat_LT2(const arma::mat& x) { // input expected X_{n x p} n << p                               
int nr, nc;
Col<double> col0, col1;

nr = x.n_rows;
nc = x.n_cols;

sp_mat out(nc, nc);
out = trimatl(x.t() * x, k=-1);
return out;
}

仍然需要几分钟。虽然它使用了大量的内存,所以我怀疑你能否同时在内存中拥有很多对象。

代码可能会被优化为只计算下/上三角矩阵。


只是为了显示 100*800 矩阵的加速:

> microbenchmark(crossprod(X, X), arma_distmat_LT(X), arma_distmat_LT2(X))
Unit: milliseconds
expr min lq mean median uq
crossprod(X, X) 50.25574 53.72049 57.98812 56.29532 58.71277
arma_distmat_LT(X) 1331.83243 1471.42465 1523.74060 1492.84611 1512.45416
arma_distmat_LT2(X) 29.69420 33.23954 36.24613 35.54700 38.05208
max neval cld
160.81227 100 a
3080.37891 100 b
66.07351 100 a

如您所见,通过暴力破解可以显着提高速度。话虽如此,我确信叉积可以进一步优化。

关于c++ - Armadillo 中的有效距离计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44508366/

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