Commit 5c7d5c33 by guanxing

guan-mermaid-modification

parent 53c41166
import numpy as np
import math
import json
from mermaid import preprocessing as pp
from mermaid import sessions
from mermaid import models
import json
import os
from tqdm import tqdm_notebook
import gensim
from mermaid.embeddings import Embedding
from mermaid import preprocessing as pp
from mermaid.preprocessing import WordIndex
from mermaid import plotting
from mermaid import models
import numpy as np
import mermaid
from mermaid.factory import Factory
from mermaid import sessions
import keras
sentence_set = []
with open('/home/NewPartion/e2e-coref/dev.english.jsonlines','r') as file:
for f in file.readlines():
f = json.loads(f)
sentence_set.append(f['sentences'])
print(len(sentence_set))
antecedent_scores = np.load('/home/NewPartion/e2e-coref/antecedents.npz', encoding='bytes')['arr_0']
mention_starts = np.load('/home/NewPartion/e2e-coref/mention_starts.npz', encoding='bytes')['arr_0']
mention_ends = np.load('/home/NewPartion/e2e-coref/mention_ends.npz', encoding='bytes')['arr_0']
new_sentence_set = []
for item in sentence_set:
new_item = []
for a in item:
for b in a:
new_item.append(b)
new_sentence_set.append(new_item)
print(len(new_sentence_set[0]))
i=0
count=0
for index in range(len(mention_starts[i])):
first_mention = new_sentence_set[i][mention_starts[i][index]:mention_ends[i][index]]
for index2 in range(index + 1, len(mention_ends[i])):
if mention_starts[i][index2] < mention_ends[i][index]:
continue
second_mention = new_sentence_set[i][mention_starts[i][index2]:mention_ends[i][index2]]
split_index = math.ceil((mention_starts[i][index2] - mention_ends[i][index]) / 2)
splitted_sentence1 = ' '.join(new_sentence_set[i][:split_index])
splitted_sentence2 = ' '.join(new_sentence_set[i][split_index:])
count+=1
if count == 10000:
break
print(antecedent_scores[i].shape)
print(len(mention_ends[i]))
print(len(mention_starts[i]))
print(count)
class LoadedWordVecEmbedding(Embedding):
def __init__(self, word_vector_file_path, dim):
super().__init__()
self._w2v = gensim.models.KeyedVectors.load_word2vec_format(word_vector_file_path)
self._word_index = WordIndex({
token: self._w2v.vocab[token].index + 2 for token in self._w2v.vocab
})
self._dim = dim
def make_layer(self):
embedding_matrix = np.zeros((self.vocab_size, self._dim))
for key, index in self._word_index.items():
embedding_matrix[index] = self._w2v[key]
return keras.layers.Embedding(
self.vocab_size,
self._dim,
weights=[embedding_matrix],
trainable=self._trainable
)
@property
def vocab_size(self):
return len(self._word_index) + 2
@property
def word_index(self):
return self._word_index
@property
def index_word(self):
return self._word_index.rev()
def __getitem__(self, item):
return self._w2v[item]
sess = sessions.DQTrainingSession()
sess.setup.embedding('pre-trained')
sess.setup.embedding('loadedwordvecembedding-legruwxj6pwz')
sess.setup.model('convknrm-z3kmin68al3z')
sess.setup.preprocessor('word.30','word.30')
sess.compile()
to_predict_sentence = {'d':splitted_sentence1,'q':splitted_sentence2}
predict_stream = pp.Stream([pp.Entry(**to_predict_sentence)])
sess.build_stream_tokens(predict_stream)
sess.build_stream_sequences(predict_stream)
sess.model.predict(sess.X(predict_stream))
\ No newline at end of file
import operator
import random
import math
import json
import threading
import numpy as np
import tensorflow as tf
import util
import coref_ops
import conll
import metrics
from tensorflow import Session as sess
from coref_model import CorefModel
class CorefMermaidModel(CorefModel):
def matrix_combination(self, matrix1, matrix2, ratio):
"""
Calculate the matrix from matrix1 and matrix2 combination with ratio . matrix1 and matrix2 should have same shape.
:param matrix1:
:param matrix2:
:param ratio: combination ratio of matrix1 : matrix2
:return: combined matrix
"""
assert matrix1.shape == matrix2.shape
ratio=5
print("Using combination ratio: {}".format(ratio))
#combined_matrix = (matrix1 * ratio/(1+ratio) ) + (matrix2 * 1/(1+ratio) )
#combined_matrix = matrix1 + matrix2 * ratio
combined_matrix = matrix2
return np.array(combined_matrix)
def sub_certain_value_from_matrix(self, matrix, value):
print('Subing value {}'.format(value))
new_matrix = matrix
for i, item1 in enumerate(matrix):
for j, item2 in enumerate(item1):
if j > 0:
item2 = item2 - value
new_matrix[i, j] = item2
return np.array(new_matrix)
def evaluate(self, session, sub_value, official_stdout=False):
self.load_eval_data()
def _k_to_tag(k):
if k == -3:
return "oracle"
elif k == -2:
return "actual"
elif k == -1:
return "exact"
elif k == 0:
return "threshold"
else:
return "{}%".format(k)
mention_evaluators = {k: util.RetrievalEvaluator() for k in [-3, -2, -1, 0, 10, 15, 20, 25, 30, 40, 50]}
coref_predictions = {}
coref_evaluator = metrics.CorefEvaluator()
antecedent_scores_set = []
mention_starts_set = []
mention_ends_set = []
#file1 = file('correcting_matrix_loss0.514.npz','rb')
#file1 = file('origin_correcting_matrix.npz','rb')
#file1 = file('corrected_matrix.npz','rb')
#file1 = file('corrected_matrix_halfbyhalf_loss0.514.npz','rb')
#file1 = file('corrected_matrix_halfbyhalf_epoch0180wan.npz','rb')
#file1 = file('no_streched_matrix_epoch0180wan','rb')
#file1 = file('filtered_by_confidence_correcting_matrix_0epoch180wan.npz', 'rb')
#file1 = file('no_strech_filtered_matrix_-0.2_0epoch180wan.npz','rb')
#file1 = file('l2regulazation_matrix_0epoch180wan.npz','rb')
#file1 = file('filtered_by_confidence0.2_epoch261800wan.npz','rb')
#file1 = file('l2regularzation_correcting_matrix_epoch26_1800wan','rb')
#file1 = file('filtered_by_confidence_correcting_matrix_epoch0_313wan_similar_texts.npz', 'rb')
#file1 = file('test_correcting_matrix_performence_no_strech.npz', 'rb')
#file1 = file('test_correcting_matrix_performence_strech.npz','rb')
#file1 = file('correcting_matrix_long_training_data_model.npz','rb')
#file1 = file('correcting_matrix_long_training_data_model_no_-inf.npz', 'rb')
#file1 = file('perfect_correcting_matrix_long_training_data_model.npz', 'rb')
#file1 = file('1500wan_epoch16_model.npz', 'rb')
#file1 = file('340wan_replace_upper_word_without_the.npz', 'rb')
#file1 = file('340wan_replace_upper_word_without_the_filtered_by_0.3.npz','rb')
file1 = file('sub_1_antecedent_scores', 'rb')
correcting_matrix = np.load(file1)['arr_0']
print('using correcting file: ',file1)
for example_num, (tensorized_example, example) in enumerate(self.eval_data):
_, _, _, _, _, _, gold_starts, gold_ends, _ = tensorized_example
feed_dict = {i: t for i, t in zip(self.input_tensors, tensorized_example)}
candidate_starts, candidate_ends, mention_scores, mention_starts, mention_ends, antecedents, antecedent_scores = session.run(
self.predictions, feed_dict=feed_dict)
# # Generated Random Antecedent-scores
# size = antecedent_scores.shape
# antecedent_scores = np.zeros((size[0],size[1]))
# for index in range(1, size[0]):
# for index2 in range(0, min(index,size[1])-1):
# antecedent_scores[index, index2 + 1] = random.randint(-20, 20)
#
# antecedent_scores_set.append(antecedent_scores)
# mention_starts_set.append(mention_starts)
# mention_ends_set.append(mention_ends)
correcting_matrix_one = correcting_matrix[example_num]
wow = antecedent_scores.shape
antecedent_scores = self.matrix_combination(antecedent_scores, correcting_matrix_one, self.config['combination_ratio'])
#antecedent_scores = correcting_matrix_one
antecedent_scores = self.sub_certain_value_from_matrix(antecedent_scores, sub_value)
assert antecedent_scores.shape == wow
self.evaluate_mentions(candidate_starts, candidate_ends, mention_starts, mention_ends, mention_scores,
gold_starts, gold_ends, example, mention_evaluators)
predicted_antecedents = self.get_predicted_antecedents(antecedents, antecedent_scores)
coref_predictions[example["doc_key"]] = self.evaluate_coref(mention_starts, mention_ends,
predicted_antecedents, example["clusters"],
coref_evaluator)
if example_num % 10 == 0:
print ("Evaluated {}/{} examples.".format(example_num + 1, len(self.eval_data)))
#file1 = file('antecedents.npz','wb')
#file2 = file('mention_starts.npz','wb')
#file3 = file('mention_ends.npz','wb')
#np.savez(file1, antecedent_scores_set)
#np.savez(file2, mention_starts_set)
#np.savez(file3, mention_ends_set)
summary_dict = {}
for k, evaluator in sorted(mention_evaluators.items(), key=operator.itemgetter(0)):
tags = ["{} @ {}".format(t, _k_to_tag(k)) for t in ("R", "P", "F")]
results_to_print = []
for t, v in zip(tags, evaluator.metrics()):
results_to_print.append("{:<10}: {:.2f}".format(t, v))
summary_dict[t] = v
print (", ".join(results_to_print))
conll_results = conll.evaluate_conll(self.config["conll_eval_path"], coref_predictions, official_stdout)
average_f1 = sum(results["f"] for results in conll_results.values()) / len(conll_results)
summary_dict["Average F1 (conll)"] = average_f1
print "Average F1 (conll): {:.2f}%".format(average_f1)
p, r, f = coref_evaluator.get_prf()
muc_p, muc_r, muc_f = coref_evaluator.get_muc_prf()
bcubed_p, bcubed_r, bcubed_f = coref_evaluator.get_b_cubed_prf()
ceaf_p, ceaf_r, ceaf_f = coref_evaluator.get_ceaf_prf()
summary_dict["Average F1 (py)"] = f[0]
print "Average F1 (py): {:.2f}%".format(f[0] * 100)
summary_dict["Average precision (py)"] = p[0]
print "Average precision (py): {:.2f}%".format(p[0] * 100)
summary_dict["Average recall (py)"] = r[0]
print "Average recall (py): {:.2f}%".format(r[0] * 100)
print "MUC F1 : {:.2f}%".format(f[1][0] * 100)
print "MUC Precision : {:.2f}%".format(p[1][0] * 100)
print "MUC Recall : {:.2f}%".format(r[1][0] * 100)
print "B_CUBED F1 : {:.2f}%".format(f[1][1] * 100)
print "B_CUBED Precision : {:.2f}%".format(p[1][1] * 100)
print "B_CUBED Recall : {:.2f}%".format(r[1][1] * 100)
print "CEAF F1 : {:.2f}%".format(f[1][2] * 100)
print "CEAF Precision : {:.2f}%".format(p[1][2] * 100)
print "CEAF Recall : {:.2f}%".format(r[1][2] * 100)
return util.make_summary(summary_dict), average_f1, p[0]*100, r[0]*100
...@@ -11,483 +11,554 @@ import coref_ops ...@@ -11,483 +11,554 @@ import coref_ops
import conll import conll
import metrics import metrics
class CorefModel(object): class CorefModel(object):
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
self.embedding_info = [(emb["size"], emb["lowercase"]) for emb in config["embeddings"]] self.embedding_info = [(emb["size"], emb["lowercase"]) for emb in config["embeddings"]]
self.embedding_size = sum(size for size, _ in self.embedding_info) self.embedding_size = sum(size for size, _ in self.embedding_info)
self.char_embedding_size = config["char_embedding_size"] self.char_embedding_size = config["char_embedding_size"]
self.char_dict = util.load_char_dict(config["char_vocab_path"]) self.char_dict = util.load_char_dict(config["char_vocab_path"])
self.embedding_dicts = [util.load_embedding_dict(emb["path"], emb["size"], emb["format"]) for emb in config["embeddings"]] self.embedding_dicts = [util.load_embedding_dict(emb["path"], emb["size"], emb["format"]) for emb in
self.max_mention_width = config["max_mention_width"] config["embeddings"]]
self.genres = { g:i for i,g in enumerate(config["genres"]) } self.max_mention_width = config["max_mention_width"]
self.eval_data = None # Load eval data lazily. self.genres = {g: i for i, g in enumerate(config["genres"])}
self.eval_data = None # Load eval data lazily.
input_props = []
input_props.append((tf.float32, [None, None, self.embedding_size])) # Text embeddings. input_props = []
input_props.append((tf.int32, [None, None, None])) # Character indices. input_props.append((tf.float32, [None, None, self.embedding_size])) # Text embeddings.
input_props.append((tf.int32, [None])) # Text lengths. input_props.append((tf.int32, [None, None, None])) # Character indices.
input_props.append((tf.int32, [None])) # Speaker IDs. input_props.append((tf.int32, [None])) # Text lengths.
input_props.append((tf.int32, [])) # Genre. input_props.append((tf.int32, [None])) # Speaker IDs.
input_props.append((tf.bool, [])) # Is training. input_props.append((tf.int32, [])) # Genre.
input_props.append((tf.int32, [None])) # Gold starts. input_props.append((tf.bool, [])) # Is training.
input_props.append((tf.int32, [None])) # Gold ends. input_props.append((tf.int32, [None])) # Gold starts.
input_props.append((tf.int32, [None])) # Cluster ids. input_props.append((tf.int32, [None])) # Gold ends.
input_props.append((tf.int32, [None])) # Cluster ids.
self.queue_input_tensors = [tf.placeholder(dtype, shape) for dtype, shape in input_props]
dtypes, shapes = zip(*input_props) self.queue_input_tensors = [tf.placeholder(dtype, shape) for dtype, shape in input_props]
queue = tf.PaddingFIFOQueue(capacity=10, dtypes=dtypes, shapes=shapes) dtypes, shapes = zip(*input_props)
self.enqueue_op = queue.enqueue(self.queue_input_tensors) queue = tf.PaddingFIFOQueue(capacity=10, dtypes=dtypes, shapes=shapes)
self.input_tensors = queue.dequeue() self.enqueue_op = queue.enqueue(self.queue_input_tensors)
self.input_tensors = queue.dequeue()
self.predictions, self.loss = self.get_predictions_and_loss(*self.input_tensors)
self.global_step = tf.Variable(0, name="global_step", trainable=False) self.predictions, self.loss = self.get_predictions_and_loss(*self.input_tensors)
self.reset_global_step = tf.assign(self.global_step, 0) self.global_step = tf.Variable(0, name="global_step", trainable=False)
learning_rate = tf.train.exponential_decay(self.config["learning_rate"], self.global_step, self.reset_global_step = tf.assign(self.global_step, 0)
self.config["decay_frequency"], self.config["decay_rate"], staircase=True) learning_rate = tf.train.exponential_decay(self.config["learning_rate"], self.global_step,
trainable_params = tf.trainable_variables() self.config["decay_frequency"], self.config["decay_rate"],
gradients = tf.gradients(self.loss, trainable_params) staircase=True)
gradients, _ = tf.clip_by_global_norm(gradients, self.config["max_gradient_norm"]) trainable_params = tf.trainable_variables()
optimizers = { gradients = tf.gradients(self.loss, trainable_params)
"adam" : tf.train.AdamOptimizer, gradients, _ = tf.clip_by_global_norm(gradients, self.config["max_gradient_norm"])
"sgd" : tf.train.GradientDescentOptimizer optimizers = {
} "adam": tf.train.AdamOptimizer,
optimizer = optimizers[self.config["optimizer"]](learning_rate) "sgd" : tf.train.GradientDescentOptimizer
self.train_op = optimizer.apply_gradients(zip(gradients, trainable_params), global_step=self.global_step) }
optimizer = optimizers[self.config["optimizer"]](learning_rate)
def start_enqueue_thread(self, session): self.train_op = optimizer.apply_gradients(zip(gradients, trainable_params), global_step=self.global_step)
with open(self.config["train_path"]) as f:
train_examples = [json.loads(jsonline) for jsonline in f.readlines()] def start_enqueue_thread(self, session):
def _enqueue_loop(): with open(self.config["train_path"]) as f:
while True: train_examples = [json.loads(jsonline) for jsonline in f.readlines()]
random.shuffle(train_examples)
for example in train_examples: def _enqueue_loop():
tensorized_example = self.tensorize_example(example, is_training=True) while True:
feed_dict = dict(zip(self.queue_input_tensors, tensorized_example)) random.shuffle(train_examples)
session.run(self.enqueue_op, feed_dict=feed_dict) for example in train_examples:
enqueue_thread = threading.Thread(target=_enqueue_loop) tensorized_example = self.tensorize_example(example, is_training=True)
enqueue_thread.daemon = True feed_dict = dict(zip(self.queue_input_tensors, tensorized_example))
enqueue_thread.start() session.run(self.enqueue_op, feed_dict=feed_dict)
def tensorize_mentions(self, mentions): enqueue_thread = threading.Thread(target=_enqueue_loop)
if len(mentions) > 0: enqueue_thread.daemon = True
starts, ends = zip(*mentions) enqueue_thread.start()
else:
starts, ends = [], [] def tensorize_mentions(self, mentions):
return np.array(starts), np.array(ends) if len(mentions) > 0:
starts, ends = zip(*mentions)
def tensorize_example(self, example, is_training, oov_counts=None): else:
clusters = example["clusters"] starts, ends = [], []
return np.array(starts), np.array(ends)
gold_mentions = sorted(tuple(m) for m in util.flatten(clusters))
gold_mention_map = {m:i for i,m in enumerate(gold_mentions)} def tensorize_example(self, example, is_training, oov_counts=None):
cluster_ids = np.zeros(len(gold_mentions)) clusters = example["clusters"]
for cluster_id, cluster in enumerate(clusters):
for mention in cluster: gold_mentions = sorted(tuple(m) for m in util.flatten(clusters))
cluster_ids[gold_mention_map[tuple(mention)]] = cluster_id gold_mention_map = {m: i for i, m in enumerate(gold_mentions)}
cluster_ids = np.zeros(len(gold_mentions))
sentences = example["sentences"] for cluster_id, cluster in enumerate(clusters):
num_words = sum(len(s) for s in sentences) for mention in cluster:
speakers = util.flatten(example["speakers"]) cluster_ids[gold_mention_map[tuple(mention)]] = cluster_id
assert num_words == len(speakers) sentences = example["sentences"]
num_words = sum(len(s) for s in sentences)
max_sentence_length = max(len(s) for s in sentences) speakers = util.flatten(example["speakers"])
max_word_length = max(max(max(len(w) for w in s) for s in sentences), max(self.config["filter_widths"]))
word_emb = np.zeros([len(sentences), max_sentence_length, self.embedding_size]) assert num_words == len(speakers)
char_index = np.zeros([len(sentences), max_sentence_length, max_word_length])
text_len = np.array([len(s) for s in sentences]) max_sentence_length = max(len(s) for s in sentences)
for i, sentence in enumerate(sentences): max_word_length = max(max(max(len(w) for w in s) for s in sentences), max(self.config["filter_widths"]))
for j, word in enumerate(sentence): word_emb = np.zeros([len(sentences), max_sentence_length, self.embedding_size])
current_dim = 0 char_index = np.zeros([len(sentences), max_sentence_length, max_word_length])
for k, (d, (s,l)) in enumerate(zip(self.embedding_dicts, self.embedding_info)): text_len = np.array([len(s) for s in sentences])
if l: for i, sentence in enumerate(sentences):
current_word = word.lower() for j, word in enumerate(sentence):
else: current_dim = 0
current_word = word for k, (d, (s, l)) in enumerate(zip(self.embedding_dicts, self.embedding_info)):
if oov_counts is not None and current_word not in d: if l:
oov_counts[k] += 1 current_word = word.lower()
word_emb[i, j, current_dim:current_dim + s] = util.normalize(d[current_word]) else:
current_dim += s current_word = word
char_index[i, j, :len(word)] = [self.char_dict[c] for c in word] if oov_counts is not None and current_word not in d:
oov_counts[k] += 1
speaker_dict = { s:i for i,s in enumerate(set(speakers)) } word_emb[i, j, current_dim:current_dim + s] = util.normalize(d[current_word])
speaker_ids = np.array([speaker_dict[s] for s in speakers]) current_dim += s
char_index[i, j, :len(word)] = [self.char_dict[c] for c in word]
doc_key = example["doc_key"]
genre = self.genres[doc_key[:2]] speaker_dict = {s: i for i, s in enumerate(set(speakers))}
speaker_ids = np.array([speaker_dict[s] for s in speakers])
gold_starts, gold_ends = self.tensorize_mentions(gold_mentions)
doc_key = example["doc_key"]
if is_training and len(sentences) > self.config["max_training_sentences"]: genre = self.genres[doc_key[:2]]
return self.truncate_example(word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids)
else: gold_starts, gold_ends = self.tensorize_mentions(gold_mentions)
return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids
if is_training and len(sentences) > self.config["max_training_sentences"]:
def truncate_example(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids): return self.truncate_example(word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts,
max_training_sentences = self.config["max_training_sentences"] gold_ends, cluster_ids)
num_sentences = word_emb.shape[0] else:
assert num_sentences > max_training_sentences return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids
sentence_offset = random.randint(0, num_sentences - max_training_sentences) def truncate_example(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends,
word_offset = text_len[:sentence_offset].sum() cluster_ids):
num_words = text_len[sentence_offset:sentence_offset + max_training_sentences].sum() max_training_sentences = self.config["max_training_sentences"]
word_emb = word_emb[sentence_offset:sentence_offset + max_training_sentences,:,:] num_sentences = word_emb.shape[0]
char_index = char_index[sentence_offset:sentence_offset + max_training_sentences,:,:] assert num_sentences > max_training_sentences
text_len = text_len[sentence_offset:sentence_offset + max_training_sentences]
sentence_offset = random.randint(0, num_sentences - max_training_sentences)
speaker_ids = speaker_ids[word_offset: word_offset + num_words] word_offset = text_len[:sentence_offset].sum()
gold_spans = np.logical_and(gold_ends >= word_offset, gold_starts < word_offset + num_words) num_words = text_len[sentence_offset:sentence_offset + max_training_sentences].sum()
gold_starts = gold_starts[gold_spans] - word_offset word_emb = word_emb[sentence_offset:sentence_offset + max_training_sentences, :, :]
gold_ends = gold_ends[gold_spans] - word_offset char_index = char_index[sentence_offset:sentence_offset + max_training_sentences, :, :]
cluster_ids = cluster_ids[gold_spans] text_len = text_len[sentence_offset:sentence_offset + max_training_sentences]
return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids speaker_ids = speaker_ids[word_offset: word_offset + num_words]
gold_spans = np.logical_and(gold_ends >= word_offset, gold_starts < word_offset + num_words)
def get_predictions_and_loss(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids): gold_starts = gold_starts[gold_spans] - word_offset
self.dropout = 1 - (tf.to_float(is_training) * self.config["dropout_rate"]) gold_ends = gold_ends[gold_spans] - word_offset
self.lexical_dropout = 1 - (tf.to_float(is_training) * self.config["lexical_dropout_rate"]) cluster_ids = cluster_ids[gold_spans]
num_sentences = tf.shape(word_emb)[0] return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids
max_sentence_length = tf.shape(word_emb)[1]
def get_predictions_and_loss(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts,
text_emb_list = [word_emb] gold_ends, cluster_ids):
self.dropout = 1 - (tf.to_float(is_training) * self.config["dropout_rate"])
if self.config["char_embedding_size"] > 0: self.lexical_dropout = 1 - (tf.to_float(is_training) * self.config["lexical_dropout_rate"])
char_emb = tf.gather(tf.get_variable("char_embeddings", [len(self.char_dict), self.config["char_embedding_size"]]), char_index) # [num_sentences, max_sentence_length, max_word_length, emb]
flattened_char_emb = tf.reshape(char_emb, [num_sentences * max_sentence_length, util.shape(char_emb, 2), util.shape(char_emb, 3)]) # [num_sentences * max_sentence_length, max_word_length, emb] num_sentences = tf.shape(word_emb)[0]
flattened_aggregated_char_emb = util.cnn(flattened_char_emb, self.config["filter_widths"], self.config["filter_size"]) # [num_sentences * max_sentence_length, emb] max_sentence_length = tf.shape(word_emb)[1]
aggregated_char_emb = tf.reshape(flattened_aggregated_char_emb, [num_sentences, max_sentence_length, util.shape(flattened_aggregated_char_emb, 1)]) # [num_sentences, max_sentence_length, emb]
text_emb_list.append(aggregated_char_emb) text_emb_list = [word_emb]
text_emb = tf.concat(text_emb_list, 2) if self.config["char_embedding_size"] > 0:
text_emb = tf.nn.dropout(text_emb, self.lexical_dropout) char_emb = tf.gather(
tf.get_variable("char_embeddings", [len(self.char_dict), self.config["char_embedding_size"]]),
text_len_mask = tf.sequence_mask(text_len, maxlen=max_sentence_length) char_index) # [num_sentences, max_sentence_length, max_word_length, emb]
text_len_mask = tf.reshape(text_len_mask, [num_sentences * max_sentence_length]) flattened_char_emb = tf.reshape(char_emb, [num_sentences * max_sentence_length, util.shape(char_emb, 2),
util.shape(char_emb,
text_outputs = self.encode_sentences(text_emb, text_len, text_len_mask) 3)]) # [num_sentences * max_sentence_length, max_word_length, emb]
text_outputs = tf.nn.dropout(text_outputs, self.dropout) flattened_aggregated_char_emb = util.cnn(flattened_char_emb, self.config["filter_widths"], self.config[
"filter_size"]) # [num_sentences * max_sentence_length, emb]
genre_emb = tf.gather(tf.get_variable("genre_embeddings", [len(self.genres), self.config["feature_size"]]), genre) # [emb] aggregated_char_emb = tf.reshape(flattened_aggregated_char_emb, [num_sentences, max_sentence_length,
util.shape(flattened_aggregated_char_emb,
sentence_indices = tf.tile(tf.expand_dims(tf.range(num_sentences), 1), [1, max_sentence_length]) # [num_sentences, max_sentence_length] 1)]) # [num_sentences, max_sentence_length, emb]
flattened_sentence_indices = self.flatten_emb_by_sentence(sentence_indices, text_len_mask) # [num_words] text_emb_list.append(aggregated_char_emb)
flattened_text_emb = self.flatten_emb_by_sentence(text_emb, text_len_mask) # [num_words]
text_emb = tf.concat(text_emb_list, 2)
candidate_starts, candidate_ends = coref_ops.spans( text_emb = tf.nn.dropout(text_emb, self.lexical_dropout)
sentence_indices=flattened_sentence_indices,
max_width=self.max_mention_width) text_len_mask = tf.sequence_mask(text_len, maxlen=max_sentence_length)
candidate_starts.set_shape([None]) text_len_mask = tf.reshape(text_len_mask, [num_sentences * max_sentence_length])
candidate_ends.set_shape([None])
text_outputs = self.encode_sentences(text_emb, text_len, text_len_mask)
candidate_mention_emb = self.get_mention_emb(flattened_text_emb, text_outputs, candidate_starts, candidate_ends) # [num_candidates, emb] text_outputs = tf.nn.dropout(text_outputs, self.dropout)
candidate_mention_scores = self.get_mention_scores(candidate_mention_emb) # [num_mentions, 1]
candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [num_mentions] genre_emb = tf.gather(tf.get_variable("genre_embeddings", [len(self.genres), self.config["feature_size"]]),
genre) # [emb]
k = tf.to_int32(tf.floor(tf.to_float(tf.shape(text_outputs)[0]) * self.config["mention_ratio"]))
predicted_mention_indices = coref_ops.extract_mentions(candidate_mention_scores, candidate_starts, candidate_ends, k) # ([k], [k]) sentence_indices = tf.tile(tf.expand_dims(tf.range(num_sentences), 1),
predicted_mention_indices.set_shape([None]) [1, max_sentence_length]) # [num_sentences, max_sentence_length]
flattened_sentence_indices = self.flatten_emb_by_sentence(sentence_indices, text_len_mask) # [num_words]
mention_starts = tf.gather(candidate_starts, predicted_mention_indices) # [num_mentions] flattened_text_emb = self.flatten_emb_by_sentence(text_emb, text_len_mask) # [num_words]
mention_ends = tf.gather(candidate_ends, predicted_mention_indices) # [num_mentions]
mention_emb = tf.gather(candidate_mention_emb, predicted_mention_indices) # [num_mentions, emb] candidate_starts, candidate_ends = coref_ops.spans(
mention_scores = tf.gather(candidate_mention_scores, predicted_mention_indices) # [num_mentions] sentence_indices=flattened_sentence_indices,
max_width=self.max_mention_width)
mention_start_emb = tf.gather(text_outputs, mention_starts) # [num_mentions, emb] candidate_starts.set_shape([None])
mention_end_emb = tf.gather(text_outputs, mention_ends) # [num_mentions, emb] candidate_ends.set_shape([None])
mention_speaker_ids = tf.gather(speaker_ids, mention_starts) # [num_mentions]
candidate_mention_emb = self.get_mention_emb(flattened_text_emb, text_outputs, candidate_starts,
max_antecedents = self.config["max_antecedents"] candidate_ends) # [num_candidates, emb]
antecedents, antecedent_labels, antecedents_len = coref_ops.antecedents(mention_starts, mention_ends, gold_starts, gold_ends, cluster_ids, max_antecedents) # ([num_mentions, max_ant], [num_mentions, max_ant + 1], [num_mentions] candidate_mention_scores = self.get_mention_scores(candidate_mention_emb) # [num_mentions, 1]
antecedents.set_shape([None, None]) candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [num_mentions]
antecedent_labels.set_shape([None, None])
antecedents_len.set_shape([None]) k = tf.to_int32(tf.floor(tf.to_float(tf.shape(text_outputs)[0]) * self.config["mention_ratio"]))
predicted_mention_indices = coref_ops.extract_mentions(candidate_mention_scores, candidate_starts,
antecedent_scores = self.get_antecedent_scores(mention_emb, mention_scores, antecedents, antecedents_len, mention_starts, mention_ends, mention_speaker_ids, genre_emb) # [num_mentions, max_ant + 1] candidate_ends, k) # ([k], [k])
predicted_mention_indices.set_shape([None])
loss = self.softmax_loss(antecedent_scores, antecedent_labels) # [num_mentions]
loss = tf.reduce_sum(loss) # [] mention_starts = tf.gather(candidate_starts, predicted_mention_indices) # [num_mentions]
mention_ends = tf.gather(candidate_ends, predicted_mention_indices) # [num_mentions]
return [candidate_starts, candidate_ends, candidate_mention_scores, mention_starts, mention_ends, antecedents, antecedent_scores], loss mention_emb = tf.gather(candidate_mention_emb, predicted_mention_indices) # [num_mentions, emb]
mention_scores = tf.gather(candidate_mention_scores, predicted_mention_indices) # [num_mentions]
def get_mention_emb(self, text_emb, text_outputs, mention_starts, mention_ends):
mention_emb_list = [] print('mention scores is: ',mention_scores)
mention_start_emb = tf.gather(text_outputs, mention_starts) # [num_mentions, emb]
mention_start_emb = tf.gather(text_outputs, mention_starts) # [num_mentions, emb] mention_end_emb = tf.gather(text_outputs, mention_ends) # [num_mentions, emb]
mention_emb_list.append(mention_start_emb) mention_speaker_ids = tf.gather(speaker_ids, mention_starts) # [num_mentions]
mention_end_emb = tf.gather(text_outputs, mention_ends) # [num_mentions, emb] max_antecedents = self.config["max_antecedents"]
mention_emb_list.append(mention_end_emb) antecedents, antecedent_labels, antecedents_len = coref_ops.antecedents(mention_starts, mention_ends,
gold_starts, gold_ends, cluster_ids,
mention_width = 1 + mention_ends - mention_starts # [num_mentions] max_antecedents) # ([num_mentions, max_ant], [num_mentions, max_ant + 1], [num_mentions]
if self.config["use_features"]: antecedents.set_shape([None, None])
mention_width_index = mention_width - 1 # [num_mentions] antecedent_labels.set_shape([None, None])
mention_width_emb = tf.gather(tf.get_variable("mention_width_embeddings", [self.config["max_mention_width"], self.config["feature_size"]]), mention_width_index) # [num_mentions, emb] antecedents_len.set_shape([None])
mention_width_emb = tf.nn.dropout(mention_width_emb, self.dropout)
mention_emb_list.append(mention_width_emb) antecedent_scores = self.get_antecedent_scores(mention_emb, mention_scores, antecedents, antecedents_len,
mention_starts, mention_ends, mention_speaker_ids,
if self.config["model_heads"]: genre_emb) # [num_mentions, max_ant + 1]
mention_indices = tf.expand_dims(tf.range(self.config["max_mention_width"]), 0) + tf.expand_dims(mention_starts, 1) # [num_mentions, max_mention_width]
mention_indices = tf.minimum(util.shape(text_outputs, 0) - 1, mention_indices) # [num_mentions, max_mention_width] loss = self.softmax_loss(antecedent_scores, antecedent_labels) # [num_mentions]
mention_text_emb = tf.gather(text_emb, mention_indices) # [num_mentions, max_mention_width, emb] loss = tf.reduce_sum(loss) # []
self.head_scores = util.projection(text_outputs, 1) # [num_words, 1]
mention_head_scores = tf.gather(self.head_scores, mention_indices) # [num_mentions, max_mention_width, 1] return [candidate_starts, candidate_ends, candidate_mention_scores, mention_starts, mention_ends, antecedents,
mention_mask = tf.expand_dims(tf.sequence_mask(mention_width, self.config["max_mention_width"], dtype=tf.float32), 2) # [num_mentions, max_mention_width, 1] antecedent_scores], loss
mention_attention = tf.nn.softmax(mention_head_scores + tf.log(mention_mask), dim=1) # [num_mentions, max_mention_width, 1]
mention_head_emb = tf.reduce_sum(mention_attention * mention_text_emb, 1) # [num_mentions, emb] def get_mention_emb(self, text_emb, text_outputs, mention_starts, mention_ends):
mention_emb_list.append(mention_head_emb) mention_emb_list = []
mention_emb = tf.concat(mention_emb_list, 1) # [num_mentions, emb] mention_start_emb = tf.gather(text_outputs, mention_starts) # [num_mentions, emb]
return mention_emb mention_emb_list.append(mention_start_emb)
def get_mention_scores(self, mention_emb): mention_end_emb = tf.gather(text_outputs, mention_ends) # [num_mentions, emb]
with tf.variable_scope("mention_scores"): mention_emb_list.append(mention_end_emb)
return util.ffnn(mention_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [num_mentions, 1]
mention_width = 1 + mention_ends - mention_starts # [num_mentions]
def softmax_loss(self, antecedent_scores, antecedent_labels): if self.config["use_features"]:
gold_scores = antecedent_scores + tf.log(tf.to_float(antecedent_labels)) # [num_mentions, max_ant + 1] mention_width_index = mention_width - 1 # [num_mentions]
marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [num_mentions] mention_width_emb = tf.gather(tf.get_variable("mention_width_embeddings", [self.config["max_mention_width"],
log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [num_mentions] self.config["feature_size"]]),
return log_norm - marginalized_gold_scores # [num_mentions] mention_width_index) # [num_mentions, emb]
mention_width_emb = tf.nn.dropout(mention_width_emb, self.dropout)
def get_antecedent_scores(self, mention_emb, mention_scores, antecedents, antecedents_len, mention_starts, mention_ends, mention_speaker_ids, genre_emb): mention_emb_list.append(mention_width_emb)
num_mentions = util.shape(mention_emb, 0)
max_antecedents = util.shape(antecedents, 1) if self.config["model_heads"]:
mention_indices = tf.expand_dims(tf.range(self.config["max_mention_width"]), 0) + tf.expand_dims(
feature_emb_list = [] mention_starts, 1) # [num_mentions, max_mention_width]
mention_indices = tf.minimum(util.shape(text_outputs, 0) - 1,
if self.config["use_metadata"]: mention_indices) # [num_mentions, max_mention_width]
antecedent_speaker_ids = tf.gather(mention_speaker_ids, antecedents) # [num_mentions, max_ant] mention_text_emb = tf.gather(text_emb, mention_indices) # [num_mentions, max_mention_width, emb]
same_speaker = tf.equal(tf.expand_dims(mention_speaker_ids, 1), antecedent_speaker_ids) # [num_mentions, max_ant] self.head_scores = util.projection(text_outputs, 1) # [num_words, 1]
speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]), tf.to_int32(same_speaker)) # [num_mentions, max_ant, emb] mention_head_scores = tf.gather(self.head_scores, mention_indices) # [num_mentions, max_mention_width, 1]
feature_emb_list.append(speaker_pair_emb) mention_mask = tf.expand_dims(
tf.sequence_mask(mention_width, self.config["max_mention_width"], dtype=tf.float32),
tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0), [num_mentions, max_antecedents, 1]) # [num_mentions, max_ant, emb] 2) # [num_mentions, max_mention_width, 1]
feature_emb_list.append(tiled_genre_emb) mention_attention = tf.nn.softmax(mention_head_scores + tf.log(mention_mask),
dim=1) # [num_mentions, max_mention_width, 1]
if self.config["use_features"]: mention_head_emb = tf.reduce_sum(mention_attention * mention_text_emb, 1) # [num_mentions, emb]
target_indices = tf.range(num_mentions) # [num_mentions] mention_emb_list.append(mention_head_emb)
mention_distance = tf.expand_dims(target_indices, 1) - antecedents # [num_mentions, max_ant]
mention_distance_bins = coref_ops.distance_bins(mention_distance) # [num_mentions, max_ant] mention_emb = tf.concat(mention_emb_list, 1) # [num_mentions, emb]
mention_distance_bins.set_shape([None, None]) return mention_emb
mention_distance_emb = tf.gather(tf.get_variable("mention_distance_emb", [10, self.config["feature_size"]]), mention_distance_bins) # [num_mentions, max_ant]
feature_emb_list.append(mention_distance_emb) def get_mention_scores(self, mention_emb):
with tf.variable_scope("mention_scores"):
feature_emb = tf.concat(feature_emb_list, 2) # [num_mentions, max_ant, emb] return util.ffnn(mention_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1,
feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [num_mentions, max_ant, emb] self.dropout) # [num_mentions, 1]
antecedent_emb = tf.gather(mention_emb, antecedents) # [num_mentions, max_ant, emb] def softmax_loss(self, antecedent_scores, antecedent_labels):
target_emb_tiled = tf.tile(tf.expand_dims(mention_emb, 1), [1, max_antecedents, 1]) # [num_mentions, max_ant, emb] gold_scores = antecedent_scores + tf.log(tf.to_float(antecedent_labels)) # [num_mentions, max_ant + 1]
similarity_emb = antecedent_emb * target_emb_tiled # [num_mentions, max_ant, emb] marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [num_mentions]
log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [num_mentions]
pair_emb = tf.concat([target_emb_tiled, antecedent_emb, similarity_emb, feature_emb], 2) # [num_mentions, max_ant, emb] return log_norm - marginalized_gold_scores # [num_mentions]
with tf.variable_scope("iteration"): def get_antecedent_scores(self, mention_emb, mention_scores, antecedents, antecedents_len, mention_starts,
with tf.variable_scope("antecedent_scoring"): mention_ends, mention_speaker_ids, genre_emb):
antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [num_mentions, max_ant, 1] num_mentions = util.shape(mention_emb, 0)
antecedent_scores = tf.squeeze(antecedent_scores, 2) # [num_mentions, max_ant] max_antecedents = util.shape(antecedents, 1)
antecedent_mask = tf.log(tf.sequence_mask(antecedents_len, max_antecedents, dtype=tf.float32)) # [num_mentions, max_ant] feature_emb_list = []
antecedent_scores += antecedent_mask # [num_mentions, max_ant]
if self.config["use_metadata"]:
antecedent_scores += tf.expand_dims(mention_scores, 1) + tf.gather(mention_scores, antecedents) # [num_mentions, max_ant] antecedent_speaker_ids = tf.gather(mention_speaker_ids, antecedents) # [num_mentions, max_ant]
antecedent_scores = tf.concat([tf.zeros([util.shape(mention_scores, 0), 1]), antecedent_scores], 1) # [num_mentions, max_ant + 1] same_speaker = tf.equal(tf.expand_dims(mention_speaker_ids, 1),
return antecedent_scores # [num_mentions, max_ant + 1] antecedent_speaker_ids) # [num_mentions, max_ant]
speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]),
tf.to_int32(same_speaker)) # [num_mentions, max_ant, emb]
def flatten_emb_by_sentence(self, emb, text_len_mask): feature_emb_list.append(speaker_pair_emb)
num_sentences = tf.shape(emb)[0]
max_sentence_length = tf.shape(emb)[1] tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0),
[num_mentions, max_antecedents, 1]) # [num_mentions, max_ant, emb]
emb_rank = len(emb.get_shape()) feature_emb_list.append(tiled_genre_emb)
if emb_rank == 2:
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length]) if self.config["use_features"]:
elif emb_rank == 3: target_indices = tf.range(num_mentions) # [num_mentions]
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)]) mention_distance = tf.expand_dims(target_indices, 1) - antecedents # [num_mentions, max_ant]
else: mention_distance_bins = coref_ops.distance_bins(mention_distance) # [num_mentions, max_ant]
raise ValueError("Unsupported rank: {}".format(emb_rank)) mention_distance_bins.set_shape([None, None])
return tf.boolean_mask(flattened_emb, text_len_mask) mention_distance_emb = tf.gather(tf.get_variable("mention_distance_emb", [10, self.config["feature_size"]]),
mention_distance_bins) # [num_mentions, max_ant]
def encode_sentences(self, text_emb, text_len, text_len_mask): feature_emb_list.append(mention_distance_emb)
num_sentences = tf.shape(text_emb)[0]
max_sentence_length = tf.shape(text_emb)[1] feature_emb = tf.concat(feature_emb_list, 2) # [num_mentions, max_ant, emb]
feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [num_mentions, max_ant, emb]
# Transpose before and after for efficiency.
inputs = tf.transpose(text_emb, [1, 0, 2]) # [max_sentence_length, num_sentences, emb] antecedent_emb = tf.gather(mention_emb, antecedents) # [num_mentions, max_ant, emb]
target_emb_tiled = tf.tile(tf.expand_dims(mention_emb, 1),
with tf.variable_scope("fw_cell"): [1, max_antecedents, 1]) # [num_mentions, max_ant, emb]
cell_fw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout) similarity_emb = antecedent_emb * target_emb_tiled # [num_mentions, max_ant, emb]
preprocessed_inputs_fw = cell_fw.preprocess_input(inputs)
with tf.variable_scope("bw_cell"): pair_emb = tf.concat([target_emb_tiled, antecedent_emb, similarity_emb, feature_emb],
cell_bw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout) 2) # [num_mentions, max_ant, emb]
preprocessed_inputs_bw = cell_bw.preprocess_input(inputs)
preprocessed_inputs_bw = tf.reverse_sequence(preprocessed_inputs_bw, with tf.variable_scope("iteration"):
seq_lengths=text_len, with tf.variable_scope("antecedent_scoring"):
seq_dim=0, antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1,
batch_dim=1) self.dropout) # [num_mentions, max_ant, 1]
state_fw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_fw.initial_state.c, [num_sentences, 1]), tf.tile(cell_fw.initial_state.h, [num_sentences, 1])) antecedent_scores = tf.squeeze(antecedent_scores, 2) # [num_mentions, max_ant]
state_bw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_bw.initial_state.c, [num_sentences, 1]), tf.tile(cell_bw.initial_state.h, [num_sentences, 1]))
with tf.variable_scope("lstm"): antecedent_mask = tf.log(
with tf.variable_scope("fw_lstm"): tf.sequence_mask(antecedents_len, max_antecedents, dtype=tf.float32)) # [num_mentions, max_ant]
fw_outputs, fw_states = tf.nn.dynamic_rnn(cell=cell_fw, antecedent_scores += antecedent_mask # [num_mentions, max_ant]
inputs=preprocessed_inputs_fw,
sequence_length=text_len, antecedent_scores += tf.expand_dims(mention_scores, 1) + tf.gather(mention_scores,
initial_state=state_fw, antecedents) # [num_mentions, max_ant]
time_major=True) antecedent_scores = tf.concat([tf.zeros([util.shape(mention_scores, 0), 1]), antecedent_scores],
with tf.variable_scope("bw_lstm"): 1) # [num_mentions, max_ant + 1]
bw_outputs, bw_states = tf.nn.dynamic_rnn(cell=cell_bw, return antecedent_scores # [num_mentions, max_ant + 1]
inputs=preprocessed_inputs_bw,
sequence_length=text_len, def flatten_emb_by_sentence(self, emb, text_len_mask):
initial_state=state_bw, num_sentences = tf.shape(emb)[0]
time_major=True) max_sentence_length = tf.shape(emb)[1]
bw_outputs = tf.reverse_sequence(bw_outputs, emb_rank = len(emb.get_shape())
seq_lengths=text_len, if emb_rank == 2:
seq_dim=0, flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length])
batch_dim=1) elif emb_rank == 3:
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)])
text_outputs = tf.concat([fw_outputs, bw_outputs], 2) else:
text_outputs = tf.transpose(text_outputs, [1, 0, 2]) # [num_sentences, max_sentence_length, emb] raise ValueError("Unsupported rank: {}".format(emb_rank))
return self.flatten_emb_by_sentence(text_outputs, text_len_mask) return tf.boolean_mask(flattened_emb, text_len_mask)
def evaluate_mentions(self, candidate_starts, candidate_ends, mention_starts, mention_ends, mention_scores, gold_starts, gold_ends, example, evaluators): def encode_sentences(self, text_emb, text_len, text_len_mask):
text_length = sum(len(s) for s in example["sentences"]) num_sentences = tf.shape(text_emb)[0]
gold_spans = set(zip(gold_starts, gold_ends)) max_sentence_length = tf.shape(text_emb)[1]
if len(candidate_starts) > 0: # Transpose before and after for efficiency.
sorted_starts, sorted_ends, _ = zip(*sorted(zip(candidate_starts, candidate_ends, mention_scores), key=operator.itemgetter(2), reverse=True)) inputs = tf.transpose(text_emb, [1, 0, 2]) # [max_sentence_length, num_sentences, emb]
else:
sorted_starts = [] with tf.variable_scope("fw_cell"):
sorted_ends = [] cell_fw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout)
preprocessed_inputs_fw = cell_fw.preprocess_input(inputs)
for k, evaluator in evaluators.items(): with tf.variable_scope("bw_cell"):
if k == -3: cell_bw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout)
predicted_spans = set(zip(candidate_starts, candidate_ends)) & gold_spans preprocessed_inputs_bw = cell_bw.preprocess_input(inputs)
else: preprocessed_inputs_bw = tf.reverse_sequence(preprocessed_inputs_bw,
if k == -2: seq_lengths=text_len,
predicted_starts = mention_starts seq_dim=0,
predicted_ends = mention_ends batch_dim=1)
elif k == 0: state_fw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_fw.initial_state.c, [num_sentences, 1]),
is_predicted = mention_scores > 0 tf.tile(cell_fw.initial_state.h, [num_sentences, 1]))
predicted_starts = candidate_starts[is_predicted] state_bw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_bw.initial_state.c, [num_sentences, 1]),
predicted_ends = candidate_ends[is_predicted] tf.tile(cell_bw.initial_state.h, [num_sentences, 1]))
with tf.variable_scope("lstm"):
with tf.variable_scope("fw_lstm"):
fw_outputs, fw_states = tf.nn.dynamic_rnn(cell=cell_fw,
inputs=preprocessed_inputs_fw,
sequence_length=text_len,
initial_state=state_fw,
time_major=True)
with tf.variable_scope("bw_lstm"):
bw_outputs, bw_states = tf.nn.dynamic_rnn(cell=cell_bw,
inputs=preprocessed_inputs_bw,
sequence_length=text_len,
initial_state=state_bw,
time_major=True)
bw_outputs = tf.reverse_sequence(bw_outputs,
seq_lengths=text_len,
seq_dim=0,
batch_dim=1)
text_outputs = tf.concat([fw_outputs, bw_outputs], 2)
text_outputs = tf.transpose(text_outputs, [1, 0, 2]) # [num_sentences, max_sentence_length, emb]
return self.flatten_emb_by_sentence(text_outputs, text_len_mask)
def evaluate_mentions(self, candidate_starts, candidate_ends, mention_starts, mention_ends, mention_scores,
gold_starts, gold_ends, example, evaluators):
text_length = sum(len(s) for s in example["sentences"])
gold_spans = set(zip(gold_starts, gold_ends))
if len(candidate_starts) > 0:
sorted_starts, sorted_ends, _ = zip(
*sorted(zip(candidate_starts, candidate_ends, mention_scores), key=operator.itemgetter(2),
reverse=True))
else: else:
if k == -1: sorted_starts = []
num_predictions = len(gold_spans) sorted_ends = []
else:
num_predictions = (k * text_length) / 100 for k, evaluator in evaluators.items():
predicted_starts = sorted_starts[:num_predictions] if k == -3:
predicted_ends = sorted_ends[:num_predictions] predicted_spans = set(zip(candidate_starts, candidate_ends)) & gold_spans
predicted_spans = set(zip(predicted_starts, predicted_ends)) else:
evaluator.update(gold_set=gold_spans, predicted_set=predicted_spans) if k == -2:
predicted_starts = mention_starts
def get_predicted_antecedents(self, antecedents, antecedent_scores): predicted_ends = mention_ends
predicted_antecedents = [] elif k == 0:
for i, index in enumerate(np.argmax(antecedent_scores, axis=1) - 1): is_predicted = mention_scores > 0
if index < 0: predicted_starts = candidate_starts[is_predicted]
predicted_antecedents.append(-1) predicted_ends = candidate_ends[is_predicted]
else: else:
predicted_antecedents.append(antecedents[i, index]) if k == -1:
return predicted_antecedents num_predictions = len(gold_spans)
else:
def get_predicted_clusters(self, mention_starts, mention_ends, predicted_antecedents): num_predictions = (k * text_length) / 100
mention_to_predicted = {} predicted_starts = sorted_starts[:num_predictions]
predicted_clusters = [] predicted_ends = sorted_ends[:num_predictions]
for i, predicted_index in enumerate(predicted_antecedents): predicted_spans = set(zip(predicted_starts, predicted_ends))
if predicted_index < 0: evaluator.update(gold_set=gold_spans, predicted_set=predicted_spans)
continue
assert i > predicted_index def get_predicted_antecedents(self, antecedents, antecedent_scores):
predicted_antecedent = (int(mention_starts[predicted_index]), int(mention_ends[predicted_index])) predicted_antecedents = []
if predicted_antecedent in mention_to_predicted: for i, index in enumerate(np.argmax(antecedent_scores, axis=1) - 1):
predicted_cluster = mention_to_predicted[predicted_antecedent] if index < 0:
else: predicted_antecedents.append(-1)
predicted_cluster = len(predicted_clusters) else:
predicted_clusters.append([predicted_antecedent]) predicted_antecedents.append(antecedents[i, index])
mention_to_predicted[predicted_antecedent] = predicted_cluster return predicted_antecedents
mention = (int(mention_starts[i]), int(mention_ends[i])) def get_predicted_clusters(self, mention_starts, mention_ends, predicted_antecedents):
predicted_clusters[predicted_cluster].append(mention) mention_to_predicted = {}
mention_to_predicted[mention] = predicted_cluster predicted_clusters = []
for i, predicted_index in enumerate(predicted_antecedents):
predicted_clusters = [tuple(pc) for pc in predicted_clusters] if predicted_index < 0:
mention_to_predicted = { m:predicted_clusters[i] for m,i in mention_to_predicted.items() } continue
assert i > predicted_index
return predicted_clusters, mention_to_predicted predicted_antecedent = (int(mention_starts[predicted_index]), int(mention_ends[predicted_index]))
if predicted_antecedent in mention_to_predicted:
def evaluate_coref(self, mention_starts, mention_ends, predicted_antecedents, gold_clusters, evaluator): predicted_cluster = mention_to_predicted[predicted_antecedent]
gold_clusters = [tuple(tuple(m) for m in gc) for gc in gold_clusters] else:
mention_to_gold = {} predicted_cluster = len(predicted_clusters)
for gc in gold_clusters: predicted_clusters.append([predicted_antecedent])
for mention in gc: mention_to_predicted[predicted_antecedent] = predicted_cluster
mention_to_gold[mention] = gc
mention = (int(mention_starts[i]), int(mention_ends[i]))
predicted_clusters, mention_to_predicted = self.get_predicted_clusters(mention_starts, mention_ends, predicted_antecedents) predicted_clusters[predicted_cluster].append(mention)
evaluator.update(predicted_clusters, gold_clusters, mention_to_predicted, mention_to_gold) mention_to_predicted[mention] = predicted_cluster
return predicted_clusters
predicted_clusters = [tuple(pc) for pc in predicted_clusters]
def load_eval_data(self): mention_to_predicted = {m: predicted_clusters[i] for m, i in mention_to_predicted.items()}
if self.eval_data is None:
oov_counts = [0 for _ in self.embedding_dicts] return predicted_clusters, mention_to_predicted
with open(self.config["eval_path"]) as f:
self.eval_data = map(lambda example: (self.tensorize_example(example, is_training=False, oov_counts=oov_counts), example), (json.loads(jsonline) for jsonline in f.readlines())) def evaluate_coref(self, mention_starts, mention_ends, predicted_antecedents, gold_clusters, evaluator):
num_words = sum(tensorized_example[2].sum() for tensorized_example, _ in self.eval_data) gold_clusters = [tuple(tuple(m) for m in gc) for gc in gold_clusters]
for emb, c in zip(self.config["embeddings"], oov_counts): mention_to_gold = {}
print("OOV rate for {}: {:.2f}%".format(emb["path"], (100.0 * c) / num_words)) for gc in gold_clusters:
print("Loaded {} eval examples.".format(len(self.eval_data))) for mention in gc:
mention_to_gold[mention] = gc
def evaluate(self, session, official_stdout=False):
self.load_eval_data() predicted_clusters, mention_to_predicted = self.get_predicted_clusters(mention_starts, mention_ends,
predicted_antecedents)
def _k_to_tag(k): evaluator.update(predicted_clusters, gold_clusters, mention_to_predicted, mention_to_gold)
if k == -3: return predicted_clusters
return "oracle"
elif k == -2: def load_eval_data(self):
return "actual" if self.eval_data is None:
elif k == -1: oov_counts = [0 for _ in self.embedding_dicts]
return "exact" with open(self.config["eval_path"]) as f:
elif k == 0: self.eval_data = map(lambda example: (
return "threshold" self.tensorize_example(example, is_training=False, oov_counts=oov_counts), example),
else: (json.loads(jsonline) for jsonline in f.readlines()))
return "{}%".format(k) num_words = sum(tensorized_example[2].sum() for tensorized_example, _ in self.eval_data)
mention_evaluators = { k:util.RetrievalEvaluator() for k in [-3, -2, -1, 0, 10, 15, 20, 25, 30, 40, 50] } for emb, c in zip(self.config["embeddings"], oov_counts):
print("OOV rate for {}: {:.2f}%".format(emb["path"], (100.0 * c) / num_words))
coref_predictions = {} print("Loaded {} eval examples.".format(len(self.eval_data)))
coref_evaluator = metrics.CorefEvaluator()
def evaluate(self, session, official_stdout=False):
for example_num, (tensorized_example, example) in enumerate(self.eval_data): self.load_eval_data()
_, _, _, _, _, _, gold_starts, gold_ends, _ = tensorized_example
feed_dict = {i:t for i,t in zip(self.input_tensors, tensorized_example)} def _k_to_tag(k):
candidate_starts, candidate_ends, mention_scores, mention_starts, mention_ends, antecedents, antecedent_scores = session.run(self.predictions, feed_dict=feed_dict) if k == -3:
return "oracle"
self.evaluate_mentions(candidate_starts, candidate_ends, mention_starts, mention_ends, mention_scores, gold_starts, gold_ends, example, mention_evaluators) elif k == -2:
predicted_antecedents = self.get_predicted_antecedents(antecedents, antecedent_scores) return "actual"
elif k == -1:
coref_predictions[example["doc_key"]] = self.evaluate_coref(mention_starts, mention_ends, predicted_antecedents, example["clusters"], coref_evaluator) return "exact"
elif k == 0:
if example_num % 10 == 0: return "threshold"
print "Evaluated {}/{} examples.".format(example_num + 1, len(self.eval_data)) else:
return "{}%".format(k)
summary_dict = {}
for k, evaluator in sorted(mention_evaluators.items(), key=operator.itemgetter(0)): mention_evaluators = {k: util.RetrievalEvaluator() for k in [-3, -2, -1, 0, 10, 15, 20, 25, 30, 40, 50]}
tags = ["{} @ {}".format(t, _k_to_tag(k)) for t in ("R", "P", "F")]
results_to_print = [] coref_predictions = {}
for t, v in zip(tags, evaluator.metrics()): coref_evaluator = metrics.CorefEvaluator()
results_to_print.append("{:<10}: {:.2f}".format(t, v))
summary_dict[t] = v for example_num, (tensorized_example, example) in enumerate(self.eval_data):
print ", ".join(results_to_print) _, _, _, _, _, _, gold_starts, gold_ends, _ = tensorized_example
feed_dict = {i: t for i, t in zip(self.input_tensors, tensorized_example)}
conll_results = conll.evaluate_conll(self.config["conll_eval_path"], coref_predictions, official_stdout) candidate_starts, candidate_ends, mention_scores, mention_starts, mention_ends, antecedents, antecedent_scores = session.run(
average_f1 = sum(results["f"] for results in conll_results.values()) / len(conll_results) self.predictions, feed_dict=feed_dict)
summary_dict["Average F1 (conll)"] = average_f1
print "Average F1 (conll): {:.2f}%".format(average_f1) self.evaluate_mentions(candidate_starts, candidate_ends, mention_starts, mention_ends, mention_scores,
gold_starts, gold_ends, example, mention_evaluators)
p,r,f = coref_evaluator.get_prf() predicted_antecedents = self.get_predicted_antecedents(antecedents, antecedent_scores)
summary_dict["Average F1 (py)"] = f
print "Average F1 (py): {:.2f}%".format(f * 100) coref_predictions[example["doc_key"]] = self.evaluate_coref(mention_starts, mention_ends,
summary_dict["Average precision (py)"] = p predicted_antecedents, example["clusters"],
print "Average precision (py): {:.2f}%".format(p * 100) coref_evaluator)
summary_dict["Average recall (py)"] = r
print "Average recall (py): {:.2f}%".format(r * 100) if example_num % 10 == 0:
print "Evaluated {}/{} examples.".format(example_num + 1, len(self.eval_data))
return util.make_summary(summary_dict), average_f1
summary_dict = {}
for k, evaluator in sorted(mention_evaluators.items(), key=operator.itemgetter(0)):
tags = ["{} @ {}".format(t, _k_to_tag(k)) for t in ("R", "P", "F")]
results_to_print = []
for t, v in zip(tags, evaluator.metrics()):
results_to_print.append("{:<10}: {:.2f}".format(t, v))
summary_dict[t] = v
print ", ".join(results_to_print)
conll_results = conll.evaluate_conll(self.config["conll_eval_path"], coref_predictions, official_stdout)
average_f1 = sum(results["f"] for results in conll_results.values()) / len(conll_results)
summary_dict["Average F1 (conll)"] = average_f1
print "Average F1 (conll): {:.2f}%".format(average_f1)
p, r, f = coref_evaluator.get_prf()
muc_p, muc_r, muc_f = coref_evaluator.get_muc_prf()
bcubed_p, bcubed_r, bcubed_f = coref_evaluator.get_b_cubed_prf()
ceaf_p, ceaf_r, ceaf_f = coref_evaluator.get_ceaf_prf()
summary_dict["Average F1 (py)"] = f[0]
print "Average F1 (py): {:.2f}%".format(f[0] * 100)
summary_dict["Average precision (py)"] = p[0]
print "Average precision (py): {:.2f}%".format(p[0] * 100)
summary_dict["Average recall (py)"] = r[0]
print "Average recall (py): {:.2f}%".format(r[0] * 100)
print "MUC F1 : {:.2f}%".format(f[1][0] * 100)
print "MUC Precision : {:.2f}%".format(p[1][0] * 100)
print "MUC Recall : {:.2f}%".format(r[1][0] * 100)
print "B_CUBED F1 : {:.2f}%".format(f[1][1] * 100)
print "B_CUBED Precision : {:.2f}%".format(p[1][1] * 100)
print "B_CUBED Recall : {:.2f}%".format(r[1][1] * 100)
print "CEAF F1 : {:.2f}%".format(f[1][2] * 100)
print "CEAF Precision : {:.2f}%".format(p[1][2] * 100)
print "CEAF Recall : {:.2f}%".format(r[1][2] * 100)
return util.make_summary(summary_dict), average_f1
import os
import sys
import time
import json
import numpy as np
import cgi
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import ssl
import math
import tensorflow as tf
import coref_model as cm
import util
import coref_mermaid_model as cmm
import nltk
nltk.download("punkt")
from nltk.tokenize import sent_tokenize, word_tokenize
from demo import make_predictions, create_example
sentence = 'Phi4 Ceti is a solitary, orange-hued star in the equatorial constellation Cetus.\
It is faintly visible to the naked eye with an apparent visual magnitude of 5.61.\
Based upon an annual parallax shift of 10.20 mas as seen from Earth, it is located roughly 320 light years from the Sun.\
At that distance, the visual magnitude of the star is diminished by an extinction factor of 0.10 due to interstellar dust.[4]'
sentence = 'Large Electric said the Postal Service connected the Large Electric. Large Electric is great'
#sentence = 'In the summer of 2005 , a picture that people have long been looking forward to started emerging with frequency in various major Hong Kong media .With their unique charm , these well - known cartoon images once again caused Hong Kong to be a focus of worldwide attention .'
#sentence = 'Strains of anarchism have often been divided into the categories of social and individualist anarchism or similar dual classifications,\
# Many types and traditions of anarchism exist , not all of which are mutually exclusive .'
example = create_example(sentence)
name = 'best'
print "Running experiment: {}.".format(name)
config = util.get_config("experiments.conf")[name]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config)
model = cmm.CorefMermaidModel(config)
print('execueted before session')
saver = tf.train.Saver()
log_dir = config["log_dir"]
with tf.Session() as session:
checkpoint_path = os.path.join(log_dir, "model.max.ckpt")
saver.restore(session, checkpoint_path)
tensorized_example = model.tensorize_example(example, is_training=False)
feed_dict = {i: t for i, t in zip(model.input_tensors, tensorized_example)}
print('prepared to run session!')
_, _, _, mention_starts, mention_ends, antecedents, antecedent_scores, head_scores = session.run(
model.predictions + [model.head_scores], feed_dict=feed_dict)
mention_dict = {}
mention_dict.setdefault('mention_starts', mention_starts)
mention_dict.setdefault('mention_ends',mention_ends)
mention_dict.setdefault('antecedent_scores', antecedent_scores)
file1 = file('antecedent.npz','wb')
file2 = file('mention_starts.npy','ab')
file3 = file('mention_ends.npy','ab')
np.savez(file2, mention_starts)
np.savez(file3, mention_ends)
np.savez(file1, antecedent_scores)
wow = np.arange(10)
np.savez(file1, wow)
#print('mention scores is: ', mention_scores)
predicted_antecedents = model.get_predicted_antecedents(antecedents, antecedent_scores)
print('antecedent_scores is: \n', antecedent_scores)
print('antecedent_scores shape is : \n', len(antecedent_scores), len(antecedent_scores[0]))
print('antecedents is: \n', antecedents)
example["predicted_clusters"], _ = model.get_predicted_clusters(mention_starts, mention_ends, predicted_antecedents)
example["top_spans"] = zip((int(i) for i in mention_starts), (int(i) for i in mention_ends))
example["head_scores"] = head_scores.tolist()
print('predicted_antecedentts: ', predicted_antecedents)
print('mention start is {},\n, mention end is {}, \n, antecedent scores is {}, \n, head scores is {}'.format(
mention_starts, mention_ends, antecedent_scores, head_scores))
print(example)
for cluster in example["predicted_clusters"]:
words = util.flatten(example["sentences"])
print(u"Predicted cluster: {}".format([" ".join(words[m[0]:m[1]+1]) for m in cluster]))
...@@ -3,65 +3,74 @@ ...@@ -3,65 +3,74 @@
import os import os
import re import re
import sys import sys
sys.path.append(os.getcwd()) sys.path.append(os.getcwd())
import time
import random
import shutil import shutil
import numpy as np import coref_mermaid_model as cmm
import tensorflow as tf import tensorflow as tf
import coref_model as cm
import util import util
def copy_checkpoint(source, target): def copy_checkpoint(source, target):
for ext in (".index", ".data-00000-of-00001"): for ext in (".index", ".data-00000-of-00001"):
shutil.copyfile(source + ext, target + ext) shutil.copyfile(source + ext, target + ext)
if __name__ == "__main__": if __name__ == "__main__":
util.set_gpus() util.set_gpus()
if len(sys.argv) > 1:
name = sys.argv[1]
print
"Running experiment: {} (from command-line argument).".format(name)
else:
name = os.environ["EXP"]
print
"Running experiment: {} (from environment variable).".format(name)
config = util.get_config("experiments.conf")[name]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
config["combination_ratio"] = 1
if len(sys.argv) > 1: util.print_config(config)
name = sys.argv[1] # model = cm.CorefModel(config)
print "Running experiment: {} (from command-line argument).".format(name)
else:
name = os.environ["EXP"]
print "Running experiment: {} (from environment variable).".format(name)
config = util.get_config("experiments.conf")[name] sub_values = [1.25, 1.5,1.75,2.5,3.5,4,4.5]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name)) for sub_value in sub_values:
tf.reset_default_graph()
model = cmm.CorefMermaidModel(config)
util.print_config(config) saver = tf.train.Saver()
model = cm.CorefModel(config) log_dir = config["log_dir"]
writer = tf.summary.FileWriter(log_dir, flush_secs=20)
evaluated_checkpoints = set()
max_f1 = 0
checkpoint_pattern = re.compile(".*model.ckpt-([0-9]*)\Z")
saver = tf.train.Saver() with tf.Session() as session:
log_dir = config["log_dir"] ckpt = tf.train.get_checkpoint_state(log_dir)
writer = tf.summary.FileWriter(log_dir, flush_secs=20) if ckpt and ckpt.model_checkpoint_path and ckpt.model_checkpoint_path not in evaluated_checkpoints:
evaluated_checkpoints = set() print("Evaluating {}".format(ckpt.model_checkpoint_path))
max_f1 = 0
checkpoint_pattern = re.compile(".*model.ckpt-([0-9]*)\Z")
with tf.Session() as session: # Move it to a temporary location to avoid being deleted by the training supervisor.
while True: tmp_checkpoint_path = os.path.join(log_dir, "model.tmp.ckpt")
ckpt = tf.train.get_checkpoint_state(log_dir) copy_checkpoint(ckpt.model_checkpoint_path, tmp_checkpoint_path)
if ckpt and ckpt.model_checkpoint_path and ckpt.model_checkpoint_path not in evaluated_checkpoints:
print "Evaluating {}".format(ckpt.model_checkpoint_path)
# Move it to a temporary location to avoid being deleted by the training supervisor. global_step = int(checkpoint_pattern.match(ckpt.model_checkpoint_path).group(1))
tmp_checkpoint_path = os.path.join(log_dir, "model.tmp.ckpt") saver.restore(session, ckpt.model_checkpoint_path)
copy_checkpoint(ckpt.model_checkpoint_path, tmp_checkpoint_path)
global_step = int(checkpoint_pattern.match(ckpt.model_checkpoint_path).group(1)) eval_summary, f1, average_precion, average_recall = model.evaluate(session, sub_value)
saver.restore(session, ckpt.model_checkpoint_path)
eval_summary, f1 = model.evaluate(session) if f1 > max_f1:
max_f1 = f1
copy_checkpoint(tmp_checkpoint_path, os.path.join(log_dir, "model.max.ckpt"))
if f1 > max_f1: print("Current max F1: {:.2f}".format(max_f1))
max_f1 = f1
copy_checkpoint(tmp_checkpoint_path, os.path.join(log_dir, "model.max.ckpt"))
print "Current max F1: {:.2f}".format(max_f1) writer.add_summary(eval_summary, global_step)
writer.add_summary(eval_summary, global_step) with open('./precision_recall.txt', 'a') as f:
print "Evaluation written to {} at step {}".format(log_dir, global_step) f.write(str(sub_value)+' '+str(average_precion)+' '+str(average_recall)+'\n')
evaluated_checkpoints.add(ckpt.model_checkpoint_path) evaluated_checkpoints.add(ckpt.model_checkpoint_path)
...@@ -106,6 +106,6 @@ nofeatures = ${best} { ...@@ -106,6 +106,6 @@ nofeatures = ${best} {
# For evaluation. Do not use for training (i.e. only for decoder.py, ensembler.py, visualize.py and demo.py). Rename `best0` directory to `final`. # For evaluation. Do not use for training (i.e. only for decoder.py, ensembler.py, visualize.py and demo.py). Rename `best0` directory to `final`.
final = ${best} { final = ${best} {
embeddings = [${glove_300d}, ${turian_50d}] embeddings = [${glove_300d}, ${turian_50d}]
eval_path = test.english.jsonlines eval_path = eval_file
conll_eval_path = test.english.v4_gold_conll conll_eval_path = test.english.v4_gold_conll
} }
...@@ -20,17 +20,36 @@ class CorefEvaluator(object): ...@@ -20,17 +20,36 @@ class CorefEvaluator(object):
e.update(predicted, gold, mention_to_predicted, mention_to_gold) e.update(predicted, gold, mention_to_predicted, mention_to_gold)
def get_f1(self): def get_f1(self):
return sum(e.get_f1() for e in self.evaluators) / len(self.evaluators) return sum(e.get_f1() for e in self.evaluators) / len(self.evaluators), [e.get_f1() for e in self.evaluators]
def get_recall(self): def get_recall(self):
return sum(e.get_recall() for e in self.evaluators) / len(self.evaluators) return sum(e.get_recall() for e in self.evaluators) / len(self.evaluators), [e.get_recall() for e in self.evaluators]
def get_precision(self): def get_precision(self):
return sum(e.get_precision() for e in self.evaluators) / len(self.evaluators) muc_precision = Evaluator(muc).get_precision()
return sum(e.get_precision() for e in self.evaluators) / len(self.evaluators), [e.get_precision() for e in self.evaluators]
def get_prf(self): def get_prf(self):
return self.get_precision(), self.get_recall(), self.get_f1() return self.get_precision(), self.get_recall(), self.get_f1()
def get_muc_prf(self):
muc_precision = Evaluator(muc).get_precision()
muc_recall = Evaluator(muc).get_recall()
muc_f1 = Evaluator(muc).get_f1()
return muc_precision, muc_recall, muc_f1
def get_b_cubed_prf(self):
muc_precision = Evaluator(b_cubed).get_precision()
muc_recall = Evaluator(b_cubed).get_recall()
muc_f1 = Evaluator(b_cubed).get_f1()
return muc_precision, muc_recall, muc_f1
def get_ceaf_prf(self):
muc_precision = Evaluator(ceafe).get_precision()
muc_recall = Evaluator(ceafe).get_recall()
muc_f1 = Evaluator(ceafe).get_f1()
return muc_precision, muc_recall, muc_f1
class Evaluator(object): class Evaluator(object):
def __init__(self, metric, beta=1): def __init__(self, metric, beta=1):
self.p_num = 0 self.p_num = 0
......
...@@ -11,132 +11,168 @@ import collections ...@@ -11,132 +11,168 @@ import collections
import util import util
import conll import conll
class DocumentState(object): class DocumentState(object):
def __init__(self): def __init__(self):
self.doc_key = None self.doc_key = None
self.text = [] self.text = []
self.text_speakers = [] self.text_speakers = []
self.speakers = [] self.speakers = []
self.sentences = [] self.sentences = []
self.clusters = collections.defaultdict(list) self.clusters = collections.defaultdict(list)
self.stacks = collections.defaultdict(list) self.stacks = collections.defaultdict(list)
def assert_empty(self): def assert_empty(self):
assert self.doc_key is None assert self.doc_key is None
assert len(self.text) == 0 assert len(self.text) == 0
assert len(self.text_speakers) == 0 assert len(self.text_speakers) == 0
assert len(self.sentences) == 0 assert len(self.sentences) == 0
assert len(self.speakers) == 0 assert len(self.speakers) == 0
assert len(self.clusters) == 0 assert len(self.clusters) == 0
assert len(self.stacks) == 0 assert len(self.stacks) == 0
def assert_finalizable(self): def assert_finalizable(self):
assert self.doc_key is not None assert self.doc_key is not None
assert len(self.text) == 0 assert len(self.text) == 0
assert len(self.text_speakers) == 0 assert len(self.text_speakers) == 0
assert len(self.sentences) > 0 assert len(self.sentences) > 0
assert len(self.speakers) > 0 assert len(self.speakers) > 0
assert all(len(s) == 0 for s in self.stacks.values()) assert all(len(s) == 0 for s in self.stacks.values())
def finalize(self): def finalize(self):
merged_clusters = [] merged_clusters = []
for c1 in self.clusters.values(): for c1 in self.clusters.values():
existing = None existing = None
for m in c1: for m in c1:
for c2 in merged_clusters: for c2 in merged_clusters:
if m in c2: if m in c2:
existing = c2 existing = c2
break break
if existing is not None: if existing is not None:
break break
if existing is not None: if existing is not None:
print("Merging clusters (shouldn't happen very often.)") print("Merging clusters (shouldn't happen very often.)")
existing.update(c1) existing.update(c1)
else: else:
merged_clusters.append(set(c1)) merged_clusters.append(set(c1))
merged_clusters = [list(c) for c in merged_clusters] merged_clusters = [list(c) for c in merged_clusters]
all_mentions = util.flatten(merged_clusters) all_mentions = util.flatten(merged_clusters)
assert len(all_mentions) == len(set(all_mentions)) assert len(all_mentions) == len(set(all_mentions))
return { return {
"doc_key": self.doc_key, "doc_key" : self.doc_key,
"sentences": self.sentences, "sentences": self.sentences,
"speakers": self.speakers, "speakers" : self.speakers,
"clusters": merged_clusters "clusters" : merged_clusters
} }
def normalize_word(word): def normalize_word(word):
if word == "/." or word == "/?": if word == "/." or word == "/?":
return word[1:] return word[1:]
else: else:
return word return word
def handle_line(line, document_state): def handle_line(line, document_state):
begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line) begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line)
if begin_document_match: if begin_document_match:
document_state.assert_empty() document_state.assert_empty()
document_state.doc_key = conll.get_doc_key(begin_document_match.group(1), begin_document_match.group(2)) document_state.doc_key = conll.get_doc_key(begin_document_match.group(1), begin_document_match.group(2))
return None return None
elif line.startswith("#end document"): elif line.startswith("#end document"):
document_state.assert_finalizable() document_state.assert_finalizable()
return document_state.finalize() return document_state.finalize()
else: else:
row = line.split() row = line.split()
if len(row) == 0: if len(row) == 0:
document_state.sentences.append(tuple(document_state.text)) document_state.sentences.append(tuple(document_state.text))
del document_state.text[:] del document_state.text[:]
document_state.speakers.append(tuple(document_state.text_speakers)) document_state.speakers.append(tuple(document_state.text_speakers))
del document_state.text_speakers[:] del document_state.text_speakers[:]
return None return None
assert len(row) >= 12 assert len(row) >= 12
word = normalize_word(row[3]) word = normalize_word(row[3])
coref = row[-1] coref = row[-1]
doc_key = conll.get_doc_key(row[0], row[1]) doc_key = conll.get_doc_key(row[0], row[1])
speaker = row[9] speaker = row[9]
word_index = len(document_state.text) + sum(len(s) for s in document_state.sentences) word_index = len(document_state.text) + sum(len(s) for s in document_state.sentences)
document_state.text.append(word) document_state.text.append(word)
document_state.text_speakers.append(speaker) document_state.text_speakers.append(speaker)
if coref == "-": if coref == "-":
return None return None
for segment in coref.split("|"): for segment in coref.split("|"):
if segment[0] == "(": if segment[0] == "(":
if segment[-1] == ")": if segment[-1] == ")":
cluster_id = int(segment[1:-1]) cluster_id = int(segment[1:-1])
document_state.clusters[cluster_id].append((word_index, word_index)) document_state.clusters[cluster_id].append((word_index, word_index))
else: else:
cluster_id = int(segment[1:]) cluster_id = int(segment[1:])
document_state.stacks[cluster_id].append(word_index) document_state.stacks[cluster_id].append(word_index)
else: else:
cluster_id = int(segment[:-1]) cluster_id = int(segment[:-1])
start = document_state.stacks[cluster_id].pop() start = document_state.stacks[cluster_id].pop()
document_state.clusters[cluster_id].append((start, word_index)) document_state.clusters[cluster_id].append((start, word_index))
return None return None
def minimize_partition(name, language, extension): def minimize_partition(name, language, extension):
input_path = "{}.{}.{}".format(name, language, extension) input_path = "{}.{}.{}".format(name, language, extension)
output_path = "{}.{}.jsonlines".format(name, language) output_path = "{}.{}.jsonlines".format(name, language)
count = 0 count = 0
print "Minimizing {}".format(input_path) print(input_path)
with open(input_path, "r") as input_file: print "minimizing {}".format(input_path)
with open(output_path, "w") as output_file: with open(input_path, "r") as input_file:
document_state = DocumentState() with open(output_path, "w") as output_file:
for line in input_file.readlines(): document_state = DocumentState()
document = handle_line(line, document_state) for line in input_file.readlines():
if document is not None: begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line)
output_file.write(json.dumps(document)) if begin_document_match:
output_file.write("\n") document_state = DocumentState()
count += 1 document = handle_line(line, document_state)
document_state = DocumentState() if document is not None:
print "Wrote {} documents to {}".format(count, output_path) output_file.write(json.dumps(document))
output_file.write("\n")
count += 1
document_state = DocumentState()
print "Wrote {} documents to {}".format(count, output_path)
def creating_new_data(name, language, extension):
input_path = "{}.{}.{}".format(name, language, extension)
output_path = "{}.{}.{}.new2".format(name, language, extension)
print("recreating {}".format(input_path))
doc_list = []
with open(input_path, "r") as input_file:
with open(output_path, "w") as output_file:
for line in input_file.readlines():
doc_list.append(line)
trouble_doc_index = 0
for item in doc_list:
if item.startswith('#end document'):
while trouble_doc_index+1<len(doc_list) and doc_list[trouble_doc_index+1] == '\n':
del doc_list[trouble_doc_index+1]
trouble_doc_index += 1
for item in doc_list:
output_file.write(item+'\n')
keyword = ['cctv_0003', '10', '14', 'Xing']
if all(item in line for item in keyword):
output_file.write('#end document' + '\n')
def minimize_language(language): def minimize_language(language):
minimize_partition("dev", language, "v4_auto_conll") minimize_partition("dev", language, "v4_auto_conll")
minimize_partition("train", language, "v4_auto_conll") minimize_partition("train", language, "v4_auto_conll")
minimize_partition("test", language, "v4_gold_conll") minimize_partition("test", language, "v4_gold_conll")
if __name__ == "__main__": if __name__ == "__main__":
minimize_language("english") #creating_new_data("train", "english", "v4_auto_conll")
minimize_language("english")
import json
import flask
from flask import render_template, flash, request, redirect, url_for
import coref_model as cm
class WebServer():
app = flask.Flask(__name__)
@app.route('/coref/', methods=['GET', 'POST'])
def coref_input(self):
try:
data = json.loads(flask.request.get_json())
except:
data = flask.request.get_json()
app = flask.Flask(__name__)
'''
@app.route("/", methods=['POST', 'GET'])
def run_web_server():
return render_template("web_server.html", title='Coreference Resolution Service')
'''
@app.route("/coref", methods=['POST', 'GET'])
def run_web_http_request_service():
data = json.loads(flask.request.get_json())
result = coref_resolve(data)
return flask.jsonify({'result': result})
def coref_resolve(data):
pass
def create_example(text):
raw_sentences = sent_tokenize(text)
sentences = [word_tokenize(s) for s in raw_sentences]
speakers = [["" for _ in sentence] for sentence in sentences]
return {
"doc_key": "nw",
"clusters": [],
"sentences": sentences,
"speakers": speakers,
}
class CorefRequestHandler(BaseHTTPRequestHandler):
model = None
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={"REQUEST_METHOD":"POST",
"CONTENT_TYPE":self.headers["Content-Type"]
})
if "text" in form:
text = form["text"].value.decode("utf-8")
if len(text) <= 10000:
print(u"Document text: {}".format(text))
example = make_predictions(text, self.model)
print_predictions(example)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(example))
return
self.send_response(400)
self.send_header("Content-Type", "application/json")
self.end_headers()
app.run(host='localhost', port=5700, debug=True, threaded=True)
CorefRequestHandler.model = cm.CorefModel('pre-trained')
import requests
import json
import flask
sentence = 'Hey! Thanks for the ans, but i think i wasnt clear enough about what i need to do.\
I having for example, one computer running the servers script, and another computer runnig client script.\
The client need to send a true var for if he is alive and this need to be an http request, \
so i dont really have a url, just an ip address'
#r = requests.post('localhost:5702/post', data=sentence)
#print(r.text)
app = flask.Flask(__name__)
@app.route('/test/', methods=['GET', 'POST'])
def index():
data = json.loads(flask.request.get_json())
print(data['data'])
print(data)
data = data+' processed!'
return flask.jsonify(data)
app.run('localhost', 8888)
resp = requests.post('localhost:8888', data='this is a test')
#!/bin/bash #!/bin/bash
# Download pretrained embeddings. # Download pretrained embeddings.
curl -O https://lil.cs.washington.edu/coref/turian.50d.txt #curl -O https://lil.cs.washington.edu/coref/turian.50d.txt
curl -O https://nlp.stanford.edu/data/glove.840B.300d.zip #curl -O https://nlp.stanford.edu/data/glove.840B.300d.zip
unzip glove.840B.300d.zip #unzip glove.840B.300d.zip
rm glove.840B.300d.zip #rm glove.840B.300d.zip
# Build custom kernels. # Build custom kernels.
TF_INC=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())') TF_INC=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())')
# Linux (pip) # Linux (pip)
#g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0 g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0
# Linux (build from source) # Linux (build from source)
g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC #g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC
# Mac # Mac
#g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0 -undefined dynamic_lookup #g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0 -undefined dynamic_lookup
...@@ -3,6 +3,6 @@ ...@@ -3,6 +3,6 @@
curl -O https://lil.cs.washington.edu/coref/char_vocab.english.txt curl -O https://lil.cs.washington.edu/coref/char_vocab.english.txt
curl -O https://lil.cs.washington.edu/coref/final.tgz curl -O https://lil.cs.washington.edu/coref/final.tgz
mkdir -p logs #mkdir -p logs
tar -xzvf final.tgz -C logs tar -xzvf final.tgz -C logs
rm final.tgz rm final.tgz
...@@ -7,18 +7,19 @@ dlx() { ...@@ -7,18 +7,19 @@ dlx() {
} }
conll_url=http://conll.cemantix.org/2012/download conll_url=http://conll.cemantix.org/2012/download
dlx $conll_url conll-2012-train.v4.tar.gz #dlx $conll_url conll-2012-train.v4.tar.gz
dlx $conll_url conll-2012-development.v4.tar.gz #dlx $conll_url conll-2012-development.v4.tar.gz
dlx $conll_url/test conll-2012-test-key.tar.gz #dlx $conll_url/test conll-2012-test-key.tar.gz
dlx $conll_url/test conll-2012-test-official.v9.tar.gz #dlx $conll_url/test conll-2012-test-official.v9.tar.gz
dlx $conll_url conll-2012-scripts.v3.tar.gz #dlx $conll_url conll-2012-scripts.v3.tar.gz
dlx http://conll.cemantix.org/download reference-coreference-scorers.v8.01.tar.gz #dlx http://conll.cemantix.org/download reference-coreference-scorers.v8.01.tar.gz
mv reference-coreference-scorers conll-2012/scorer #mv reference-coreference-scorers conll-2012/scorer
ontonotes_path=/projects/WebWare6/ontonotes-release-5.0 #ontonotes_path=/home/NewPartion/conll-formatted-ontonotes-5.0
bash conll-2012/v3/scripts/skeleton2conll.sh -D $ontonotes_path/data/files/data conll-2012 ontonotes_path=/home/NewPartion/ontonotes-release-5.0
#bash conll-2012/v3/scripts/skeleton2conll.sh -D $ontonotes_path/data/files/data conll-2012
function compile_partition() { function compile_partition() {
rm -f $2.$5.$3$4 rm -f $2.$5.$3$4
...@@ -31,7 +32,7 @@ function compile_language() { ...@@ -31,7 +32,7 @@ function compile_language() {
compile_partition test test v4 _gold_conll $1 compile_partition test test v4 _gold_conll $1
} }
compile_language english #compile_language english
python minimize.py python minimize.py
python get_char_vocab.py python get_char_vocab.py
......
...@@ -23,10 +23,11 @@ if __name__ == "__main__": ...@@ -23,10 +23,11 @@ if __name__ == "__main__":
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name)) config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config) util.print_config(config)
if "GPU" in os.environ: #if "GPU" in os.environ:
util.set_gpus(int(os.environ["GPU"])) #util.set_gpus(int(os.environ["GPU"]))
else: #else:
util.set_gpus() #util.set_gpus()
util.set_gpus(0)
model = cm.CorefModel(config) model = cm.CorefModel(config)
saver = tf.train.Saver() saver = tf.train.Saver()
......
<!DOCTYPE html>
<title>Flaskr</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Flaskr</h1>
<div class=metanav>
<form>
</form>
</div>
{% for message in get_flashed_messages() %}
<div class=flash>{{ message }}</div>
{% endfor %}
{% block body %}{% endblock %}
</div>
...@@ -49,6 +49,7 @@ def load_embedding_dict(embedding_path, embedding_size, embedding_format): ...@@ -49,6 +49,7 @@ def load_embedding_dict(embedding_path, embedding_size, embedding_format):
if skip_first and i == 0: if skip_first and i == 0:
continue continue
splits = line.split() splits = line.split()
assert len(splits) == embedding_size + 1 assert len(splits) == embedding_size + 1
word = splits[0] word = splits[0]
embedding = np.array([float(s) for s in splits[1:]]) embedding = np.array([float(s) for s in splits[1:]])
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment