我正在寻找一种更有效的方法来获取汉明距离的距离矩阵。
背景资料
我知道hamming.distance()
包中有一个函数e1071
来计算距离矩阵,但是我怀疑当涉及到一个有很多行的大矩阵时,它可能会非常慢,因为它应用了嵌套for
循环来进行计算。
到目前为止,我methodB
在下面的代码中有一个更快的方法(请参阅参考资料)。但是,它仅适用于二进制域,即{0,1}^n
。但是,当遇到包含两个以上元素(即)的域时,此功能不可用{0,1,2,...,K-1}^n
。从这个意义上讲,methodB
不是针对一般的汉明距离。
目的
我的目标是找到一种具有以下功能的方法:
Rcpp
用于重写函数以加快速度)methodB()
的特殊情况快k=2
k
hamming.distance()
打包速度e1071
我的密码
library(e1071)
# vector length, i.e., number of matrix
n <- 7
# number of elements to consist of domain {0,1,...,k-1}^n
k <- 2
# matrix for computing hamming distances by rows
m <- as.matrix(do.call(expand.grid,replicate(n,list(0:k-1))))
# applying `hamming.distance()` from package "e1071", which is generic so it is available for any positive integer `k`
methodA <- function(M) hamming.distance(M)
# my customized method from base R function `dist()`, which is not available for cases `k >= 2`
methodB <- function(M) as.matrix(round(dist(M,upper = T,diag = T)**2))
而基准给出
microbenchmark::microbenchmark(
methodA(m),
methodB(m),
unit = "relative",
check = "equivalent",
times = 50
)
Unit: relative
expr min lq mean median uq max neval
methodA(m) 33.45844 33.81716 33.963 34.30313 34.92493 14.92111 50
methodB(m) 1.00000 1.00000 1.000 1.00000 1.00000 1.00000 50
预先赞赏!
methodM <- function(x) {
xt <- t(x)
sapply(1:nrow(x), function(y) colSums(xt != xt[, y]))
}
microbenchmark::microbenchmark(
methodB(m), methodM(m),
unit = "relative", check = "equivalent", times = 50
)
# Unit: relative
# expr min lq mean median uq max neval cld
# methodB(m) 1.00 1.000000 1.000000 1.000000 1.000000 1.000000 50 a
# methodM(m) 1.25 1.224827 1.359573 1.219507 1.292463 4.550159 50 b
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句