code
stringlengths
17
6.64M
def set_template(args): if (args.template.find('jpeg') >= 0): args.data_train = 'DIV2K_jpeg' args.data_test = 'DIV2K_jpeg' args.epochs = 200 args.lr_decay = 100 if (args.template.find('EDSR_paper') >= 0): args.model = 'EDSR' args.n_resblocks = 32 args.n_...
class Trainer(): def __init__(self, args, loader, my_model, my_loss, ckp): self.args = args self.scale = args.scale self.ckp = ckp self.loader_train = loader.loader_train self.loader_test = loader.loader_test self.model = my_model self.loss = my_loss ...
class BaseDataClass(object): '\n Base class for objects dealing with data pprerocessing\n and preparing data for training and evaluating the models.\n ' def __init__(self, config): self.config = (config or dict()) self.max_src_len = self.config['max_src_len'] self.max_tgt_len...
def gen_multi_ref_dev(dev_xy, fname): "\n A utility function for generating a mutli-reference file\n from the data provided by the E2E NLG organizers.\n\n :param dev_xy: a list of M tuples, where M is the number of data instances.\n Each tuple contains a src string and a tgt string.\n For example:\...
def truncate_pad_sentence(snt_ids, max_len, add_start=True, add_end=True): '\n Given an iterable\n :param snt_ids:\n :param max_len:\n :param add_start:\n :param add_end:\n :return:\n ' x_trunc = truncate_sentence(snt_ids, max_len, add_start, add_end) x_trunc_pad = pad_snt(x_trunc, ma...
def truncate_sentence(snt_ids, max_len, add_start=True, add_end=True): '\n Given a list of token ids and maxium sequence length,\n take only the first "max_len" items.\n\n :param snt_ids: sequence of elements (token ids)\n :param max_len: cut-off value for truncation\n :param add_start: add "beginn...
def pad_snt(snt_ids_trunc, max_len): '\n Given a list of token ids and maxium sequence length,\n pad the sentence, if necessary, so that it contains exactly "max_len" items.\n\n :param snt_ids_trunc: possibly truncated sequence of items to be padded\n :param max_len: cut-off value for padding\n :re...
def generator_wrapper(iterable): '\n A utility function wrapping an iterable into a generator.\n\n :param iterable:\n :return:\n ' num_items = len(iterable) for idx in range(num_items): (yield iterable[idx])
def cuda_if_gpu(T): '\n Move tensor to GPU, if one is available.\n\n :param T:\n :return:\n ' return (T.cuda() if use_cuda else T)
def cudify(fn): '\n A simple decorator for wrapping functions that return tensors\n to move them to a GPU, if one is available.\n\n :param fn: function to be wrapped\n :return:\n ' @functools.wraps(fn) def wrapper(*args, **kwargs): result = fn(*args, **kwargs) return cuda_i...
@cudify def ids2var(snt_ids, *dims, addEOS=True): '\n Convert a sequence of ids to a matrix of size specified by the dims.\n\n :param snt_ids: s\n :param addEOS:\n :return: A matrix of shape: (*dims)\n ' snt_ids_copy = copy.deepcopy(snt_ids) if addEOS: snt_ids_copy.append(EOS_ID) ...
@cudify def cat2onehot_var(snt_ids, vocab_size, batch_size): '\n Convert a sequence of categorical values to one-hot representation\n Based on: https://stackoverflow.com/questions/38592324/one-hot-encoding-using-numpy#38592416\n ' targets = np.array([snt_ids]).reshape((- 1)) one_hot_targets = np....
def test_ids2var(): snt_ids = [1, 1, 1, 1, 1] snt_ids_var = ids2var(snt_ids, 1, 2, 3, addEOS=True) snt_ids_var_shape = snt_ids_var.data.size() assert (snt_ids_var_shape == torch.Size([1, 2, 3])) print('Test (ids2var): passed')
class E2EMLPData(BaseDataClass): def process_e2e_mr(self, mr_string): '\n Processing E2E NLG Challenge meaning representation\n Represent each MR as a list of 8 attributes, specified in MR_KEYMAP.\n\n :param mr_string:\n :return:\n ' items = mr_string.split(', '...
class VocabularyBase(object): '\n Common methods for all vocabulary classes.\n ' def load_vocabulary(self, vocabulary_path): '\n Load vocabulary from file.\n ' if check_file_exists([vocabulary_path]): logger.debug(('Loading vocabulary from %s' % vocabulary_path...
class VocabularyOneSide(VocabularyBase): def __init__(self, vocab_path, data_raw=None, lower=True): '\n Initialize a vocabulary class. Either you specify a vocabulary path to load\n the vocabulary from a file, or you provide training data to create one.\n :param vocab_path: path to a...
class VocabularyShared(VocabularyBase): def __init__(self, vocab_path, data_raw_src=None, data_raw_tgt=None, lower=True): '\n Initialize a vocabulary class. Either you specify a vocabulary path to load\n the vocabulary from a file, or you provide training data to create one.\n :param...
class BaseEvaluator(object): '\n Base class containing methods for evaluation of E2E NLG models.\n ' def __init__(self, config): self.config = (config or dict()) def label2snt(self, id2word, ids): tokens = [id2word[t] for t in ids] return (tokens, ' '.join(tokens)) def...
def eval_output(ref_fn, pred_fn): '\n Runs an external evaluation script (COCO/MTeval evaluation, measure_scores.py) and retrieves the scores\n :param pred_fn:\n :param ref_fn:\n :return:\n ' pat = '==============\\nBLEU: (\\d+\\.?\\d*)\\nNIST: (\\d+\\.?\\d*)\\nMETEOR: (\\d+\\.?\\d*)\\nROUGE_L:...
def _sh_eval(pred_fn, ref_fn): '\n Runs measure_scores.py script and processes the output\n :param pred_fn:\n :param ref_fn:\n :return:\n ' this_dir = os.path.dirname(os.path.abspath(__file__)) script_fname = os.path.join(this_dir, 'eval_scripts/run_eval.sh') out = subprocess.check_outp...
class Sequence(object): 'Represents a complete or partial sequence.' def __init__(self, output, state, logprob, score, attention=None): 'Initializes the Sequence.\n Args:\n output: List of word ids in the sequence.\n state: Model state after generating the previous word.\n ...
class TopN(object): 'Maintains the top n elements of an incrementally provided set.' def __init__(self, n): self._n = n self._data = [] def size(self): assert (self._data is not None) return len(self._data) def push(self, x): 'Pushes a new element.' a...
class BaseModel(nn.Module): def __init__(self, config): super(BaseModel, self).__init__() self.config = config self.use_cuda = torch.cuda.is_available()
class Seq2SeqModel(BaseModel): def set_src_vocab_size(self, vocab_size): self._src_vocab_size = vocab_size def set_tgt_vocab_size(self, vocab_size): self._tgt_vocab_size = vocab_size def set_max_src_len(self, l): self._max_src_len = l def set_max_tgt_len(self, l): s...
class E2ESeq2SeqModel(Seq2SeqModel): def setup(self, data): self.set_flags() self.set_data_dependent_params(data) self.set_embeddings() self.set_encoder() self.set_decoder() def set_data_dependent_params(self, data): vocabsize = len(data.vocab) self.se...
def get_GRU_unit(gru_config): return nn.GRU(input_size=gru_config['input_size'], hidden_size=gru_config['hidden_size'], dropout=gru_config['dropout'], bidirectional=gru_config.get('bidirectional', False))
def get_embed_matrix(vocab_size, embedding_dim): return nn.Embedding(vocab_size, embedding_dim, padding_idx=PAD_ID)
class AttnBahd(nn.Module): def __init__(self, enc_dim, dec_dim, num_directions, attn_dim=None): '\n Attention mechanism\n :param enc_dim: Dimension of hidden states of the encoder h_j\n :param dec_dim: Dimension of the hidden states of the decoder s_{i-1}\n :param attn_dim: Di...
class DecoderRNNAttnBase(nn.Module): '\n To be implemented for each Decoder:\n self.rnn\n self.attn_module\n self.combine_context_run_rnn\n self.compute_output\n ' def forward(self, prev_y_batch, prev_h_batch, encoder_outputs_batch): '\n A forward step of the Decoder.\n ...
class DecoderRNNAttnBahd(DecoderRNNAttnBase): def __init__(self, rnn_config, output_size, prev_y_dim, enc_dim, enc_num_directions): super(DecoderRNNAttnBahd, self).__init__() self.rnn = get_GRU_unit(rnn_config) dec_dim = rnn_config['hidden_size'] self.attn_module = AttnBahd(enc_di...
class EncoderMLP(nn.Module): def __init__(self, config): super(EncoderMLP, self).__init__() self.config = config self.input_size = self.config['input_size'] self.hidden_size = self.config['hidden_size'] self.W = nn.Linear(self.input_size, self.hidden_size) self.rel...
class EncoderGRU(EncoderRNN): def __init__(self, config): super(EncoderGRU, self).__init__() self.config = config self.rnn = get_GRU_unit(config)
def process_e2e_mr(s): '\n Extract key-value pairs from the input and pack them into a dictionary.\n :param s: src string containing key-value pairs.\n :return: a dictionary w/ key-value pairs corresponding to MR keys and their values on the src side of the input.\n ' items = s.split(', ') k2v...
def _get_price_str(mr_val): "\n Handle the price prediction part.\n :param mr_val: value of the 'price' field.\n :return: refined sentence string.\n " if (not mr_val): s = '.' return s if ('£' in mr_val): s = (' in the price range of %s.' % mr_val) else: mr_...
def _get_rating(mr_val, snt): "\n Handle the rating part.\n :param mr_val: value of the 'customerRating' field.\n :param snt: sentence string built so far.\n :return: refined sentence string.\n " if (snt[(- 1)] != '.'): beginning = ' with' else: beginning = ' It has' if ...
def _get_loc(area_val, near_val, snt): "\n Handle location string, variant 1.\n :param area_val: value of the 'area' field.\n :param near_val: value of the 'near' field.\n :param snt: incomplete sentence string (string built so far)\n :return:\n " tokens = snt.split() if ('It' in tokens)...
def _get_loc2(area_val, near_val): "\n Handle location string, variant 2.\n :param area_val: value of the 'area' field.\n :param near_val: value of the 'near' field.\n :return:\n " if area_val: s = (' located in the %s area' % area_val) if near_val: s += (', near %s....
def postprocess(snt): '\n Fix some spelling and punctuation.\n :param snt: sentence string before post-processing\n :return: sentence string after post-processing\n ' tokens = snt.split() for (idx, t) in enumerate(tokens): if (t.lower() == 'a'): if (tokens[(idx + 1)][0] in ...
def make_prediction(xd): '\n Main function to make a prediction.\n\n Our template has a generic part and a field-specific part which we called SUBTEMPLATE:\n\n [SUBTEMPLATE-1] which serves [food] in the [price] price range.\n It has a [customerRating] customer rating.\n It is located in...
def run(fname, mode='dev'): '\n Main function.\n :param fname: filename with the input.\n :param mode: operation mode, either dev (input has both MR and TEXT) or test (only MR given).\n :return:\n ' input_data = [] predictions = [] with open(fname, 'r') as csv_file: reader = csv...
def test(): logger.info('Running a test: prediction by a template baseline') x1 = 'name[The Vaults]' x2 = 'name[The Vaults], eatType[pub]' x3 = 'name[The Vaults], eatType[pub], priceRange[more than £30]' x4 = 'name[The Vaults], eatType[pub], priceRange[more than £30], customer rating[5 out of 5]' ...
class BaseTrainer(object): def __init__(self, config): self.config = config self.init_params() def init_params(self): self.n_epochs = self.config['n_epochs'] self.batch_size = self.config['batch_size'] self.lr = self.config['learning_rate'] self.model_dir = se...
class E2EMLPTrainer(BaseTrainer): def set_train_criterion(self, vocab_size, pad_id): '\n NMT Criterion from: https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/Loss.py\n :return:\n\n ' weight = torch.ones(vocab_size) weight[pad_id] = 0 self.criterion = nn....
def load_config(config_path): 'Loads and reads a yaml configuration file\n\n :param config_path: path of the configuration file to load\n :type config_path: str\n :return: the configuration dictionary\n :rtype: dict\n ' with open(config_path, 'r') as user_config_file: return yaml.load(u...
def fix_seed(seed): logger.debug(('Fixing seed: %d' % seed)) np.random.seed(seed) random.seed(seed) torch.manual_seed(seed)
def process_e2e_text(s): words = [] for fragment in s.strip().split(): fragment_tokens = _WORD_SPLIT.split(fragment) words.extend(fragment_tokens) tokens = [w for w in words if w] return tokens
def process_e2e_mr(s): items = s.split(', ') mr_data = ([None] * MR_KEY_NUM) for (idx, item) in enumerate(items): (key, raw_val) = item.split('[') key_idx = MR_KEYMAP[key] mr_data[key_idx] = raw_val[:(- 1)] return dict(zip(MR_FIELDS, mr_data))
def process_e2e_mr_delex(s): items = s.split(', ') mr_data = ([None] * MR_KEY_NUM) lex = [None, None] for (idx, item) in enumerate(items): (key, raw_val) = item.split('[') key_idx = MR_KEYMAP[key] if (key == 'name'): mr_val = NAME_TOKEN lex[0] = raw_val[...
def cnt_bins_and_cnts(): lengths_to_consider = [0, 10, 20, 30, 40, 50, 60, 70, 80] bins = [(lengths_to_consider[i], lengths_to_consider[(i + 1)]) for i in range((len(lengths_to_consider) - 1))] cnts = ([0] * len(bins)) for l in references_lens: for (bin_idx, b) in enumerate(bins): ...
def plot_len_hist(lens, fname): references_lens_df = pd.DataFrame(references_lens) mean = float(references_lens_df.mean()) std = float(references_lens_df.std()) min_len = int(references_lens_df.min()) max_len = int(references_lens_df.max()) pp = PdfPages(fname) (n, bins, patches) = plt.his...
def check_file_exists(fname): if (not os.path.exists(os.path.abspath(fname))): logger.warning(('%s does not exist!' % fname)) return False
def check_files_exist(args): for arg in args: check_file_exists(arg) return True
def set_logger(stdout_level=logging.INFO, log_fn=None): '\n Set python logger for this experiment.\n Based on:\n\n https://stackoverflow.com/questions/25187083/python-logging-to-multiple-handlers-at-different-log-levels\n\n :param stdout_level:\n :param log_fn:\n :return:\n ' simple_f...
def main(src_fn, num_samples=100): '\n Sample input data and write to a separate file for further analysis.\n\n :param src_fn: trainset data\n :param num_samples: number of samples to draw\n :return:\n ' print('AUX_DATA_ANALYSIS: Sampling input data') num_samples = int(num_samples) with...
def main(base_out_fn, model4_out_fn, template_out_fn, src_fn, num_samples=100): '\n Sample predictions by the three models and write them to separate files for further analysis.\n See subsection 5.2 of the paper.\n\n :param base_out_fn: Baseline prediction file\n :param model4_out_fn: MLPModel predic...
def save_config(config_dict, fname=None): '\n Save configuration dictionary (n json format).\n\n :param config_dict: configuration dictionary\n :param fname: name of the file to save the dictionary in\n :return:\n ' with open(fname, mode='w', encoding='utf-8') as f: json.dump(config_dic...
def save_model(model, model_fn): '\n Serialize the trained model.\n\n :param model: instance of the ModelClass\n :param model_fn: name of the file where to store the model\n :return:\n ' logger.info(('Saving model to --> %s' % model_fn)) torch.save(model.state_dict(), open(model_fn, 'wb'))
def save_predictions_json(predictions, fname): '\n Save predictions done by a trained model in json format.\n\n :param predictions: a list of strings, each corresponding to one predicted snt.\n :param fname: name of the file to save the predictions in\n :return:\n ' with open(fname, mode='w', e...
def save_predictions_txt(predictions, fname): '\n Save predictions done by a trained model in txt format.\n :param predictions:\n :param fname:\n :return:\n ' logger.info(('Saving predictions to a txt file --> %s' % fname)) with open(fname, mode='w', encoding='utf-8') as f: if (type...
def save_scores(scores, header, fname): '\n Save the performance of the model as measured for each epoch by the E2E NLG Challenge scoring metrics.\n\n :param scores: a list of lists of scores:\n - bleu_scores\n - nist_scores\n - cider_scores\n - rouge_scores\n ...
def load_model(model, model_weights_fn): '\n Load serialized model.\n\n :param model: instance of the ModelClass.\n :param model_weights_fn: name of the file w/ the serialized model.\n :return:\n ' logger.info(('Loading the model <-- %s' % model_weights_fn)) model.load_state_dict(torch.load...
def get_experiment_name(config_d): '\n Create a simple unique name for the experiment.\n Consists of model type, timestamp and specific hyper-parameter (hp) values.\n\n :param config_d: configuration dictionary\n :return: name of the current experiment (string)\n ' model_type = get_model_type(c...
def get_model_type(config_d): '\n Generate part of the experiment name: model type to be trained.\n Model types correspond to non-qualified names of the python files with the code for the model.\n For example, if the code for our model is stored in "components/model/e2e_model_MLP.py",\n then model typ...
def get_timestamp(): '\n Generate a timestep to be included as part of the model name.\n\n :return: current timestamp (string)\n ' return '{:%Y-%b-%d_%H:%M:%S}'.format(datetime.now())
def get_hp_value_name(config_dict): '\n Generate a string which store hyper-parameter values as part of the model name.\n This is useful for hp-optimization, if you decide to perform one.\n\n :param config_dict: configuration dictionary retrieved from the .yaml file.\n :return: concatenated hp values ...
def make_model_dir(config): '\n Create a directory to contain various files for the current experiment.\n :param config: config dictionary\n :return: name of the directory\n ' mode = config['mode'] if (mode == 'predict'): model_fn = config['model_fn'] model_dirname = os.path.sp...
def test_save_scores(): scores = [[(1, 2), 3], [(1, 2), 4], [(1, 2), 5]] HEADER = ['loss', 'cider'] with open('todelete.csv', 'w') as csv_out: csv_writer = csv.writer(csv_out, delimiter=',') csv_writer.writerow(HEADER) for epoch_scores in scores: csv_writer.writerow(epo...
def timeSince(since, percent): '\n A helper function to print time elapsed and\n estimated time remaining given the current time and progress\n :param since:\n :param percent:\n :return:\n ' now = time.time() s = (now - since) es = (s / percent) rs = (es - s) return ('%s (- %...
def asMinutes(s): '\n A helper function to convert elapsed time to minutes.\n :param s:\n :return:\n ' m = math.floor((s / 60)) s -= (m * 60) return ('%dm %ds' % (m, s))
def create_progress_bar(dynamic_msg=None): widgets = [' [batch ', progressbar.SimpleProgress(), '] ', progressbar.Bar(), ' (', progressbar.ETA(), ') '] if (dynamic_msg is not None): widgets.append(progressbar.DynamicMessage(dynamic_msg)) return progressbar.ProgressBar(widgets=widgets)
class NGramScore(object): 'Base class for BLEU & NIST, providing tokenization and some basic n-gram matching\n functions.' def __init__(self, max_ngram, case_sensitive): 'Create the scoring object.\n @param max_ngram: the n-gram level to compute the score for\n @param case_sensitive:...
class BLEUScore(NGramScore): "An accumulator object capable of computing BLEU score using multiple references.\n\n The BLEU score is always smoothed a bit so that it's never undefined. For sentence-level\n measurements, proper smoothing should be used via the smoothing parameter (set to 1.0 for\n the sam...
class NISTScore(NGramScore): 'An accumulator object capable of computing NIST score using multiple references.' BETA = ((- math.log(0.5)) / (math.log(1.5) ** 2)) def __init__(self, max_ngram=5, case_sensitive=False): 'Create the scoring object.\n @param max_ngram: the n-gram level to compu...
class Bleu(): def __init__(self, n=4): self._n = n self._hypo_for_image = {} self.ref_for_image = {} def compute_score(self, gts, res): assert (gts.keys() == res.keys()) imgIds = gts.keys() bleu_scorer = BleuScorer(n=self._n) for id in imgIds: ...
class Cider(): '\n Main Class to compute the CIDEr metric \n\n ' def __init__(self, test=None, refs=None, n=4, sigma=6.0): self._n = n self._sigma = sigma def compute_score(self, gts, res): '\n Main function to compute CIDEr score\n :param hypo_for_image (dic...
def precook(s, n=4, out=False): '\n Takes a string as input and returns an object that can be given to\n either cook_refs or cook_test. This is optional: cook_refs and cook_test\n can take string arguments as well.\n :param s: string : sentence to be converted into ngrams\n :param n: int : numbe...
def cook_refs(refs, n=4): 'Takes a list of reference sentences for a single segment\n and returns an object that encapsulates everything that BLEU\n needs to know about them.\n :param refs: list of string : reference sentences for some image\n :param n: int : number of ngrams for which (ngram) represe...
def cook_test(test, n=4): 'Takes a test sentence and returns an object that\n encapsulates everything that BLEU needs to know about it.\n :param test: list of string : hypothesis sentence for some image\n :param n: int : number of ngrams for which (ngram) representation is calculated\n :return: result...
class CiderScorer(object): 'CIDEr scorer.\n ' def copy(self): ' copy the refs.' new = CiderScorer(n=self.n) new.ctest = copy.copy(self.ctest) new.crefs = copy.copy(self.crefs) return new def __init__(self, test=None, refs=None, n=4, sigma=6.0): ' singul...
class COCOEvalCap(): def __init__(self, coco, cocoRes): self.evalImgs = [] self.eval = {} self.imgToEval = {} self.coco = coco self.cocoRes = cocoRes self.params = {'image_id': coco.getImgIds()} def evaluate(self): imgIds = self.params['image_id'] ...
class Meteor(): def __init__(self): self.meteor_cmd = ['java', '-jar', '-Xmx2G', METEOR_JAR, '-', '-', '-stdio', '-l', 'en', '-norm'] self.meteor_p = subprocess.Popen(self.meteor_cmd, cwd=os.path.dirname(os.path.abspath(__file__)), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess....
def my_lcs(string, sub): '\n Calculates longest common subsequence for a pair of tokenized strings\n :param string : list of str : tokens from a string split using whitespace\n :param sub : list of str : shorter string, also split using whitespace\n :returns: length (list of int): length of the longes...
class Rouge(): '\n Class for computing ROUGE-L score for a set of candidate sentences for the MS COCO test set\n\n ' def __init__(self): self.beta = 1.2 def calc_score(self, candidate, refs): '\n Compute ROUGE-L score given one candidate and references for an image\n ...
class PTBTokenizer(): 'Python wrapper of Stanford PTBTokenizer' def tokenize(self, captions_for_image): cmd = ['java', '-cp', STANFORD_CORENLP_3_4_1_JAR, 'edu.stanford.nlp.process.PTBTokenizer', '-preserveLines', '-lowerCase'] final_tokenized_captions_for_image = {} image_id = [k for ...
class AttentionWeightedAverage(Layer): '\n Computes a weighted average of the different channels across timesteps.\n Uses 1 parameter pr. channel to compute the attention value for a single timestep.\n ' def __init__(self, return_attention=False, **kwargs): self.init = initializers.get('unif...
def finetuning_callbacks(checkpoint_path, patience, verbose): ' Callbacks for model training.\n # Arguments:\n checkpoint_path: Where weight checkpoints should be saved.\n patience: Number of epochs with no improvement after which\n training will be stopped.\n # Returns:\n Ar...
def reconstructor(w2v_dim, pretrain_w2v, nb_tokens, max_src_len, mr_value_num, MR_FIELDS, ra=False, embed_l2=1e-06): model_input = Input(shape=(max_src_len,), dtype='int32') embed_reg = (L1L2(l2=embed_l2) if (embed_l2 != 0) else None) if (pretrain_w2v is None): embed = Embedding(input_dim=nb_token...
class AttentionWeightedAverage(Layer): '\n Computes a weighted average of the different channels across timesteps.\n Uses 1 parameter pr. channel to compute the attention value for a single timestep.\n ' def __init__(self, return_attention=False, **kwargs): self.init = initializers.get('unif...
def finetuning_callbacks(checkpoint_path, patience, verbose): ' Callbacks for model training.\n # Arguments:\n checkpoint_path: Where weight checkpoints should be saved.\n patience: Number of epochs with no improvement after which\n training will be stopped.\n # Returns:\n Ar...
def reconstructor(w2v_dim, pretrain_w2v, nb_tokens, max_src_len, mr_value_num, MR_FIELDS, ra=False, embed_l2=1e-06): model_input = Input(shape=(max_src_len,), dtype='int32') embed_reg = (L1L2(l2=embed_l2) if (embed_l2 != 0) else None) if (pretrain_w2v is None): embed = Embedding(input_dim=nb_token...
def minmax(a): return ((a - min(a)) / (1.0 * (max(a) - min(a))))
def reranker(fw_weight, bw_weight): global output_name, input_name with open(input_name, 'r') as stream, open(('rerank/%s_%.2f' % (output_name, fw_weight)), 'w') as out: for line in stream: data = line.strip().split('\t') texts = json.loads(data[0]) fw_score = np.ar...
def tidy_total(input_name): global beam_size import pickle as pk dev_recs_loss = pk.load(open('dev_recs_loss.pkl', 'rb')) with open(input_name, 'r') as stream, open('devset.recs.full.txt', 'w') as stream_1: for (idx, line) in enumerate(stream): data = line.strip().split('\t') ...
def pad_snt(snt_ids_trunc, max_len): snt_ids_trunc_pad = (snt_ids_trunc + ([PAD_ID] * (max_len - len(snt_ids_trunc)))) return snt_ids_trunc_pad
def parse_data_recs(mr_value_vocab2id, mr_value_num, data_process): global MR_FIELDS, id2tok (data_new, it_num, fa_num) = ([[], []], 0, 0) (data_new_x, data_new_y) = ([], [[] for i in range(len(MR_FIELDS))]) print(len(data_process[0]), len(data_process[1])) for (data_src, data_tgt) in zip(data_pro...
def tidy_recs(): global data, MR_FIELDS all_input = ((data.dev[0] + data.train[0]) + data.test[0]) all_input = set([tuple(x) for x in all_input]) print(len(all_input), len(data.lexicalizations['train']), len(data.lexicalizations['test']), len(data.lexicalizations['dev'])) lexical = ((data.lexicali...
def w2v(dim): global data import gensim sentences = (data.dev[1] + data.train[1]) sentences = [[str(x) for x in s] for s in sentences] model = gensim.models.Word2Vec(size=dim, min_count=0, workers=16, sg=1) model.build_vocab(sentences) model.train(sentences, total_examples=model.corpus_cou...
def pre_w2v(dim): global id2tok w2v_pre = {} with open('recs/word2vec.{}d.3k.w2v'.format(dim), encoding='utf8') as stream: for (idx, line) in enumerate(stream): if (idx == 0): continue split = line.rstrip().split(' ') word = int(split[0]) ...
def run(config_dict): data_module = config_dict['data-module'] model_module = config_dict['model-module'] training_module = config_dict['training-module'] evaluation_module = config_dict.get('evaluation-module', None) mode = config_dict['mode'] DataClass = importlib.import_module(data_module)....
def save_beam_fw(fw_probs, decode_snts, beam_size, filename): with open(filename, 'w') as outstream: (pp, pp_u) = ([], set()) for dec_idx in range(len(decode_snts[0])): (dec_cur, fw_cur) = ([], []) for beam_idx in range(beam_size): tmp_cur = ' '.join(decode_...