【发布时间】:2017-04-04 14:15:55
【问题描述】:
我在 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
【问题讨论】:
-
请注意,这不是全对距离计算。它只是计算 nrow(df) 距离。这不是最近邻搜索。