code
stringlengths
17
6.64M
def get_plot_params(plot_params, show_score_diffs, diff): defaults = {'all_pos_contributions': False, 'alpha_fade': 0.35, 'bar_linewidth': 0.25, 'bar_type_space_scaling': 0.015, 'bar_width': 0.8, 'cumulative_xlabel': None, 'cumulative_xticklabels': None, 'cumulative_xticks': None, 'cumulative_ylabel': None, 'deta...
def set_serif(): rcParams['font.family'] = 'serif' rcParams['mathtext.fontset'] = 'dejavuserif'
def get_bar_dims(type_scores, norm, plot_params): "\n Gets the height and location of every bar needed to plot each type's\n contribution.\n\n Parameters\n ----------\n type_scores: list of tuples\n List of tuples of the form (type,p_diff,s_diff,p_avg,s_ref_diff,shift_score)\n for eve...
def get_bar_colors(type_scores, plot_params): "\n Returns the component colors of each type's contribution bars.\n\n Parameters\n ----------\n type_scores: list of tuples\n List of tuples of the form (type,p_diff,s_diff,p_avg,s_ref_diff,shift_score)\n for every type scored in the two sys...
def plot_contributions(ax, top_n, bar_dims, bar_colors, plot_params): '\n Plots all of the type contributions as horizontal bars\n\n Parameters\n ----------\n ax: Matplotlib ax\n Current ax of the shift graph\n top_n: int\n The number of types being plotted on the shift graph\n bar...
def get_bar_order(plot_params): '\n Gets which cumulative bars to show at the top of the graph given what level\n of detail is being specified\n\n Parameters\n ----------\n plot_params: dict\n Dictionary of plotting parameters. Here, `all_pos_contributions`,\n `detailed`, `show_score_...
def plot_total_contribution_sums(ax, total_comp_sums, bar_order, top_n, bar_dims, plot_params): '\n Plots the cumulative contribution bars at the top of the shift graph\n\n Parameters\n ----------\n ax: Matplotlib ax\n Current ax of the shift graph\n total_comp_sums: dict\n Dictionary...
def get_bar_type_space(ax, plot_params): '\n Gets the amount of space to place in between the ends of bars and labels\n ' x_width = (2 * abs(max(ax.get_xlim(), key=(lambda x: abs(x))))) bar_type_space = (plot_params['bar_type_space_scaling'] * x_width) return bar_type_space
def set_bar_labels(ax, top_n, type_labels, full_bar_heights, comp_bar_heights, plot_params): "\n Sets the labels on the end of each type's contribution bar\n\n Parameters\n ----------\n ax: Matplotlib ax\n Current ax of the shift graph\n top_n: int\n The number of types being plotted ...
def adjust_axes_for_labels(ax, bar_ends, comp_bars, text_objs, bar_type_space, plot_params): '\n Attempts to readjusts the axes to account for newly plotted labels\n\n Parameters\n ----------\n ax: Matplotlib ax\n Current ax of the shift graph\n bar_ends: list of floats\n List of heig...
def set_ticks(ax, top_n, plot_params): '\n Sets ticks and tick labels of the shift graph\n\n Parameters\n ----------\n ax: Matplotlib ax\n Current ax of the shift graph\n top_n: int\n The number of types being plotted on the shift graph\n plot_parms: dict\n Dictionary of plo...
def set_spines(ax, plot_params): '\n Sets spines of the shift graph to be invisible if chosen by the user\n\n Parameters\n ----------\n ax: Matplotlib ax\n Current ax of the shift graph\n plot_parms: dict\n Dictionary of plotting parameters. Here `invisible_spines` is used\n ' ...
def remove_yaxis_ticks(ax, major=True, minor=True): '\n Removes all y-axis ticks on the shift graph\n ' if major: for tic in ax.yaxis.get_major_ticks(): tic.tick1line.set_visible(False) tic.tick2line.set_visible(False) if minor: for tic in ax.yaxis.get_minor_t...
def remove_xaxis_ticks(ax, major=True, minor=True): '\n Removes all x-axis ticks on the shift graph\n ' if major: for tic in ax.xaxis.get_major_ticks(): tic.tick1line.set_visible(False) tic.tick2line.set_visible(False) if minor: for tic in ax.xaxis.get_minor_t...
def get_cumulative_inset(f, type2shift_score, top_n, normalization, plot_params): "\n Plots the cumulative contribution inset on the shift graph\n\n Parameters\n ----------\n f: Matpotlib figure\n Current figure of the shift graph\n type2shift_score: dict\n Keys are types and values a...
def get_text_size_inset(f, type2freq_1, type2freq_2, plot_params): '\n Plots the relative text size inset on the shift graph\n\n Parameters\n ----------\n f: Matpotlib figure\n Current figure of the shift graph\n type2freq_1, type2freq_2: dict\n Keys are types, values are their freque...
class Shift(): "\n Shift object for calculating weighted scores of two systems of types,\n and the shift between them\n\n Parameters\n ----------\n type2freq_1, type2freq_2: dict\n Keys are types of a system and values are frequencies of those types\n type2score_1, type2score_2: dict or s...
class WeightedAvgShift(Shift): "\n Shift object for calculating weighted scores of two systems of types,\n and the shift between them\n\n Parameters\n ----------\n type2freq_1, type2freq_2: dict\n Keys are types of a system and values are frequencies of those types\n type2score_1, type2sc...
class ProportionShift(Shift): '\n Shift object for calculating differences in proportions of types across two\n systems\n\n Parameters\n __________\n type2freq_1, type2freq_2: dict\n Keys are types of a system and values are frequencies of those types\n ' def __init__(self, type2freq...
class EntropyShift(Shift): "\n Shift object for calculating the shift in entropy between two systems\n\n Parameters\n ----------\n type2freq_1, type2freq_2: dict\n Keys are types of a system and values are frequencies of those types\n base: float, optional\n Base of the logarithm for ...
class KLDivergenceShift(Shift): "\n Shift object for calculating the Kullback-Leibler divergence (KLD) between\n two systems\n\n Parameters\n ----------\n type2freq_1, type2freq_2: dict\n Keys are types of a system and values are frequencies of those types.\n The KLD will be computed ...
class JSDivergenceShift(Shift): "\n Shift object for calculating the Jensen-Shannon divergence (JSD) between two\n systems\n\n Parameters\n ----------\n type2freq_1, type2freq_2: dict\n Keys are types of a system and values are frequencies of those types\n weight_1, weight_2: float\n ...
def test_jsd_shift_1(): shift = JSDivergenceShift(system_1_a, system_2_a) shift.get_shift_graph(system_names=['1A', '2A'])
def test_entropy_shift_1(): shift = EntropyShift(system_1_a, system_2_a) shift.get_shift_graph(system_names=['1A', '2A'])
def test_tsallis_shift_plus_1(): shift = EntropyShift(system_1_a, system_2_a, alpha=2) shift.get_shift_graph(system_names=['1A', '2A'])
def test_tsallis_shift_minus_1(): shift = EntropyShift(system_1_a, system_2_a, alpha=0.5) shift.get_shift_graph(system_names=['1A', '2A'])
def test_jsd_shift_2(): shift = JSDivergenceShift(system_1_b, system_2_b) shift.get_shift_graph(system_names=['1B', '2B'])
def test_entropy_shift_2(): shift = EntropyShift(system_1_b, system_2_b) shift.get_shift_graph(system_names=['1B', '2B'])
def test_tsallis_shift_plus_2(): shift = EntropyShift(system_1_b, system_2_b, alpha=2) shift.get_shift_graph(system_names=['1B', '2B'])
def test_tsallis_shift_minus_2(): shift = EntropyShift(system_1_b, system_2_b, alpha=0.5) shift.get_shift_graph(system_names=['1B', '2B'])
class EvaluationTap(Tap): dataset_test_path: str dataset_dev_path: str prediction_test_path: str prediction_dev_path: str evaluate_bootstrap: bool = False filtering: Optional[str] = None document_level: bool = False
def binarize_scores(threshold: float, scores: list[float]) -> list[int]: return (np.array(scores) > threshold).astype(int).tolist()
def get_evaluation_scores(score_name: Literal[('f1', 'accuracy', 'balanced_accuracy')], test_labels: list[int], dev_labels: list[int], test_scores: list[float], dev_scores: list[float], provided_threshold: Optional[float]=None, threshold_min: float=0.0, threshold_max: float=1.0) -> dict: threshold: float = 0.0 ...
def filter_prediction(datasets: dict[(DevTest, list[RawData])], predictions: dict[(DevTest, dict[(str, dict)])], filtering_type: Optional[str]=None) -> tuple[(dict[(DevTest, list[RawData])], dict[(DevTest, dict[(str, dict)])])]: 'This filtering is not used in the final version of WiCE paper.' if (filtering_ty...
def convert_to_document_level(predictions: dict[(str, float)]): output_dict: dict[(str, float)] = {} for (sentence_id, score) in predictions.items(): article_id = '_'.join(sentence_id.split('_')[:(- 1)]) if (article_id in output_dict.keys()): output_dict[article_id] = min(output_di...
def make_prediction_list(datasets: dict[(DevTest, list[RawData])], predictions: dict[(DevTest, dict[(str, dict)])]) -> tuple[(dict[(DevTest, list[int])], dict[(DevTest, list[float])])]: 'Convert dataset and predictions to list of labels and scores.' scores_dict_of_list: dict[(DevTest, list[float])] = {} l...
def get_list_of_prediction_scores_for_target_labels(target_labels: list[int], label_list: list[int], score_list: list[float]) -> list[float]: 'Get list of prediction scores for target labels.' output_list: list[float] = [] for (idx, score) in enumerate(score_list): if (label_list[idx] in target_la...
def evaluate_entailment_classification(labels_dict_of_list: dict[(DevTest, list[int])], scores_dict_of_list: dict[(DevTest, list[float])], provided_thresholds_dict: Optional[dict]=None): evaluation_output: dict = {'label_distribution': {}, 'roc': {}, 'f1': {}, 'accuracy': {}, 'balanced_accuracy': {}} for labe...
def get_article_for_bootstrap(dataset: list[dict], article_ids_list: list[str]) -> list[dict]: 'Get article data for bootstrap.' dataset_id_to_data: dict[(str, dict)] = {} for d in dataset: dataset_id_to_data[d['meta']['id']] = d output_list = [] for article_id in article_ids_list: ...
class PostprocessTap(Tap): entailment_input_jsonl_path: str prediction_txt_path: str evaluation_num: int = 100
class GPTEvalTap(Tap): model: Literal[('gpt-3.5-turbo-0613', 'gpt-4-0613')] claim_subclaim: Literal[('claim', 'subclaim')] split: Literal[('dev', 'test')] = 'test' evaluation_num: int = 100
def process_gpt_output(gpt_output: dict) -> float: 'Postprocess the output and get the entailment score {"supported": 1.0, "partially_supported": 0.5, "not_supported": 0.0, "invalid": -1.0}\n The input format is {"prompt": prompt (str), "response": response from gpt (str)}' try: response: str = gpt...
def get_gpt_prompt(claim: str, evidence_list: list[str], line_idx: list[int]) -> str: assert (len(evidence_list) == len(line_idx)), f'{len(evidence_list)} != {len(line_idx)}, {line_idx}' evidence_string = '\n'.join([f' <sentence_{idx}>{line}</sentence_{idx}>' for (idx, line) in zip(line_idx, evidence_l...
class PreprocessTap(Tap): split: str claim_type: Literal[('claim', 'subclaim')] word_num_in_chunk: int = 256 add_claim_context: bool = False add_evidence_context: bool = False dataset_dir: Path = Path('../../data/entailment_retrieval/') output_dir: Path = Path('../entailment_inputs/') ...
def split_into_chunks(article_sentences: list[str], article_indices: list[int], word_num_in_chunk: int) -> Chunks: 'Split article (list of sentences) into overlapping chunks. This function does not split in the middle of sentences.\n\n Args:\n article_sentences (list[str]): list of sentences in an artic...
def get_chunk_label(article_label: ThreeLabels, supporting_sentences_list: list[list[int]], chunk_idx_list: list[int]) -> ThreeLabels: 'Get chunk label based on the article label and supporting sentences.' if (article_label == 'not_supported'): return 'not_supported' partially_supported: bool = Fa...
def get_chunk_stats(chunks_list: list[ProcessedData]): labels_list: list[str] = [] for d in chunks_list: labels_list.append(d['label']) counter = Counter(labels_list) output_dict: dict[(str, int)] = {} for label_name in ['supported', 'partially_supported', 'not_supported']: output_...
def get_balanced_output_list_for_evidence_context_data(output_list: list[ProcessedData]): 'If args.add_evidence_context, we only include sentences. Therefore, there will be too many non-supported cases.\n We make a balanced dataset by randomly sample (discard) non-supported cases.\n ' label_split = {'su...
def check_oracle_chunk(chunk_idx: list[int], oracle_idx: list[int]) -> bool: 'chunk_idx is a list of sentence indices in a chunk that will be used as the oracle set. oracle_idx is the ground truth oracle idx.\n \n This function check the following property: \n If len(chunk_idx) >= len(oracle_idx), all el...
class RawData(TypedDict): label: ThreeLabels supporting_sentences: list[list[int]] claim: str evidence: list[str] meta: dict
class Chunks(TypedDict): chunks_list: list[list[str]] sentence_idx_list: list[list[int]]
class ProcessedData(TypedDict): label: str claim: str evidence: str meta: dict[(str, str)]
@nox.session def format(session): session.run('yapf', '-i', '-p', '--recursive', 'utils', external=True) session.notify('lint')
@nox.session def format_check(session): assert session.run('yapf', '-d', '-p', '--recursive', 'utils', external=True)
@nox.session def lint(session): session.run('pylint', 'utils/', external=True) session.notify('type_check')
@nox.session def type_check(session): session.run('mypy', 'utils/', external=True)
def get_mutator_so_path(database): if (database == 'mariadb'): database = 'mysql' return f'{ROOTPATH}/build/lib{database}_mutator.so'
def get_config_path(database): return f'{ROOTPATH}/data/config_{database}.yml'
def set_env(database): os.environ['AFL_CUSTOM_MUTATOR_ONLY'] = '1' os.environ['AFL_DISABLE_TRIM'] = '1' os.environ['AFL_FAST_CAL'] = '1' os.environ['AFL_CUSTOM_MUTATOR_LIBRARY'] = get_mutator_so_path(database) os.environ['SQUIRREL_CONFIG'] = get_config_path(database)
def run(database, input_dir, output_dir=None, config_file=None, fuzzer=None): if (database not in DBMS): print(f'Unsupported database. The supported ones are {DBMS}') return if (not output_dir): output_dir = '/tmp/fuzz' if (not config_file): config_file = get_config_path(da...
def read_json_line(path): output = [] with open(path, 'r') as f: for line in f: output.append(json.loads(line)) return output
def write_json_line(data, path): with open(path, 'w') as f: for i in data: f.write(('%s\n' % json.dumps(i))) return None
def acquire_from_twitter_api(input_data): auth = tweepy.OAuthHandler(args.API_key, args.API_secret_key) auth.set_access_token(args.access_token, args.access_token_secret) api = tweepy.API(auth, parser=tweepy.parsers.JSONParser(), wait_on_rate_limit=True) tweets_by_API = [] wrong_ones = [] for ...
def writeJSONLine(data, path): with open(path, 'w') as f: for i in data: f.write(('%s\n' % json.dumps(i))) return None
def read_jsonl_datafile(data_file): data_instances = [] with open(data_file, 'r') as reader: for line in reader: line = line.strip() if line: data_instances.append(json.loads(line)) return data_instances
def get_label_for_key_from_annotation(key, annotation, candidate_chunk): tagged_chunks = annotation[key] label = 0 if tagged_chunks: if ((key in ['name', 'who_cure', 'close_contact', 'opinion']) and (('I' in tagged_chunks) or ('i' in tagged_chunks))): tagged_chunks.append('AUTHOR OF TH...
def get_tagged_label_for_key_from_annotation(key, annotation): tagged_chunks = annotation[key] return tagged_chunks
def get_label_from_tagged_label(tagged_label): if (tagged_label == 'Not Specified'): return 0 elif (tagged_label == 'Yes'): return 1 elif (tagged_label == 'Male'): return 1 elif (tagged_label == 'Female'): return 1 elif tagged_label.startswith('no_cure'): re...
def find_text_to_tweet_tokens_mapping(text, tweet_tokens): current_tok = 0 current_tok_c_pos = 0 n_toks = len(tweet_tokens) tweet_toks_c_mapping = [list()] for (c_pos, c) in enumerate(text): if c.isspace(): continue if (current_tok_c_pos == len(tweet_tokens[current_tok]...
def get_tweet_tokens_from_tags(tags): tokens = [e.rsplit('/', 3)[0] for e in tags.split()] return ' '.join(tokens)
def make_instances_from_dataset(dataset): task_instances_dict = dict() question_keys_and_tags = list() dummy_annotation = dataset[0]['annotation'] for key in dummy_annotation.keys(): if (key.startswith('part2-') and key.endswith('.Response')): question_tag = key.replace('part2-', '...
def main(): logging.info(f'Reading annotations from {args.data_file} file...') dataset = read_jsonl_datafile(args.data_file) logging.info(f'Total annotations:{len(dataset)}') logging.info(f'Creating labeled data instances from annotations...') print(dataset[0].keys()) (task_instances_dict, tag...
def print_list(l): for e in l: print(e) print()
def log_list(l): for e in l: logging.info(e) logging.info('')
def save_in_pickle(save_object, save_file): with open(save_file, 'wb') as pickle_out: pickle.dump(save_object, pickle_out)
def load_from_pickle(pickle_file): with open(pickle_file, 'rb') as pickle_in: return pickle.load(pickle_in)
def save_in_json(save_dict, save_file): with open(save_file, 'w') as fp: json.dump(save_dict, fp)
def load_from_json(json_file): with open(json_file, 'r') as fp: return json.load(fp)
def read_json_line(path): output = [] with open(path, 'r') as f: for line in f: output.append(json.loads(line)) return output
def write_json_line(data, path): with open(path, 'w') as f: for i in data: f.write(('%s\n' % json.dumps(i))) return None
def make_dir_if_not_exists(directory): if (not os.path.exists(directory)): logging.info('Creating new directory: {}'.format(directory)) os.makedirs(directory)
def extract_instances_for_current_subtask(task_instances, sub_task): return task_instances[sub_task]
def get_multitask_instances_for_valid_tasks(task_instances, tag_statistics): subtasks = list() for subtask in task_instances.keys(): current_question_tag_statistics = tag_statistics[0][subtask] if ((len(current_question_tag_statistics) > 1) and (current_question_tag_statistics[1] >= MIN_POS_SA...
def split_multitask_instances_in_train_dev_test(multitask_instances, TRAIN_RATIO=0.6, DEV_RATIO=0.15): original_tweets = dict() original_tweets_list = list() for (tweet, _, _, _, _, _, _, _) in multitask_instances: if (tweet not in original_tweets): original_tweets[tweet] = 1 ...
def split_instances_in_train_dev_test(instances, TRAIN_RATIO=0.6, DEV_RATIO=0.15): original_tweets = dict() original_tweets_list = list() for (tweet, _, _, _, _, _, _, _, _) in instances: if (tweet not in original_tweets): original_tweets[tweet] = 1 original_tweets_list.app...
def log_data_statistics(data): logging.info(f'Total instances in the data = {len(data)}') pos_count = sum((label for (_, _, _, _, _, _, _, _, label) in data)) logging.info(f'Positive labels = {pos_count} Negative labels = {(len(data) - pos_count)}') return (len(data), pos_count, (len(data) - pos_count...
def normalize_answer(s): 'Lower text and remove punctuation, articles and extra whitespace.' def remove_articles(text): regex = re.compile('\\b(a|an|the)\\b', re.UNICODE) return re.sub(regex, ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc...
def get_tokens(s): if (not s): return [] return normalize_answer(s).split()
def compute_exact(a_gold, a_pred): return int((normalize_answer(a_gold) == normalize_answer(a_pred)))
def compute_f1(a_gold, a_pred): gold_toks = get_tokens(a_gold) pred_toks = get_tokens(a_pred) common = (collections.Counter(gold_toks) & collections.Counter(pred_toks)) num_same = sum(common.values()) if ((len(gold_toks) == 0) or (len(pred_toks) == 0)): return int((gold_toks == pred_toks))...
def get_raw_scores(data, prediction_scores, positive_only=False): predicted_chunks_for_each_instance = dict() for ((text, chunk, chunk_id, chunk_start_text_id, chunk_end_text_id, tokenized_tweet, tokenized_tweet_with_masked_chunk, gold_chunk, label), prediction_score) in zip(data, prediction_scores): ...
def get_TP_FP_FN(data, prediction_scores, THRESHOLD=0.5): predicted_chunks_for_each_instance = dict() for ((text, chunk, chunk_id, chunk_start_text_id, chunk_end_text_id, tokenized_tweet, tokenized_tweet_with_masked_chunk, gold_chunk, label), prediction_score) in zip(data, prediction_scores): original...
def read_json_line(path): output = [] with open(path, 'r') as f: for line in f: output.append(json.loads(line)) return output
def main(): system_predictions = read_json_line(args.prediction) golden_predictions = read_json_line(args.golden) golden_predictions_dict = {} for each_line in golden_predictions: golden_predictions_dict[each_line['id']] = each_line question_tag = golden_predictions[0]['golden_annotation']...
def read_json_line(path): output = [] with open(path, 'r') as f: for line in f: output.append(json.loads(line)) return output
def format_checker_each_file(category, input_data_path): print('[I] Checking', category.upper(), 'category') try: input_data = read_json_line(input_data_path) except: input_data = None print('[ERROR] check your file format, should be .jsonl') assert (len(input_data) == 500), 'c...
def format_checker(input_folder_path): input_files = glob.glob((input_folder_path + '*.jsonl')) assert (len(input_files) == 5), 'missing prediction files - should be 5 files' for each_file in input_files: curr_category_name = each_file.split('/')[(- 1)].split('-')[(- 1)].replace('.jsonl', '') ...
def calPR(true_label, conf_score): '\n calculate precision / recall curve\n :param true_label: true labels\n :param conf_score: predictions scores\n :return: precision, recall values\n ' combine = [] for i in range(len(true_label)): combine.append((conf_score[i], true_label[i])) ...
def printTopFeatures(train_ngram_dict, lr): '\n evaluate top ranked features for logistic regression\n :param train_ngram_dict: trained n-gram dictionary\n :param lr: trained lr model\n :return: None\n ' train_ngram_dict_reverse = {} for i in train_ngram_dict.items(): train_ngram_di...
def convertToSparseMatrix(features_idx, features_dict): '\n convert feature idx matrix in to sparse matrix\n :param features_idx: [list] original feature idx matrix\n :param features_dict: [dict] train_ngram_dict (for determine the dimension)\n :return: [dict] sparse matrix tuple\n ' location =...