使用 R 的 h2o 中的有效欧几里得距离
Efficient Euclidean distance in h2o with R
我在 H2O 中有一个大的六边形框架,为此我需要计算每行中两点之间的欧氏距离。虽然它产生了正确的结果,但以下 H2O R 代码运行速度太慢。 30分钟过去了,还是运行。我什至有时间在 Whosebug 运行时 post 这个问题。
这个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
您可以使用 h2o.distance()
功能 measure = "l2"
,它最近已提交到 master 分支但尚未发布。要使用它,您需要 build H2O from master. An example of how to use the function is here.
您也可以尝试从 http://h2o.ai/download 下载最新的每晚构建版本,这里是 R 中距离函数的测试:
这个表达式应该可以解决问题:
sqrt(apply((hex[,cols1] - hex[,col2])^2, 1, sum))
我在 H2O 中有一个大的六边形框架,为此我需要计算每行中两点之间的欧氏距离。虽然它产生了正确的结果,但以下 H2O R 代码运行速度太慢。 30分钟过去了,还是运行。我什至有时间在 Whosebug 运行时 post 这个问题。
这个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
您可以使用 h2o.distance()
功能 measure = "l2"
,它最近已提交到 master 分支但尚未发布。要使用它,您需要 build H2O from master. An example of how to use the function is here.
您也可以尝试从 http://h2o.ai/download 下载最新的每晚构建版本,这里是 R 中距离函数的测试:
这个表达式应该可以解决问题:
sqrt(apply((hex[,cols1] - hex[,col2])^2, 1, sum))