-
Notifications
You must be signed in to change notification settings - Fork 0
/
tf-idf.js
97 lines (77 loc) · 2.69 KB
/
tf-idf.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const { dotMultiply, matrix, log10 } = require('mathjs');
const computeTf = (tokenOccurence, tokenCount) => {
let tf = [];
for (const token in tokenOccurence) {
tf.push(tokenOccurence[token] / tokenCount);
}
tf.map(v => { return log10(v); });
return matrix(tf);
};
const computeIdf = (tokenOccurence) => {
const documentCount = 1;
let idf = [];
for (const token in tokenOccurence) {
idf.push(documentCount / tokenOccurence[token]);
}
idf.map(v => { return log10(v); });
return matrix(idf);
}
const cleanSource = (source) => {
const stopwords = [
'i', 'me', 'my', 'myself',
'we', 'our', 'ours', 'ourselves',
'you', 'your', 'yours', 'yourself',
'yourselves', 'he', 'him', 'his',
'himself', 'she', 'her', 'hers',
'herself', 'it', 'its','itself',
'they', 'them', 'their', 'theirs',
'themselves', 'what', 'which', 'who',
'whom', 'this', 'that', 'these',
'those', 'am', 'is', 'are',
'was', 'were', 'be', 'been',
'being', 'have', 'has', 'had',
'having', 'do', 'does', 'did',
'doing', 'a', 'an', 'the',
'and', 'but', 'if', 'or',
'because', 'as', 'until', 'while',
'of', 'at', 'by', 'for',
'with', 'about', 'against', 'between',
'into', 'through', 'during', 'before',
'after', 'above', 'below', 'to',
'from', 'up', 'down', 'in',
'out', 'on', 'off', 'over',
'under', 'again', 'further', 'then',
'once', 'here', 'there', 'when',
'where', 'why', 'how', 'all',
'any', 'both', 'each', 'few',
'more', 'most', 'other', 'some',
'such', 'no', 'nor', 'not',
'only', 'own', 'same', 'so',
'than', 'too', 'very', 's',
't', 'can', 'will', 'just',
'don', 'should', 'now'];
source = source.toLowerCase();
source = source.replace(/[^\w\s]|_/g, "").replace(/\s+/g, " ");
const tokens = source.split(' ');
let trimmed = [];
// for (let i = 0; tokens.length; i++) {
// if (!stopwords.includes(tokens[i])) {
// trimmed.push(tokens[i]);
// }
// }
// source = trimmed.join(' ');
return source;
}
const tfidfDistance = (source) => {
source = cleanSource(source);
let tokens = source.split(' ');
let tokensSet = [...new Set(source.split(' '))];
let tokenOccurence = [];
tokensSet.forEach(token => {
tokenOccurence[token] = tokens.filter(word => word == token).length;
});
let tf = computeTf(tokenOccurence, tokens.length);
let idf = computeIdf(tokenOccurence);
return dotMultiply(tf, idf);
}
module.exports.tfidfDistance = tfidfDistance;