在 R 中有比这更有效的成对比较方法吗?

时间:2021-04-17 17:27:42

标签: r

我正在使用一个函数来比较列表中每个项目的相似度,如下所示:

sim.items <- outer(items, items, similarity.function)

该列表大约有 11,000 个项目,自然而然,即使在 2.4 GHz 8 核、32GB RAM 的 Macbook Pro 上也能运行数小时。除了优化相似度函数本身之外,是否有更有效的方法来成对比较项目,以生成相似度矩阵(使用我的自定义相似度函数)?我应该完全放弃我的方法吗?

library(tidyverse)

get_all_ngrams <- function(x, N = 3){
  l <- length(x) - N + 1
  stopifnot(l > 0)
  map_df(1:l, function(i){
    ngram <- x[i:(i + N - 1)]
    tibble(start = i, N = N, value = paste(ngram, collapse = ","))
  })
}


similarity.function <- function(x, y, N = 3){
  x <- get_all_ngrams(x, N = N) %>% pull(value)
  y <- get_all_ngrams(y, N = N) %>% pull(value)
  joint <- c(x, y) %>% table()
  tx <- factor(x, levels = names(joint)) %>% table()
  ty <- factor(y, levels = names(joint)) %>% table()
  1 - sum(abs(tx  - ty))/(length(x) + length(y))
}

1 个答案:

答案 0 :(得分:1)

我们可以使用combn

combn(items, 2, FUN = function(x) similarity.function(x[1], x[2]),
           simplify = FALSE)
相关问题