首页 文章

高效的欧几里德距离在h2o与R

提问于
浏览
1

我在H2O中有一个大的六边形框架,我需要计算每行中两个点之间的欧氏距离 . 虽然它产生了正确的结果,但以下H2O R代码运行得太慢 . 已经过了30分钟,它仍然在运行 . 我甚至有时间在运行时将此问题发布到stackoverflow .

这个h2o代码是否有更高效的设计?

# H2O R code to row-wise compute Euclidean distance between two points s1 and s2 contained in each row.
# Is this the most efficient H2O code that is possible? Real world will run on a big hex frame.
h2odistance = function(hex, cols1, cols2) {
    nr = h2o.nrow(hex)
    for (r in 1:nr) {
        dif = hex[r,cols1] - hex[r,cols2]
        sq = dif * dif
        sm = h2o.sum(sq)
        rt[r] = h2o.sqrt(sm)
    }
    rt  
}

这是它的简单R代码,用于比较 . 我正在包含一个小的测试用例数据帧以进行正确性检查:

(df = data.frame(s1_c1=c(1,3), s1_c2=c(2,20), s1_c3=c(3,3), s2_c1=c(9,21), s2_c2=c(10,22), s2_c3=c(0,0)))
fn <- function(z) {sqrt(sum((z[1:3] - z[4:6])^2))}
(rt = apply(df, 1, fn))

这是普通R代码的正确输出以供参考:

11.7046999107196 18.3575597506858

h2o代码也输出正确的值:

h2odistance(as.h2o(df), 1:3, 4:6)

11.7046999107196 18.3575597506858

3 回答

相关问题