-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNaturalnessModel.js
75 lines (67 loc) · 2.48 KB
/
NaturalnessModel.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
const Sequence = require('./Sequence.js');
const NgramSuccessorModel = require('./NgramSuccessorModel.js');
const Ngram = require('./Ngram.js');
const PROBA_OF_UNKNOWN = 0; //0.000001;
const DEPTH = 3;
class NaturalnessModel {
constructor(depth, probaOfUnknown) {
this.ngramMap = new Map();
this.depth = depth || DEPTH;
this.probaOfUnknown = probaOfUnknown || PROBA_OF_UNKNOWN;
}
crossEntropy(sequence) {
checkSequenceType(sequence);
if (sequence.eventList.length === 0) return this.probaOfUnknown;
let probabilitySum = 0;
for (let index = 0; index < sequence.eventList.length; index++) {
let currentEvent = sequence.eventList[index];
let currentNgram = sequence.getNgram(index, this.depth);
let modelProba = this.getProbability(currentNgram, currentEvent);
let proba;
if (modelProba === 0) {
proba = this.probaOfUnknown;
} else {
proba = modelProba * (1 - this.probaOfUnknown);
}
probabilitySum = probabilitySum + Math.log2(proba);
}
return -(probabilitySum / sequence.eventList.length);
}
getProbability(ngram, event) {
let successor = this.ngramMap.get(ngram.key);
if (successor === undefined) {
return 0;
}
return successor.getProbability(event);
}
learn(sequence) {
checkSequenceType(sequence);
for (let index = 0; index < sequence.eventList.length; index++) {
let ngram = sequence.getNgram(index, this.depth);
let ngramSuccessor = this.ngramMap.get(ngram.key);
if (ngramSuccessor === undefined) {
ngramSuccessor = new NgramSuccessorModel();
this.ngramMap.set(ngram.key, ngramSuccessor);
}
ngramSuccessor.learn(sequence.eventList[index]);
}
}
getNgramSuccessorModel(ngram) {
checkNgramType(ngram);
return this.ngramMap.get(ngram.key);
}
}
function checkSequenceType(sequence) {
if (!(sequence instanceof Sequence)) {
throw 'sequence is not a Sequence';
}
}
function checkNgramType(ngram) {
if (ngram === undefined || ngram === null ) {
throw 'ngram is null or undefined';
}
if (!(ngram instanceof Ngram)) {
throw 'ngram is not a Ngram';
}
}
module.exports = NaturalnessModel;