zoukankan      html  css  js  c++  java
  • 自然语言处理(5)之Levenshtein最小编辑距离算法

    自然语言处理(5)之Levenshtein最小编辑距离算法

    题记:之前在公司使用Levenshtein最小编辑距离算法来实现相似车牌的计算的特性开发,正好本节来总结下Levenshtein最小编辑距离算法。

    算法简介:

          Levenshtein距离,是俄罗斯科学家Vladimir Levenshtein在1965年提出这个概念。它是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。因此可以使用Levenshtein距离算法来描述两个字符串的相似程度。

    例如将kitten一字经过3步转成sitting:

    1. sitten (k→s)
    2. sittin (e→i)
    3. sitting (→g)

    算法描述:      

         我们定义这样一个函数——edit(i, j),它表示第一个字符串的长度为i的子串到第二个字符串的长度为j的子串的编辑距离。

    显然可以有如下动态规划公式:

    • if i == 0 且 j == 0,edit(i, j) = 0
    • if i == 0 且 j > 0,edit(i, j) = j
    • if i > 0 且j == 0,edit(i, j) = i
    • if i ≥ 1  且 j ≥ 1 ,edit(i, j) == min{ edit(i-1, j) + 1, edit(i, j-1) + 1, edit(i-1, j-1) + f(i, j) },当第一个字符串的第i个字符不等于第二个字符串的第j个字符时,f(i, j) = 1;否则,f(i, j) = 0。 
    • 网上关于这部分的描述很多都存在错误。假设两个字符串分别为A和B,他们的长度分别为length(A),length(B),那么建立的矩阵的大小应该为(length(A)+1)*(length(B)+1)。其中第一行和第一列只是初始化,如下面的步骤所示。
        0 f a i l i n g
                       
    0                  
    s                  
    a                  
    i                  
    l                  
    n                  
        0 a i l i n g
      0 1 3 4 5 6 7 8
    0 1 0 2 3 4 5 6 7
    s 2 1           6
    a 3 2            
    i 4 3            
    l 5 4            
    n 6 5            
    •  计算edit(1, 1),
      • edit(0, 1) + 1 == 2,
      • edit(1, 0) + 1 == 2,
      • edit(0, 0) + f(1, 1) == 0 + 1 == 1,
      • min(edit(0, 1),edit(1, 0),edit(0, 0) + f(1, 1))==1,
      • 因此edit(1, 1) == 1。 依次类推:
        0 f a i l i n g
      0 1 2 3 4 5 6 7 8
    0 1 0 1 2 3 4 5 6 7
    s 2 1 1 2          
    a 3 2 2          
    i 4 3          
    l 5 4          
    n 6 5          
    • edit(2, 1) + 1 == 3,
      • edit(1, 2) + 1 == 3,
      • edit(1, 1) + f(2, 2) == 1 + 0 == 1,其中s1[2] == 'a' 而 s2[1] == 'f'‘,两者不相同,所以交换相邻字符的操作不计入比较最小数中计算。
      • 以此计算,得出最后矩阵为:
        0 f a i l i n g
      0 1 2 3 4 5 6 7 8
    0 1 0 1 2 3 4 5 6 7
    s 2 1 1 2 3 4 5 6 7
    a 3 2 2 1 2 3 4 5 6
    i 4 3 3 2 1 2 3 4 5
    l 5 4 4 3 2 1 2 3 4
    n 6 5 5 4 3 2 2 2 3
    • 最后可以求出S1=osailn 和 S2=ofailin 的编辑距离为3,即由一个字符替换,有一个字符增加,S1经过两步可以转换成S2。
    • 上述算法中对角线上的计算是计算字符替换操作,而横向和竖向的计算则是计算增加和删除操作,通过逐行比较且相加的方式把几个操作的结果进行汇总。

    算法实现:

         下面用JAVA代码来实现上述过程:

     1 public class LevenshteinEdit {
     2 
     3     public int editDistanceCompute(String strA,String strB){
     4         
     5         int iLengthA = strA.length()+1;
     6         int iLengthB = strB.length()+1;
     7         int maxtri[][] = new int[iLengthA][iLengthB];
     8         
     9         for(int i = 0 ; i < iLengthA ; i++){
    10             maxtri[i][0]=i;
    11         }
    12         
    13         for(int j = 1; j < iLengthB ; j++){
    14             maxtri[0][j]=j;
    15         }
    16         
    17         for(int j = 1 ; j < iLengthB ; j++ ){
    18             
    19             for(int i = 1 ; i < iLengthA ; i++ ){
    20                 
    21                 int min = maxtri[i-1][j-1]+(strA.charAt(i-1) == strB.charAt(j-1)? 0 : 1);
    22                 
    23                 int iUp = maxtri[i][j-1] + 1;
    24                 
    25                 int iLeft = maxtri[i-1][j] + 1;
    26                 
    27                 if ( min > iUp) {
    28                     min = iUp;
    29                 }
    30                 
    31                 if ( min > iLeft ) {
    32                     min = iLeft;
    33                 }
    34                 
    35                 maxtri[i][j] = min;
    36             }
    37         }
    38         
    39         return maxtri[iLengthA-1][iLengthB-1];
    40     }
    41 
    42     public static void main(String[] args) {
    43         String strA = "osailn";
    44         String strB = "ofailin";
    45         LevenshteinEdit le = new LevenshteinEdit();
    46         System.out.println(le.editDistanceCompute(strA, strB));
    47         System.out.println(le.editDistanceCompute("asailn", strB));
    48     }
    49 }

    SOLR实现:

          上述代码还是存在优化的空间的,比如实际上每次只需要存储上一行和当前行的数据就行,这样可以减少字符串长时运算所需要的内存。

          Solr/Lucene当中也使用了Levenshtein距离来进行拼写检查的,同上述的代码不同之处就是Solr使用了前文讲到的存储优化。

     1  //*****************************
     2     // Compute Levenshtein distance: see org.apache.commons.lang.StringUtils#getLevenshteinDistance(String, String)
     3     //*****************************
     4     @Override
     5     public float getDistance (String target, String other) {
     6       char[] sa;
     7       int n;
     8       int p[]; //'previous' cost array, horizontally
     9       int d[]; // cost array, horizontally
    10       int _d[]; //placeholder to assist in swapping p and d
    11       
    12         /*
    13            The difference between this impl. and the previous is that, rather
    14            than creating and retaining a matrix of size s.length()+1 by t.length()+1,
    15            we maintain two single-dimensional arrays of length s.length()+1.  The first, d,
    16            is the 'current working' distance array that maintains the newest distance cost
    17            counts as we iterate through the characters of String s.  Each time we increment
    18            the index of String t we are comparing, d is copied to p, the second int[].  Doing so
    19            allows us to retain the previous cost counts as required by the algorithm (taking
    20            the minimum of the cost count to the left, up one, and diagonally up and to the left
    21            of the current cost count being calculated).  (Note that the arrays aren't really
    22            copied anymore, just switched...this is clearly much better than cloning an array
    23            or doing a System.arraycopy() each time  through the outer loop.)
    24 
    25            Effectively, the difference between the two implementations is this one does not
    26            cause an out of memory condition when calculating the LD over two very large strings.
    27          */
    28 
    29         sa = target.toCharArray();
    30         n = sa.length;
    31         p = new int[n+1]; 
    32         d = new int[n+1]; 
    33       
    34         final int m = other.length();
    35         if (n == 0 || m == 0) {
    36           if (n == m) {
    37             return 1;
    38           }
    39           else {
    40             return 0;
    41           }
    42         } 
    43 
    44 
    45         // indexes into strings s and t
    46         int i; // iterates through s
    47         int j; // iterates through t
    48 
    49         char t_j; // jth character of t
    50 
    51         int cost; // cost
    52 
    53         for (i = 0; i<=n; i++) {
    54             p[i] = i;
    55         }
    56 
    57         for (j = 1; j<=m; j++) {
    58             t_j = other.charAt(j-1);
    59             d[0] = j;
    60 
    61             for (i=1; i<=n; i++) {
    62                 cost = sa[i-1]==t_j ? 0 : 1;
    63                 // minimum of cell to the left+1, to the top+1, diagonally left and up +cost
    64                 d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1),  p[i-1]+cost);
    65             }
    66 
    67             // copy current distance counts to 'previous row' distance counts
    68             _d = p;
    69             p = d;
    70             d = _d;
    71         }
    72 
    73         // our last action in the above loop was to switch d and p, so p now
    74         // actually has the most recent cost counts
    75         return 1.0f - ((float) p[n] / Math.max(other.length(), sa.length));
    76     }

    总结

        本节学习了很常用的一个字符串比较算法,Levenshtein距离,算法内容以及实现还是比较简单。Solr给我们提供了使用的很好例子。

        但是上述的算法还是比较原始,还是可以有很大的改善空间,比如可以区分替换,删除,增加操作的不同权重,本人在公司相似车牌特性中就使用了不同的权重,后续会整理写出。

  • 相关阅读:
    js数组去重五种方法
    wm_concat 多行字符串拼接
    ORACLE WITH AS 简单用法
    layui laytpl 语法
    看懂Oracle执行计划
    GIT RM -R --CACHED 去掉已经托管在GIT上的文件
    sourceTree使用教程--拉取、获取
    SourceTree忽略文件和文件夹
    layui table 详细讲解
    利用POI实现下拉框级联
  • 原文地址:https://www.cnblogs.com/rcfeng/p/4067812.html
Copyright © 2011-2022 走看看