code
stringlengths
17
6.64M
def rebuild_col_unit_col(valid_col_units, col_unit, kmap): if (col_unit is None): return col_unit (agg_id, col_id, distinct) = col_unit if ((col_id in kmap) and (col_id in valid_col_units)): col_id = kmap[col_id] if DISABLE_DISTINCT: distinct = None return (agg_id, col_id, ...
def rebuild_val_unit_col(valid_col_units, val_unit, kmap): if (val_unit is None): return val_unit (unit_op, col_unit1, col_unit2) = val_unit col_unit1 = rebuild_col_unit_col(valid_col_units, col_unit1, kmap) col_unit2 = rebuild_col_unit_col(valid_col_units, col_unit2, kmap) return (unit_op...
def rebuild_table_unit_col(valid_col_units, table_unit, kmap): if (table_unit is None): return table_unit (table_type, col_unit_or_sql) = table_unit if isinstance(col_unit_or_sql, tuple): col_unit_or_sql = rebuild_col_unit_col(valid_col_units, col_unit_or_sql, kmap) return (table_type,...
def rebuild_cond_unit_col(valid_col_units, cond_unit, kmap): if (cond_unit is None): return cond_unit (not_op, op_id, val_unit, val1, val2) = cond_unit val_unit = rebuild_val_unit_col(valid_col_units, val_unit, kmap) return (not_op, op_id, val_unit, val1, val2)
def rebuild_condition_col(valid_col_units, condition, kmap): for idx in range(len(condition)): if ((idx % 2) == 0): condition[idx] = rebuild_cond_unit_col(valid_col_units, condition[idx], kmap) return condition
def rebuild_select_col(valid_col_units, sel, kmap): if (sel is None): return sel (distinct, _list) = sel new_list = [] for it in _list: (agg_id, val_unit) = it new_list.append((agg_id, rebuild_val_unit_col(valid_col_units, val_unit, kmap))) if DISABLE_DISTINCT: dist...
def rebuild_from_col(valid_col_units, from_, kmap): if (from_ is None): return from_ from_['table_units'] = [rebuild_table_unit_col(valid_col_units, table_unit, kmap) for table_unit in from_['table_units']] from_['conds'] = rebuild_condition_col(valid_col_units, from_['conds'], kmap) return fr...
def rebuild_group_by_col(valid_col_units, group_by, kmap): if (group_by is None): return group_by return [rebuild_col_unit_col(valid_col_units, col_unit, kmap) for col_unit in group_by]
def rebuild_order_by_col(valid_col_units, order_by, kmap): if ((order_by is None) or (len(order_by) == 0)): return order_by (direction, val_units) = order_by new_val_units = [rebuild_val_unit_col(valid_col_units, val_unit, kmap) for val_unit in val_units] return (direction, new_val_units)
def rebuild_sql_col(valid_col_units, sql, kmap): if (sql is None): return sql sql['select'] = rebuild_select_col(valid_col_units, sql['select'], kmap) sql['from'] = rebuild_from_col(valid_col_units, sql['from'], kmap) sql['where'] = rebuild_condition_col(valid_col_units, sql['where'], kmap) ...
def build_foreign_key_map(entry): cols_orig = entry['column_names_original'] tables_orig = entry['table_names_original'] cols = [] for col_orig in cols_orig: if (col_orig[0] >= 0): t = tables_orig[col_orig[0]] c = col_orig[1] cols.append((((('__' + t.lower()...
def build_foreign_key_map_from_json(table): with open(table) as f: data = json.load(f) tables = {} for entry in data: tables[entry['db_id']] = build_foreign_key_map(entry) return tables
class Schema(): '\n Simple schema which maps table&column to a unique identifier\n ' def __init__(self, schema): self._schema = schema self._idMap = self._map(self._schema) @property def schema(self): return self._schema @property def idMap(self): retur...
def get_schema(db): "\n Get database's schema, which is a dict with table name as key\n and list of column names as value\n :param db: database path\n :return: schema dict\n " schema = {} conn = sqlite3.connect(db) cursor = conn.cursor() cursor.execute("SELECT name FROM sqlite_maste...
def get_schema_from_json(fpath): with open(fpath) as f: data = json.load(f) schema = {} for entry in data: table = str(entry['table'].lower()) cols = [str(col['column_name'].lower()) for col in entry['col_data']] schema[table] = cols return schema
def tokenize(string): string = str(string) string = string.replace("'", '"') quote_idxs = [idx for (idx, char) in enumerate(string) if (char == '"')] assert ((len(quote_idxs) % 2) == 0), 'Unexpected quote' vals = {} for i in range((len(quote_idxs) - 1), (- 1), (- 2)): qidx1 = quote_idx...
def scan_alias(toks): "Scan the index of 'as' and build the map for all alias" as_idxs = [idx for (idx, tok) in enumerate(toks) if (tok == 'as')] alias = {} for idx in as_idxs: alias[toks[(idx + 1)]] = toks[(idx - 1)] return alias
def get_tables_with_alias(schema, toks): tables = scan_alias(toks) for key in schema: assert (key not in tables), 'Alias {} has the same name in table'.format(key) tables[key] = key return tables
def parse_col(toks, start_idx, tables_with_alias, schema, default_tables=None): '\n :returns next idx, column id\n ' tok = toks[start_idx] if (tok == '*'): return ((start_idx + 1), schema.idMap[tok]) if ('.' in tok): (alias, col) = tok.split('.') key = ((tables_with_a...
def parse_col_unit(toks, start_idx, tables_with_alias, schema, default_tables=None): '\n :returns next idx, (agg_op id, col_id)\n ' idx = start_idx len_ = len(toks) isBlock = False isDistinct = False if (toks[idx] == '('): isBlock = True idx += 1 if (toks[idx] in ...
def parse_val_unit(toks, start_idx, tables_with_alias, schema, default_tables=None): idx = start_idx len_ = len(toks) isBlock = False if (toks[idx] == '('): isBlock = True idx += 1 col_unit1 = None col_unit2 = None unit_op = UNIT_OPS.index('none') (idx, col_unit1) = par...
def parse_table_unit(toks, start_idx, tables_with_alias, schema): '\n :returns next idx, table id, table name\n ' idx = start_idx len_ = len(toks) key = tables_with_alias[toks[idx]] if (((idx + 1) < len_) and (toks[(idx + 1)] == 'as')): idx += 3 else: idx += 1 ret...
def parse_value(toks, start_idx, tables_with_alias, schema, default_tables=None): idx = start_idx len_ = len(toks) isBlock = False if (toks[idx] == '('): isBlock = True idx += 1 if (toks[idx] == 'select'): (idx, val) = parse_sql(toks, idx, tables_with_alias, schema) eli...
def parse_condition(toks, start_idx, tables_with_alias, schema, default_tables=None): idx = start_idx len_ = len(toks) conds = [] while (idx < len_): (idx, val_unit) = parse_val_unit(toks, idx, tables_with_alias, schema, default_tables) not_op = False if (toks[idx] == 'not'): ...
def parse_select(toks, start_idx, tables_with_alias, schema, default_tables=None): idx = start_idx len_ = len(toks) assert (toks[idx] == 'select'), "'select' not found" idx += 1 isDistinct = False if ((idx < len_) and (toks[idx] == 'distinct')): idx += 1 isDistinct = True v...
def parse_from(toks, start_idx, tables_with_alias, schema): '\n Assume in the from clause, all table units are combined with join\n ' assert ('from' in toks[start_idx:]), "'from' not found" len_ = len(toks) idx = (toks.index('from', start_idx) + 1) default_tables = [] table_units = [] ...
def parse_where(toks, start_idx, tables_with_alias, schema, default_tables): idx = start_idx len_ = len(toks) if ((idx >= len_) or (toks[idx] != 'where')): return (idx, []) idx += 1 (idx, conds) = parse_condition(toks, idx, tables_with_alias, schema, default_tables) return (idx, conds)...
def parse_group_by(toks, start_idx, tables_with_alias, schema, default_tables): idx = start_idx len_ = len(toks) col_units = [] if ((idx >= len_) or (toks[idx] != 'group')): return (idx, col_units) idx += 1 assert (toks[idx] == 'by') idx += 1 while ((idx < len_) and (not ((toks...
def parse_order_by(toks, start_idx, tables_with_alias, schema, default_tables): idx = start_idx len_ = len(toks) val_units = [] order_type = 'asc' if ((idx >= len_) or (toks[idx] != 'order')): return (idx, val_units) idx += 1 assert (toks[idx] == 'by') idx += 1 while ((idx ...
def parse_having(toks, start_idx, tables_with_alias, schema, default_tables): idx = start_idx len_ = len(toks) if ((idx >= len_) or (toks[idx] != 'having')): return (idx, []) idx += 1 (idx, conds) = parse_condition(toks, idx, tables_with_alias, schema, default_tables) return (idx, cond...
def parse_limit(toks, start_idx): idx = start_idx len_ = len(toks) if ((idx < len_) and (toks[idx] == 'limit')): idx += 2 if (type(toks[(idx - 1)]) != int): return (idx, 1) return (idx, int(toks[(idx - 1)])) return (idx, None)
def parse_sql(toks, start_idx, tables_with_alias, schema): isBlock = False len_ = len(toks) idx = start_idx sql = {} if (toks[idx] == '('): isBlock = True idx += 1 (from_end_idx, table_units, conds, default_tables) = parse_from(toks, start_idx, tables_with_alias, schema) sq...
def load_data(fpath): with open(fpath) as f: data = json.load(f) return data
def get_sql(schema, query): toks = tokenize(query) tables_with_alias = get_tables_with_alias(schema.schema, toks) (_, sql) = parse_sql(toks, 0, tables_with_alias, schema) return sql
def skip_semicolon(toks, start_idx): idx = start_idx while ((idx < len(toks)) and (toks[idx] == ';')): idx += 1 return idx
class Logger(): 'Attributes:\n\n fileptr (file): File pointer for input/output.\n lines (list of str): The lines read from the log.\n ' def __init__(self, filename, option): self.fileptr = open(filename, option) if (option == 'r'): self.lines = self.fileptr.readlines() ...
class AttentionResult(namedtuple('AttentionResult', ('scores', 'distribution', 'vector'))): 'Stores the result of an attention calculation.' __slots__ = ()
class Attention(torch.nn.Module): 'Attention mechanism class. Stores parameters for and computes attention.\n\n Attributes:\n transform_query (bool): Whether or not to transform the query being\n passed in with a weight transformation before computing attentino.\n transform_key (bool): Wh...
def convert(): config = BertConfig.from_json_file(args.bert_config_file) model = BertModel(config) path = args.tf_checkpoint_path print('Converting TensorFlow checkpoint from {}'.format(path)) init_vars = tf.train.list_variables(path) names = [] arrays = [] for (name, shape) in init_va...
def input_fn_builder(features, seq_length, drop_remainder): 'Creates an `input_fn` closure to be passed to TPUEstimator.' all_unique_ids = [] all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_start_positions = [] all_end_positions = [] for feature in features: all...
def model_fn_builder(bert_config, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): 'Returns `model_fn` closure for TPUEstimator.' def model_fn(features, labels, mode, params): 'The `model_fn` for TPUEstimator.' tf.logging.info('*** Features ...
def _get_best_indexes(logits, n_best_size): 'Get the n-best logits from a list.' index_and_score = sorted(enumerate(logits), key=(lambda x: x[1]), reverse=True) best_indexes = [] for i in range(len(index_and_score)): if (i >= n_best_size): break best_indexes.append(index_an...
def _compute_softmax(scores): 'Compute softmax probability over raw logits.' if (not scores): return [] max_score = None for score in scores: if ((max_score is None) or (score > max_score)): max_score = score exp_scores = [] total_sum = 0.0 for score in scores: ...
def compute_predictions(all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case): 'Compute final predictions.' example_index_to_features = collections.defaultdict(list) for feature in all_features: example_index_to_features[feature.example_index].append(feature) ...
def convert_to_unicode(text): "Converts `text` to Unicode (if it's not already), assuming utf-8 input." if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode('utf-8', 'ignore') else: raise ValueError(('Uns...
def printable_text(text): 'Returns text encoded in a way suitable for print or `tf.logging`.' if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode('utf-8', 'ignore') else: raise ValueError(('Unsupported s...
def load_vocab(vocab_file): 'Loads a vocabulary file into a dictionary.' vocab = collections.OrderedDict() index = 0 with open(vocab_file, 'r', encoding='utf-8') as reader: while True: token = convert_to_unicode(reader.readline()) if (not token): break ...
def convert_tokens_to_ids(vocab, tokens): 'Converts a sequence of tokens into ids using the vocab.' ids = [] for token in tokens: ids.append(vocab[token]) return ids
def whitespace_tokenize(text): 'Runs basic whitespace cleaning and splitting on a piece of text.' text = text.strip() if (not text): return [] tokens = text.split() return tokens
class FullTokenizer(object): 'Runs end-to-end tokenziation.' def __init__(self, vocab_file, do_lower_case=True): self.vocab = load_vocab(vocab_file) self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab) ...
class BasicTokenizer(object): 'Runs basic tokenization (punctuation splitting, lower casing, etc.).' def __init__(self, do_lower_case=True): 'Constructs a BasicTokenizer.\n\n Args:\n do_lower_case: Whether to lower case the input.\n ' self.do_lower_case = do_lower_case ...
class WordpieceTokenizer(object): 'Runs WordPiece tokenization.' def __init__(self, vocab, unk_token='[UNK]', max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): 'T...
def _is_whitespace(char): 'Checks whether `chars` is a whitespace character.' if ((char == ' ') or (char == '\t') or (char == '\n') or (char == '\r')): return True cat = unicodedata.category(char) if (cat == 'Zs'): return True return False
def _is_control(char): 'Checks whether `chars` is a control character.' if ((char == '\t') or (char == '\n') or (char == '\r')): return False cat = unicodedata.category(char) if cat.startswith('C'): return True return False
def _is_punctuation(char): 'Checks whether `chars` is a punctuation character.' cp = ord(char) if (((cp >= 33) and (cp <= 47)) or ((cp >= 58) and (cp <= 64)) or ((cp >= 91) and (cp <= 96)) or ((cp >= 123) and (cp <= 126))): return True cat = unicodedata.category(char) if cat.startswith('P'...
def flatten_distribution(distribution_map, probabilities): ' Flattens a probability distribution given a map of "unique" values.\n All values in distribution_map with the same value should get the sum\n of the probabilities.\n\n Arguments:\n distribution_map (list of str): List of ...
class SQLPrediction(namedtuple('SQLPrediction', ('predictions', 'sequence', 'probability'))): 'Contains prediction for a sequence.' __slots__ = () def __str__(self): return ((str(self.probability) + '\t') + ' '.join(self.sequence))
class SequencePredictorWithSchema(torch.nn.Module): ' Predicts a sequence.\n\n Attributes:\n lstms (list of dy.RNNBuilder): The RNN used.\n token_predictor (TokenPredictor): Used to actually predict tokens.\n ' def __init__(self, params, input_size, output_embedder, column_name_token_embe...
class Embedder(torch.nn.Module): ' Embeds tokens. ' def __init__(self, embedding_size, name='', initializer=None, vocabulary=None, num_tokens=(- 1), anonymizer=None, freeze=False, use_unk=True): super().__init__() if vocabulary: assert (num_tokens < 0), ('Specified a vocabulary bu...
def bow_snippets(token, snippets, output_embedder, input_schema): ' Bag of words embedding for snippets' assert (snippet_handler.is_snippet(token) and snippets) snippet_sequence = [] for snippet in snippets: if (snippet.name == token): snippet_sequence = snippet.sequence ...
class Encoder(torch.nn.Module): ' Encodes an input sequence. ' def __init__(self, num_layers, input_size, state_size): super().__init__() self.num_layers = num_layers self.forward_lstms = create_multilayer_lstm_params(self.num_layers, input_size, (state_size / 2), 'LSTM-ef') s...
def get_token_indices(token, index_to_token): ' Maps from a gold token (string) to a list of indices.\n\n Inputs:\n token (string): String to look up.\n index_to_token (list of tokens): Ordered list of tokens.\n\n Returns:\n list of int, representing the indices of the token in the prob...
def flatten_utterances(utterances): ' Gets a flat sequence from a sequence of utterances.\n\n Inputs:\n utterances (list of list of str): Utterances to concatenate.\n\n Returns:\n list of str, representing the flattened sequence with separating\n delimiter tokens.\n ' sequenc...
def encode_snippets_with_states(snippets, states): ' Encodes snippets by using previous query states instead.\n\n Inputs:\n snippets (list of Snippet): Input snippets.\n states (list of dy.Expression): Previous hidden states to use.\n TODO: should this by dy.Expression or vector values?\n ...
def load_word_embeddings(input_vocabulary, output_vocabulary, output_vocabulary_schema, params): print(output_vocabulary.inorder_tokens) print() def read_glove_embedding(embedding_filename, embedding_size): glove_embeddings = {} with open(embedding_filename) as f: cnt = 1 ...
class ATISModel(torch.nn.Module): ' Sequence-to-sequence model for predicting a SQL query given an utterance\n and an interaction prefix.\n ' def __init__(self, params, input_vocabulary, output_vocabulary, output_vocabulary_schema, anonymizer): super().__init__() self.params = param...
class SchemaInteractionATISModel(ATISModel): ' Interaction ATIS model, where an interaction is processed all at once.\n ' def __init__(self, params, input_vocabulary, output_vocabulary, output_vocabulary_schema, anonymizer): ATISModel.__init__(self, params, input_vocabulary, output_vocabulary, out...
class PredictionInput(namedtuple('PredictionInput', ('decoder_state', 'input_hidden_states', 'snippets', 'input_sequence'))): ' Inputs to the token predictor. ' __slots__ = ()
class PredictionInputWithSchema(namedtuple('PredictionInputWithSchema', ('decoder_state', 'input_hidden_states', 'schema_states', 'snippets', 'input_sequence', 'previous_queries', 'previous_query_states', 'input_schema'))): ' Inputs to the token predictor. ' __slots__ = ()
class TokenPrediction(namedtuple('TokenPrediction', ('scores', 'aligned_tokens', 'utterance_attention_results', 'schema_attention_results', 'query_attention_results', 'copy_switch', 'query_scores', 'query_tokens', 'decoder_state'))): 'A token prediction.' __slots__ = ()
def score_snippets(snippets, scorer): ' Scores snippets given a scorer.\n\n Inputs:\n snippets (list of Snippet): The snippets to score.\n scorer (dy.Expression): Dynet vector against which to score the snippets.\n\n Returns:\n dy.Expression, list of str, where the first is the scores ...
def score_schema_tokens(input_schema, schema_states, scorer): scores = torch.t(torch.mm(torch.t(scorer), schema_states)) if (scores.size()[0] != len(input_schema)): raise ValueError((((('Got ' + str(scores.size()[0])) + ' scores for ') + str(len(input_schema))) + ' schema tokens')) return (scores,...
def score_query_tokens(previous_query, previous_query_states, scorer): scores = torch.t(torch.mm(torch.t(scorer), previous_query_states)) if (scores.size()[0] != len(previous_query)): raise ValueError((((('Got ' + str(scores.size()[0])) + ' scores for ') + str(len(previous_query))) + ' query tokens'))...
class TokenPredictor(torch.nn.Module): ' Predicts a token given a (decoder) state.\n\n Attributes:\n vocabulary (Vocabulary): A vocabulary object for the output.\n attention_module (Attention): An attention module.\n state_transformation_weights (dy.Parameters): Transforms the input state\...
class SchemaTokenPredictor(TokenPredictor): ' Token predictor that also predicts snippets.\n\n Attributes:\n snippet_weights (dy.Parameter): Weights for scoring snippets against some\n state.\n ' def __init__(self, params, vocabulary, utterance_attention_key_size, schema_attention_key...
class SnippetTokenPredictor(TokenPredictor): ' Token predictor that also predicts snippets.\n\n Attributes:\n snippet_weights (dy.Parameter): Weights for scoring snippets against some\n state.\n ' def __init__(self, params, vocabulary, attention_key_size, snippet_size): TokenP...
class AnonymizationTokenPredictor(TokenPredictor): ' Token predictor that also predicts anonymization tokens.\n\n Attributes:\n anonymizer (Anonymizer): The anonymization object.\n\n ' def __init__(self, params, vocabulary, attention_key_size, anonymizer): TokenPredictor.__init__(self, p...
class SnippetAnonymizationTokenPredictor(SnippetTokenPredictor, AnonymizationTokenPredictor): ' Token predictor that both anonymizes and scores snippets.' def __init__(self, params, vocabulary, attention_key_size, snippet_size, anonymizer): AnonymizationTokenPredictor.__init__(self, params, vocabular...
def construct_token_predictor(params, vocabulary, utterance_attention_key_size, schema_attention_key_size, snippet_size, anonymizer=None): ' Constructs a token predictor given the parameters.\n\n Inputs:\n parameter_collection (dy.ParameterCollection): Contains the parameters.\n params (dictionar...
def linear_layer(exp, weights, biases=None): if (exp.dim() == 1): exp = torch.unsqueeze(exp, 0) assert (exp.size()[1] == weights.size()[0]) if (biases is not None): assert (weights.size()[1] == biases.size()[0]) result = (torch.mm(exp, weights) + biases) else: result = ...
def compute_loss(gold_seq, scores, index_to_token_maps, gold_tok_to_id, noise=1e-08): ' Computes the loss of a gold sequence given scores.\n\n Inputs:\n gold_seq (list of str): A sequence of gold tokens.\n scores (list of dy.Expression): Expressions representing the scores of\n potenti...
def get_seq_from_scores(scores, index_to_token_maps): 'Gets the argmax sequence from a set of scores.\n\n Inputs:\n scores (list of dy.Expression): Sequences of output scores.\n index_to_token_maps (list of list of str): For each output token, maps\n the index in the probability distri...
def per_token_accuracy(gold_seq, pred_seq): ' Returns the per-token accuracy comparing two strings (recall).\n\n Inputs:\n gold_seq (list of str): A list of gold tokens.\n pred_seq (list of str): A list of predicted tokens.\n\n Returns:\n float, representing the accuracy.\n ' num...
def forward_one_multilayer(rnns, lstm_input, layer_states, dropout_amount=0.0): " Goes forward for one multilayer RNN cell step.\n\n Inputs:\n lstm_input (dy.Expression): Some input to the step.\n layer_states (list of dy.RNNState): The states of each layer in the cell.\n dropout_amount (f...
def encode_sequence(sequence, rnns, embedder, dropout_amount=0.0): " Encodes a sequence given RNN cells and an embedding function.\n\n Inputs:\n seq (list of str): The sequence to encode.\n rnns (list of dy._RNNBuilder): The RNNs to use.\n emb_fn (dict str->dy.Expression): Function that em...
def create_multilayer_lstm_params(num_layers, in_size, state_size, name=''): ' Adds a multilayer LSTM to the model parameters.\n\n Inputs:\n num_layers (int): Number of layers to create.\n in_size (int): The input size to the first layer.\n state_size (int): The size of the states.\n ...
def add_params(size, name=''): ' Adds parameters to the model.\n\n Inputs:\n model (dy.ParameterCollection): The parameter collection for the model.\n size (tuple of int): The size to create.\n name (str, optional): The name of the parameters.\n ' if (len(size) == 1): print(...
def write_prediction(fileptr, identifier, input_seq, probability, prediction, flat_prediction, gold_query, flat_gold_queries, gold_tables, index_in_interaction, database_username, database_password, database_timeout, compute_metrics=True): pred_obj = {} pred_obj['identifier'] = identifier if (len(identifi...
class Metrics(Enum): 'Definitions of simple metrics to compute.' LOSS = 1 TOKEN_ACCURACY = 2 STRING_ACCURACY = 3 CORRECT_TABLES = 4 STRICT_CORRECT_TABLES = 5 SEMANTIC_QUERIES = 6 SYNTACTIC_QUERIES = 7
def get_progressbar(name, size): 'Gets a progress bar object given a name and the total size.\n\n Inputs:\n name (str): The name to display on the side.\n size (int): The maximum size of the progress bar.\n\n ' return progressbar.ProgressBar(maxval=size, widgets=[name, progressbar.Bar('=',...
def train_epoch_with_utterances(batches, model, randomize=True): 'Trains model for a single epoch given batches of utterance data.\n\n Inputs:\n batches (UtteranceBatch): The batches to give to training.\n model (ATISModel): The model obect.\n learning_rate (float): The learning rate to us...
def train_epoch_with_interactions(interaction_batches, params, model, randomize=True): 'Trains model for single epoch given batches of interactions.\n\n Inputs:\n interaction_batches (list of InteractionBatch): The batches to train on.\n params (namespace): Parameters to run with.\n model ...
def update_sums(metrics, metrics_sums, predicted_sequence, flat_sequence, gold_query, original_gold_query, gold_forcing=False, loss=None, token_accuracy=0.0, database_username='', database_password='', database_timeout=0, gold_table=None): '" Updates summing for metrics in an aggregator.\n\n TODO: don\'t use s...
def construct_averages(metrics_sums, total_num): ' Computes the averages for metrics.\n\n Inputs:\n metrics_sums (dict Metric -> float): Sums for a metric.\n total_num (int): Number to divide by (average).\n ' metrics_averages = {} for (metric, value) in metrics_sums.items(): m...
def evaluate_utterance_sample(sample, model, max_generation_length, name='', gold_forcing=False, metrics=None, total_num=(- 1), database_username='', database_password='', database_timeout=0, write_results=False): 'Evaluates a sample of utterance examples.\n\n Inputs:\n sample (list of Utterance): Examp...
def evaluate_interaction_sample(sample, model, max_generation_length, name='', gold_forcing=False, metrics=None, total_num=(- 1), database_username='', database_password='', database_timeout=0, use_predicted_queries=False, write_results=False, use_gpu=False, compute_metrics=False): ' Evaluates a sample of interac...
def evaluate_using_predicted_queries(sample, model, name='', gold_forcing=False, metrics=None, total_num=(- 1), database_username='', database_password='', database_timeout=0, snippet_keep_age=1): predictions_file = open((name + '_predictions.json'), 'w') print(('Predicting with file ' + str((name + '_predict...
def interpret_args(): ' Interprets the command line arguments, and returns a dictionary. ' parser = argparse.ArgumentParser() parser.add_argument('--no_gpus', type=bool, default=1) parser.add_argument('--raw_train_filename', type=str, default='../atis_data/data/resplit/processed/train_with_tables.pkl'...
def find_shortest_path(start, end, graph): stack = [[start, []]] visited = set() while (len(stack) > 0): (ele, history) = stack.pop() if (ele == end): return history for node in graph[ele]: if (node[0] not in visited): stack.append((node[0], ...
def gen_from(candidate_tables, schema): if (len(candidate_tables) <= 1): if (len(candidate_tables) == 1): ret = 'from {}'.format(schema['table_names_original'][list(candidate_tables)[0]]) else: ret = 'from {}'.format(schema['table_names_original'][0]) return ({}, re...