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

时间:2017-04-04 14:15:56

标签: r h2o

我在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 个答案:

答案 0 :(得分:1)

您可以将h2o.distance()函数用于measure = "l2",该函数最近已提交到主分支但尚未发布。要使用它,您需要build H2O from master。如何使用该函数的示例是here

答案 1 :(得分:1)

你也可以尝试从http://h2o.ai/download下载最新的夜间版本,这里是对R中该距离函数的测试:

https://github.com/h2oai/h2o-3/blob/277ce7d3bd14514b5c34bc58c18514011256f533/h2o-r/tests/testdir_munging/runit_distance.R

答案 2 :(得分:0)

这个表达式可以解决这个问题: sqrt(apply((hex[,cols1] - hex[,col2])^2, 1, sum))