2016-02-29 65 views
0

我正在努力測量字符串之間相似度的方法的性能。 什麼此方法確實:R中元素的字符串元素之間的相似性測量

它的測量與另一個字符串元素每串元素之間的相似性sentenceMatch數據幀。我正在使用levenshteinSimFunction進行字符串之間的相似度測量,稍微修正levenshteinDist函數。

下面是我的方法。

sentenceMatch <- data.frame(Sentence=c("job not ready time window pmg inc gvu austin timedout pmg inc plm", 
            "data delay hpsb unable deliver icon scp action required http hpedia osp", 
            "job completed abnormally wwapo bw kili inc promaster", 
            "job completed abnormally apo ww promaster net apoww abend apo ww", 
            "error occurred launching job apo ww inc promaster net errorlaunching apo")) 

sentenceMatch$Sentence <- as.character(sentenceMatch$Sentence) 

overallMatrix <- matrix(, nrow = dim(sentenceMatch)[1], ncol = dim(sentenceMatch)[1]) # creating output matrix 

for (k in 1:dim(sentenceMatch)[1]) { 
    for (l in 1:dim(sentenceMatch)[1]) { 
     ifelse(k == l, overallMatrix[k, l] <- 0, overallMatrix[k, l] <- levenshteinSimFunction(sentenceMatch[k, ], sentenceMatch[l, ])) 
     if (overallMatrix[k, l] < .2) {overallMatrix[k, l] <- 0} 
    } 
    } 

這導致到這些比較的矩陣,其中,所述輸出矩陣的每個元素表示levenshteinSimFunction(sentenceMatch [K],sentenceMatch並[]) 0和之間返回數(相似性度量) 1.

levenshteinSimFunction = function (str1, str2) 
{ 
    if (str1 != "" && str2 != "") { 
    return(1 - (levenshteinDist(str1, str2)/max(nchar(str1), 
              nchar(str2)))) 
    } 
    else {return (0)} 
} 

> overallMatrix 
      1   2   3   4   5 
1 0.0000000 0.2394366 0.2615385 0.2307692 0.3055556 
2 0.2394366 0.0000000 0.0000000 0.0000000 0.0000000 
3 0.2615385 0.0000000 0.0000000 0.5156250 0.2916667 
4 0.2307692 0.0000000 0.5156250 0.0000000 0.4444444 
5 0.3055556 0.0000000 0.2916667 0.4444444 0.0000000 

一切都按照我的意料的作品,但我碰上,因爲兩個for循環的性能問題。

是否有另一個(更好),解決方案如何避免這兩個for循環,並加快性能。

性能是由高於2的組合數n驅動的,其指數地增加了處理時間,因此對於例如1000個句子,計算時間爲257.97秒。在我的情況下,我有25K的句子。

+0

levenshteinSimFunction來自哪裏?沒有該功能,您的代碼就無法測試或複製。 – Heroka

+0

對不起。我在描述中添加了這個函數。 – martinkabe

+0

'levenshteinDist'從哪裏來? –

回答

0

你可以使用packagedist包。使用命令stringdistmatrix可以計算矩陣形式的字符串距離。其中一個選項是運行多線程,請檢查??stringdistmatrix。在基本形式下,它的工作原理如下。

library(stringdist) 

sentenceMatch <- data.frame(Sentence=c("job not ready time window pmg inc gvu austin timedout pmg inc plm", 
             "data delay hpsb unable deliver icon scp action required http hpedia osp", 
             "job completed abnormally wwapo bw kili inc promaster", 
             "job completed abnormally apo ww promaster net apoww abend apo ww", 
             "error occurred launching job apo ww inc promaster net errorlaunching apo")) 

sentenceMatch$Sentence <- as.character(sentenceMatch$Sentence) 

overallMatrix <- stringdistmatrix(sentenceMatch$Sentence, sentenceMatch$Sentence, method = "lv") 
+0

這非常好,謝謝你。但不幸的是,它返回兩個字符串組合的匹配字符數。我如何能夠從這兩個字符串中的每個字符串中獲得更長的字符串? – martinkabe

+0

@martinkabe,請參閱[此鏈接](http://stackoverflow.com/questions/35701428/max-nchar-from-two-strings-in-matrix)的類似問題。 – phiver