DiceCoefficient [Dice系数]
# 介绍
骰子系数(Dice coefficient),也称索伦森 - 骰子系数(Sørensen–Dice coefficient),是一种集合相似度度量函数,通常用于计算两个样本的相似度(也可以度量字符串的相似性)。
Dice 系数可以计算两个字符串的相似度: Dice(s1,s2)=2*comm(s1,s2)/(leng(s1)+leng(s2))
。其中, comm (s1,s2)
是 s1、s2 中相同字符的个数 leng(s1),leng(s2)
是字符串 s1、s2 的长度。
# 实现
# JavaScript
Dice 系数是通过比较两个字符串的 bigrams 来计算的, 一个 bigrams 是长度为 2 的字符串的一个子串。
/* The Sørensen–Dice coefficient(系数) is a statistic used to (估计) the similarity of two samples.
* Applied to strings, it can give you a value between 0 and 1 (included) which tells you how similar they are.
* Dice coefficient is calculated by comparing the bigrams of both strings,
* a bigram is a substring of the string of length 2.
* read more: https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
*/
// Time complexity: O(m + n), m and n being the sizes of string A and string B
// Find the bistrings of a string and return a hashmap (key => bistring, value => count)
function mapBigrams(string) {
const bigrams = new Map();
for (let i = 0; i < string.length - 1; i++) {
const bigram = string.substring(i, i + 2);
const count = bigrams.get(bigram);
bigrams.set(bigram, (count || 0) + 1);
}
return bigrams;
}
// Calculate the number of common bigrams between a map of bigrams and a string
function countCommonBigrams(bigrams, string) {
let count = 0;
for (let i = 0; i < string.length - 1; i++) {
const bigram = string.substring(i, i + 2);
if (bigrams.has(bigram)) count++;
}
return count;
}
// Calculate Dice coeff of 2 strings
function diceCoefficient(stringA, stringB) {
if (stringA === stringB) return 1;
else if (stringA.length < 2 || stringB.length < 2) return 0;
const bigramsA = mapBigrams(stringA);
const lengthA = stringA.length - 1;
const lengthB = stringB.length - 1;
let dice = (2 * countCommonBigrams(bigramsA, stringB)) / (lengthA + lengthB);
// cut 0.xxxxxx to 0.xx for simplicity
dice = Math.floor(dice * 100) / 100;
return dice;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
- substring() (opens new window) 方法返回一个字符串在开始索引到结束索引之间的一个子集,或从开始索引直到字符串的末尾的一个子集。
# 扩展
# 参考
编辑 (opens new window)
上次更新: 2022/10/20, 20:45:42