r语言 - 使用 H2O 存储距离的最佳方法是什么?



Supose 我有 2 个 data.frame,我想计算它们所有行之间的欧几里得距离。我的代码是:

set.seed(121)
# Load library
library(h2o)
system.time({
h2o.init()
# Create the df and convert to h2o frame format
df1 <- as.h2o(matrix(rnorm(7500 * 40), ncol = 40))
df2 <- as.h2o(matrix(rnorm(1250 * 40), ncol = 40))
# Create a matrix in which I will record the distances
matrix1 <- as.h2o(matrix(0, nrow = 7500, ncol = 40))
# Loop to calculate all the distances
for (i in 1:nrow(df2)){
matrix1[, i] <- h2o.sqrt(h2o.distance(df1, df2[, i]))
}
})

我相信有更有效的方法将其存储到矩阵中。

您不需要计算循环内的距离,H2O 的距离函数可以有效地计算所有行的距离。对于具有n x km x k维度的两个数据框,您可以通过以下方式找到n x m距离矩阵:

distance_matrix <- h2o.distance(df1, df2, 'l2')

无需取平方根,因为h2o.distance()函数允许您指定要使用的距离度量:"l1"- 绝对距离(L1 范数(,"l2"- 欧几里得距离(L2 范数(,"cosine"- 余弦相似性和"cosine_sq"- 平方余弦相似性。

按照您的示例,计算欧几里得距离矩阵的代码将是:

library(h2o)
h2o.init()
df1 <- as.h2o(matrix(rnorm(7500 * 40), ncol = 40))
df2 <- as.h2o(matrix(rnorm(1250 * 40), ncol = 40))
distance_matrix <- h2o.distance(df1, df2, 'l2')

生成维度为7500 rows x 1250 columns的矩阵。

相关内容

最新更新