【问题标题】:distance matrix for a matrix of size 100k * 100k in RR中大小为100k * 100k的矩阵的距离矩阵
【发布时间】:2018-08-21 10:13:56
【问题描述】:

我有一个大小为 100k+ 的向量 A,我想计算该向量的每个元素与其他所有元素之间的距离。我试图在 R 中解决这个问题,使用其内置的 adist 函数并尝试使用 stringdist 包。 问题是它的计算量非常大,而且它会连续运行好几天而没有结束。

我要解决的最终问题是使用距离度量查找重复或接近重复,然后围绕它构建某种分类模型。

我目前使用的代码是

 # declare an empty data frame and append data to it
matchedStr_vecA <- data.frame(row_index = integer(),
                              col_index = integer(),
                              vecA_i = character(),
                              vecA_j = character(),
                              dist_diff_vecA = double(),
                              stringsAsFactors=FALSE)


k = 1 # (keeps track of the pointer to the data frame)
# Run 2 different loops to calculate the bottom half of the matrix (below the diagonal - 
# as the diagonal elements will be zero and the upper half is the mirror image of the bottom half)
for (i in 1:length(vecA)) { 
  for (j in 1:length(vecA)) { 
    if (i < j) {
      dist_diff_vecA <- stringdist(vecA[i], vecA[j], method = "lv")
      matchedStr_invId[k,] <- c(i, j, vecA[i], vecA[j], dist_diff_vecA)
      k <- k + 1
    }
  }
}

请帮我把这个计算从 O(n^2) 带到 O(n)。我也可以使用 python。有人告诉我这可以使用动态编程来解决,但我不知道如何实现它。

谢谢大家

【问题讨论】:

  • 首先,你知道算法吗?
  • 你想做choose(100e3, 2)比较。这必然很耗时,但您应该使用编译语言和/或大规模并行化来完成。当然,对于您实际想要实现的任何目标,最好从蛮力转换为智能方法。
  • @Ronald 和用户 202729:我是编程/编码领域的新手,不知道要使用的方法/算法。有人能指出我正确的方向吗
  • 我没有使用过stringdist::stringdist 函数,但如果它与adist 相似,则该函数是矢量化的,因此stringdist(vecA, method = "lv") 应该返回结果矩阵。这比双循环要快得多(快 100-1000 倍)。然后解析矩阵以获得所需的结果。当然,问题就变成了你是否有 100k x100k 矩阵的内存。
  • @Dave2e:即使使用 8 GB RAM 也存在内存问题。这就是我正在寻找其他选择的原因.. 对动态编程或其他方法等替代方法的任何帮助

标签: python r string matrix duplicates


【解决方案1】:

我在计算距离矩阵时遇到了同样的问题,我已经在 Python 中成功解决了这个问题。这个问题讨论了解决方案的关键要素,以确保您在线程之间平等地划分计算: How to split diagonal matrix into equal number of items each along one of axis?

有两点需要指出:

  1. 两点之间的距离通常是对称的,因此您可以重复使用此数学特征并计算一次 ij 元素之间的距离,然后将其存储或重复使用以计算 j 和 @ 之间的距离987654325@.

  2. 算法无法在 O(n^2) 以下进行优化,除非您可以接受不精确的结果。而且由于您是编程新手,我什至不会考虑这样做。

  3. 您应该能够使用索引拆分来并行计算,正如我在上述问题中建议的那样,以获得接近最佳的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2019-09-04
    • 2021-10-26
    • 2016-12-29
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多