создать матрицу расстояний для строк - PullRequest
2 голосов
/ 02 мая 2019

Я хотел бы ускорить следующий код. Может ли кто-нибудь быть таким добрым и внести некоторые предложения?

library(dplyr)
library(fuzzywuzzyR)

set.seed(42)
rm(list = ls())
options(scipen = 999)

init = FuzzMatcher$new()

data <- data.frame(string = c("hello world", "hello vorld", "hello world 1", "hello world", "hello world hello world"))
data$string <- as.character(data$string)

distance_function <- function(string_1, string_2) {
    init$Token_set_ratio(string1 = string_1, string2 = string_2)
}

combinations <- combn(nrow(data), 2)
distances <- matrix(, nrow = 1, ncol = ncol(combinations))

distance_matrix <- matrix(NA, nrow = nrow(data), ncol = nrow(data), dimnames = list(data$string, data$string))

for (i in 1:ncol(combinations)) {

    distance <- distance_function(data[combinations[1, i], 1], data[combinations[2, i], 1])

    #print(data[combinations[1, i], 1])
    #print(data[combinations[2, i], 1])
    #print(distance)

    distance_matrix[combinations[1, i], combinations[2, i]] <- distance
    distance_matrix[combinations[2, i], combinations[1, i]] <- distance

}

distance_matrix

Кстати, я безуспешно пытался использовать proxy :: dist и другие подходы. Я также не думаю, что функция расстояния до строки работает так, как ожидалось, но это уже другая история.

В конечном счете, я хочу использовать матрицу расстояний, чтобы выполнить некоторую кластеризацию для группировки похожих строк (независимо от порядка слов).

1 Ответ

1 голос
/ 02 мая 2019

Если вы хотите матрицу, вы можете использовать пакет stringdist.Из того, что я мог сказать, пакет, который вы использовали, вычислял расстояние Левенштейна, поэтому я включил method = "lv" (вы могли бы попробовать и другие методы).Дайте мне знать, если у вас есть проблемы, или если предпочтителен формат, отличный от матрицы.Кроме того, вы можете рассмотреть возможность использования метода, отличного от расстояния Левенштейна (т. Е. Изменение 2 в четырехбуквенном слове выглядит так же, как изменение двух в предложении из 20 слов).Удачи !!!

library(dplyr)
library(stringdist)

set.seed(42)
rm(list = ls())
options(scipen = 999)

data <- data.frame(string = c("hello world", "hello vorld", "hello world 1", "hello world", "hello world hello world"))
data$string <- as.character(data$string)

dist_mat <- stringdist::stringdistmatrix(data$string, data$string, method = "lv")

rownames(dist_mat) <- data$string
colnames(dist_mat) <- data$string

dist_mat
                        hello world hello vorld hello world 1 hello world hello world hello world
hello world                       0           1             2           0                      12
hello vorld                       1           0             3           1                      13
hello world 1                     2           3             0           2                      11
hello world                       0           1             2           0                      12
hello world hello world          12          13            11          12                       0
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...