-
Notifications
You must be signed in to change notification settings - Fork 19
/
frequency.py
executable file
·74 lines (54 loc) · 1.54 KB
/
frequency.py
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
# -*- coding: utf-8 -*-
import good_turing
class BaseProb(object):
def __init__(self):
self.d = {}
self.total = 0.0
self.none = 0
def exists(self, key):
return key in self.d
def getsum(self):
return self.total
def get(self, key):
if not self.exists(key):
return False, self.none
return True, self.d[key]
def freq(self, key):
return float(self.get(key)[1])/self.total
def samples(self):
return self.d.keys()
class NormalProb(BaseProb):
def add(self, key, value):
if not self.exists(key):
self.d[key] = 0
self.d[key] += value
self.total += value
class AddOneProb(BaseProb):
def __init__(self):
self.d = {}
self.total = 0.0
self.none = 1
def add(self, key, value):
self.total += value
if not self.exists(key):
self.d[key] = 1
self.total += 1
self.d[key] += value
class GoodTuringProb(BaseProb):
def __init__(self):
self.d = {}
self.total = 0.0
self.handled = False
def add(self, key, value):
if not self.exists(key):
self.d[key] = 0
self.d[key] += value
def get(self, key):
if not self.handled:
self.handled = True
tmp, self.d = good_turing.main(self.d)
self.none = tmp
self.total = sum(self.d.values())+0.0
if not self.exists(key):
return False, self.none
return True, self.d[key]