summaryrefslogtreecommitdiff
path: root/gi/posterior-regularisation/train_pr_agree.py
blob: bbd6e0070d92af553b8857db696bb5a420f88e35 (plain)
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import sys
import scipy.optimize
from scipy.stats import geom
from numpy import *
from numpy.random import random, seed

style = sys.argv[1]
if len(sys.argv) >= 3:
     seed(int(sys.argv[2]))

#
# Step 1: load the concordance counts
# 

edges = []
word_types = {}
phrase_types = {}
context_types = {}

for line in sys.stdin:
    phrase, rest = line.strip().split('\t')
    ptoks = tuple(map(lambda t: word_types.setdefault(t, len(word_types)), phrase.split()))
    pid = phrase_types.setdefault(ptoks, len(phrase_types))

    parts = rest.split('|||')
    for i in range(0, len(parts), 2):
        context, count = parts[i:i+2]

        ctx = filter(lambda x: x != '<PHRASE>', context.split())
        ctoks = tuple(map(lambda t: word_types.setdefault(t, len(word_types)), ctx))
        cid = context_types.setdefault(ctoks, len(context_types))

        cnt = int(count.strip()[2:])
        edges.append((pid, cid, cnt))

word_type_list = [None] * len(word_types)
for typ, index in word_types.items():
    word_type_list[index] = typ

phrase_type_list = [None] * len(phrase_types)
for typ, index in phrase_types.items():
    phrase_type_list[index] = typ

context_type_list = [None] * len(context_types)
for typ, index in context_types.items():
    context_type_list[index] = typ

num_tags = 5
num_types = len(word_types)
num_phrases = len(phrase_types)
num_contexts = len(context_types)
num_edges = len(edges)

print 'Read in', num_edges, 'edges', num_phrases, 'phrases', num_contexts, 'contexts and', num_types, 'word types'

#
# Step 2:  expectation maximisation 
#

def normalise(a):
    return a / float(sum(a))

class PhraseToContextModel:
    def __init__(self):
        # Pr(tag | phrase)
        self.tagDist = [normalise(random(num_tags)+1) for p in range(num_phrases)]
        # Pr(context at pos i = w | tag) indexed by i, tag, word
        self.contextWordDist = [[normalise(random(num_types)+1) for t in range(num_tags)] for i in range(4)]

    def prob(self, pid, cid):
        # return distribution p(tag, context | phrase) as vector of length |tags|
        context = context_type_list[cid]
        dist = zeros(num_tags)
        for t in range(num_tags):
            prob = self.tagDist[pid][t]
            for k, tokid in enumerate(context):
                prob *= self.contextWordDist[k][t][tokid]
            dist[t] = prob
        return dist

    def expectation_maximisation_step(self, lamba=None):
        tagCounts = zeros((num_phrases, num_tags))
        contextWordCounts = zeros((4, num_tags, num_types))

        # E-step
        llh = 0
        for pid, cid, cnt in edges:
            q = self.prob(pid, cid)
            z = sum(q)
            q /= z
            llh += log(z)
            context = context_type_list[cid]
            if lamba != None:
                q *= exp(lamba)
                q /= sum(q)
            for t in range(num_tags):
                tagCounts[pid][t] += cnt * q[t]
            for i in range(4):
                for t in range(num_tags):
                    contextWordCounts[i][t][context[i]] += cnt * q[t]

        # M-step
        for p in range(num_phrases):
            self.tagDist[p] = normalise(tagCounts[p])
        for i in range(4):
            for t in range(num_tags):
                self.contextWordDist[i][t] = normalise(contextWordCounts[i,t])

        return llh

class ContextToPhraseModel:
    def __init__(self):
        # Pr(tag | context) = Multinomial
        self.tagDist = [normalise(random(num_tags)+1) for p in range(num_contexts)]
        # Pr(phrase = w | tag) = Multinomial
        self.phraseSingleDist = [normalise(random(num_types)+1) for t in range(num_tags)]
        # Pr(phrase_1 = w | tag) = Multinomial
        self.phraseLeftDist = [normalise(random(num_types)+1) for t in range(num_tags)]
        # Pr(phrase_-1 = w | tag) = Multinomial
        self.phraseRightDist = [normalise(random(num_types)+1) for t in range(num_tags)]
        # Pr(|phrase| = l | tag) = Geometric
        self.phraseLengthDist = [0.5] * num_tags
        # n.b. internal words for phrases of length >= 3 are drawn from uniform distribution

    def prob(self, pid, cid):
        # return distribution p(tag, phrase | context) as vector of length |tags|
        phrase = phrase_type_list[pid]
        dist = zeros(num_tags)
        for t in range(num_tags):
            prob = self.tagDist[cid][t]
            f = self.phraseLengthDist[t]
            prob *= geom.pmf(len(phrase), f)
            if len(phrase) == 1:
                prob *= self.phraseSingleDist[t][phrase[0]]
            else:
                prob *= self.phraseLeftDist[t][phrase[0]]
                prob *= self.phraseRightDist[t][phrase[-1]]
            dist[t] = prob
        return dist

    def expectation_maximisation_step(self, lamba=None):
        tagCounts = zeros((num_contexts, num_tags))
        phraseSingleCounts = zeros((num_tags, num_types))
        phraseLeftCounts = zeros((num_tags, num_types))
        phraseRightCounts = zeros((num_tags, num_types))
        phraseLength = zeros(num_types)

        # E-step
        llh = 0
        for pid, cid, cnt in edges:
            q = self.prob(pid, cid)
            z = sum(q)
            q /= z
            llh += log(z)
            if lamba != None:
                q *= exp(lamba)
                q /= sum(q)
            #print 'p', phrase_type_list[pid], 'c', context_type_list[cid], 'q', q
            phrase = phrase_type_list[pid]
            for t in range(num_tags):
                tagCounts[cid][t] += cnt * q[t]
                phraseLength[t] += cnt * len(phrase) * q[t]
                if len(phrase) == 1:
                    phraseSingleCounts[t][phrase[0]] += cnt * q[t]
                else:
                    phraseLeftCounts[t][phrase[0]] += cnt * q[t]
                    phraseRightCounts[t][phrase[-1]] += cnt * q[t]

        # M-step
        for t in range(num_tags):
            self.phraseLengthDist[t] = min(max(sum(tagCounts[:,t]) / phraseLength[t], 1e-6), 1-1e-6)
            self.phraseSingleDist[t] = normalise(phraseSingleCounts[t])
            self.phraseLeftDist[t] = normalise(phraseLeftCounts[t])
            self.phraseRightDist[t] = normalise(phraseRightCounts[t])
        for c in range(num_contexts):
            self.tagDist[c] = normalise(tagCounts[c])

        #print 't', self.tagDist
        #print 'l', self.phraseLengthDist
        #print 's', self.phraseSingleDist
        #print 'L', self.phraseLeftDist
        #print 'R', self.phraseRightDist

        return llh

class ProductModel:
    """
    WARNING: I haven't verified the maths behind this model. It's quite likely to be incorrect.
    """

    def __init__(self):
        self.pcm = PhraseToContextModel()
        self.cpm = ContextToPhraseModel()

    def prob(self, pid, cid):
        p1 = self.pcm.prob(pid, cid)
        p2 = self.cpm.prob(pid, cid)
        return (p1 / sum(p1)) * (p2 / sum(p2))

    def expectation_maximisation_step(self):
        tagCountsGivenPhrase = zeros((num_phrases, num_tags))
        contextWordCounts = zeros((4, num_tags, num_types))

        tagCountsGivenContext = zeros((num_contexts, num_tags))
        phraseSingleCounts = zeros((num_tags, num_types))
        phraseLeftCounts = zeros((num_tags, num_types))
        phraseRightCounts = zeros((num_tags, num_types))
        phraseLength = zeros(num_types)

        kl = llh1 = llh2 = 0
        for pid, cid, cnt in edges:
            p1 = self.pcm.prob(pid, cid)
            llh1 += log(sum(p1)) * cnt
            p2 = self.cpm.prob(pid, cid)
            llh2 += log(sum(p2)) * cnt

            q = (p1 / sum(p1)) * (p2 / sum(p2))
            kl += log(sum(q)) * cnt
            qi = sqrt(q)
            qi /= sum(qi)

            phrase = phrase_type_list[pid]
            context = context_type_list[cid]
            for t in range(num_tags):
                tagCountsGivenPhrase[pid][t] += cnt * qi[t]
                tagCountsGivenContext[cid][t] += cnt * qi[t]
                phraseLength[t] += cnt * len(phrase) * qi[t]
                if len(phrase) == 1:
                    phraseSingleCounts[t][phrase[0]] += cnt * qi[t]
                else:
                    phraseLeftCounts[t][phrase[0]] += cnt * qi[t]
                    phraseRightCounts[t][phrase[-1]] += cnt * qi[t]
                for i in range(4):
                    contextWordCounts[i][t][context[i]] += cnt * qi[t]

        kl *= -2

        for t in range(num_tags):
            for i in range(4):
                self.pcm.contextWordDist[i][t] = normalise(contextWordCounts[i,t])
            self.cpm.phraseLengthDist[t] = min(max(sum(tagCountsGivenContext[:,t]) / phraseLength[t], 1e-6), 1-1e-6)
            self.cpm.phraseSingleDist[t] = normalise(phraseSingleCounts[t])
            self.cpm.phraseLeftDist[t] = normalise(phraseLeftCounts[t])
            self.cpm.phraseRightDist[t] = normalise(phraseRightCounts[t])
        for p in range(num_phrases):
            self.pcm.tagDist[p] = normalise(tagCountsGivenPhrase[p])
        for c in range(num_contexts):
            self.cpm.tagDist[c] = normalise(tagCountsGivenContext[c])

        # return the overall objective
        return llh1 + llh2 + kl

class InterpolatedModel:
    def __init__(self, epsilon):
        self.pcm = PhraseToContextModel()
        self.cpm = ContextToPhraseModel()
        self.epsilon = epsilon
        self.lamba = zeros(num_tags)

    def prob(self, pid, cid):
        p1 = self.pcm.prob(pid, cid)
        p2 = self.cpm.prob(pid, cid)
        return (p1 + p2) / 2

    def dual(self, lamba):
        return self.logz(lamba) + self.epsilon * dot(lamba, lamba) ** 0.5

    def dual_gradient(self, lamba):
        return self.expected_features(lamba) + self.epsilon * 2 * lamba

    def expectation_maximisation_step(self):
        # PR-step: optimise lambda to minimise log(z_lambda) + eps ||lambda||_2
        self.lamba = scipy.optimize.fmin_slsqp(self.dual, self.lamba,
                                bounds=[(0, 1e100)] * num_tags,
                                fprime=self.dual_gradient, iprint=0)

        # E,M-steps: collect expected counts under q_lambda and normalise
        #llh1 = self.pcm.expectation_maximisation_step(self.lamba)
        #llh2 = self.cpm.expectation_maximisation_step(-self.lamba)

        # return the overall objective: llh1 + llh2 - KL(q||p1.p2)
        pass

    def logz(self, lamba):
        # FIXME: complete this!
        lz = 0
        for pid, cid, cnt in edges:
            p1 = self.pcm.prob(pid, cid)
            z1 = dot(p1 / sum(p1), exp(lamba))
            lz += log(z1) * cnt

            p2 = self.cpm.prob(pid, cid)
            z2 = dot(p2 / sum(p2), exp(-lamba))
            lz += log(z2) * cnt
        return lz

    def expected_features(self, lamba):
        fs = zeros(num_tags)
        for pid, cid, cnt in edges:
            p1 = self.pcm.prob(pid, cid)
            q1 = (p1 / sum(p1)) * exp(lamba)
            fs += cnt * q1 / sum(q1)

            p2 = self.cpm.prob(pid, cid)
            q2 = (p2 / sum(p2)) * exp(-lamba)
            fs -= cnt * q2 / sum(q2)
        return fs

if style == 'p2c':
    m = PhraseToContextModel()
elif style == 'c2p':
    m = ContextToPhraseModel()
elif style == 'prod':
    m = ProductModel()
elif style == 'sum':
    m = InterpolatedModel()

for iteration in range(30):
    obj = m.expectation_maximisation_step()
    print 'iteration', iteration, 'objective', obj

for pid, cid, cnt in edges:
    p = m.prob(pid, cid)
    phrase = phrase_type_list[pid]
    phrase_str = ' '.join(map(word_type_list.__getitem__, phrase))
    context = context_type_list[cid]
    context_str = ' '.join(map(word_type_list.__getitem__, context))
    print '%s\t%s ||| C=%d' % (phrase_str, context_str, argmax(p))