forked from mathias-madsen/information_theory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
predictive_model.py
93 lines (56 loc) · 2.65 KB
/
predictive_model.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import numpy as np
class PredictiveModel(object):
def __init__(self, alphabet="ABC"):
self.alphabet = sorted(alphabet)
def conditionals(self, context):
""" Compute the conditional distribution given the context. """
raise NotImplementedError
def conditional(self, context, letter):
""" Compute P(letter | context). """
distribution = self.conditionals(context)
return distribution[letter]
def cumulatives(self, context):
""" Compute the cumulative distribution vector given the context. """
distribution = self.conditionals(context)
probabilities = [distribution[a] for a in self.alphabet]
return np.cumsum([0] + probabilities)
def cumulative(self, context, letter):
""" Compute P(letter | context) for all letters more to the 'left'. """
cumulatives = self.cumulatives(context)
letter_index = self.alphabet.index(letter)
return cumulatives[letter_index]
def sample(self, length):
""" Sample a sequence of the given lenghth from this random process. """
text = ""
for t in range(length):
distribution = self.conditionals(text)
letters = sorted(distribution.keys())
probabilities = [distribution[letter] for letter in letters]
text += np.random.choice(letters, p=probabilities)
return text
class PolyaUrnModel(PredictiveModel):
def conditionals(self, context):
""" Compute the conditional distribution given the context. """
frequencies = np.array([context.count(a) for a in self.alphabet])
smooth_frequences = 1 + frequencies
probabilities = smooth_frequences / np.sum(smooth_frequences)
return dict(zip(self.alphabet, probabilities))
class MarkovModel(PredictiveModel):
def __init__(self, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ "):
self.alphabet = sorted(alphabet)
alpha = np.ones(len(self.alphabet))
self.initials = np.random.dirichlet(alpha)
self.transitions = {letter: np.random.dirichlet(alpha)
for letter in self.alphabet}
def conditionals(self, context):
""" Compute the conditional distribution given the context. """
if context:
probabilities = self.transitions[context[-1]]
else:
probabilities = self.initials
return dict(zip(self.alphabet, probabilities))
class MixedModel(PredictiveModel):
def __init__(self, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ "):
from mixed_model import alphabet, conditionals
self.alphabet = alphabet
self.conditionals = conditionals