Blame view

bin/results_cnn.py 12.6 KB
362b552ee   Rouvier Mickael   upload system
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
  from keras.models import Sequential
  from keras.layers.core import TimeDistributedDense
  from keras.layers.advanced_activations import PReLU
  from keras.layers.normalization import BatchNormalization
  from keras import backend as K
  #from keras.layers.core import Dense, Dropout, Activation, Reshape, Flatten
  from keras.layers import TimeDistributed, Lambda, Input, merge, Bidirectional
  from keras.layers.core import Dense, Activation, Dropout, Flatten
  from keras.layers import GlobalAveragePooling1D, GlobalMaxPooling1D, Conv1D, MaxPooling1D
  #from keras.layers.convolutional import Convolution1D, MaxPooling1D, AveragePooling1D
  from keras.optimizers import SGD, Adadelta, Adam, Adamax, RMSprop
  from keras.models import Model
  #from keras.layers.recurrent import LSTM, GRU, SimpleRNN
  from keras.constraints import maxnorm
  from keras.callbacks import Callback, EarlyStopping
  from keras.preprocessing import sequence
  from keras.layers.embeddings import Embedding
  from keras.regularizers import l2, activity_l2
  from keras import regularizers
  from keras.models import model_from_json
  import theano
  from theano import tensor
  import warnings
  import sys
  import time
  import os
  import numpy as np
  import fileinput
  import math
  
  warnings.filterwarnings("ignore")
  
  def create_class_weight(labels_dict,mu=0.55):
      total = np.sum(labels_dict.values())
      keys = labels_dict.keys()
      class_weight = dict()
  
      for key in keys:
          score = math.log(mu*total/float(labels_dict[key]))
          class_weight[key] = score if score > 1.0 else 1.0
  
      return class_weight
  
  
  def score_deft_2017(pred, gold, task):
      t = ConfusionMatrix()
      for x in range(0, len(gold)):
          a = pred[x].tolist()
          b = gold[x].tolist()
          t.store(a.index(max(a)), b.index(max(b)))
      return t.score_deft_2017(task)
  
  
  def score_semeval_2017(pred, gold):
      t = ConfusionMatrix()
      for x in range(0, len(gold)):
          a = pred[x].tolist()
          b = gold[x].tolist()
          t.store(a.index(max(a)), b.index(max(b)))
      return t.score_semeval_2017()
  
  def score_semeval_2016(pred, gold):
      t = ConfusionMatrix()
      for x in range(0, len(gold)):
          a = pred[x].tolist()
          b = gold[x].tolist()
          t.store(a.index(max(a)), b.index(max(b)))
      return t.score_semeval_2016()
  
  
  
  
  class validation_semeval(Callback):
  
      def __init__(self, dev_files, word_word2vec, maxlen, output, task, patience=5):
          super(Callback, self).__init__()
          self.best_result = -1.0
          self.best_round = 1
          self.wait = 0
          self.output = output
          self.patience = patience
          self.counter = 0
          self.maxlen = maxlen
          self.dev_files = dev_files
          self.word_word2vec = word_word2vec
          self.task = task
  
      
      def on_epoch_end(self, epoch, logs={}):
          self.counter += 1
          current = 0
  
          id_train, X_word_train, y_train = read_sentiment(self.dev_files, self.word_word2vec, self.task)
          X_word_train = sequence.pad_sequences(X_word_train, maxlen=self.maxlen, padding='post', truncating='post')
          #predict = self.model.predict([X_word_train, X_highlevel_train], batch_size=1024, verbose=1)
          predict = self.model.predict(X_word_train, batch_size=1024, verbose=1)
          current = score_deft_2017(predict, y_train, self.task)
              
          if self.best_result < current:
              self.best_result = current
              self.best_round = self.counter
              self.wait = 0
  
              json_string = self.model.to_json()
              open(self.output+".json", 'w').write(json_string)
              self.model.save_weights(self.output+".h5", overwrite=True)
  
  
          print "
  
  "
          print "Dev score 2017 : "+str(current)
          print "Best score 2017 : "+str(self.best_result)
          print "
  
  "
  
  
  
  class ConfusionMatrix(object):
  
      def __init__(self):
          self.h = {}
          self.total = 0
  
      def store(self, actual, truth):
          if actual not in self.h.keys():
              self.h[ actual ] = {"tp": 0, "tn": 0, "fp": 0, "fn": 0}
          if truth not in self.h.keys():
              self.h[ truth ] = {"tp": 0, "tn": 0, "fp": 0, "fn": 0}
  
          if actual == truth:
              self.h[actual]["tp"] += 1
          else:
              self.h[actual]["fp"] += 1
              self.h[truth]["fn"] += 1
              self.h[truth]["tn"] += 1
              self.total += 1
  
      def recall(self, name):
          t = self.h[name]["tp"] + self.h[name]["fn"]
      
          if t == 0:
              return 0
          return ( (float)(self.h[name]["tp"]) / (float)( t ) )
  
  
      def precision(self, name):
          t = self.h[name]["tp"] + self.h[name]["fp"]
          if t == 0:
              return 0
          return ( (float)(self.h[name]["tp"]) / (float)( t ) )
  
  
      def fscore(self, name):
          t = self.precision(name) + self.recall(name)
          if t == 0:
              return 0
          return (2 * self.precision(name) * self.recall(name) ) / (t )
  
      def score_semeval_2016(self):
          return ( self.fscore(0) + self.fscore(1) ) / 2
  
      def score_semeval_2017(self):
          return ( self.recall(0) + self.recall(1) + self.recall(2)  ) / 3
  
      def score_deft_2017(self, task):
          print self.h
  
          if task == "task1":
              print "negative : "+str(self.fscore(0))
              print "positive : "+str(self.fscore(1))
              print "objective : "+str(self.fscore(2))
              print "mixed : "+str(self.fscore(3))
              return (self.fscore(0) + self.fscore(1) + self.fscore(2) + self.fscore(3) ) / 4
  
          if task == "task3":
              print "negative : "+str(self.fscore(0))
              print "positive : "+str(self.fscore(1))
              print "objective : "+str(self.fscore(2))
              print "mixed : "+str(self.fscore(3))
              return (self.fscore(0) + self.fscore(1) + self.fscore(2) + self.fscore(3) ) / 4
  
          if task == "task2":
              print "figurative : "+str(self.fscore(0))
              print "nonfigurative : "+str(self.fscore(1))
              return (self.fscore(0) + self.fscore(1) ) / 2
  
  
  
      def info(self):
          print self.h
  
  
  def read_word2vec(embedding_file):
      ar = []
      dico = {}
      size = 0
      counter = 0
  
      with open(embedding_file) as f:
          for line in f:
              line = line.strip()
              line = line.split(" ")
              if len(line) > 3:
                  ar.append( map(float, line[1:] ) )
                  dico[  line[0] ] = counter
                  counter += 1
              if len(line) < 3:
                  size = int(line[1])
      
      ar = np.array(ar, dtype='float')
  
      return counter, size, dico, ar
  
  def read_sentiment_train(sentiment_file, word_word2vec, task):
      X_word = []
      Y = []
      Z = []
  
      Y_COUNTER = None
      if task == "task1":
          Y_COUNTER = [0.0]*4
      if task == "task2":
          Y_COUNTER = [0.0]*2
      if task == "task3":
          Y_COUNTER = [0.0]*4
  
      total = 0
  
      with open(sentiment_file) as f:
          for line in f:
              line = line.strip()
              line = line.split("\t")
  
              if task == "task1":
                  if line[1] == "negative":
                      Y_COUNTER[0] += 1
                  if line[1] == "positive":
                      Y_COUNTER[1] += 1
                  if line[1] == "objective":
                      Y_COUNTER[2] += 1
                  if line[1] == "mixed":
                      Y_COUNTER[3] += 1
                  total += 1
  
              if task == "task3":
                  if line[1] == "negative":
                      Y_COUNTER[0] += 1
                  if line[1] == "positive":
                      Y_COUNTER[1] += 1
                  if line[1] == "objective":
                      Y_COUNTER[2] += 1
                  if line[1] == "mixed":
                      Y_COUNTER[3] += 1
                  total += 1
  
              if task == "task2":
                  if line[1] == "figurative":
                      Y_COUNTER[0] += 1
                  if line[1] == "nonfigurative":
                      Y_COUNTER[1] += 1
                  total += 1
  
  
  
      print Y_COUNTER 
      hash_y_counter = None
      if task == "task1":
          hash_y_counter = {0: Y_COUNTER[0], 1: Y_COUNTER[1], 2: Y_COUNTER[2], 3: Y_COUNTER[3]}
      if task == "task3":
          hash_y_counter = {0: Y_COUNTER[0], 1: Y_COUNTER[1], 2: Y_COUNTER[2], 3: Y_COUNTER[3]}
      if task == "task2":
          hash_y_counter = {0: Y_COUNTER[0], 1: Y_COUNTER[1]}
      print hash_y_counter
      cw_y = create_class_weight(hash_y_counter, 0.5)
      print cw_y
  
  
  
      with open(sentiment_file) as f:
          for line in f:
              line = line.strip()
              line = line.split("\t")
  
              Z.append( line[0] )
  
              ar_y = None
              if task == "task1":
                  ar_y = [0]*4
  
                  if line[1] == "negative":
                      ar_y[0] = 1
                  if line[1] == "positive":
                      ar_y[1] = 1
                  if line[1] == "objective":
                      ar_y[2] = 1
                  if line[1] == "mixed":
                      ar_y[3] = 1
  
  
              if task == "task2":
                  ar_y = [0]*2
  
                  if line[1] == "figurative":
                      ar_y[0] = 1
                  if line[1] == "nonfigurative":
                      ar_y[1] = 1
  
  
              if task == "task3":
                  ar_y = [0]*4
  
                  if line[1] == "negative":
                      ar_y[0] = 1
                  if line[1] == "positive":
                      ar_y[1] = 1
                  if line[1] == "objective":
                      ar_y[2] = 1
                  if line[1] == "mixed":
                      ar_y[3] = 1
  
  
              Y.append( ar_y )
  
              tok = line[2].split(" ")
              word_ar = []
              for x in tok:
                  if x in word_word2vec:
                      word_ar.append( word_word2vec[ x ] )
              X_word.append( word_ar )
              
      X_word = np.array(X_word)
      Y = np.array(Y)
      Z = np.array(Z)
  
      return (Z, X_word, Y, cw_y)
  
  
  def read_sentiment_test(sentiment_file, word_word2vec):
      X_word = []
      Y = []
      Z = []
  
      with open(sentiment_file) as f:
          for line in f:
              line = line.strip()
              line = line.split("\t")
  
              Z.append( line[0] )
  
              ar_y = [0]
              Y.append( ar_y )
  
              tok = line[2].split(" ")
              word_ar = []
              for x in tok:
                  if x in word_word2vec:
                      word_ar.append( word_word2vec[ x ] )
              X_word.append( word_ar )
              
      X_word = np.array(X_word)
      Y = np.array(Y)
      Z = np.array(Z)
  
      return (Z, X_word, Y)
  
  
  
  
  def read_sentiment(sentiment_file, word_word2vec, task):
      X_word = []
      Y = []
      Z = []
  
      with open(sentiment_file) as f:
          for line in f:
              line = line.strip()
              line = line.split("\t")
  
              Z.append( line[0] )
  
              ar_y = None
              if task == "task1":
                  ar_y = [0]*4
  
                  if line[1] == "negative":
                      ar_y[0] = 1
                  if line[1] == "positive":
                      ar_y[1] = 1
                  if line[1] == "objective":
                      ar_y[2] = 1
                  if line[1] == "mixed":
                      ar_y[3] = 1
  
  
              if task == "task2":
                  ar_y = [0]*2
  
                  if line[1] == "figurative":
                      ar_y[0] = 1
                  if line[1] == "nonfigurative":
                      ar_y[1] = 1
  
  
              if task == "task3":
                  ar_y = [0]*4
  
                  if line[1] == "negative":
                      ar_y[0] = 1
                  if line[1] == "positive":
                      ar_y[1] = 1
                  if line[1] == "objective":
                      ar_y[2] = 1
                  if line[1] == "mixed":
                      ar_y[3] = 1
  
  
              Y.append( ar_y )
  
              tok = line[2].split(" ")
              word_ar = []
              for x in tok:
                  if x in word_word2vec:
                      word_ar.append( word_word2vec[ x ] )
              X_word.append( word_ar )
              
      X_word = np.array(X_word)
      Y = np.array(Y)
      Z = np.array(Z)
  
      return (Z, X_word, Y)
  
  
  
  maxlen = 150
  word_nb_feature_maps = 200
  hidden_size = 64
  
  word_embedding_file = sys.argv[1]
  test_file = sys.argv[2]
  model_file = sys.argv[3]
  
  
  model = model_from_json(open(model_file+".json").read())
  model.load_weights(model_file+".h5")
  
  
  word_vocab_size, word_embedding_size, word_dico, word_initialize_weight = read_word2vec(word_embedding_file)
  ID_train, X_word_train, Y_train = read_sentiment_test(test_file, word_dico)
  X_word_train = sequence.pad_sequences(X_word_train, maxlen=maxlen, padding='post', truncating='post')
  
  
  predict = model.predict(X_word_train, batch_size=2048, verbose=0)
  
  
  counter = 0
  for x in ID_train:
      print x+"\t"+" ".join(map(str, predict[counter]))
      counter += 1