-
Notifications
You must be signed in to change notification settings - Fork 3
/
crf.py
294 lines (228 loc) · 9.76 KB
/
crf.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import numpy as np
import scipy.misc
def node_potentials(features, state_params):
"""
Returns a w x k numpy array of node potentials,
where w is the word length and k is the size of the alphabet.
Parameters:
- features, a w x n numpy array of feature vectors,
where n is the length of the feature vector; and
- state_params, a k x n numpy array of state parameters.
"""
return np.dot(features, np.transpose(state_params))
def clique_potentials(node_factor1, node_factor2, trans_params):
"""
Computes the clique potentials of a single clique.
Returns a k x k numpy array, where k is the size of the alphabet.
Parameters:
- node_factor1, a k-dimensional numpy array of node potentials;
- node_factor2, a k-dimensional numpy array of node potentials or a None object; and
- trans_params, a k x k numpy array of transition parameters.
"""
psi = trans_params + node_factor1[:, np.newaxis]
if node_factor2 is not None:
psi += node_factor2
return psi
def clique_tree_potentials(theta, features):
"""
Computes the clique potentials of the entire chain.
Returns a (w-1) x k x k numpy array,
where w is the word length and k is the size of the alphabet.
Parameters:
- theta, a [state_params, trans_params] list; and
- features, a w x n numpy array, where n is the length of the feature vector.
"""
state_params, trans_params = theta
phi = node_potentials(features, state_params)
# Include the potentials of the last two nodes in the same clique
cliques = [(node, None) for node in phi[:-2]] + [(phi[-2], phi[-1])]
psi = [clique_potentials(n1, n2, trans_params) for n1, n2 in cliques]
return np.array(psi)
def sum_product_messages(psi):
"""
Returns the (backward messages, forward messages) tuple.
Each messages is a (w-2) x k numpy array,
where w is the word length and k is the size of the alphabet.
Parameter:
- psi, a (w-1) x k x k numpy array of clique tree potentials.
"""
# Backward messages
bwd = []
prev_msgs = np.zeros(psi.shape[1])
for clique in psi[:0:-1]:
msg = scipy.misc.logsumexp(clique + prev_msgs, axis=1)
bwd.append(msg)
prev_msgs += msg
# Forward messages
fwd = []
prev_msgs = np.zeros(psi.shape[1])
for clique in psi[:-1]:
msg = scipy.misc.logsumexp(clique + prev_msgs[:, np.newaxis], axis=0)
fwd.append(msg)
prev_msgs += msg
return (np.array(bwd), np.array(fwd))
def beliefs(theta, features):
"""
Returns a numpy array of size (w-1) x k x k,
where w is the word length and k is the size of the alphabet.
Parameters:
- theta, a [state_params, trans_params] list; and
- features, a w x n numpy array of feature vectors,
where n is the length of the feature vector.
"""
psi = clique_tree_potentials(theta, features)
delta_bwd, delta_fwd = sum_product_messages(psi)
k = delta_fwd.shape[1]
delta_fwd = np.concatenate(([np.zeros(k)], delta_fwd))
delta_bwd = np.concatenate((delta_bwd[::-1], [np.zeros(k)]))
beta = psi + delta_fwd[:, :, np.newaxis] + delta_bwd[:, np.newaxis]
return np.array(beta)
def pairwise_prob(beta):
"""
Computes the pairwise marginal probabilities.
Returns a numpy array of size (w-1) x k x k,
where w is the word length and k is the size of the alphabet.
Parameter:
- beta, a (w-1) x k x k numpy array of log belief tables.
"""
return np.exp(beta - scipy.misc.logsumexp(beta, axis=(1,2))[:, np.newaxis, np.newaxis])
def single_prob(pairwise_p):
"""
Computes the singleton marginal probabilities.
Returns a w x k numpy array, where n is the word length and k is the size of the alphabet.
Parameter:
- pairwise_p, a numpy array of size (w-1) x k x k of pairwise marginal probabilities.
"""
p = np.sum(pairwise_p, axis=2)
q = np.sum(pairwise_p[-1], axis=0) # Last character in the word
return np.concatenate((p, q[np.newaxis, :]))
def joint_prob(single_p, label, alphabet):
"""
Computes the joint probability of the label given singleton marginal probabilities.
Returns a scalar.
Parameters:
- single_p, a w x k numpy array of singleton marginal probabilities,
where n is the word length and k is the size of the alphabet;
- label, a list of character labels; and
- alphabet, a list of all possible character labels.
"""
p = [np.log(marginal[alphabet.index(c)]) for (c, marginal) in zip(label, single_p)]
return np.sum(p)
def likelihood(theta, data, alphabet):
"""
Objective function to minimize.
Returns the negative average log likelihood of theta given the data.
Parameters:
- theta, a [state_params, trans_params] list;
- data, a list of (word_label, word_features) tuples; and
- alphabet, a list of all possible character labels.
"""
# If flattened, reshape theta into a list of state parameter table of size n x k
# and transition parameter table of size k x k,
# where n is the length of the feature vector and k is the size of the alphabet
if len(theta) != 2:
k = len(alphabet) # number of possible character labels
n = len(data[0][1][0]) # length of feature vector
mid = k * n
state_params = np.reshape(theta[:mid], (k, n))
trans_params = np.reshape(theta[mid:], (k, k))
theta = [state_params, trans_params]
p = []
for label, features in data:
beta = beliefs(theta, features)
pairwise_p = pairwise_prob(beta)
single_p = single_prob(pairwise_p)
p.append(joint_prob(single_p, label, alphabet))
return -np.sum(p)/len(data)
def state_gradient(theta, data, alphabet):
"""
Returns a flattened k x n numpy array,
where k is the size of the alphabet and n is the length of the feature vector.
Parameters:
- theta, a [state_params, trans_params] list;
- data, a list of (word_label, word_features) tuples; and
- alphabet, a list of all possible character labels.
"""
# Initialize a state gradient table of size k x n with zeros
gradient = np.zeros((len(alphabet), len(data[0][1][0])))
for label, features in data:
beta = beliefs(theta, features)
pairwise_p = pairwise_prob(beta)
single_p = single_prob(pairwise_p)
for v, c, p in zip(features, label, single_p):
for i in range(gradient.shape[0]): # possible labels
for j in range(gradient.shape[1]): # features
indicator = 0
if c == alphabet[i]:
indicator = 1
gradient[i][j] += (indicator - p[i]) * v[j]
gradient /= len(data)
return np.ndarray.flatten(np.negative(gradient))
def transition_gradient(theta, data, alphabet):
"""
Returns a flattened k x k numpy array, where k is the size of the alphabet.
Parameters:
- theta, a [state_params, trans_params] list;
- data, a list of (word_label, word_features) tuples; and
- alphabet, a list of all possible character labels.
"""
# Initialize a transition gradient table of size k x k with zeros
gradient = np.zeros((len(alphabet), len(alphabet)))
for label, features in data:
beta = beliefs(theta, features)
pairwise_p = pairwise_prob(beta)
label_pairs = zip([None] + label, label + [None])[1:-1]
for (label1, label2), p in zip(label_pairs, pairwise_p):
for i in range(gradient.shape[0]):
for j in range(gradient.shape[1]):
indicator = 0
if label1 == alphabet[i] and label2 == alphabet[j]:
indicator = 1
gradient[i][j] += indicator - p[i][j]
gradient /= len(data)
return np.ndarray.flatten(np.negative(gradient))
def likelihood_prime(theta, data, alphabet):
"""
Returns a flattened numpy array of the [feature_gradient, transition_gradient] list.
Parameters:
- theta, a [state_params, trans_params] list;
- data, a list of (word_label, word_features) tuples; and
- alphabet, a list of all possible character labels.
"""
# Reshape flattened theta into a list of k x n state parameter table and
# k x k transition parameter table, where k is the size of the alphabet and
# n is the length of the feature vector. Both parameter tables are numpy arrays.
k = len(alphabet) # number of possible character labels
n = len(data[0][1][0]) # length of feature vector
mid = k * n
state_params = np.reshape(theta[:mid], (k, n))
trans_params = np.reshape(theta[mid:], (k, k))
theta = [state_params, trans_params]
return np.concatenate((state_gradient(theta, data, alphabet),
transition_gradient(theta, data, alphabet)))
def predict_word(single_p, alphabet):
"""
Returns a list of predicted characters of a word.
Parameters:
- single_p, a w x k numpy array of singleton marginal probabilities,
where w is the word length and k is the size of the alphabet; and
- alphabet, a list of all possible character labels.
"""
indices = np.argmax(single_p, axis=1)
return [alphabet[i] for i in indices]
def predict(theta, data, alphabet):
"""
Returns a list of predictions, where each prediction is
a list of predicted character labels of a word.
Parameters:
- theta, a [state_params, trans_params] list;
- data, a list of (word_label, word_features) tuples; and
- alphabet, a list of all possible character labels.
"""
predictions = []
for _, features in data:
beta = beliefs(theta, features)
pairwise_p = pairwise_prob(beta)
single_p = single_prob(pairwise_p)
predictions.append(predict_word(single_p, alphabet))
return predictions