DTW-js版

最近想试试语音识别,然后看到了DTW这个算法

主要参考:http://www.cnblogs.com/rockyf/articles/4519352.html

 1 function dtw(arr1, arr2){
 2     var matrix = [];
 3     arr1.forEach(function(value1){
 4         var line = [];
 5         matrix.push(line);
 6         arr2.forEach(function(value2){
 7             line.push(distance(value1, value2));
 8         });
 9     });
10     console.log(matrix);
11 
12     console.log(minSearch(matrix, arr2.length, arr1.length));
13 }
14 
15 function minSearch(matrix, i, j){
16     if(i == 0 || j == 0){
17         return 0;
18     }
19     var d = matrix[j - 1][i - 1];
20     var a = minSearch(matrix, i - 1, j) + d;
21     var b = minSearch(matrix, i, j - 1) + d;
22     var c = minSearch(matrix, i - 1, j - 1) + d * 2;
23     return Math.min(a, b, c);
24 }
25 
26 function distance(value1, value2){
27     return Math.abs(value1 - value2);
28 }
29 
30 dtw([1, 2], [1, 3]);

很简单的一个递归来做最小值查找,即可查找到最优路径和两个数组的距离。

posted @ 2015-05-21 13:06  RockyF  阅读(673)  评论(1编辑  收藏  举报