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