diff --git a/Mermaid_part.py b/Mermaid_part.py new file mode 100644 index 0000000..be4733d --- /dev/null +++ b/Mermaid_part.py @@ -0,0 +1,111 @@ +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 diff --git a/coref_mermaid_model.py b/coref_mermaid_model.py new file mode 100644 index 0000000..379c05e --- /dev/null +++ b/coref_mermaid_model.py @@ -0,0 +1,174 @@ +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 diff --git a/coref_model.py b/coref_model.py index 7096f8d..ead96e4 100644 --- a/coref_model.py +++ b/coref_model.py @@ -11,483 +11,554 @@ import coref_ops import conll import metrics + class CorefModel(object): - def __init__(self, config): - self.config = config - self.embedding_info = [(emb["size"], emb["lowercase"]) for emb in config["embeddings"]] - self.embedding_size = sum(size for size, _ in self.embedding_info) - self.char_embedding_size = config["char_embedding_size"] - 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.max_mention_width = config["max_mention_width"] - 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.append((tf.int32, [None, None, None])) # Character indices. - input_props.append((tf.int32, [None])) # Text lengths. - input_props.append((tf.int32, [None])) # Speaker IDs. - input_props.append((tf.int32, [])) # Genre. - input_props.append((tf.bool, [])) # Is training. - input_props.append((tf.int32, [None])) # Gold starts. - 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) - queue = tf.PaddingFIFOQueue(capacity=10, dtypes=dtypes, shapes=shapes) - 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.reset_global_step = tf.assign(self.global_step, 0) - learning_rate = tf.train.exponential_decay(self.config["learning_rate"], self.global_step, - self.config["decay_frequency"], self.config["decay_rate"], staircase=True) - trainable_params = tf.trainable_variables() - gradients = tf.gradients(self.loss, trainable_params) - gradients, _ = tf.clip_by_global_norm(gradients, self.config["max_gradient_norm"]) - optimizers = { - "adam" : tf.train.AdamOptimizer, - "sgd" : tf.train.GradientDescentOptimizer - } - optimizer = optimizers[self.config["optimizer"]](learning_rate) - self.train_op = optimizer.apply_gradients(zip(gradients, trainable_params), global_step=self.global_step) - - def start_enqueue_thread(self, session): - with open(self.config["train_path"]) as f: - train_examples = [json.loads(jsonline) for jsonline in f.readlines()] - def _enqueue_loop(): - while True: - random.shuffle(train_examples) - for example in train_examples: - tensorized_example = self.tensorize_example(example, is_training=True) - feed_dict = dict(zip(self.queue_input_tensors, tensorized_example)) - session.run(self.enqueue_op, feed_dict=feed_dict) - enqueue_thread = threading.Thread(target=_enqueue_loop) - enqueue_thread.daemon = True - enqueue_thread.start() - - def tensorize_mentions(self, mentions): - if len(mentions) > 0: - starts, ends = zip(*mentions) - else: - starts, ends = [], [] - return np.array(starts), np.array(ends) - - def tensorize_example(self, example, is_training, oov_counts=None): - clusters = example["clusters"] - - gold_mentions = sorted(tuple(m) for m in util.flatten(clusters)) - gold_mention_map = {m:i for i,m in enumerate(gold_mentions)} - cluster_ids = np.zeros(len(gold_mentions)) - for cluster_id, cluster in enumerate(clusters): - for mention in cluster: - cluster_ids[gold_mention_map[tuple(mention)]] = cluster_id - - sentences = example["sentences"] - num_words = sum(len(s) for s in sentences) - speakers = util.flatten(example["speakers"]) - - assert num_words == len(speakers) - - max_sentence_length = max(len(s) for s in sentences) - 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]) - char_index = np.zeros([len(sentences), max_sentence_length, max_word_length]) - text_len = np.array([len(s) for s in sentences]) - for i, sentence in enumerate(sentences): - for j, word in enumerate(sentence): - current_dim = 0 - for k, (d, (s,l)) in enumerate(zip(self.embedding_dicts, self.embedding_info)): - if l: - current_word = word.lower() - else: - current_word = word - if oov_counts is not None and current_word not in d: - oov_counts[k] += 1 - word_emb[i, j, current_dim:current_dim + s] = util.normalize(d[current_word]) - current_dim += s - char_index[i, j, :len(word)] = [self.char_dict[c] for c in word] - - speaker_dict = { s:i for i,s in enumerate(set(speakers)) } - speaker_ids = np.array([speaker_dict[s] for s in speakers]) - - doc_key = example["doc_key"] - genre = self.genres[doc_key[:2]] - - gold_starts, gold_ends = self.tensorize_mentions(gold_mentions) - - if is_training and len(sentences) > self.config["max_training_sentences"]: - return self.truncate_example(word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids) - else: - return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids - - def truncate_example(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids): - max_training_sentences = self.config["max_training_sentences"] - num_sentences = word_emb.shape[0] - assert num_sentences > max_training_sentences - - sentence_offset = random.randint(0, num_sentences - max_training_sentences) - word_offset = text_len[:sentence_offset].sum() - num_words = text_len[sentence_offset:sentence_offset + max_training_sentences].sum() - word_emb = word_emb[sentence_offset:sentence_offset + max_training_sentences,:,:] - char_index = char_index[sentence_offset:sentence_offset + max_training_sentences,:,:] - text_len = text_len[sentence_offset:sentence_offset + max_training_sentences] - - 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) - gold_starts = gold_starts[gold_spans] - word_offset - gold_ends = gold_ends[gold_spans] - word_offset - cluster_ids = cluster_ids[gold_spans] - - return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids - - def get_predictions_and_loss(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids): - self.dropout = 1 - (tf.to_float(is_training) * self.config["dropout_rate"]) - self.lexical_dropout = 1 - (tf.to_float(is_training) * self.config["lexical_dropout_rate"]) - - num_sentences = tf.shape(word_emb)[0] - max_sentence_length = tf.shape(word_emb)[1] - - text_emb_list = [word_emb] - - if self.config["char_embedding_size"] > 0: - 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] - flattened_aggregated_char_emb = util.cnn(flattened_char_emb, self.config["filter_widths"], self.config["filter_size"]) # [num_sentences * max_sentence_length, emb] - 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 = tf.concat(text_emb_list, 2) - text_emb = tf.nn.dropout(text_emb, self.lexical_dropout) - - text_len_mask = tf.sequence_mask(text_len, maxlen=max_sentence_length) - text_len_mask = tf.reshape(text_len_mask, [num_sentences * max_sentence_length]) - - text_outputs = self.encode_sentences(text_emb, text_len, text_len_mask) - text_outputs = tf.nn.dropout(text_outputs, self.dropout) - - genre_emb = tf.gather(tf.get_variable("genre_embeddings", [len(self.genres), self.config["feature_size"]]), genre) # [emb] - - sentence_indices = tf.tile(tf.expand_dims(tf.range(num_sentences), 1), [1, max_sentence_length]) # [num_sentences, max_sentence_length] - flattened_sentence_indices = self.flatten_emb_by_sentence(sentence_indices, text_len_mask) # [num_words] - flattened_text_emb = self.flatten_emb_by_sentence(text_emb, text_len_mask) # [num_words] - - candidate_starts, candidate_ends = coref_ops.spans( - sentence_indices=flattened_sentence_indices, - max_width=self.max_mention_width) - candidate_starts.set_shape([None]) - candidate_ends.set_shape([None]) - - candidate_mention_emb = self.get_mention_emb(flattened_text_emb, text_outputs, candidate_starts, candidate_ends) # [num_candidates, emb] - candidate_mention_scores = self.get_mention_scores(candidate_mention_emb) # [num_mentions, 1] - candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [num_mentions] - - 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]) - predicted_mention_indices.set_shape([None]) - - mention_starts = tf.gather(candidate_starts, predicted_mention_indices) # [num_mentions] - mention_ends = tf.gather(candidate_ends, predicted_mention_indices) # [num_mentions] - 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] - - 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_speaker_ids = tf.gather(speaker_ids, mention_starts) # [num_mentions] - - max_antecedents = self.config["max_antecedents"] - 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] - antecedents.set_shape([None, None]) - antecedent_labels.set_shape([None, None]) - antecedents_len.set_shape([None]) - - 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] - - loss = self.softmax_loss(antecedent_scores, antecedent_labels) # [num_mentions] - loss = tf.reduce_sum(loss) # [] - - return [candidate_starts, candidate_ends, candidate_mention_scores, mention_starts, mention_ends, antecedents, antecedent_scores], loss - - def get_mention_emb(self, text_emb, text_outputs, mention_starts, mention_ends): - mention_emb_list = [] - - mention_start_emb = tf.gather(text_outputs, mention_starts) # [num_mentions, emb] - mention_emb_list.append(mention_start_emb) - - mention_end_emb = tf.gather(text_outputs, mention_ends) # [num_mentions, emb] - mention_emb_list.append(mention_end_emb) - - mention_width = 1 + mention_ends - mention_starts # [num_mentions] - if self.config["use_features"]: - mention_width_index = mention_width - 1 # [num_mentions] - 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] - mention_width_emb = tf.nn.dropout(mention_width_emb, self.dropout) - mention_emb_list.append(mention_width_emb) - - if self.config["model_heads"]: - 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] - mention_text_emb = tf.gather(text_emb, mention_indices) # [num_mentions, max_mention_width, emb] - 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] - 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] - 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] - mention_emb_list.append(mention_head_emb) - - mention_emb = tf.concat(mention_emb_list, 1) # [num_mentions, emb] - return mention_emb - - def get_mention_scores(self, mention_emb): - with tf.variable_scope("mention_scores"): - return util.ffnn(mention_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [num_mentions, 1] - - def softmax_loss(self, antecedent_scores, antecedent_labels): - gold_scores = antecedent_scores + tf.log(tf.to_float(antecedent_labels)) # [num_mentions, max_ant + 1] - marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [num_mentions] - log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [num_mentions] - return log_norm - marginalized_gold_scores # [num_mentions] - - def get_antecedent_scores(self, mention_emb, mention_scores, antecedents, antecedents_len, mention_starts, mention_ends, mention_speaker_ids, genre_emb): - num_mentions = util.shape(mention_emb, 0) - max_antecedents = util.shape(antecedents, 1) - - feature_emb_list = [] - - if self.config["use_metadata"]: - antecedent_speaker_ids = tf.gather(mention_speaker_ids, antecedents) # [num_mentions, max_ant] - same_speaker = tf.equal(tf.expand_dims(mention_speaker_ids, 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] - feature_emb_list.append(speaker_pair_emb) - - 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] - feature_emb_list.append(tiled_genre_emb) - - if self.config["use_features"]: - target_indices = tf.range(num_mentions) # [num_mentions] - 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_distance_bins.set_shape([None, None]) - 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) - - 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] - - antecedent_emb = tf.gather(mention_emb, antecedents) # [num_mentions, max_ant, emb] - target_emb_tiled = tf.tile(tf.expand_dims(mention_emb, 1), [1, max_antecedents, 1]) # [num_mentions, max_ant, emb] - similarity_emb = antecedent_emb * target_emb_tiled # [num_mentions, max_ant, emb] - - pair_emb = tf.concat([target_emb_tiled, antecedent_emb, similarity_emb, feature_emb], 2) # [num_mentions, max_ant, emb] - - with tf.variable_scope("iteration"): - with tf.variable_scope("antecedent_scoring"): - antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [num_mentions, max_ant, 1] - antecedent_scores = tf.squeeze(antecedent_scores, 2) # [num_mentions, max_ant] - - antecedent_mask = tf.log(tf.sequence_mask(antecedents_len, max_antecedents, dtype=tf.float32)) # [num_mentions, max_ant] - antecedent_scores += antecedent_mask # [num_mentions, max_ant] - - antecedent_scores += tf.expand_dims(mention_scores, 1) + tf.gather(mention_scores, 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] - return antecedent_scores # [num_mentions, max_ant + 1] - - - def flatten_emb_by_sentence(self, emb, text_len_mask): - num_sentences = tf.shape(emb)[0] - max_sentence_length = tf.shape(emb)[1] - - emb_rank = len(emb.get_shape()) - if emb_rank == 2: - flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length]) - elif emb_rank == 3: - flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)]) - else: - raise ValueError("Unsupported rank: {}".format(emb_rank)) - return tf.boolean_mask(flattened_emb, text_len_mask) - - def encode_sentences(self, text_emb, text_len, text_len_mask): - num_sentences = tf.shape(text_emb)[0] - max_sentence_length = tf.shape(text_emb)[1] - - # Transpose before and after for efficiency. - inputs = tf.transpose(text_emb, [1, 0, 2]) # [max_sentence_length, num_sentences, emb] - - with tf.variable_scope("fw_cell"): - cell_fw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout) - preprocessed_inputs_fw = cell_fw.preprocess_input(inputs) - with tf.variable_scope("bw_cell"): - cell_bw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout) - preprocessed_inputs_bw = cell_bw.preprocess_input(inputs) - preprocessed_inputs_bw = tf.reverse_sequence(preprocessed_inputs_bw, - seq_lengths=text_len, - seq_dim=0, - batch_dim=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])) - 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"): - 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: - sorted_starts = [] - sorted_ends = [] - - for k, evaluator in evaluators.items(): - if k == -3: - predicted_spans = set(zip(candidate_starts, candidate_ends)) & gold_spans - else: - if k == -2: - predicted_starts = mention_starts - predicted_ends = mention_ends - elif k == 0: - is_predicted = mention_scores > 0 - predicted_starts = candidate_starts[is_predicted] - predicted_ends = candidate_ends[is_predicted] + def __init__(self, config): + self.config = config + self.embedding_info = [(emb["size"], emb["lowercase"]) for emb in config["embeddings"]] + self.embedding_size = sum(size for size, _ in self.embedding_info) + self.char_embedding_size = config["char_embedding_size"] + 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.max_mention_width = config["max_mention_width"] + 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.append((tf.int32, [None, None, None])) # Character indices. + input_props.append((tf.int32, [None])) # Text lengths. + input_props.append((tf.int32, [None])) # Speaker IDs. + input_props.append((tf.int32, [])) # Genre. + input_props.append((tf.bool, [])) # Is training. + input_props.append((tf.int32, [None])) # Gold starts. + 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) + queue = tf.PaddingFIFOQueue(capacity=10, dtypes=dtypes, shapes=shapes) + 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.reset_global_step = tf.assign(self.global_step, 0) + learning_rate = tf.train.exponential_decay(self.config["learning_rate"], self.global_step, + self.config["decay_frequency"], self.config["decay_rate"], + staircase=True) + trainable_params = tf.trainable_variables() + gradients = tf.gradients(self.loss, trainable_params) + gradients, _ = tf.clip_by_global_norm(gradients, self.config["max_gradient_norm"]) + optimizers = { + "adam": tf.train.AdamOptimizer, + "sgd" : tf.train.GradientDescentOptimizer + } + optimizer = optimizers[self.config["optimizer"]](learning_rate) + self.train_op = optimizer.apply_gradients(zip(gradients, trainable_params), global_step=self.global_step) + + def start_enqueue_thread(self, session): + with open(self.config["train_path"]) as f: + train_examples = [json.loads(jsonline) for jsonline in f.readlines()] + + def _enqueue_loop(): + while True: + random.shuffle(train_examples) + for example in train_examples: + tensorized_example = self.tensorize_example(example, is_training=True) + feed_dict = dict(zip(self.queue_input_tensors, tensorized_example)) + session.run(self.enqueue_op, feed_dict=feed_dict) + + enqueue_thread = threading.Thread(target=_enqueue_loop) + enqueue_thread.daemon = True + enqueue_thread.start() + + def tensorize_mentions(self, mentions): + if len(mentions) > 0: + starts, ends = zip(*mentions) + else: + starts, ends = [], [] + return np.array(starts), np.array(ends) + + def tensorize_example(self, example, is_training, oov_counts=None): + clusters = example["clusters"] + + gold_mentions = sorted(tuple(m) for m in util.flatten(clusters)) + gold_mention_map = {m: i for i, m in enumerate(gold_mentions)} + cluster_ids = np.zeros(len(gold_mentions)) + for cluster_id, cluster in enumerate(clusters): + for mention in cluster: + cluster_ids[gold_mention_map[tuple(mention)]] = cluster_id + + sentences = example["sentences"] + num_words = sum(len(s) for s in sentences) + speakers = util.flatten(example["speakers"]) + + assert num_words == len(speakers) + + max_sentence_length = max(len(s) for s in sentences) + 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]) + char_index = np.zeros([len(sentences), max_sentence_length, max_word_length]) + text_len = np.array([len(s) for s in sentences]) + for i, sentence in enumerate(sentences): + for j, word in enumerate(sentence): + current_dim = 0 + for k, (d, (s, l)) in enumerate(zip(self.embedding_dicts, self.embedding_info)): + if l: + current_word = word.lower() + else: + current_word = word + if oov_counts is not None and current_word not in d: + oov_counts[k] += 1 + word_emb[i, j, current_dim:current_dim + s] = util.normalize(d[current_word]) + current_dim += s + char_index[i, j, :len(word)] = [self.char_dict[c] for c in word] + + speaker_dict = {s: i for i, s in enumerate(set(speakers))} + speaker_ids = np.array([speaker_dict[s] for s in speakers]) + + doc_key = example["doc_key"] + genre = self.genres[doc_key[:2]] + + gold_starts, gold_ends = self.tensorize_mentions(gold_mentions) + + if is_training and len(sentences) > self.config["max_training_sentences"]: + return self.truncate_example(word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, + gold_ends, cluster_ids) + else: + return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids + + def truncate_example(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, + cluster_ids): + max_training_sentences = self.config["max_training_sentences"] + num_sentences = word_emb.shape[0] + assert num_sentences > max_training_sentences + + sentence_offset = random.randint(0, num_sentences - max_training_sentences) + word_offset = text_len[:sentence_offset].sum() + num_words = text_len[sentence_offset:sentence_offset + max_training_sentences].sum() + word_emb = word_emb[sentence_offset:sentence_offset + max_training_sentences, :, :] + char_index = char_index[sentence_offset:sentence_offset + max_training_sentences, :, :] + text_len = text_len[sentence_offset:sentence_offset + max_training_sentences] + + 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) + gold_starts = gold_starts[gold_spans] - word_offset + gold_ends = gold_ends[gold_spans] - word_offset + cluster_ids = cluster_ids[gold_spans] + + return word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids + + def get_predictions_and_loss(self, word_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, + gold_ends, cluster_ids): + self.dropout = 1 - (tf.to_float(is_training) * self.config["dropout_rate"]) + self.lexical_dropout = 1 - (tf.to_float(is_training) * self.config["lexical_dropout_rate"]) + + num_sentences = tf.shape(word_emb)[0] + max_sentence_length = tf.shape(word_emb)[1] + + text_emb_list = [word_emb] + + if self.config["char_embedding_size"] > 0: + 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] + flattened_aggregated_char_emb = util.cnn(flattened_char_emb, self.config["filter_widths"], self.config[ + "filter_size"]) # [num_sentences * max_sentence_length, emb] + 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 = tf.concat(text_emb_list, 2) + text_emb = tf.nn.dropout(text_emb, self.lexical_dropout) + + text_len_mask = tf.sequence_mask(text_len, maxlen=max_sentence_length) + text_len_mask = tf.reshape(text_len_mask, [num_sentences * max_sentence_length]) + + text_outputs = self.encode_sentences(text_emb, text_len, text_len_mask) + text_outputs = tf.nn.dropout(text_outputs, self.dropout) + + genre_emb = tf.gather(tf.get_variable("genre_embeddings", [len(self.genres), self.config["feature_size"]]), + genre) # [emb] + + sentence_indices = tf.tile(tf.expand_dims(tf.range(num_sentences), 1), + [1, max_sentence_length]) # [num_sentences, max_sentence_length] + flattened_sentence_indices = self.flatten_emb_by_sentence(sentence_indices, text_len_mask) # [num_words] + flattened_text_emb = self.flatten_emb_by_sentence(text_emb, text_len_mask) # [num_words] + + candidate_starts, candidate_ends = coref_ops.spans( + sentence_indices=flattened_sentence_indices, + max_width=self.max_mention_width) + candidate_starts.set_shape([None]) + candidate_ends.set_shape([None]) + + candidate_mention_emb = self.get_mention_emb(flattened_text_emb, text_outputs, candidate_starts, + candidate_ends) # [num_candidates, emb] + candidate_mention_scores = self.get_mention_scores(candidate_mention_emb) # [num_mentions, 1] + candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [num_mentions] + + 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]) + predicted_mention_indices.set_shape([None]) + + mention_starts = tf.gather(candidate_starts, predicted_mention_indices) # [num_mentions] + mention_ends = tf.gather(candidate_ends, predicted_mention_indices) # [num_mentions] + 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] + + print('mention scores is: ',mention_scores) + 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_speaker_ids = tf.gather(speaker_ids, mention_starts) # [num_mentions] + + max_antecedents = self.config["max_antecedents"] + 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] + antecedents.set_shape([None, None]) + antecedent_labels.set_shape([None, None]) + antecedents_len.set_shape([None]) + + 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] + + loss = self.softmax_loss(antecedent_scores, antecedent_labels) # [num_mentions] + loss = tf.reduce_sum(loss) # [] + + return [candidate_starts, candidate_ends, candidate_mention_scores, mention_starts, mention_ends, antecedents, + antecedent_scores], loss + + def get_mention_emb(self, text_emb, text_outputs, mention_starts, mention_ends): + mention_emb_list = [] + + mention_start_emb = tf.gather(text_outputs, mention_starts) # [num_mentions, emb] + mention_emb_list.append(mention_start_emb) + + mention_end_emb = tf.gather(text_outputs, mention_ends) # [num_mentions, emb] + mention_emb_list.append(mention_end_emb) + + mention_width = 1 + mention_ends - mention_starts # [num_mentions] + if self.config["use_features"]: + mention_width_index = mention_width - 1 # [num_mentions] + 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] + mention_width_emb = tf.nn.dropout(mention_width_emb, self.dropout) + mention_emb_list.append(mention_width_emb) + + if self.config["model_heads"]: + 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] + mention_text_emb = tf.gather(text_emb, mention_indices) # [num_mentions, max_mention_width, emb] + 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] + 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] + 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] + mention_emb_list.append(mention_head_emb) + + mention_emb = tf.concat(mention_emb_list, 1) # [num_mentions, emb] + return mention_emb + + def get_mention_scores(self, mention_emb): + with tf.variable_scope("mention_scores"): + return util.ffnn(mention_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, + self.dropout) # [num_mentions, 1] + + def softmax_loss(self, antecedent_scores, antecedent_labels): + gold_scores = antecedent_scores + tf.log(tf.to_float(antecedent_labels)) # [num_mentions, max_ant + 1] + marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [num_mentions] + log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [num_mentions] + return log_norm - marginalized_gold_scores # [num_mentions] + + def get_antecedent_scores(self, mention_emb, mention_scores, antecedents, antecedents_len, mention_starts, + mention_ends, mention_speaker_ids, genre_emb): + num_mentions = util.shape(mention_emb, 0) + max_antecedents = util.shape(antecedents, 1) + + feature_emb_list = [] + + if self.config["use_metadata"]: + antecedent_speaker_ids = tf.gather(mention_speaker_ids, antecedents) # [num_mentions, max_ant] + same_speaker = tf.equal(tf.expand_dims(mention_speaker_ids, 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] + feature_emb_list.append(speaker_pair_emb) + + 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] + feature_emb_list.append(tiled_genre_emb) + + if self.config["use_features"]: + target_indices = tf.range(num_mentions) # [num_mentions] + 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_distance_bins.set_shape([None, None]) + 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) + + 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] + + antecedent_emb = tf.gather(mention_emb, antecedents) # [num_mentions, max_ant, emb] + target_emb_tiled = tf.tile(tf.expand_dims(mention_emb, 1), + [1, max_antecedents, 1]) # [num_mentions, max_ant, emb] + similarity_emb = antecedent_emb * target_emb_tiled # [num_mentions, max_ant, emb] + + pair_emb = tf.concat([target_emb_tiled, antecedent_emb, similarity_emb, feature_emb], + 2) # [num_mentions, max_ant, emb] + + with tf.variable_scope("iteration"): + with tf.variable_scope("antecedent_scoring"): + antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, + self.dropout) # [num_mentions, max_ant, 1] + antecedent_scores = tf.squeeze(antecedent_scores, 2) # [num_mentions, max_ant] + + antecedent_mask = tf.log( + tf.sequence_mask(antecedents_len, max_antecedents, dtype=tf.float32)) # [num_mentions, max_ant] + antecedent_scores += antecedent_mask # [num_mentions, max_ant] + + antecedent_scores += tf.expand_dims(mention_scores, 1) + tf.gather(mention_scores, + 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] + return antecedent_scores # [num_mentions, max_ant + 1] + + def flatten_emb_by_sentence(self, emb, text_len_mask): + num_sentences = tf.shape(emb)[0] + max_sentence_length = tf.shape(emb)[1] + + emb_rank = len(emb.get_shape()) + if emb_rank == 2: + flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length]) + elif emb_rank == 3: + flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)]) + else: + raise ValueError("Unsupported rank: {}".format(emb_rank)) + return tf.boolean_mask(flattened_emb, text_len_mask) + + def encode_sentences(self, text_emb, text_len, text_len_mask): + num_sentences = tf.shape(text_emb)[0] + max_sentence_length = tf.shape(text_emb)[1] + + # Transpose before and after for efficiency. + inputs = tf.transpose(text_emb, [1, 0, 2]) # [max_sentence_length, num_sentences, emb] + + with tf.variable_scope("fw_cell"): + cell_fw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout) + preprocessed_inputs_fw = cell_fw.preprocess_input(inputs) + with tf.variable_scope("bw_cell"): + cell_bw = util.CustomLSTMCell(self.config["lstm_size"], num_sentences, self.dropout) + preprocessed_inputs_bw = cell_bw.preprocess_input(inputs) + preprocessed_inputs_bw = tf.reverse_sequence(preprocessed_inputs_bw, + seq_lengths=text_len, + seq_dim=0, + batch_dim=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])) + 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"): + 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: - if k == -1: - num_predictions = len(gold_spans) - else: - num_predictions = (k * text_length) / 100 - predicted_starts = sorted_starts[:num_predictions] - predicted_ends = sorted_ends[:num_predictions] - predicted_spans = set(zip(predicted_starts, predicted_ends)) - evaluator.update(gold_set=gold_spans, predicted_set=predicted_spans) - - def get_predicted_antecedents(self, antecedents, antecedent_scores): - predicted_antecedents = [] - for i, index in enumerate(np.argmax(antecedent_scores, axis=1) - 1): - if index < 0: - predicted_antecedents.append(-1) - else: - predicted_antecedents.append(antecedents[i, index]) - return predicted_antecedents - - def get_predicted_clusters(self, mention_starts, mention_ends, predicted_antecedents): - mention_to_predicted = {} - predicted_clusters = [] - for i, predicted_index in enumerate(predicted_antecedents): - if predicted_index < 0: - continue - assert i > predicted_index - predicted_antecedent = (int(mention_starts[predicted_index]), int(mention_ends[predicted_index])) - if predicted_antecedent in mention_to_predicted: - predicted_cluster = mention_to_predicted[predicted_antecedent] - else: - predicted_cluster = len(predicted_clusters) - predicted_clusters.append([predicted_antecedent]) - mention_to_predicted[predicted_antecedent] = predicted_cluster - - mention = (int(mention_starts[i]), int(mention_ends[i])) - predicted_clusters[predicted_cluster].append(mention) - mention_to_predicted[mention] = predicted_cluster - - predicted_clusters = [tuple(pc) for pc in predicted_clusters] - mention_to_predicted = { m:predicted_clusters[i] for m,i in mention_to_predicted.items() } - - return predicted_clusters, mention_to_predicted - - def evaluate_coref(self, mention_starts, mention_ends, predicted_antecedents, gold_clusters, evaluator): - gold_clusters = [tuple(tuple(m) for m in gc) for gc in gold_clusters] - mention_to_gold = {} - for gc in gold_clusters: - for mention in gc: - mention_to_gold[mention] = gc - - predicted_clusters, mention_to_predicted = self.get_predicted_clusters(mention_starts, mention_ends, predicted_antecedents) - evaluator.update(predicted_clusters, gold_clusters, mention_to_predicted, mention_to_gold) - return predicted_clusters - - def load_eval_data(self): - if self.eval_data is None: - oov_counts = [0 for _ in self.embedding_dicts] - 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())) - num_words = sum(tensorized_example[2].sum() for tensorized_example, _ in self.eval_data) - for emb, c in zip(self.config["embeddings"], oov_counts): - print("OOV rate for {}: {:.2f}%".format(emb["path"], (100.0 * c) / num_words)) - print("Loaded {} eval examples.".format(len(self.eval_data))) - - def evaluate(self, session, 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() - - 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) - - 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)) - - 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() - summary_dict["Average F1 (py)"] = f - print "Average F1 (py): {:.2f}%".format(f * 100) - summary_dict["Average precision (py)"] = p - print "Average precision (py): {:.2f}%".format(p * 100) - summary_dict["Average recall (py)"] = r - print "Average recall (py): {:.2f}%".format(r * 100) - - return util.make_summary(summary_dict), average_f1 + sorted_starts = [] + sorted_ends = [] + + for k, evaluator in evaluators.items(): + if k == -3: + predicted_spans = set(zip(candidate_starts, candidate_ends)) & gold_spans + else: + if k == -2: + predicted_starts = mention_starts + predicted_ends = mention_ends + elif k == 0: + is_predicted = mention_scores > 0 + predicted_starts = candidate_starts[is_predicted] + predicted_ends = candidate_ends[is_predicted] + else: + if k == -1: + num_predictions = len(gold_spans) + else: + num_predictions = (k * text_length) / 100 + predicted_starts = sorted_starts[:num_predictions] + predicted_ends = sorted_ends[:num_predictions] + predicted_spans = set(zip(predicted_starts, predicted_ends)) + evaluator.update(gold_set=gold_spans, predicted_set=predicted_spans) + + def get_predicted_antecedents(self, antecedents, antecedent_scores): + predicted_antecedents = [] + for i, index in enumerate(np.argmax(antecedent_scores, axis=1) - 1): + if index < 0: + predicted_antecedents.append(-1) + else: + predicted_antecedents.append(antecedents[i, index]) + return predicted_antecedents + + def get_predicted_clusters(self, mention_starts, mention_ends, predicted_antecedents): + mention_to_predicted = {} + predicted_clusters = [] + for i, predicted_index in enumerate(predicted_antecedents): + if predicted_index < 0: + continue + assert i > predicted_index + predicted_antecedent = (int(mention_starts[predicted_index]), int(mention_ends[predicted_index])) + if predicted_antecedent in mention_to_predicted: + predicted_cluster = mention_to_predicted[predicted_antecedent] + else: + predicted_cluster = len(predicted_clusters) + predicted_clusters.append([predicted_antecedent]) + mention_to_predicted[predicted_antecedent] = predicted_cluster + + mention = (int(mention_starts[i]), int(mention_ends[i])) + predicted_clusters[predicted_cluster].append(mention) + mention_to_predicted[mention] = predicted_cluster + + predicted_clusters = [tuple(pc) for pc in predicted_clusters] + mention_to_predicted = {m: predicted_clusters[i] for m, i in mention_to_predicted.items()} + + return predicted_clusters, mention_to_predicted + + def evaluate_coref(self, mention_starts, mention_ends, predicted_antecedents, gold_clusters, evaluator): + gold_clusters = [tuple(tuple(m) for m in gc) for gc in gold_clusters] + mention_to_gold = {} + for gc in gold_clusters: + for mention in gc: + mention_to_gold[mention] = gc + + predicted_clusters, mention_to_predicted = self.get_predicted_clusters(mention_starts, mention_ends, + predicted_antecedents) + evaluator.update(predicted_clusters, gold_clusters, mention_to_predicted, mention_to_gold) + return predicted_clusters + + def load_eval_data(self): + if self.eval_data is None: + oov_counts = [0 for _ in self.embedding_dicts] + 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())) + num_words = sum(tensorized_example[2].sum() for tensorized_example, _ in self.eval_data) + for emb, c in zip(self.config["embeddings"], oov_counts): + print("OOV rate for {}: {:.2f}%".format(emb["path"], (100.0 * c) / num_words)) + print("Loaded {} eval examples.".format(len(self.eval_data))) + + def evaluate(self, session, 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() + + 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) + + 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)) + + 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 diff --git a/evaluate_single_sentence_score.py b/evaluate_single_sentence_score.py new file mode 100644 index 0000000..7658e5f --- /dev/null +++ b/evaluate_single_sentence_score.py @@ -0,0 +1,92 @@ +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])) diff --git a/evaluator.py b/evaluator.py index 0bea170..2931be1 100755 --- a/evaluator.py +++ b/evaluator.py @@ -3,65 +3,74 @@ import os import re import sys + sys.path.append(os.getcwd()) -import time -import random import shutil -import numpy as np +import coref_mermaid_model as cmm import tensorflow as tf -import coref_model as cm import util + def copy_checkpoint(source, target): - for ext in (".index", ".data-00000-of-00001"): - shutil.copyfile(source + ext, target + ext) + for ext in (".index", ".data-00000-of-00001"): + shutil.copyfile(source + ext, target + ext) + 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: - 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) + util.print_config(config) + # model = cm.CorefModel(config) - config = util.get_config("experiments.conf")[name] - config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name)) + sub_values = [1.25, 1.5,1.75,2.5,3.5,4,4.5] + for sub_value in sub_values: + tf.reset_default_graph() + model = cmm.CorefMermaidModel(config) - util.print_config(config) - model = cm.CorefModel(config) + saver = tf.train.Saver() + 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() - 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") + with tf.Session() as session: + ckpt = tf.train.get_checkpoint_state(log_dir) + if ckpt and ckpt.model_checkpoint_path and ckpt.model_checkpoint_path not in evaluated_checkpoints: + print("Evaluating {}".format(ckpt.model_checkpoint_path)) - with tf.Session() as session: - while True: - ckpt = tf.train.get_checkpoint_state(log_dir) - 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. + tmp_checkpoint_path = os.path.join(log_dir, "model.tmp.ckpt") + copy_checkpoint(ckpt.model_checkpoint_path, tmp_checkpoint_path) - # Move it to a temporary location to avoid being deleted by the training supervisor. - tmp_checkpoint_path = os.path.join(log_dir, "model.tmp.ckpt") - copy_checkpoint(ckpt.model_checkpoint_path, tmp_checkpoint_path) + global_step = int(checkpoint_pattern.match(ckpt.model_checkpoint_path).group(1)) + saver.restore(session, ckpt.model_checkpoint_path) - global_step = int(checkpoint_pattern.match(ckpt.model_checkpoint_path).group(1)) - saver.restore(session, ckpt.model_checkpoint_path) + eval_summary, f1, average_precion, average_recall = model.evaluate(session, sub_value) - 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: - max_f1 = f1 - copy_checkpoint(tmp_checkpoint_path, os.path.join(log_dir, "model.max.ckpt")) + print("Current max F1: {:.2f}".format(max_f1)) - print "Current max F1: {:.2f}".format(max_f1) + writer.add_summary(eval_summary, global_step) - writer.add_summary(eval_summary, global_step) - print "Evaluation written to {} at step {}".format(log_dir, global_step) + with open('./precision_recall.txt', 'a') as f: + 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) diff --git a/experiments.conf b/experiments.conf index 3239242..f9429af 100644 --- a/experiments.conf +++ b/experiments.conf @@ -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`. final = ${best} { embeddings = [${glove_300d}, ${turian_50d}] - eval_path = test.english.jsonlines + eval_path = eval_file conll_eval_path = test.english.v4_gold_conll } diff --git a/metrics.py b/metrics.py index f2a5439..022c210 100644 --- a/metrics.py +++ b/metrics.py @@ -20,17 +20,36 @@ class CorefEvaluator(object): e.update(predicted, gold, mention_to_predicted, mention_to_gold) 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): - 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): - 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): 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): def __init__(self, metric, beta=1): self.p_num = 0 diff --git a/minimize.py b/minimize.py index b5bbc67..ab12484 100755 --- a/minimize.py +++ b/minimize.py @@ -11,132 +11,168 @@ import collections import util import conll + class DocumentState(object): - def __init__(self): - self.doc_key = None - self.text = [] - self.text_speakers = [] - self.speakers = [] - self.sentences = [] - self.clusters = collections.defaultdict(list) - self.stacks = collections.defaultdict(list) - - def assert_empty(self): - assert self.doc_key is None - assert len(self.text) == 0 - assert len(self.text_speakers) == 0 - assert len(self.sentences) == 0 - assert len(self.speakers) == 0 - assert len(self.clusters) == 0 - assert len(self.stacks) == 0 - - def assert_finalizable(self): - assert self.doc_key is not None - assert len(self.text) == 0 - assert len(self.text_speakers) == 0 - assert len(self.sentences) > 0 - assert len(self.speakers) > 0 - assert all(len(s) == 0 for s in self.stacks.values()) - - def finalize(self): - merged_clusters = [] - for c1 in self.clusters.values(): - existing = None - for m in c1: - for c2 in merged_clusters: - if m in c2: - existing = c2 - break - if existing is not None: - break - if existing is not None: - print("Merging clusters (shouldn't happen very often.)") - existing.update(c1) - else: - merged_clusters.append(set(c1)) - merged_clusters = [list(c) for c in merged_clusters] - all_mentions = util.flatten(merged_clusters) - assert len(all_mentions) == len(set(all_mentions)) - - return { - "doc_key": self.doc_key, - "sentences": self.sentences, - "speakers": self.speakers, - "clusters": merged_clusters - } + def __init__(self): + self.doc_key = None + self.text = [] + self.text_speakers = [] + self.speakers = [] + self.sentences = [] + self.clusters = collections.defaultdict(list) + self.stacks = collections.defaultdict(list) + + def assert_empty(self): + assert self.doc_key is None + assert len(self.text) == 0 + assert len(self.text_speakers) == 0 + assert len(self.sentences) == 0 + assert len(self.speakers) == 0 + assert len(self.clusters) == 0 + assert len(self.stacks) == 0 + + def assert_finalizable(self): + assert self.doc_key is not None + assert len(self.text) == 0 + assert len(self.text_speakers) == 0 + assert len(self.sentences) > 0 + assert len(self.speakers) > 0 + assert all(len(s) == 0 for s in self.stacks.values()) + + def finalize(self): + merged_clusters = [] + for c1 in self.clusters.values(): + existing = None + for m in c1: + for c2 in merged_clusters: + if m in c2: + existing = c2 + break + if existing is not None: + break + if existing is not None: + print("Merging clusters (shouldn't happen very often.)") + existing.update(c1) + else: + merged_clusters.append(set(c1)) + merged_clusters = [list(c) for c in merged_clusters] + all_mentions = util.flatten(merged_clusters) + assert len(all_mentions) == len(set(all_mentions)) + + return { + "doc_key" : self.doc_key, + "sentences": self.sentences, + "speakers" : self.speakers, + "clusters" : merged_clusters + } + def normalize_word(word): - if word == "/." or word == "/?": - return word[1:] - else: - return word + if word == "/." or word == "/?": + return word[1:] + else: + return word + def handle_line(line, document_state): - begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line) - if begin_document_match: - document_state.assert_empty() - document_state.doc_key = conll.get_doc_key(begin_document_match.group(1), begin_document_match.group(2)) - return None - elif line.startswith("#end document"): - document_state.assert_finalizable() - return document_state.finalize() - else: - row = line.split() - if len(row) == 0: - document_state.sentences.append(tuple(document_state.text)) - del document_state.text[:] - document_state.speakers.append(tuple(document_state.text_speakers)) - del document_state.text_speakers[:] - return None - assert len(row) >= 12 - - word = normalize_word(row[3]) - coref = row[-1] - doc_key = conll.get_doc_key(row[0], row[1]) - speaker = row[9] - - word_index = len(document_state.text) + sum(len(s) for s in document_state.sentences) - document_state.text.append(word) - document_state.text_speakers.append(speaker) - - if coref == "-": - return None - - for segment in coref.split("|"): - if segment[0] == "(": - if segment[-1] == ")": - cluster_id = int(segment[1:-1]) - document_state.clusters[cluster_id].append((word_index, word_index)) - else: - cluster_id = int(segment[1:]) - document_state.stacks[cluster_id].append(word_index) - else: - cluster_id = int(segment[:-1]) - start = document_state.stacks[cluster_id].pop() - document_state.clusters[cluster_id].append((start, word_index)) - return None + begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line) + if begin_document_match: + document_state.assert_empty() + document_state.doc_key = conll.get_doc_key(begin_document_match.group(1), begin_document_match.group(2)) + return None + elif line.startswith("#end document"): + document_state.assert_finalizable() + return document_state.finalize() + else: + row = line.split() + if len(row) == 0: + document_state.sentences.append(tuple(document_state.text)) + del document_state.text[:] + document_state.speakers.append(tuple(document_state.text_speakers)) + del document_state.text_speakers[:] + return None + assert len(row) >= 12 + + word = normalize_word(row[3]) + coref = row[-1] + doc_key = conll.get_doc_key(row[0], row[1]) + speaker = row[9] + + word_index = len(document_state.text) + sum(len(s) for s in document_state.sentences) + document_state.text.append(word) + document_state.text_speakers.append(speaker) + + if coref == "-": + return None + + for segment in coref.split("|"): + if segment[0] == "(": + if segment[-1] == ")": + cluster_id = int(segment[1:-1]) + document_state.clusters[cluster_id].append((word_index, word_index)) + else: + cluster_id = int(segment[1:]) + document_state.stacks[cluster_id].append(word_index) + else: + cluster_id = int(segment[:-1]) + start = document_state.stacks[cluster_id].pop() + document_state.clusters[cluster_id].append((start, word_index)) + return None + def minimize_partition(name, language, extension): - input_path = "{}.{}.{}".format(name, language, extension) - output_path = "{}.{}.jsonlines".format(name, language) - count = 0 - print "Minimizing {}".format(input_path) - with open(input_path, "r") as input_file: - with open(output_path, "w") as output_file: - document_state = DocumentState() - for line in input_file.readlines(): - document = handle_line(line, document_state) - if document is not None: - output_file.write(json.dumps(document)) - output_file.write("\n") - count += 1 - document_state = DocumentState() - print "Wrote {} documents to {}".format(count, output_path) + input_path = "{}.{}.{}".format(name, language, extension) + output_path = "{}.{}.jsonlines".format(name, language) + count = 0 + print(input_path) + print "minimizing {}".format(input_path) + with open(input_path, "r") as input_file: + with open(output_path, "w") as output_file: + document_state = DocumentState() + for line in input_file.readlines(): + begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line) + if begin_document_match: + document_state = DocumentState() + document = handle_line(line, document_state) + if document is not None: + 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 +Flaskr + +
+

Flaskr

+
+
+ +
+
+ {% for message in get_flashed_messages() %} +
{{ message }}
+ {% endfor %} + {% block body %}{% endblock %} +
diff --git a/util.py b/util.py index 7a0061c..09ca6a2 100644 --- a/util.py +++ b/util.py @@ -49,6 +49,7 @@ def load_embedding_dict(embedding_path, embedding_size, embedding_format): if skip_first and i == 0: continue splits = line.split() + assert len(splits) == embedding_size + 1 word = splits[0] embedding = np.array([float(s) for s in splits[1:]])