partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
WikiTablesSemanticParser._get_neighbor_indices
This method returns the indices of each entity's neighbors. A tensor is accepted as a parameter for copying purposes. Parameters ---------- worlds : ``List[WikiTablesWorld]`` num_entities : ``int`` tensor : ``torch.Tensor`` Used for copying the constructed li...
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
def _get_neighbor_indices(worlds: List[WikiTablesWorld], num_entities: int, tensor: torch.Tensor) -> torch.LongTensor: """ This method returns the indices of each entity's neighbors. A tensor is accepted as a parameter for copying purpo...
def _get_neighbor_indices(worlds: List[WikiTablesWorld], num_entities: int, tensor: torch.Tensor) -> torch.LongTensor: """ This method returns the indices of each entity's neighbors. A tensor is accepted as a parameter for copying purpo...
[ "This", "method", "returns", "the", "indices", "of", "each", "entity", "s", "neighbors", ".", "A", "tensor", "is", "accepted", "as", "a", "parameter", "for", "copying", "purposes", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L299-L341
[ "def", "_get_neighbor_indices", "(", "worlds", ":", "List", "[", "WikiTablesWorld", "]", ",", "num_entities", ":", "int", ",", "tensor", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "LongTensor", ":", "num_neighbors", "=", "0", "for", "world", "in...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesSemanticParser._get_type_vector
Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's type. In addition, a map from a flattened entity index to type is returned to combine entity type operations into one method. Parameters ---------- worlds : ``List[WikiTablesWorld]`` n...
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
def _get_type_vector(worlds: List[WikiTablesWorld], num_entities: int, tensor: torch.Tensor) -> Tuple[torch.LongTensor, Dict[int, int]]: """ Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's type. In addition,...
def _get_type_vector(worlds: List[WikiTablesWorld], num_entities: int, tensor: torch.Tensor) -> Tuple[torch.LongTensor, Dict[int, int]]: """ Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's type. In addition,...
[ "Produces", "a", "tensor", "with", "shape", "(", "batch_size", "num_entities", ")", "that", "encodes", "each", "entity", "s", "type", ".", "In", "addition", "a", "map", "from", "a", "flattened", "entity", "index", "to", "type", "is", "returned", "to", "com...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L344-L390
[ "def", "_get_type_vector", "(", "worlds", ":", "List", "[", "WikiTablesWorld", "]", ",", "num_entities", ":", "int", ",", "tensor", ":", "torch", ".", "Tensor", ")", "->", "Tuple", "[", "torch", ".", "LongTensor", ",", "Dict", "[", "int", ",", "int", "...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesSemanticParser._get_linking_probabilities
Produces the probability of an entity given a question word and type. The logic below separates the entities by type since the softmax normalization term sums over entities of a single type. Parameters ---------- worlds : ``List[WikiTablesWorld]`` linking_scores : ``torc...
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
def _get_linking_probabilities(self, worlds: List[WikiTablesWorld], linking_scores: torch.FloatTensor, question_mask: torch.LongTensor, entity_type_dict: Dict[int, int]) -> torch.F...
def _get_linking_probabilities(self, worlds: List[WikiTablesWorld], linking_scores: torch.FloatTensor, question_mask: torch.LongTensor, entity_type_dict: Dict[int, int]) -> torch.F...
[ "Produces", "the", "probability", "of", "an", "entity", "given", "a", "question", "word", "and", "type", ".", "The", "logic", "below", "separates", "the", "entities", "by", "type", "since", "the", "softmax", "normalization", "term", "sums", "over", "entities",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L392-L472
[ "def", "_get_linking_probabilities", "(", "self", ",", "worlds", ":", "List", "[", "WikiTablesWorld", "]", ",", "linking_scores", ":", "torch", ".", "FloatTensor", ",", "question_mask", ":", "torch", ".", "LongTensor", ",", "entity_type_dict", ":", "Dict", "[", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesSemanticParser.get_metrics
We track three metrics here: 1. dpd_acc, which is the percentage of the time that our best output action sequence is in the set of action sequences provided by DPD. This is an easy-to-compute lower bound on denotation accuracy for the set of examples where we actually have DPD outp...
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
def get_metrics(self, reset: bool = False) -> Dict[str, float]: """ We track three metrics here: 1. dpd_acc, which is the percentage of the time that our best output action sequence is in the set of action sequences provided by DPD. This is an easy-to-compute lower bound ...
def get_metrics(self, reset: bool = False) -> Dict[str, float]: """ We track three metrics here: 1. dpd_acc, which is the percentage of the time that our best output action sequence is in the set of action sequences provided by DPD. This is an easy-to-compute lower bound ...
[ "We", "track", "three", "metrics", "here", ":" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L486-L511
[ "def", "get_metrics", "(", "self", ",", "reset", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "float", "]", ":", "return", "{", "'dpd_acc'", ":", "self", ".", "_action_sequence_accuracy", ".", "get_metric", "(", "reset", ")", ",", "'d...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesSemanticParser._create_grammar_state
This method creates the LambdaGrammarStatelet object that's used for decoding. Part of creating that is creating the `valid_actions` dictionary, which contains embedded representations of all of the valid actions. So, we create that here as well. The way we represent the valid expansions is a...
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
def _create_grammar_state(self, world: WikiTablesWorld, possible_actions: List[ProductionRule], linking_scores: torch.Tensor, entity_types: torch.Tensor) -> LambdaGrammarStatelet: """ ...
def _create_grammar_state(self, world: WikiTablesWorld, possible_actions: List[ProductionRule], linking_scores: torch.Tensor, entity_types: torch.Tensor) -> LambdaGrammarStatelet: """ ...
[ "This", "method", "creates", "the", "LambdaGrammarStatelet", "object", "that", "s", "used", "for", "decoding", ".", "Part", "of", "creating", "that", "is", "creating", "the", "valid_actions", "dictionary", "which", "contains", "embedded", "representations", "of", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L513-L620
[ "def", "_create_grammar_state", "(", "self", ",", "world", ":", "WikiTablesWorld", ",", "possible_actions", ":", "List", "[", "ProductionRule", "]", ",", "linking_scores", ":", "torch", ".", "Tensor", ",", "entity_types", ":", "torch", ".", "Tensor", ")", "->"...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesSemanticParser._compute_validation_outputs
Does common things for validation time: computing logical form accuracy (which is expensive and unnecessary during training), adding visualization info to the output dictionary, etc. This doesn't return anything; instead it `modifies` the given ``outputs`` dictionary, and calls metrics on ``sel...
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
def _compute_validation_outputs(self, actions: List[List[ProductionRule]], best_final_states: Mapping[int, Sequence[GrammarBasedState]], world: List[WikiTablesWorld], example_l...
def _compute_validation_outputs(self, actions: List[List[ProductionRule]], best_final_states: Mapping[int, Sequence[GrammarBasedState]], world: List[WikiTablesWorld], example_l...
[ "Does", "common", "things", "for", "validation", "time", ":", "computing", "logical", "form", "accuracy", "(", "which", "is", "expensive", "and", "unnecessary", "during", "training", ")", "adding", "visualization", "info", "to", "the", "output", "dictionary", "e...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L622-L673
[ "def", "_compute_validation_outputs", "(", "self", ",", "actions", ":", "List", "[", "List", "[", "ProductionRule", "]", "]", ",", "best_final_states", ":", "Mapping", "[", "int", ",", "Sequence", "[", "GrammarBasedState", "]", "]", ",", "world", ":", "List"...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesSemanticParser.decode
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test time, to finalize predictions. This is (confusingly) a separate notion from the "decoder" in "encoder/decoder", where that decoder logic lives in the ``TransitionFunction``. This method trims the output ...
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """ This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test time, to finalize predictions. This is (confusingly) a separate notion from the "decoder" in "encoder/decoder...
def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """ This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test time, to finalize predictions. This is (confusingly) a separate notion from the "decoder" in "encoder/decoder...
[ "This", "method", "overrides", "Model", ".", "decode", "which", "gets", "called", "after", "Model", ".", "forward", "at", "test", "time", "to", "finalize", "predictions", ".", "This", "is", "(", "confusingly", ")", "a", "separate", "notion", "from", "the", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L676-L708
[ "def", "decode", "(", "self", ",", "output_dict", ":", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ")", "->", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ":", "action_mapping", "=", "output_dict", "[", "'action_mapping'", "]", "best...
648a36f77db7e45784c047176074f98534c76636
train
LinkingCoverageTransitionFunction._get_linked_logits_addition
Gets the logits of desired terminal actions yet to be produced by the decoder, and returns them for the decoder to add to the prior action logits, biasing the model towards predicting missing linked actions.
allennlp/state_machines/transition_functions/linking_coverage_transition_function.py
def _get_linked_logits_addition(checklist_state: ChecklistStatelet, action_ids: List[int], action_logits: torch.Tensor) -> torch.Tensor: """ Gets the logits of desired terminal actions yet to be produced by the decoder, and ...
def _get_linked_logits_addition(checklist_state: ChecklistStatelet, action_ids: List[int], action_logits: torch.Tensor) -> torch.Tensor: """ Gets the logits of desired terminal actions yet to be produced by the decoder, and ...
[ "Gets", "the", "logits", "of", "desired", "terminal", "actions", "yet", "to", "be", "produced", "by", "the", "decoder", "and", "returns", "them", "for", "the", "decoder", "to", "add", "to", "the", "prior", "action", "logits", "biasing", "the", "model", "to...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/linking_coverage_transition_function.py#L161-L196
[ "def", "_get_linked_logits_addition", "(", "checklist_state", ":", "ChecklistStatelet", ",", "action_ids", ":", "List", "[", "int", "]", ",", "action_logits", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# Our basic approach here will be to ...
648a36f77db7e45784c047176074f98534c76636
train
BasicTransitionFunction.attend_on_question
Given a query (which is typically the decoder hidden state), compute an attention over the output of the question encoder, and return a weighted sum of the question representations given this attention. We also return the attention weights themselves. This is a simple computation, but we have ...
allennlp/state_machines/transition_functions/basic_transition_function.py
def attend_on_question(self, query: torch.Tensor, encoder_outputs: torch.Tensor, encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Given a query (which is typically the decoder hidden state), comp...
def attend_on_question(self, query: torch.Tensor, encoder_outputs: torch.Tensor, encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Given a query (which is typically the decoder hidden state), comp...
[ "Given", "a", "query", "(", "which", "is", "typically", "the", "decoder", "hidden", "state", ")", "compute", "an", "attention", "over", "the", "output", "of", "the", "question", "encoder", "and", "return", "a", "weighted", "sum", "of", "the", "question", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/basic_transition_function.py#L393-L412
[ "def", "attend_on_question", "(", "self", ",", "query", ":", "torch", ".", "Tensor", ",", "encoder_outputs", ":", "torch", ".", "Tensor", ",", "encoder_output_mask", ":", "torch", ".", "Tensor", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch"...
648a36f77db7e45784c047176074f98534c76636
train
ActionSpaceWalker._walk
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.
allennlp/semparse/action_space_walker.py
def _walk(self) -> None: """ Walk over action space to collect completed paths of at most ``self._max_path_length`` steps. """ # Buffer of NTs to expand, previous actions incomplete_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in s...
def _walk(self) -> None: """ Walk over action space to collect completed paths of at most ``self._max_path_length`` steps. """ # Buffer of NTs to expand, previous actions incomplete_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in s...
[ "Walk", "over", "action", "space", "to", "collect", "completed", "paths", "of", "at", "most", "self", ".", "_max_path_length", "steps", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/action_space_walker.py#L35-L101
[ "def", "_walk", "(", "self", ")", "->", "None", ":", "# Buffer of NTs to expand, previous actions", "incomplete_paths", "=", "[", "(", "[", "str", "(", "type_", ")", "]", ",", "[", "f\"{START_SYMBOL} -> {type_}\"", "]", ")", "for", "type_", "in", "self", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
Batch._check_types
Check that all the instances have the same types.
allennlp/data/dataset.py
def _check_types(self) -> None: """ Check that all the instances have the same types. """ all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__ for k, v in x.fields.items()} ...
def _check_types(self) -> None: """ Check that all the instances have the same types. """ all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__ for k, v in x.fields.items()} ...
[ "Check", "that", "all", "the", "instances", "have", "the", "same", "types", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset.py#L35-L44
[ "def", "_check_types", "(", "self", ")", "->", "None", ":", "all_instance_fields_and_types", ":", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "[", "{", "k", ":", "v", ".", "__class__", ".", "__name__", "for", "k", ",", "v", "in", "x...
648a36f77db7e45784c047176074f98534c76636
train
Batch.get_padding_lengths
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance`` has multiple ``Fields``, and each ``Field`` could have multiple things that need padding. We look at all fields in all instances, and find the max values for each (field_name, padding_key) pair, returning t...
allennlp/data/dataset.py
def get_padding_lengths(self) -> Dict[str, Dict[str, int]]: """ Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance`` has multiple ``Fields``, and each ``Field`` could have multiple things that need padding. We look at all fields in all instances, and ...
def get_padding_lengths(self) -> Dict[str, Dict[str, int]]: """ Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance`` has multiple ``Fields``, and each ``Field`` could have multiple things that need padding. We look at all fields in all instances, and ...
[ "Gets", "the", "maximum", "padding", "lengths", "from", "all", "Instances", "in", "this", "batch", ".", "Each", "Instance", "has", "multiple", "Fields", "and", "each", "Field", "could", "have", "multiple", "things", "that", "need", "padding", ".", "We", "loo...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset.py#L46-L69
[ "def", "get_padding_lengths", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", ":", "padding_lengths", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", "=", "defaultdict", "(", "dict"...
648a36f77db7e45784c047176074f98534c76636
train
Batch.as_tensor_dict
This method converts this ``Batch`` into a set of pytorch Tensors that can be passed through a model. In order for the tensors to be valid tensors, all ``Instances`` in this batch need to be padded to the same lengths wherever padding is necessary, so we do that first, then we combine all of th...
allennlp/data/dataset.py
def as_tensor_dict(self, padding_lengths: Dict[str, Dict[str, int]] = None, verbose: bool = False) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]: # This complex return type is actually predefined elsewhere as a DataArray, # but we can't use it b...
def as_tensor_dict(self, padding_lengths: Dict[str, Dict[str, int]] = None, verbose: bool = False) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]: # This complex return type is actually predefined elsewhere as a DataArray, # but we can't use it b...
[ "This", "method", "converts", "this", "Batch", "into", "a", "set", "of", "pytorch", "Tensors", "that", "can", "be", "passed", "through", "a", "model", ".", "In", "order", "for", "the", "tensors", "to", "be", "valid", "tensors", "all", "Instances", "in", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset.py#L71-L148
[ "def", "as_tensor_dict", "(", "self", ",", "padding_lengths", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", "=", "None", ",", "verbose", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "Union", "[", "torch",...
648a36f77db7e45784c047176074f98534c76636
train
get_strings_from_utterance
Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to.
allennlp/semparse/worlds/atis_world.py
def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to. """ string_linking_scores: Dict[str, List[i...
def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to. """ string_linking_scores: Dict[str, List[i...
[ "Based", "on", "the", "current", "utterance", "return", "a", "dictionary", "where", "the", "keys", "are", "the", "strings", "in", "the", "database", "that", "map", "to", "lists", "of", "the", "token", "indices", "that", "they", "are", "linked", "to", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L15-L42
[ "def", "get_strings_from_utterance", "(", "tokenized_utterance", ":", "List", "[", "Token", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", "int", "]", "]", ":", "string_linking_scores", ":", "Dict", "[", "str", ",", "List", "[", "int", "]", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
AtisWorld._update_grammar
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we don't have to create a new grammar from...
allennlp/semparse/worlds/atis_world.py
def _update_grammar(self): """ We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we ...
def _update_grammar(self): """ We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we ...
[ "We", "create", "a", "new", "Grammar", "object", "from", "the", "one", "in", "AtisSqlTableContext", "that", "also", "has", "the", "new", "entities", "that", "are", "extracted", "from", "the", "utterance", ".", "Stitching", "together", "the", "expressions", "to...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L83-L183
[ "def", "_update_grammar", "(", "self", ")", ":", "# This will give us a shallow copy. We have to be careful here because the ``Grammar`` object", "# contains ``Expression`` objects that have tuples containing the members of that expression.", "# We have to create new sub-expression objects so that o...
648a36f77db7e45784c047176074f98534c76636
train
AtisWorld._update_expression_reference
When we add a new expression, there may be other expressions that refer to it, and we need to update those to point to the new expression.
allennlp/semparse/worlds/atis_world.py
def _update_expression_reference(self, # pylint: disable=no-self-use grammar: Grammar, parent_expression_nonterminal: str, child_expression_nonterminal: str) -> None: """ When we add a new expr...
def _update_expression_reference(self, # pylint: disable=no-self-use grammar: Grammar, parent_expression_nonterminal: str, child_expression_nonterminal: str) -> None: """ When we add a new expr...
[ "When", "we", "add", "a", "new", "expression", "there", "may", "be", "other", "expressions", "that", "refer", "to", "it", "and", "we", "need", "to", "update", "those", "to", "point", "to", "the", "new", "expression", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L198-L209
[ "def", "_update_expression_reference", "(", "self", ",", "# pylint: disable=no-self-use", "grammar", ":", "Grammar", ",", "parent_expression_nonterminal", ":", "str", ",", "child_expression_nonterminal", ":", "str", ")", "->", "None", ":", "grammar", "[", "parent_expres...
648a36f77db7e45784c047176074f98534c76636
train
AtisWorld._get_sequence_with_spacing
This is a helper method for generating sequences, since we often want a list of expressions with whitespaces between them.
allennlp/semparse/worlds/atis_world.py
def _get_sequence_with_spacing(self, # pylint: disable=no-self-use new_grammar, expressions: List[Expression], name: str = '') -> Sequence: """ This is a helper method for generating sequences, since...
def _get_sequence_with_spacing(self, # pylint: disable=no-self-use new_grammar, expressions: List[Expression], name: str = '') -> Sequence: """ This is a helper method for generating sequences, since...
[ "This", "is", "a", "helper", "method", "for", "generating", "sequences", "since", "we", "often", "want", "a", "list", "of", "expressions", "with", "whitespaces", "between", "them", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L211-L222
[ "def", "_get_sequence_with_spacing", "(", "self", ",", "# pylint: disable=no-self-use", "new_grammar", ",", "expressions", ":", "List", "[", "Expression", "]", ",", "name", ":", "str", "=", "''", ")", "->", "Sequence", ":", "expressions", "=", "[", "subexpressio...
648a36f77db7e45784c047176074f98534c76636
train
AtisWorld.add_to_number_linking_scores
This is a helper method for adding different types of numbers (eg. starting time ranges) as entities. We first go through all utterances in the interaction and find the numbers of a certain type and add them to the set ``all_numbers``, which is initialized with default values. We want to add all numbers...
allennlp/semparse/worlds/atis_world.py
def add_to_number_linking_scores(self, all_numbers: Set[str], number_linking_scores: Dict[str, Tuple[str, str, List[int]]], get_number_linking_dict: Callable[[str, List[Token]], ...
def add_to_number_linking_scores(self, all_numbers: Set[str], number_linking_scores: Dict[str, Tuple[str, str, List[int]]], get_number_linking_dict: Callable[[str, List[Token]], ...
[ "This", "is", "a", "helper", "method", "for", "adding", "different", "types", "of", "numbers", "(", "eg", ".", "starting", "time", "ranges", ")", "as", "entities", ".", "We", "first", "go", "through", "all", "utterances", "in", "the", "interaction", "and",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L274-L302
[ "def", "add_to_number_linking_scores", "(", "self", ",", "all_numbers", ":", "Set", "[", "str", "]", ",", "number_linking_scores", ":", "Dict", "[", "str", ",", "Tuple", "[", "str", ",", "str", ",", "List", "[", "int", "]", "]", "]", ",", "get_number_lin...
648a36f77db7e45784c047176074f98534c76636
train
AtisWorld._get_linked_entities
This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later for updating the valid actions and the grammar.
allennlp/semparse/worlds/atis_world.py
def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]: """ This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later ...
def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]: """ This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later ...
[ "This", "method", "gets", "entities", "from", "the", "current", "utterance", "finds", "which", "tokens", "they", "are", "linked", "to", ".", "The", "entities", "are", "divided", "into", "two", "main", "groups", "numbers", "and", "strings", ".", "We", "rely",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L305-L381
[ "def", "_get_linked_entities", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Tuple", "[", "str", ",", "str", ",", "List", "[", "int", "]", "]", "]", "]", ":", "current_tokenized_utterance", "=", "[", "]", "if", "not", "...
648a36f77db7e45784c047176074f98534c76636
train
AtisWorld.all_possible_actions
Return a sorted list of strings representing all possible actions of the form: nonterminal -> [right_hand_side]
allennlp/semparse/worlds/atis_world.py
def all_possible_actions(self) -> List[str]: """ Return a sorted list of strings representing all possible actions of the form: nonterminal -> [right_hand_side] """ all_actions = set() for _, action_list in self.valid_actions.items(): for action in action_list...
def all_possible_actions(self) -> List[str]: """ Return a sorted list of strings representing all possible actions of the form: nonterminal -> [right_hand_side] """ all_actions = set() for _, action_list in self.valid_actions.items(): for action in action_list...
[ "Return", "a", "sorted", "list", "of", "strings", "representing", "all", "possible", "actions", "of", "the", "form", ":", "nonterminal", "-", ">", "[", "right_hand_side", "]" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L413-L422
[ "def", "all_possible_actions", "(", "self", ")", "->", "List", "[", "str", "]", ":", "all_actions", "=", "set", "(", ")", "for", "_", ",", "action_list", "in", "self", ".", "valid_actions", ".", "items", "(", ")", ":", "for", "action", "in", "action_li...
648a36f77db7e45784c047176074f98534c76636
train
AtisWorld._flatten_entities
When we first get the entities and the linking scores in ``_get_linked_entities`` we represent as dictionaries for easier updates to the grammar and valid actions. In this method, we flatten them for the model so that the entities are represented as a list, and the linking scores are a 2D numpy ...
allennlp/semparse/worlds/atis_world.py
def _flatten_entities(self) -> Tuple[List[str], numpy.ndarray]: """ When we first get the entities and the linking scores in ``_get_linked_entities`` we represent as dictionaries for easier updates to the grammar and valid actions. In this method, we flatten them for the model so that th...
def _flatten_entities(self) -> Tuple[List[str], numpy.ndarray]: """ When we first get the entities and the linking scores in ``_get_linked_entities`` we represent as dictionaries for easier updates to the grammar and valid actions. In this method, we flatten them for the model so that th...
[ "When", "we", "first", "get", "the", "entities", "and", "the", "linking", "scores", "in", "_get_linked_entities", "we", "represent", "as", "dictionaries", "for", "easier", "updates", "to", "the", "grammar", "and", "valid", "actions", ".", "In", "this", "method...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L424-L441
[ "def", "_flatten_entities", "(", "self", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "numpy", ".", "ndarray", "]", ":", "entities", "=", "[", "]", "linking_scores", "=", "[", "]", "for", "entity", "in", "sorted", "(", "self", ".", "linked_...
648a36f77db7e45784c047176074f98534c76636
train
make_app
Creates a Flask app that serves up a simple configuration wizard.
allennlp/service/config_explorer.py
def make_app(include_packages: Sequence[str] = ()) -> Flask: """ Creates a Flask app that serves up a simple configuration wizard. """ # Load modules for package_name in include_packages: import_submodules(package_name) app = Flask(__name__) # pylint: disable=invalid-name @app.err...
def make_app(include_packages: Sequence[str] = ()) -> Flask: """ Creates a Flask app that serves up a simple configuration wizard. """ # Load modules for package_name in include_packages: import_submodules(package_name) app = Flask(__name__) # pylint: disable=invalid-name @app.err...
[ "Creates", "a", "Flask", "app", "that", "serves", "up", "a", "simple", "configuration", "wizard", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/service/config_explorer.py#L31-L105
[ "def", "make_app", "(", "include_packages", ":", "Sequence", "[", "str", "]", "=", "(", ")", ")", "->", "Flask", ":", "# Load modules", "for", "package_name", "in", "include_packages", ":", "import_submodules", "(", "package_name", ")", "app", "=", "Flask", ...
648a36f77db7e45784c047176074f98534c76636
train
train_model_from_args
Just converts from an ``argparse.Namespace`` object to string paths.
allennlp/commands/train.py
def train_model_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to string paths. """ train_model_from_file(args.param_path, args.serialization_dir, args.overrides, args.file_friendl...
def train_model_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to string paths. """ train_model_from_file(args.param_path, args.serialization_dir, args.overrides, args.file_friendl...
[ "Just", "converts", "from", "an", "argparse", ".", "Namespace", "object", "to", "string", "paths", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/train.py#L105-L116
[ "def", "train_model_from_args", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "train_model_from_file", "(", "args", ".", "param_path", ",", "args", ".", "serialization_dir", ",", "args", ".", "overrides", ",", "args", ".", "file_friendly_logging", ",...
648a36f77db7e45784c047176074f98534c76636
train
train_model_from_file
A wrapper around :func:`train_model` which loads the params from a file. Parameters ---------- parameter_filename : ``str`` A json parameter file specifying an AllenNLP experiment. serialization_dir : ``str`` The directory in which to save results and logs. We just pass this along to ...
allennlp/commands/train.py
def train_model_from_file(parameter_filename: str, serialization_dir: str, overrides: str = "", file_friendly_logging: bool = False, recover: bool = False, force: bool = False, ...
def train_model_from_file(parameter_filename: str, serialization_dir: str, overrides: str = "", file_friendly_logging: bool = False, recover: bool = False, force: bool = False, ...
[ "A", "wrapper", "around", ":", "func", ":", "train_model", "which", "loads", "the", "params", "from", "a", "file", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/train.py#L119-L160
[ "def", "train_model_from_file", "(", "parameter_filename", ":", "str", ",", "serialization_dir", ":", "str", ",", "overrides", ":", "str", "=", "\"\"", ",", "file_friendly_logging", ":", "bool", "=", "False", ",", "recover", ":", "bool", "=", "False", ",", "...
648a36f77db7e45784c047176074f98534c76636
train
train_model
Trains the model specified in the given :class:`Params` object, using the data and training parameters also specified in that object, and saves the results in ``serialization_dir``. Parameters ---------- params : ``Params`` A parameter object specifying an AllenNLP Experiment. serialization...
allennlp/commands/train.py
def train_model(params: Params, serialization_dir: str, file_friendly_logging: bool = False, recover: bool = False, force: bool = False, cache_directory: str = None, cache_prefix: str = None) -> Model: """ Trains the...
def train_model(params: Params, serialization_dir: str, file_friendly_logging: bool = False, recover: bool = False, force: bool = False, cache_directory: str = None, cache_prefix: str = None) -> Model: """ Trains the...
[ "Trains", "the", "model", "specified", "in", "the", "given", ":", "class", ":", "Params", "object", "using", "the", "data", "and", "training", "parameters", "also", "specified", "in", "that", "object", "and", "saves", "the", "results", "in", "serialization_dir...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/train.py#L163-L269
[ "def", "train_model", "(", "params", ":", "Params", ",", "serialization_dir", ":", "str", ",", "file_friendly_logging", ":", "bool", "=", "False", ",", "recover", ":", "bool", "=", "False", ",", "force", ":", "bool", "=", "False", ",", "cache_directory", "...
648a36f77db7e45784c047176074f98534c76636
train
_prf_divide
Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero.
allennlp/training/metrics/fbeta_measure.py
def _prf_divide(numerator, denominator): """Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero. """ result = numerator / denominator mask = denominator == 0.0 if not mask.any(): return result # remove nan result[mask] ...
def _prf_divide(numerator, denominator): """Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero. """ result = numerator / denominator mask = denominator == 0.0 if not mask.any(): return result # remove nan result[mask] ...
[ "Performs", "division", "and", "handles", "divide", "-", "by", "-", "zero", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/fbeta_measure.py#L231-L243
[ "def", "_prf_divide", "(", "numerator", ",", "denominator", ")", ":", "result", "=", "numerator", "/", "denominator", "mask", "=", "denominator", "==", "0.0", "if", "not", "mask", ".", "any", "(", ")", ":", "return", "result", "# remove nan", "result", "["...
648a36f77db7e45784c047176074f98534c76636
train
load_data
One sentence per line, formatted like The###DET dog###NN ate###V the###DET apple###NN Returns a list of pairs (tokenized_sentence, tags)
tutorials/tagger/basic_pytorch.py
def load_data(file_path: str) -> Tuple[List[str], List[str]]: """ One sentence per line, formatted like The###DET dog###NN ate###V the###DET apple###NN Returns a list of pairs (tokenized_sentence, tags) """ data = [] with open(file_path) as f: for line in f: pairs ...
def load_data(file_path: str) -> Tuple[List[str], List[str]]: """ One sentence per line, formatted like The###DET dog###NN ate###V the###DET apple###NN Returns a list of pairs (tokenized_sentence, tags) """ data = [] with open(file_path) as f: for line in f: pairs ...
[ "One", "sentence", "per", "line", "formatted", "like" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/tutorials/tagger/basic_pytorch.py#L23-L39
[ "def", "load_data", "(", "file_path", ":", "str", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "List", "[", "str", "]", "]", ":", "data", "=", "[", "]", "with", "open", "(", "file_path", ")", "as", "f", ":", "for", "line", "in", "f", ...
648a36f77db7e45784c047176074f98534c76636
train
pop_max_vocab_size
max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token. max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing). But it could also be a string representing an int (in the case of environment variable substitution). So we need some complex logic to handl...
allennlp/data/vocabulary.py
def pop_max_vocab_size(params: Params) -> Union[int, Dict[str, int]]: """ max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token. max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing). But it could also be a string representing an int (in the case...
def pop_max_vocab_size(params: Params) -> Union[int, Dict[str, int]]: """ max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token. max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing). But it could also be a string representing an int (in the case...
[ "max_vocab_size", "limits", "the", "size", "of", "the", "vocabulary", "not", "including", "the", "@@UNKNOWN@@", "token", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L117-L134
[ "def", "pop_max_vocab_size", "(", "params", ":", "Params", ")", "->", "Union", "[", "int", ",", "Dict", "[", "str", ",", "int", "]", "]", ":", "size", "=", "params", ".", "pop", "(", "\"max_vocab_size\"", ",", "None", ")", "if", "isinstance", "(", "s...
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary.save_to_files
Persist this Vocabulary to files so it can be reloaded later. Each namespace corresponds to one file. Parameters ---------- directory : ``str`` The directory where we save the serialized vocabulary.
allennlp/data/vocabulary.py
def save_to_files(self, directory: str) -> None: """ Persist this Vocabulary to files so it can be reloaded later. Each namespace corresponds to one file. Parameters ---------- directory : ``str`` The directory where we save the serialized vocabulary. ...
def save_to_files(self, directory: str) -> None: """ Persist this Vocabulary to files so it can be reloaded later. Each namespace corresponds to one file. Parameters ---------- directory : ``str`` The directory where we save the serialized vocabulary. ...
[ "Persist", "this", "Vocabulary", "to", "files", "so", "it", "can", "be", "reloaded", "later", ".", "Each", "namespace", "corresponds", "to", "one", "file", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L270-L294
[ "def", "save_to_files", "(", "self", ",", "directory", ":", "str", ")", "->", "None", ":", "os", ".", "makedirs", "(", "directory", ",", "exist_ok", "=", "True", ")", "if", "os", ".", "listdir", "(", "directory", ")", ":", "logging", ".", "warning", ...
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary.from_files
Loads a ``Vocabulary`` that was serialized using ``save_to_files``. Parameters ---------- directory : ``str`` The directory containing the serialized vocabulary.
allennlp/data/vocabulary.py
def from_files(cls, directory: str) -> 'Vocabulary': """ Loads a ``Vocabulary`` that was serialized using ``save_to_files``. Parameters ---------- directory : ``str`` The directory containing the serialized vocabulary. """ logger.info("Loading token d...
def from_files(cls, directory: str) -> 'Vocabulary': """ Loads a ``Vocabulary`` that was serialized using ``save_to_files``. Parameters ---------- directory : ``str`` The directory containing the serialized vocabulary. """ logger.info("Loading token d...
[ "Loads", "a", "Vocabulary", "that", "was", "serialized", "using", "save_to_files", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L297-L326
[ "def", "from_files", "(", "cls", ",", "directory", ":", "str", ")", "->", "'Vocabulary'", ":", "logger", ".", "info", "(", "\"Loading token dictionary from %s.\"", ",", "directory", ")", "with", "codecs", ".", "open", "(", "os", ".", "path", ".", "join", "...
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary.set_from_file
If you already have a vocabulary file for a trained model somewhere, and you really want to use that vocabulary file instead of just setting the vocabulary from a dataset, for whatever reason, you can do that with this method. You must specify the namespace to use, and we assume that you want t...
allennlp/data/vocabulary.py
def set_from_file(self, filename: str, is_padded: bool = True, oov_token: str = DEFAULT_OOV_TOKEN, namespace: str = "tokens"): """ If you already have a vocabulary file for a trained model somewhere, and you really w...
def set_from_file(self, filename: str, is_padded: bool = True, oov_token: str = DEFAULT_OOV_TOKEN, namespace: str = "tokens"): """ If you already have a vocabulary file for a trained model somewhere, and you really w...
[ "If", "you", "already", "have", "a", "vocabulary", "file", "for", "a", "trained", "model", "somewhere", "and", "you", "really", "want", "to", "use", "that", "vocabulary", "file", "instead", "of", "just", "setting", "the", "vocabulary", "from", "a", "dataset"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L328-L378
[ "def", "set_from_file", "(", "self", ",", "filename", ":", "str", ",", "is_padded", ":", "bool", "=", "True", ",", "oov_token", ":", "str", "=", "DEFAULT_OOV_TOKEN", ",", "namespace", ":", "str", "=", "\"tokens\"", ")", ":", "if", "is_padded", ":", "self...
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary.from_instances
Constructs a vocabulary given a collection of `Instances` and some parameters. We count all of the vocabulary items in the instances, then pass those counts and the other parameters, to :func:`__init__`. See that method for a description of what the other parameters do.
allennlp/data/vocabulary.py
def from_instances(cls, instances: Iterable['adi.Instance'], min_count: Dict[str, int] = None, max_vocab_size: Union[int, Dict[str, int]] = None, non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES, ...
def from_instances(cls, instances: Iterable['adi.Instance'], min_count: Dict[str, int] = None, max_vocab_size: Union[int, Dict[str, int]] = None, non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES, ...
[ "Constructs", "a", "vocabulary", "given", "a", "collection", "of", "Instances", "and", "some", "parameters", ".", "We", "count", "all", "of", "the", "vocabulary", "items", "in", "the", "instances", "then", "pass", "those", "counts", "and", "the", "other", "p...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L381-L408
[ "def", "from_instances", "(", "cls", ",", "instances", ":", "Iterable", "[", "'adi.Instance'", "]", ",", "min_count", ":", "Dict", "[", "str", ",", "int", "]", "=", "None", ",", "max_vocab_size", ":", "Union", "[", "int", ",", "Dict", "[", "str", ",", ...
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary.from_params
There are two possible ways to build a vocabulary; from a collection of instances, using :func:`Vocabulary.from_instances`, or from a pre-saved vocabulary, using :func:`Vocabulary.from_files`. You can also extend pre-saved vocabulary with collection of instances using this method. This m...
allennlp/data/vocabulary.py
def from_params(cls, params: Params, instances: Iterable['adi.Instance'] = None): # type: ignore """ There are two possible ways to build a vocabulary; from a collection of instances, using :func:`Vocabulary.from_instances`, or from a pre-saved vocabulary, using :func:`Vocabulary.from_f...
def from_params(cls, params: Params, instances: Iterable['adi.Instance'] = None): # type: ignore """ There are two possible ways to build a vocabulary; from a collection of instances, using :func:`Vocabulary.from_instances`, or from a pre-saved vocabulary, using :func:`Vocabulary.from_f...
[ "There", "are", "two", "possible", "ways", "to", "build", "a", "vocabulary", ";", "from", "a", "collection", "of", "instances", "using", ":", "func", ":", "Vocabulary", ".", "from_instances", "or", "from", "a", "pre", "-", "saved", "vocabulary", "using", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L412-L487
[ "def", "from_params", "(", "cls", ",", "params", ":", "Params", ",", "instances", ":", "Iterable", "[", "'adi.Instance'", "]", "=", "None", ")", ":", "# type: ignore", "# pylint: disable=arguments-differ", "# Vocabulary is ``Registrable`` so that you can configure a custom ...
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary._extend
This method can be used for extending already generated vocabulary. It takes same parameters as Vocabulary initializer. The token2index and indextotoken mappings of calling vocabulary will be retained. It is an inplace operation so None will be returned.
allennlp/data/vocabulary.py
def _extend(self, counter: Dict[str, Dict[str, int]] = None, min_count: Dict[str, int] = None, max_vocab_size: Union[int, Dict[str, int]] = None, non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES, pretrained_files: Option...
def _extend(self, counter: Dict[str, Dict[str, int]] = None, min_count: Dict[str, int] = None, max_vocab_size: Union[int, Dict[str, int]] = None, non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES, pretrained_files: Option...
[ "This", "method", "can", "be", "used", "for", "extending", "already", "generated", "vocabulary", ".", "It", "takes", "same", "parameters", "as", "Vocabulary", "initializer", ".", "The", "token2index", "and", "indextotoken", "mappings", "of", "calling", "vocabulary...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L489-L567
[ "def", "_extend", "(", "self", ",", "counter", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", "=", "None", ",", "min_count", ":", "Dict", "[", "str", ",", "int", "]", "=", "None", ",", "max_vocab_size", ":", "Union", "[",...
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary.extend_from_instances
Extends an already generated vocabulary using a collection of instances.
allennlp/data/vocabulary.py
def extend_from_instances(self, params: Params, instances: Iterable['adi.Instance'] = ()) -> None: """ Extends an already generated vocabulary using a collection of instances. """ min_count = params.pop("min_count", None) ...
def extend_from_instances(self, params: Params, instances: Iterable['adi.Instance'] = ()) -> None: """ Extends an already generated vocabulary using a collection of instances. """ min_count = params.pop("min_count", None) ...
[ "Extends", "an", "already", "generated", "vocabulary", "using", "a", "collection", "of", "instances", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L569-L595
[ "def", "extend_from_instances", "(", "self", ",", "params", ":", "Params", ",", "instances", ":", "Iterable", "[", "'adi.Instance'", "]", "=", "(", ")", ")", "->", "None", ":", "min_count", "=", "params", ".", "pop", "(", "\"min_count\"", ",", "None", ")...
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary.is_padded
Returns whether or not there are padding and OOV tokens added to the given namespace.
allennlp/data/vocabulary.py
def is_padded(self, namespace: str) -> bool: """ Returns whether or not there are padding and OOV tokens added to the given namespace. """ return self._index_to_token[namespace][0] == self._padding_token
def is_padded(self, namespace: str) -> bool: """ Returns whether or not there are padding and OOV tokens added to the given namespace. """ return self._index_to_token[namespace][0] == self._padding_token
[ "Returns", "whether", "or", "not", "there", "are", "padding", "and", "OOV", "tokens", "added", "to", "the", "given", "namespace", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L597-L601
[ "def", "is_padded", "(", "self", ",", "namespace", ":", "str", ")", "->", "bool", ":", "return", "self", ".", "_index_to_token", "[", "namespace", "]", "[", "0", "]", "==", "self", ".", "_padding_token" ]
648a36f77db7e45784c047176074f98534c76636
train
Vocabulary.add_token_to_namespace
Adds ``token`` to the index, if it is not already present. Either way, we return the index of the token.
allennlp/data/vocabulary.py
def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int: """ Adds ``token`` to the index, if it is not already present. Either way, we return the index of the token. """ if not isinstance(token, str): raise ValueError("Vocabulary tokens must be...
def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int: """ Adds ``token`` to the index, if it is not already present. Either way, we return the index of the token. """ if not isinstance(token, str): raise ValueError("Vocabulary tokens must be...
[ "Adds", "token", "to", "the", "index", "if", "it", "is", "not", "already", "present", ".", "Either", "way", "we", "return", "the", "index", "of", "the", "token", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L603-L617
[ "def", "add_token_to_namespace", "(", "self", ",", "token", ":", "str", ",", "namespace", ":", "str", "=", "'tokens'", ")", "->", "int", ":", "if", "not", "isinstance", "(", "token", ",", "str", ")", ":", "raise", "ValueError", "(", "\"Vocabulary tokens mu...
648a36f77db7e45784c047176074f98534c76636
train
Model.get_regularization_penalty
Computes the regularization penalty for the model. Returns 0 if the model was not configured to use regularization.
allennlp/models/model.py
def get_regularization_penalty(self) -> Union[float, torch.Tensor]: """ Computes the regularization penalty for the model. Returns 0 if the model was not configured to use regularization. """ if self._regularizer is None: return 0.0 else: return se...
def get_regularization_penalty(self) -> Union[float, torch.Tensor]: """ Computes the regularization penalty for the model. Returns 0 if the model was not configured to use regularization. """ if self._regularizer is None: return 0.0 else: return se...
[ "Computes", "the", "regularization", "penalty", "for", "the", "model", ".", "Returns", "0", "if", "the", "model", "was", "not", "configured", "to", "use", "regularization", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L58-L66
[ "def", "get_regularization_penalty", "(", "self", ")", "->", "Union", "[", "float", ",", "torch", ".", "Tensor", "]", ":", "if", "self", ".", "_regularizer", "is", "None", ":", "return", "0.0", "else", ":", "return", "self", ".", "_regularizer", "(", "se...
648a36f77db7e45784c047176074f98534c76636
train
Model.forward_on_instance
Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing) and returns the result. Bef...
allennlp/models/model.py
def forward_on_instance(self, instance: Instance) -> Dict[str, numpy.ndarray]: """ Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :func:`self.forwar...
def forward_on_instance(self, instance: Instance) -> Dict[str, numpy.ndarray]: """ Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :func:`self.forwar...
[ "Takes", "an", ":", "class", ":", "~allennlp", ".", "data", ".", "instance", ".", "Instance", "which", "typically", "has", "raw", "text", "in", "it", "converts", "that", "text", "into", "arrays", "using", "this", "model", "s", ":", "class", ":", "Vocabul...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L116-L124
[ "def", "forward_on_instance", "(", "self", ",", "instance", ":", "Instance", ")", "->", "Dict", "[", "str", ",", "numpy", ".", "ndarray", "]", ":", "return", "self", ".", "forward_on_instances", "(", "[", "instance", "]", ")", "[", "0", "]" ]
648a36f77db7e45784c047176074f98534c76636
train
Model.forward_on_instances
Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing) and returns the result. Before returning the result, w...
allennlp/models/model.py
def forward_on_instances(self, instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]: """ Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :f...
def forward_on_instances(self, instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]: """ Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :f...
[ "Takes", "a", "list", "of", ":", "class", ":", "~allennlp", ".", "data", ".", "instance", ".", "Instance", "s", "converts", "that", "text", "into", "arrays", "using", "this", "model", "s", ":", "class", ":", "Vocabulary", "passes", "those", "arrays", "th...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L126-L172
[ "def", "forward_on_instances", "(", "self", ",", "instances", ":", "List", "[", "Instance", "]", ")", "->", "List", "[", "Dict", "[", "str", ",", "numpy", ".", "ndarray", "]", "]", ":", "batch_size", "=", "len", "(", "instances", ")", "with", "torch", ...
648a36f77db7e45784c047176074f98534c76636
train
Model.decode
Takes the result of :func:`forward` and runs inference / decoding / whatever post-processing you need to do your model. The intent is that ``model.forward()`` should produce potentials or probabilities, and then ``model.decode()`` can take those results and run some kind of beam search or const...
allennlp/models/model.py
def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """ Takes the result of :func:`forward` and runs inference / decoding / whatever post-processing you need to do your model. The intent is that ``model.forward()`` should produce potentials or probabilitie...
def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """ Takes the result of :func:`forward` and runs inference / decoding / whatever post-processing you need to do your model. The intent is that ``model.forward()`` should produce potentials or probabilitie...
[ "Takes", "the", "result", "of", ":", "func", ":", "forward", "and", "runs", "inference", "/", "decoding", "/", "whatever", "post", "-", "processing", "you", "need", "to", "do", "your", "model", ".", "The", "intent", "is", "that", "model", ".", "forward",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L174-L189
[ "def", "decode", "(", "self", ",", "output_dict", ":", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ")", "->", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ":", "# pylint: disable=no-self-use", "return", "output_dict" ]
648a36f77db7e45784c047176074f98534c76636
train
Model._get_prediction_device
This method checks the device of the model parameters to determine the cuda_device this model should be run on for predictions. If there are no parameters, it returns -1. Returns ------- The cuda device this model should run on for predictions.
allennlp/models/model.py
def _get_prediction_device(self) -> int: """ This method checks the device of the model parameters to determine the cuda_device this model should be run on for predictions. If there are no parameters, it returns -1. Returns ------- The cuda device this model should run ...
def _get_prediction_device(self) -> int: """ This method checks the device of the model parameters to determine the cuda_device this model should be run on for predictions. If there are no parameters, it returns -1. Returns ------- The cuda device this model should run ...
[ "This", "method", "checks", "the", "device", "of", "the", "model", "parameters", "to", "determine", "the", "cuda_device", "this", "model", "should", "be", "run", "on", "for", "predictions", ".", "If", "there", "are", "no", "parameters", "it", "returns", "-",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L206-L223
[ "def", "_get_prediction_device", "(", "self", ")", "->", "int", ":", "devices", "=", "{", "util", ".", "get_device_of", "(", "param", ")", "for", "param", "in", "self", ".", "parameters", "(", ")", "}", "if", "len", "(", "devices", ")", ">", "1", ":"...
648a36f77db7e45784c047176074f98534c76636
train
Model._maybe_warn_for_unseparable_batches
This method warns once if a user implements a model which returns a dictionary with values which we are unable to split back up into elements of the batch. This is controlled by a class attribute ``_warn_for_unseperable_batches`` because it would be extremely verbose otherwise.
allennlp/models/model.py
def _maybe_warn_for_unseparable_batches(self, output_key: str): """ This method warns once if a user implements a model which returns a dictionary with values which we are unable to split back up into elements of the batch. This is controlled by a class attribute ``_warn_for_unseperable_...
def _maybe_warn_for_unseparable_batches(self, output_key: str): """ This method warns once if a user implements a model which returns a dictionary with values which we are unable to split back up into elements of the batch. This is controlled by a class attribute ``_warn_for_unseperable_...
[ "This", "method", "warns", "once", "if", "a", "user", "implements", "a", "model", "which", "returns", "a", "dictionary", "with", "values", "which", "we", "are", "unable", "to", "split", "back", "up", "into", "elements", "of", "the", "batch", ".", "This", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L225-L237
[ "def", "_maybe_warn_for_unseparable_batches", "(", "self", ",", "output_key", ":", "str", ")", ":", "if", "output_key", "not", "in", "self", ".", "_warn_for_unseparable_batches", ":", "logger", ".", "warning", "(", "f\"Encountered the {output_key} key in the model's retur...
648a36f77db7e45784c047176074f98534c76636
train
Model._load
Instantiates an already-trained model, based on the experiment configuration and some optional overrides.
allennlp/models/model.py
def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Instantiates an already-trained model, based on the experiment configuration and some optional overrides. """ ...
def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Instantiates an already-trained model, based on the experiment configuration and some optional overrides. """ ...
[ "Instantiates", "an", "already", "-", "trained", "model", "based", "on", "the", "experiment", "configuration", "and", "some", "optional", "overrides", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L240-L285
[ "def", "_load", "(", "cls", ",", "config", ":", "Params", ",", "serialization_dir", ":", "str", ",", "weights_file", ":", "str", "=", "None", ",", "cuda_device", ":", "int", "=", "-", "1", ")", "->", "'Model'", ":", "weights_file", "=", "weights_file", ...
648a36f77db7e45784c047176074f98534c76636
train
Model.load
Instantiates an already-trained model, based on the experiment configuration and some optional overrides. Parameters ---------- config: Params The configuration that was used to train the model. It should definitely have a `model` section, and should probably hav...
allennlp/models/model.py
def load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Instantiates an already-trained model, based on the experiment configuration and some optional overrides. Parameters...
def load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Instantiates an already-trained model, based on the experiment configuration and some optional overrides. Parameters...
[ "Instantiates", "an", "already", "-", "trained", "model", "based", "on", "the", "experiment", "configuration", "and", "some", "optional", "overrides", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L288-L327
[ "def", "load", "(", "cls", ",", "config", ":", "Params", ",", "serialization_dir", ":", "str", ",", "weights_file", ":", "str", "=", "None", ",", "cuda_device", ":", "int", "=", "-", "1", ")", "->", "'Model'", ":", "# Peak at the class of the model.", "mod...
648a36f77db7e45784c047176074f98534c76636
train
Model.extend_embedder_vocab
Iterates through all embedding modules in the model and assures it can embed with the extended vocab. This is required in fine-tuning or transfer learning scenarios where model was trained with original vocabulary but during fine-tuning/tranfer-learning, it will have it work with extended vocabu...
allennlp/models/model.py
def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None: """ Iterates through all embedding modules in the model and assures it can embed with the extended vocab. This is required in fine-tuning or transfer learning scenarios where model was trained with...
def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None: """ Iterates through all embedding modules in the model and assures it can embed with the extended vocab. This is required in fine-tuning or transfer learning scenarios where model was trained with...
[ "Iterates", "through", "all", "embedding", "modules", "in", "the", "model", "and", "assures", "it", "can", "embed", "with", "the", "extended", "vocab", ".", "This", "is", "required", "in", "fine", "-", "tuning", "or", "transfer", "learning", "scenarios", "wh...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L329-L354
[ "def", "extend_embedder_vocab", "(", "self", ",", "embedding_sources_mapping", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ")", "->", "None", ":", "# self.named_modules() gives all sub-modules (including nested children)", "# The path nesting is already separated b...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.get_agenda
Returns an agenda that can be used guide search. Parameters ---------- conservative : ``bool`` Setting this flag will return a subset of the agenda items that correspond to high confidence lexical matches. You'll need this if you are going to use this agenda to ...
allennlp/semparse/domain_languages/wikitables_language.py
def get_agenda(self, conservative: bool = False): """ Returns an agenda that can be used guide search. Parameters ---------- conservative : ``bool`` Setting this flag will return a subset of the agenda items that correspond to high conf...
def get_agenda(self, conservative: bool = False): """ Returns an agenda that can be used guide search. Parameters ---------- conservative : ``bool`` Setting this flag will return a subset of the agenda items that correspond to high conf...
[ "Returns", "an", "agenda", "that", "can", "be", "used", "guide", "search", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L145-L321
[ "def", "get_agenda", "(", "self", ",", "conservative", ":", "bool", "=", "False", ")", ":", "agenda_items", "=", "[", "]", "question_tokens", "=", "[", "token", ".", "text", "for", "token", "in", "self", ".", "table_context", ".", "question_tokens", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.evaluate_logical_form
Takes a logical form, and the list of target values as strings from the original lisp string, and returns True iff the logical form executes to the target list, using the official WikiTableQuestions evaluation script.
allennlp/semparse/domain_languages/wikitables_language.py
def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool: """ Takes a logical form, and the list of target values as strings from the original lisp string, and returns True iff the logical form executes to the target list, using the official WikiTableQuestions e...
def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool: """ Takes a logical form, and the list of target values as strings from the original lisp string, and returns True iff the logical form executes to the target list, using the official WikiTableQuestions e...
[ "Takes", "a", "logical", "form", "and", "the", "list", "of", "target", "values", "as", "strings", "from", "the", "original", "lisp", "string", "and", "returns", "True", "iff", "the", "logical", "form", "executes", "to", "the", "target", "list", "using", "t...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L323-L342
[ "def", "evaluate_logical_form", "(", "self", ",", "logical_form", ":", "str", ",", "target_list", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "normalized_target_list", "=", "[", "TableQuestionContext", ".", "normalize_string", "(", "value", ")", "for...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.select_string
Select function takes a list of rows and a column name and returns a list of strings as in cells.
allennlp/semparse/domain_languages/wikitables_language.py
def select_string(self, rows: List[Row], column: StringColumn) -> List[str]: """ Select function takes a list of rows and a column name and returns a list of strings as in cells. """ return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None]
def select_string(self, rows: List[Row], column: StringColumn) -> List[str]: """ Select function takes a list of rows and a column name and returns a list of strings as in cells. """ return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None]
[ "Select", "function", "takes", "a", "list", "of", "rows", "and", "a", "column", "name", "and", "returns", "a", "list", "of", "strings", "as", "in", "cells", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L354-L359
[ "def", "select_string", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "StringColumn", ")", "->", "List", "[", "str", "]", ":", "return", "[", "str", "(", "row", ".", "values", "[", "column", ".", "name", "]", ")", "f...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.select_number
Select function takes a row (as a list) and a column name and returns the number in that column. If multiple rows are given, will return the first number that is not None.
allennlp/semparse/domain_languages/wikitables_language.py
def select_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Select function takes a row (as a list) and a column name and returns the number in that column. If multiple rows are given, will return the first number that is not None. """ numbers: List[float] = [] ...
def select_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Select function takes a row (as a list) and a column name and returns the number in that column. If multiple rows are given, will return the first number that is not None. """ numbers: List[float] = [] ...
[ "Select", "function", "takes", "a", "row", "(", "as", "a", "list", ")", "and", "a", "column", "name", "and", "returns", "the", "number", "in", "that", "column", ".", "If", "multiple", "rows", "are", "given", "will", "return", "the", "first", "number", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L362-L373
[ "def", "select_number", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "NumberColumn", ")", "->", "Number", ":", "numbers", ":", "List", "[", "float", "]", "=", "[", "]", "for", "row", "in", "rows", ":", "cell_value", "...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.select_date
Select function takes a row as a list and a column name and returns the date in that column.
allennlp/semparse/domain_languages/wikitables_language.py
def select_date(self, rows: List[Row], column: DateColumn) -> Date: """ Select function takes a row as a list and a column name and returns the date in that column. """ dates: List[Date] = [] for row in rows: cell_value = row.values[column.name] if isinsta...
def select_date(self, rows: List[Row], column: DateColumn) -> Date: """ Select function takes a row as a list and a column name and returns the date in that column. """ dates: List[Date] = [] for row in rows: cell_value = row.values[column.name] if isinsta...
[ "Select", "function", "takes", "a", "row", "as", "a", "list", "and", "a", "column", "name", "and", "returns", "the", "date", "in", "that", "column", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L376-L386
[ "def", "select_date", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "DateColumn", ")", "->", "Date", ":", "dates", ":", "List", "[", "Date", "]", "=", "[", "]", "for", "row", "in", "rows", ":", "cell_value", "=", "ro...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.same_as
Takes a row and a column and returns a list of rows from the full set of rows that contain the same value under the given column as the given row.
allennlp/semparse/domain_languages/wikitables_language.py
def same_as(self, rows: List[Row], column: Column) -> List[Row]: """ Takes a row and a column and returns a list of rows from the full set of rows that contain the same value under the given column as the given row. """ cell_value = rows[0].values[column.name] return_list...
def same_as(self, rows: List[Row], column: Column) -> List[Row]: """ Takes a row and a column and returns a list of rows from the full set of rows that contain the same value under the given column as the given row. """ cell_value = rows[0].values[column.name] return_list...
[ "Takes", "a", "row", "and", "a", "column", "and", "returns", "a", "list", "of", "rows", "from", "the", "full", "set", "of", "rows", "that", "contain", "the", "same", "value", "under", "the", "given", "column", "as", "the", "given", "row", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L389-L399
[ "def", "same_as", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "Column", ")", "->", "List", "[", "Row", "]", ":", "cell_value", "=", "rows", "[", "0", "]", ".", "values", "[", "column", ".", "name", "]", "return_lis...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.date
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order.
allennlp/semparse/domain_languages/wikitables_language.py
def date(self, year: Number, month: Number, day: Number) -> Date: """ Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order. """ return Date(year, month, day)
def date(self, year: Number, month: Number, day: Number) -> Date: """ Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order. """ return Date(year, month, day)
[ "Takes", "three", "numbers", "and", "returns", "a", "Date", "object", "whose", "year", "month", "and", "day", "are", "the", "three", "numbers", "in", "that", "order", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L402-L407
[ "def", "date", "(", "self", ",", "year", ":", "Number", ",", "month", ":", "Number", ",", "day", ":", "Number", ")", "->", "Date", ":", "return", "Date", "(", "year", ",", "month", ",", "day", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.first
Takes an expression that evaluates to a list of rows, and returns the first one in that list.
allennlp/semparse/domain_languages/wikitables_language.py
def first(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a list of rows, and returns the first one in that list. """ if not rows: logger.warning("Trying to get first row from an empty list") return [] return [rows[0]...
def first(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a list of rows, and returns the first one in that list. """ if not rows: logger.warning("Trying to get first row from an empty list") return [] return [rows[0]...
[ "Takes", "an", "expression", "that", "evaluates", "to", "a", "list", "of", "rows", "and", "returns", "the", "first", "one", "in", "that", "list", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L410-L418
[ "def", "first", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ")", "->", "List", "[", "Row", "]", ":", "if", "not", "rows", ":", "logger", ".", "warning", "(", "\"Trying to get first row from an empty list\"", ")", "return", "[", "]", "return",...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.last
Takes an expression that evaluates to a list of rows, and returns the last one in that list.
allennlp/semparse/domain_languages/wikitables_language.py
def last(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a list of rows, and returns the last one in that list. """ if not rows: logger.warning("Trying to get last row from an empty list") return [] return [rows[-1]]
def last(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a list of rows, and returns the last one in that list. """ if not rows: logger.warning("Trying to get last row from an empty list") return [] return [rows[-1]]
[ "Takes", "an", "expression", "that", "evaluates", "to", "a", "list", "of", "rows", "and", "returns", "the", "last", "one", "in", "that", "list", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L421-L429
[ "def", "last", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ")", "->", "List", "[", "Row", "]", ":", "if", "not", "rows", ":", "logger", ".", "warning", "(", "\"Trying to get last row from an empty list\"", ")", "return", "[", "]", "return", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.previous
Takes an expression that evaluates to a single row, and returns the row that occurs before the input row in the original set of rows. If the input row happens to be the top row, we will return an empty list.
allennlp/semparse/domain_languages/wikitables_language.py
def previous(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a single row, and returns the row that occurs before the input row in the original set of rows. If the input row happens to be the top row, we will return an empty list. """ if not...
def previous(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a single row, and returns the row that occurs before the input row in the original set of rows. If the input row happens to be the top row, we will return an empty list. """ if not...
[ "Takes", "an", "expression", "that", "evaluates", "to", "a", "single", "row", "and", "returns", "the", "row", "that", "occurs", "before", "the", "input", "row", "in", "the", "original", "set", "of", "rows", ".", "If", "the", "input", "row", "happens", "t...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L432-L443
[ "def", "previous", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ")", "->", "List", "[", "Row", "]", ":", "if", "not", "rows", ":", "return", "[", "]", "input_row_index", "=", "self", ".", "_get_row_index", "(", "rows", "[", "0", "]", "...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.next
Takes an expression that evaluates to a single row, and returns the row that occurs after the input row in the original set of rows. If the input row happens to be the last row, we will return an empty list.
allennlp/semparse/domain_languages/wikitables_language.py
def next(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a single row, and returns the row that occurs after the input row in the original set of rows. If the input row happens to be the last row, we will return an empty list. """ if not row...
def next(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a single row, and returns the row that occurs after the input row in the original set of rows. If the input row happens to be the last row, we will return an empty list. """ if not row...
[ "Takes", "an", "expression", "that", "evaluates", "to", "a", "single", "row", "and", "returns", "the", "row", "that", "occurs", "after", "the", "input", "row", "in", "the", "original", "set", "of", "rows", ".", "If", "the", "input", "row", "happens", "to...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L446-L457
[ "def", "next", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ")", "->", "List", "[", "Row", "]", ":", "if", "not", "rows", ":", "return", "[", "]", "input_row_index", "=", "self", ".", "_get_row_index", "(", "rows", "[", "0", "]", ")", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.mode_string
Takes a list of rows and a column and returns the most frequent values (one or more) under that column in those rows.
allennlp/semparse/domain_languages/wikitables_language.py
def mode_string(self, rows: List[Row], column: StringColumn) -> List[str]: """ Takes a list of rows and a column and returns the most frequent values (one or more) under that column in those rows. """ most_frequent_list = self._get_most_frequent_values(rows, column) if no...
def mode_string(self, rows: List[Row], column: StringColumn) -> List[str]: """ Takes a list of rows and a column and returns the most frequent values (one or more) under that column in those rows. """ most_frequent_list = self._get_most_frequent_values(rows, column) if no...
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "and", "returns", "the", "most", "frequent", "values", "(", "one", "or", "more", ")", "under", "that", "column", "in", "those", "rows", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L464-L474
[ "def", "mode_string", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "StringColumn", ")", "->", "List", "[", "str", "]", ":", "most_frequent_list", "=", "self", ".", "_get_most_frequent_values", "(", "rows", ",", "column", ")...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.mode_number
Takes a list of rows and a column and returns the most frequent value under that column in those rows.
allennlp/semparse/domain_languages/wikitables_language.py
def mode_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the most frequent value under that column in those rows. """ most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_li...
def mode_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the most frequent value under that column in those rows. """ most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_li...
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "and", "returns", "the", "most", "frequent", "value", "under", "that", "column", "in", "those", "rows", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L477-L488
[ "def", "mode_number", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "NumberColumn", ")", "->", "Number", ":", "most_frequent_list", "=", "self", ".", "_get_most_frequent_values", "(", "rows", ",", "column", ")", "if", "not", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.mode_date
Takes a list of rows and a column and returns the most frequent value under that column in those rows.
allennlp/semparse/domain_languages/wikitables_language.py
def mode_date(self, rows: List[Row], column: DateColumn) -> Date: """ Takes a list of rows and a column and returns the most frequent value under that column in those rows. """ most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_list: ...
def mode_date(self, rows: List[Row], column: DateColumn) -> Date: """ Takes a list of rows and a column and returns the most frequent value under that column in those rows. """ most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_list: ...
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "and", "returns", "the", "most", "frequent", "value", "under", "that", "column", "in", "those", "rows", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L491-L502
[ "def", "mode_date", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "DateColumn", ")", "->", "Date", ":", "most_frequent_list", "=", "self", ".", "_get_most_frequent_values", "(", "rows", ",", "column", ")", "if", "not", "most...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.argmax
Takes a list of rows and a column name and returns a list containing a single row (dict from columns to cells) that has the maximum numerical value in the given column. We return a list instead of a single dict to be consistent with the return type of ``select`` and ``all_rows``.
allennlp/semparse/domain_languages/wikitables_language.py
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]: """ Takes a list of rows and a column name and returns a list containing a single row (dict from columns to cells) that has the maximum numerical value in the given column. We return a list instead of a single dict...
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]: """ Takes a list of rows and a column name and returns a list containing a single row (dict from columns to cells) that has the maximum numerical value in the given column. We return a list instead of a single dict...
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "name", "and", "returns", "a", "list", "containing", "a", "single", "row", "(", "dict", "from", "columns", "to", "cells", ")", "that", "has", "the", "maximum", "numerical", "value", "in", "the", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L507-L520
[ "def", "argmax", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "ComparableColumn", ")", "->", "List", "[", "Row", "]", ":", "if", "not", "rows", ":", "return", "[", "]", "value_row_pairs", "=", "[", "(", "row", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.argmin
Takes a list of rows and a column and returns a list containing a single row (dict from columns to cells) that has the minimum numerical value in the given column. We return a list instead of a single dict to be consistent with the return type of ``select`` and ``all_rows``.
allennlp/semparse/domain_languages/wikitables_language.py
def argmin(self, rows: List[Row], column: ComparableColumn) -> List[Row]: """ Takes a list of rows and a column and returns a list containing a single row (dict from columns to cells) that has the minimum numerical value in the given column. We return a list instead of a single dict to b...
def argmin(self, rows: List[Row], column: ComparableColumn) -> List[Row]: """ Takes a list of rows and a column and returns a list containing a single row (dict from columns to cells) that has the minimum numerical value in the given column. We return a list instead of a single dict to b...
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "and", "returns", "a", "list", "containing", "a", "single", "row", "(", "dict", "from", "columns", "to", "cells", ")", "that", "has", "the", "minimum", "numerical", "value", "in", "the", "given", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L522-L535
[ "def", "argmin", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "ComparableColumn", ")", "->", "List", "[", "Row", "]", ":", "if", "not", "rows", ":", "return", "[", "]", "value_row_pairs", "=", "[", "(", "row", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.max_date
Takes a list of rows and a column and returns the max of the values under that column in those rows.
allennlp/semparse/domain_languages/wikitables_language.py
def max_date(self, rows: List[Row], column: DateColumn) -> Date: """ Takes a list of rows and a column and returns the max of the values under that column in those rows. """ cell_values = [row.values[column.name] for row in rows] if not cell_values: return Dat...
def max_date(self, rows: List[Row], column: DateColumn) -> Date: """ Takes a list of rows and a column and returns the max of the values under that column in those rows. """ cell_values = [row.values[column.name] for row in rows] if not cell_values: return Dat...
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "and", "returns", "the", "max", "of", "the", "values", "under", "that", "column", "in", "those", "rows", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L676-L686
[ "def", "max_date", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "DateColumn", ")", "->", "Date", ":", "cell_values", "=", "[", "row", ".", "values", "[", "column", ".", "name", "]", "for", "row", "in", "rows", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.max_number
Takes a list of rows and a column and returns the max of the values under that column in those rows.
allennlp/semparse/domain_languages/wikitables_language.py
def max_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the max of the values under that column in those rows. """ cell_values = [row.values[column.name] for row in rows] if not cell_values: retu...
def max_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the max of the values under that column in those rows. """ cell_values = [row.values[column.name] for row in rows] if not cell_values: retu...
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "and", "returns", "the", "max", "of", "the", "values", "under", "that", "column", "in", "those", "rows", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L703-L713
[ "def", "max_number", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "NumberColumn", ")", "->", "Number", ":", "cell_values", "=", "[", "row", ".", "values", "[", "column", ".", "name", "]", "for", "row", "in", "rows", "...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.average
Takes a list of rows and a column and returns the mean of the values under that column in those rows.
allennlp/semparse/domain_languages/wikitables_language.py
def average(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the mean of the values under that column in those rows. """ cell_values = [row.values[column.name] for row in rows] if not cell_values: return...
def average(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the mean of the values under that column in those rows. """ cell_values = [row.values[column.name] for row in rows] if not cell_values: return...
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "and", "returns", "the", "mean", "of", "the", "values", "under", "that", "column", "in", "those", "rows", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L737-L745
[ "def", "average", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "NumberColumn", ")", "->", "Number", ":", "cell_values", "=", "[", "row", ".", "values", "[", "column", ".", "name", "]", "for", "row", "in", "rows", "]",...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage.diff
Takes a two rows and a number column and returns the difference between the values under that column in those two rows.
allennlp/semparse/domain_languages/wikitables_language.py
def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number: """ Takes a two rows and a number column and returns the difference between the values under that column in those two rows. """ if not first_row or not second_row: return 0.0 ...
def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number: """ Takes a two rows and a number column and returns the difference between the values under that column in those two rows. """ if not first_row or not second_row: return 0.0 ...
[ "Takes", "a", "two", "rows", "and", "a", "number", "column", "and", "returns", "the", "difference", "between", "the", "values", "under", "that", "column", "in", "those", "two", "rows", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L747-L759
[ "def", "diff", "(", "self", ",", "first_row", ":", "List", "[", "Row", "]", ",", "second_row", ":", "List", "[", "Row", "]", ",", "column", ":", "NumberColumn", ")", "->", "Number", ":", "if", "not", "first_row", "or", "not", "second_row", ":", "retu...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesLanguage._get_row_index
Takes a row and returns its index in the full list of rows. If the row does not occur in the table (which should never happen because this function will only be called with a row that is the result of applying one or more functions on the table rows), the method returns -1.
allennlp/semparse/domain_languages/wikitables_language.py
def _get_row_index(self, row: Row) -> int: """ Takes a row and returns its index in the full list of rows. If the row does not occur in the table (which should never happen because this function will only be called with a row that is the result of applying one or more functions on the ta...
def _get_row_index(self, row: Row) -> int: """ Takes a row and returns its index in the full list of rows. If the row does not occur in the table (which should never happen because this function will only be called with a row that is the result of applying one or more functions on the ta...
[ "Takes", "a", "row", "and", "returns", "its", "index", "in", "the", "full", "list", "of", "rows", ".", "If", "the", "row", "does", "not", "occur", "in", "the", "table", "(", "which", "should", "never", "happen", "because", "this", "function", "will", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L785-L796
[ "def", "_get_row_index", "(", "self", ",", "row", ":", "Row", ")", "->", "int", ":", "row_index", "=", "-", "1", "for", "index", ",", "table_row", "in", "enumerate", "(", "self", ".", "table_data", ")", ":", "if", "table_row", ".", "values", "==", "r...
648a36f77db7e45784c047176074f98534c76636
train
World.is_terminal
This function will be called on nodes of a logical form tree, which are either non-terminal symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True`` if the given symbol is a terminal symbol.
allennlp/semparse/worlds/world.py
def is_terminal(self, symbol: str) -> bool: """ This function will be called on nodes of a logical form tree, which are either non-terminal symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True`` if the given symbol is a terminal symbol. """ ...
def is_terminal(self, symbol: str) -> bool: """ This function will be called on nodes of a logical form tree, which are either non-terminal symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True`` if the given symbol is a terminal symbol. """ ...
[ "This", "function", "will", "be", "called", "on", "nodes", "of", "a", "logical", "form", "tree", "which", "are", "either", "non", "-", "terminal", "symbols", "that", "can", "be", "expanded", "or", "terminal", "symbols", "that", "must", "be", "leaf", "nodes...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L76-L85
[ "def", "is_terminal", "(", "self", ",", "symbol", ":", "str", ")", "->", "bool", ":", "# We special-case 'lambda' here because it behaves weirdly in action sequences.", "return", "(", "symbol", "in", "self", ".", "global_name_mapping", "or", "symbol", "in", "self", "....
648a36f77db7e45784c047176074f98534c76636
train
World.get_paths_to_root
For a given action, returns at most ``max_num_paths`` paths to the root (production with ``START_SYMBOL``) that are not longer than ``max_path_length``.
allennlp/semparse/worlds/world.py
def get_paths_to_root(self, action: str, max_path_length: int = 20, beam_size: int = 30, max_num_paths: int = 10) -> List[List[str]]: """ For a given action, returns at most ``max_num_paths`` paths to...
def get_paths_to_root(self, action: str, max_path_length: int = 20, beam_size: int = 30, max_num_paths: int = 10) -> List[List[str]]: """ For a given action, returns at most ``max_num_paths`` paths to...
[ "For", "a", "given", "action", "returns", "at", "most", "max_num_paths", "paths", "to", "the", "root", "(", "production", "with", "START_SYMBOL", ")", "that", "are", "not", "longer", "than", "max_path_length", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L98-L140
[ "def", "get_paths_to_root", "(", "self", ",", "action", ":", "str", ",", "max_path_length", ":", "int", "=", "20", ",", "beam_size", ":", "int", "=", "30", ",", "max_num_paths", ":", "int", "=", "10", ")", "->", "List", "[", "List", "[", "str", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
World.get_multi_match_mapping
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it matches.
allennlp/semparse/worlds/world.py
def get_multi_match_mapping(self) -> Dict[Type, List[Type]]: """ Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it matches. """ if self._multi_match_mapping is None: self._multi_match_mapping = {} basic_types = sel...
def get_multi_match_mapping(self) -> Dict[Type, List[Type]]: """ Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it matches. """ if self._multi_match_mapping is None: self._multi_match_mapping = {} basic_types = sel...
[ "Returns", "a", "mapping", "from", "each", "MultiMatchNamedBasicType", "to", "all", "the", "NamedBasicTypes", "that", "it", "matches", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L184-L204
[ "def", "get_multi_match_mapping", "(", "self", ")", "->", "Dict", "[", "Type", ",", "List", "[", "Type", "]", "]", ":", "if", "self", ".", "_multi_match_mapping", "is", "None", ":", "self", ".", "_multi_match_mapping", "=", "{", "}", "basic_types", "=", ...
648a36f77db7e45784c047176074f98534c76636
train
World.parse_logical_form
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression. Parameters ---------- logical_form : ``str`` Logical form to parse remove_var_function : ``bool`` (optional) ``var`` is a special function that some languages use...
allennlp/semparse/worlds/world.py
def parse_logical_form(self, logical_form: str, remove_var_function: bool = True) -> Expression: """ Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression. Parameters ---------- l...
def parse_logical_form(self, logical_form: str, remove_var_function: bool = True) -> Expression: """ Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression. Parameters ---------- l...
[ "Takes", "a", "logical", "form", "as", "a", "string", "maps", "its", "tokens", "using", "the", "mapping", "and", "returns", "a", "parsed", "expression", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L206-L235
[ "def", "parse_logical_form", "(", "self", ",", "logical_form", ":", "str", ",", "remove_var_function", ":", "bool", "=", "True", ")", "->", "Expression", ":", "if", "not", "logical_form", ".", "startswith", "(", "\"(\"", ")", ":", "logical_form", "=", "f\"({...
648a36f77db7e45784c047176074f98534c76636
train
World.get_action_sequence
Returns the sequence of actions (as strings) that resulted in the given expression.
allennlp/semparse/worlds/world.py
def get_action_sequence(self, expression: Expression) -> List[str]: """ Returns the sequence of actions (as strings) that resulted in the given expression. """ # Starting with the type of the whole expression return self._get_transitions(expression, ...
def get_action_sequence(self, expression: Expression) -> List[str]: """ Returns the sequence of actions (as strings) that resulted in the given expression. """ # Starting with the type of the whole expression return self._get_transitions(expression, ...
[ "Returns", "the", "sequence", "of", "actions", "(", "as", "strings", ")", "that", "resulted", "in", "the", "given", "expression", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L237-L243
[ "def", "get_action_sequence", "(", "self", ",", "expression", ":", "Expression", ")", "->", "List", "[", "str", "]", ":", "# Starting with the type of the whole expression", "return", "self", ".", "_get_transitions", "(", "expression", ",", "[", "f\"{types.START_TYPE}...
648a36f77db7e45784c047176074f98534c76636
train
World.get_logical_form
Takes an action sequence and constructs a logical form from it. This is useful if you want to get a logical form from a decoded sequence of actions generated by a transition based semantic parser. Parameters ---------- action_sequence : ``List[str]`` The sequence of ...
allennlp/semparse/worlds/world.py
def get_logical_form(self, action_sequence: List[str], add_var_function: bool = True) -> str: """ Takes an action sequence and constructs a logical form from it. This is useful if you want to get a logical form from a decoded sequence of actions ...
def get_logical_form(self, action_sequence: List[str], add_var_function: bool = True) -> str: """ Takes an action sequence and constructs a logical form from it. This is useful if you want to get a logical form from a decoded sequence of actions ...
[ "Takes", "an", "action", "sequence", "and", "constructs", "a", "logical", "form", "from", "it", ".", "This", "is", "useful", "if", "you", "want", "to", "get", "a", "logical", "form", "from", "a", "decoded", "sequence", "of", "actions", "generated", "by", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L245-L285
[ "def", "get_logical_form", "(", "self", ",", "action_sequence", ":", "List", "[", "str", "]", ",", "add_var_function", ":", "bool", "=", "True", ")", "->", "str", ":", "# Basic outline: we assume that the bracketing that we get in the RHS of each action is the", "# correc...
648a36f77db7e45784c047176074f98534c76636
train
World._construct_node_from_actions
Given a current node in the logical form tree, and a list of actions in an action sequence, this method fills in the children of the current node from the action sequence, then returns whatever actions are left. For example, we could get a node with type ``c``, and an action sequence that begin...
allennlp/semparse/worlds/world.py
def _construct_node_from_actions(self, current_node: Tree, remaining_actions: List[List[str]], add_var_function: bool) -> List[List[str]]: """ Given a current node in the logical form tree, and...
def _construct_node_from_actions(self, current_node: Tree, remaining_actions: List[List[str]], add_var_function: bool) -> List[List[str]]: """ Given a current node in the logical form tree, and...
[ "Given", "a", "current", "node", "in", "the", "logical", "form", "tree", "and", "a", "list", "of", "actions", "in", "an", "action", "sequence", "this", "method", "fills", "in", "the", "children", "of", "the", "current", "node", "from", "the", "action", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L287-L349
[ "def", "_construct_node_from_actions", "(", "self", ",", "current_node", ":", "Tree", ",", "remaining_actions", ":", "List", "[", "List", "[", "str", "]", "]", ",", "add_var_function", ":", "bool", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":...
648a36f77db7e45784c047176074f98534c76636
train
World._infer_num_arguments
Takes a type signature and infers the number of arguments the corresponding function takes. Examples: e -> 0 <r,e> -> 1 <e,<e,t>> -> 2 <b,<<b,#1>,<#1,b>>> -> 3
allennlp/semparse/worlds/world.py
def _infer_num_arguments(cls, type_signature: str) -> int: """ Takes a type signature and infers the number of arguments the corresponding function takes. Examples: e -> 0 <r,e> -> 1 <e,<e,t>> -> 2 <b,<<b,#1>,<#1,b>>> -> 3 """ if no...
def _infer_num_arguments(cls, type_signature: str) -> int: """ Takes a type signature and infers the number of arguments the corresponding function takes. Examples: e -> 0 <r,e> -> 1 <e,<e,t>> -> 2 <b,<<b,#1>,<#1,b>>> -> 3 """ if no...
[ "Takes", "a", "type", "signature", "and", "infers", "the", "number", "of", "arguments", "the", "corresponding", "function", "takes", ".", "Examples", ":", "e", "-", ">", "0", "<r", "e", ">", "-", ">", "1", "<e", "<e", "t", ">>", "-", ">", "2", "<b"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L352-L380
[ "def", "_infer_num_arguments", "(", "cls", ",", "type_signature", ":", "str", ")", "->", "int", ":", "if", "not", "\"<\"", "in", "type_signature", ":", "return", "0", "# We need to find the return type from the signature. We do that by removing the outer most", "# angular b...
648a36f77db7e45784c047176074f98534c76636
train
World._process_nested_expression
``nested_expression`` is the result of parsing a logical form in Lisp format. We process it recursively and return a string in the format that NLTK's ``LogicParser`` would understand.
allennlp/semparse/worlds/world.py
def _process_nested_expression(self, nested_expression) -> str: """ ``nested_expression`` is the result of parsing a logical form in Lisp format. We process it recursively and return a string in the format that NLTK's ``LogicParser`` would understand. """ expression_is_li...
def _process_nested_expression(self, nested_expression) -> str: """ ``nested_expression`` is the result of parsing a logical form in Lisp format. We process it recursively and return a string in the format that NLTK's ``LogicParser`` would understand. """ expression_is_li...
[ "nested_expression", "is", "the", "result", "of", "parsing", "a", "logical", "form", "in", "Lisp", "format", ".", "We", "process", "it", "recursively", "and", "return", "a", "string", "in", "the", "format", "that", "NLTK", "s", "LogicParser", "would", "under...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L382-L408
[ "def", "_process_nested_expression", "(", "self", ",", "nested_expression", ")", "->", "str", ":", "expression_is_list", "=", "isinstance", "(", "nested_expression", ",", "list", ")", "expression_size", "=", "len", "(", "nested_expression", ")", "if", "expression_is...
648a36f77db7e45784c047176074f98534c76636
train
World._add_name_mapping
Utility method to add a name and its translation to the local name mapping, and the corresponding signature, if available to the local type signatures. This method also updates the reverse name mapping.
allennlp/semparse/worlds/world.py
def _add_name_mapping(self, name: str, translated_name: str, name_type: Type = None): """ Utility method to add a name and its translation to the local name mapping, and the corresponding signature, if available to the local type signatures. This method also updates the reverse name mapp...
def _add_name_mapping(self, name: str, translated_name: str, name_type: Type = None): """ Utility method to add a name and its translation to the local name mapping, and the corresponding signature, if available to the local type signatures. This method also updates the reverse name mapp...
[ "Utility", "method", "to", "add", "a", "name", "and", "its", "translation", "to", "the", "local", "name", "mapping", "and", "the", "corresponding", "signature", "if", "available", "to", "the", "local", "type", "signatures", ".", "This", "method", "also", "up...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L434-L443
[ "def", "_add_name_mapping", "(", "self", ",", "name", ":", "str", ",", "translated_name", ":", "str", ",", "name_type", ":", "Type", "=", "None", ")", ":", "self", ".", "local_name_mapping", "[", "name", "]", "=", "translated_name", "self", ".", "reverse_n...
648a36f77db7e45784c047176074f98534c76636
train
AugmentedLstm.forward
Parameters ---------- inputs : PackedSequence, required. A tensor of shape (batch_size, num_timesteps, input_size) to apply the LSTM over. initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None) A tuple (state, memory) representing the i...
allennlp/modules/augmented_lstm.py
def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None): """ Parameters ---------- inputs : PackedSequence, required. A tensor of shape (batch_size, num_ti...
def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None): """ Parameters ---------- inputs : PackedSequence, required. A tensor of shape (batch_size, num_ti...
[ "Parameters", "----------", "inputs", ":", "PackedSequence", "required", ".", "A", "tensor", "of", "shape", "(", "batch_size", "num_timesteps", "input_size", ")", "to", "apply", "the", "LSTM", "over", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/augmented_lstm.py#L96-L212
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "PackedSequence", ",", "initial_state", ":", "Optional", "[", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "]", "=", "None", ")", ":", "if", ...
648a36f77db7e45784c047176074f98534c76636
train
WikiTablesSempreExecutor._create_sempre_executor
Creates a server running SEMPRE that we can send logical forms to for evaluation. This uses inter-process communication, because SEMPRE is java code. We also need to be careful to clean up the process when our program exits.
allennlp/semparse/executors/wikitables_sempre_executor.py
def _create_sempre_executor(self) -> None: """ Creates a server running SEMPRE that we can send logical forms to for evaluation. This uses inter-process communication, because SEMPRE is java code. We also need to be careful to clean up the process when our program exits. """ ...
def _create_sempre_executor(self) -> None: """ Creates a server running SEMPRE that we can send logical forms to for evaluation. This uses inter-process communication, because SEMPRE is java code. We also need to be careful to clean up the process when our program exits. """ ...
[ "Creates", "a", "server", "running", "SEMPRE", "that", "we", "can", "send", "logical", "forms", "to", "for", "evaluation", ".", "This", "uses", "inter", "-", "process", "communication", "because", "SEMPRE", "is", "java", "code", ".", "We", "also", "need", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/executors/wikitables_sempre_executor.py#L63-L105
[ "def", "_create_sempre_executor", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_executor_process", ":", "return", "# It'd be much nicer to just use `cached_path` for these files. However, the SEMPRE jar", "# that we're using expects to find these files in a particular loca...
648a36f77db7e45784c047176074f98534c76636
train
Scorer.b_cubed
Averaged per-mention precision and recall. <https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf>
allennlp/training/metrics/conll_coref_scores.py
def b_cubed(clusters, mention_to_gold): """ Averaged per-mention precision and recall. <https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf> """ numerator, denominator = 0, 0 for cluster in clusters: if len(cluster) == 1: ...
def b_cubed(clusters, mention_to_gold): """ Averaged per-mention precision and recall. <https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf> """ numerator, denominator = 0, 0 for cluster in clusters: if len(cluster) == 1: ...
[ "Averaged", "per", "-", "mention", "precision", "and", "recall", ".", "<https", ":", "//", "pdfs", ".", "semanticscholar", ".", "org", "/", "cfe3", "/", "c24695f1c14b78a5b8e95bcbd1c666140fd1", ".", "pdf", ">" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/conll_coref_scores.py#L166-L185
[ "def", "b_cubed", "(", "clusters", ",", "mention_to_gold", ")", ":", "numerator", ",", "denominator", "=", "0", ",", "0", "for", "cluster", "in", "clusters", ":", "if", "len", "(", "cluster", ")", "==", "1", ":", "continue", "gold_counts", "=", "Counter"...
648a36f77db7e45784c047176074f98534c76636
train
Scorer.muc
Counts the mentions in each predicted cluster which need to be re-allocated in order for each predicted cluster to be contained by the respective gold cluster. <http://aclweb.org/anthology/M/M95/M95-1005.pdf>
allennlp/training/metrics/conll_coref_scores.py
def muc(clusters, mention_to_gold): """ Counts the mentions in each predicted cluster which need to be re-allocated in order for each predicted cluster to be contained by the respective gold cluster. <http://aclweb.org/anthology/M/M95/M95-1005.pdf> """ true_p, all_p = 0, ...
def muc(clusters, mention_to_gold): """ Counts the mentions in each predicted cluster which need to be re-allocated in order for each predicted cluster to be contained by the respective gold cluster. <http://aclweb.org/anthology/M/M95/M95-1005.pdf> """ true_p, all_p = 0, ...
[ "Counts", "the", "mentions", "in", "each", "predicted", "cluster", "which", "need", "to", "be", "re", "-", "allocated", "in", "order", "for", "each", "predicted", "cluster", "to", "be", "contained", "by", "the", "respective", "gold", "cluster", ".", "<http",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/conll_coref_scores.py#L188-L205
[ "def", "muc", "(", "clusters", ",", "mention_to_gold", ")", ":", "true_p", ",", "all_p", "=", "0", ",", "0", "for", "cluster", "in", "clusters", ":", "all_p", "+=", "len", "(", "cluster", ")", "-", "1", "true_p", "+=", "len", "(", "cluster", ")", "...
648a36f77db7e45784c047176074f98534c76636
train
Scorer.phi4
Subroutine for ceafe. Computes the mention F measure between gold and predicted mentions in a cluster.
allennlp/training/metrics/conll_coref_scores.py
def phi4(gold_clustering, predicted_clustering): """ Subroutine for ceafe. Computes the mention F measure between gold and predicted mentions in a cluster. """ return 2 * len([mention for mention in gold_clustering if mention in predicted_clustering]) \ / float(len...
def phi4(gold_clustering, predicted_clustering): """ Subroutine for ceafe. Computes the mention F measure between gold and predicted mentions in a cluster. """ return 2 * len([mention for mention in gold_clustering if mention in predicted_clustering]) \ / float(len...
[ "Subroutine", "for", "ceafe", ".", "Computes", "the", "mention", "F", "measure", "between", "gold", "and", "predicted", "mentions", "in", "a", "cluster", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/conll_coref_scores.py#L208-L214
[ "def", "phi4", "(", "gold_clustering", ",", "predicted_clustering", ")", ":", "return", "2", "*", "len", "(", "[", "mention", "for", "mention", "in", "gold_clustering", "if", "mention", "in", "predicted_clustering", "]", ")", "/", "float", "(", "len", "(", ...
648a36f77db7e45784c047176074f98534c76636
train
Scorer.ceafe
Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference. Gold and predicted mentions are aligned into clusterings which maximise a metric - in this case, the F measure between gold and predicted clusters. <https://www.semanticscholar.org/paper/On-Coreference-Resolu...
allennlp/training/metrics/conll_coref_scores.py
def ceafe(clusters, gold_clusters): """ Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference. Gold and predicted mentions are aligned into clusterings which maximise a metric - in this case, the F measure between gold and predicted clusters. <htt...
def ceafe(clusters, gold_clusters): """ Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference. Gold and predicted mentions are aligned into clusterings which maximise a metric - in this case, the F measure between gold and predicted clusters. <htt...
[ "Computes", "the", "Constrained", "EntityAlignment", "F", "-", "Measure", "(", "CEAF", ")", "for", "evaluating", "coreference", ".", "Gold", "and", "predicted", "mentions", "are", "aligned", "into", "clusterings", "which", "maximise", "a", "metric", "-", "in", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/conll_coref_scores.py#L217-L232
[ "def", "ceafe", "(", "clusters", ",", "gold_clusters", ")", ":", "clusters", "=", "[", "cluster", "for", "cluster", "in", "clusters", "if", "len", "(", "cluster", ")", "!=", "1", "]", "scores", "=", "np", ".", "zeros", "(", "(", "len", "(", "gold_clu...
648a36f77db7e45784c047176074f98534c76636
train
GrammarStatelet.take_action
Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack. Updating the non-terminal stack involves popping the non-terminal that was ...
allennlp/state_machines/states/grammar_statelet.py
def take_action(self, production_rule: str) -> 'GrammarStatelet': """ Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack...
def take_action(self, production_rule: str) -> 'GrammarStatelet': """ Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack...
[ "Takes", "an", "action", "in", "the", "current", "grammar", "state", "returning", "a", "new", "grammar", "state", "with", "whatever", "updates", "are", "necessary", ".", "The", "production", "rule", "is", "assumed", "to", "be", "formatted", "as", "LHS", "-",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/grammar_statelet.py#L70-L104
[ "def", "take_action", "(", "self", ",", "production_rule", ":", "str", ")", "->", "'GrammarStatelet'", ":", "left_side", ",", "right_side", "=", "production_rule", ".", "split", "(", "' -> '", ")", "assert", "self", ".", "_nonterminal_stack", "[", "-", "1", ...
648a36f77db7e45784c047176074f98534c76636
train
sparse_clip_norm
Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Supports sparse gradients. Parameters ---------- parameters : ``(Iterable[torch.Tensor])`` An iterable...
allennlp/training/util.py
def sparse_clip_norm(parameters, max_norm, norm_type=2) -> float: """Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Supports sparse gradients. Parameters ---...
def sparse_clip_norm(parameters, max_norm, norm_type=2) -> float: """Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Supports sparse gradients. Parameters ---...
[ "Clips", "gradient", "norm", "of", "an", "iterable", "of", "parameters", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L34-L78
[ "def", "sparse_clip_norm", "(", "parameters", ",", "max_norm", ",", "norm_type", "=", "2", ")", "->", "float", ":", "# pylint: disable=invalid-name,protected-access", "parameters", "=", "list", "(", "filter", "(", "lambda", "p", ":", "p", ".", "grad", "is", "n...
648a36f77db7e45784c047176074f98534c76636
train
move_optimizer_to_cuda
Move the optimizer state to GPU, if necessary. After calling, any parameter specific state in the optimizer will be located on the same device as the parameter.
allennlp/training/util.py
def move_optimizer_to_cuda(optimizer): """ Move the optimizer state to GPU, if necessary. After calling, any parameter specific state in the optimizer will be located on the same device as the parameter. """ for param_group in optimizer.param_groups: for param in param_group['params']: ...
def move_optimizer_to_cuda(optimizer): """ Move the optimizer state to GPU, if necessary. After calling, any parameter specific state in the optimizer will be located on the same device as the parameter. """ for param_group in optimizer.param_groups: for param in param_group['params']: ...
[ "Move", "the", "optimizer", "state", "to", "GPU", "if", "necessary", ".", "After", "calling", "any", "parameter", "specific", "state", "in", "the", "optimizer", "will", "be", "located", "on", "the", "same", "device", "as", "the", "parameter", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L81-L93
[ "def", "move_optimizer_to_cuda", "(", "optimizer", ")", ":", "for", "param_group", "in", "optimizer", ".", "param_groups", ":", "for", "param", "in", "param_group", "[", "'params'", "]", ":", "if", "param", ".", "is_cuda", ":", "param_state", "=", "optimizer",...
648a36f77db7e45784c047176074f98534c76636
train
get_batch_size
Returns the size of the batch dimension. Assumes a well-formed batch, returns 0 otherwise.
allennlp/training/util.py
def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int: """ Returns the size of the batch dimension. Assumes a well-formed batch, returns 0 otherwise. """ if isinstance(batch, torch.Tensor): return batch.size(0) # type: ignore elif isinstance(batch, Dict): return get_batch_s...
def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int: """ Returns the size of the batch dimension. Assumes a well-formed batch, returns 0 otherwise. """ if isinstance(batch, torch.Tensor): return batch.size(0) # type: ignore elif isinstance(batch, Dict): return get_batch_s...
[ "Returns", "the", "size", "of", "the", "batch", "dimension", ".", "Assumes", "a", "well", "-", "formed", "batch", "returns", "0", "otherwise", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L96-L106
[ "def", "get_batch_size", "(", "batch", ":", "Union", "[", "Dict", ",", "torch", ".", "Tensor", "]", ")", "->", "int", ":", "if", "isinstance", "(", "batch", ",", "torch", ".", "Tensor", ")", ":", "return", "batch", ".", "size", "(", "0", ")", "# ty...
648a36f77db7e45784c047176074f98534c76636
train
time_to_str
Convert seconds past Epoch to human readable string.
allennlp/training/util.py
def time_to_str(timestamp: int) -> str: """ Convert seconds past Epoch to human readable string. """ datetimestamp = datetime.datetime.fromtimestamp(timestamp) return '{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'.format( datetimestamp.year, datetimestamp.month, datetimestamp.day, ...
def time_to_str(timestamp: int) -> str: """ Convert seconds past Epoch to human readable string. """ datetimestamp = datetime.datetime.fromtimestamp(timestamp) return '{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'.format( datetimestamp.year, datetimestamp.month, datetimestamp.day, ...
[ "Convert", "seconds", "past", "Epoch", "to", "human", "readable", "string", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L109-L117
[ "def", "time_to_str", "(", "timestamp", ":", "int", ")", "->", "str", ":", "datetimestamp", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "timestamp", ")", "return", "'{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'", ".", "format", "(", "datetimestamp", ...
648a36f77db7e45784c047176074f98534c76636
train
str_to_time
Convert human readable string to datetime.datetime.
allennlp/training/util.py
def str_to_time(time_str: str) -> datetime.datetime: """ Convert human readable string to datetime.datetime. """ pieces: Any = [int(piece) for piece in time_str.split('-')] return datetime.datetime(*pieces)
def str_to_time(time_str: str) -> datetime.datetime: """ Convert human readable string to datetime.datetime. """ pieces: Any = [int(piece) for piece in time_str.split('-')] return datetime.datetime(*pieces)
[ "Convert", "human", "readable", "string", "to", "datetime", ".", "datetime", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L120-L125
[ "def", "str_to_time", "(", "time_str", ":", "str", ")", "->", "datetime", ".", "datetime", ":", "pieces", ":", "Any", "=", "[", "int", "(", "piece", ")", "for", "piece", "in", "time_str", ".", "split", "(", "'-'", ")", "]", "return", "datetime", ".",...
648a36f77db7e45784c047176074f98534c76636
train
datasets_from_params
Load all the datasets specified by the config. Parameters ---------- params : ``Params`` cache_directory : ``str``, optional If given, we will instruct the ``DatasetReaders`` that we construct to cache their instances in this location (or read their instances from caches in this locatio...
allennlp/training/util.py
def datasets_from_params(params: Params, cache_directory: str = None, cache_prefix: str = None) -> Dict[str, Iterable[Instance]]: """ Load all the datasets specified by the config. Parameters ---------- params : ``Params`` cache_directory : ``st...
def datasets_from_params(params: Params, cache_directory: str = None, cache_prefix: str = None) -> Dict[str, Iterable[Instance]]: """ Load all the datasets specified by the config. Parameters ---------- params : ``Params`` cache_directory : ``st...
[ "Load", "all", "the", "datasets", "specified", "by", "the", "config", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L128-L194
[ "def", "datasets_from_params", "(", "params", ":", "Params", ",", "cache_directory", ":", "str", "=", "None", ",", "cache_prefix", ":", "str", "=", "None", ")", "->", "Dict", "[", "str", ",", "Iterable", "[", "Instance", "]", "]", ":", "dataset_reader_para...
648a36f77db7e45784c047176074f98534c76636
train
create_serialization_dir
This function creates the serialization directory if it doesn't exist. If it already exists and is non-empty, then it verifies that we're recovering from a training with an identical configuration. Parameters ---------- params: ``Params`` A parameter object specifying an AllenNLP Experiment. ...
allennlp/training/util.py
def create_serialization_dir( params: Params, serialization_dir: str, recover: bool, force: bool) -> None: """ This function creates the serialization directory if it doesn't exist. If it already exists and is non-empty, then it verifies that we're recovering from a training...
def create_serialization_dir( params: Params, serialization_dir: str, recover: bool, force: bool) -> None: """ This function creates the serialization directory if it doesn't exist. If it already exists and is non-empty, then it verifies that we're recovering from a training...
[ "This", "function", "creates", "the", "serialization", "directory", "if", "it", "doesn", "t", "exist", ".", "If", "it", "already", "exists", "and", "is", "non", "-", "empty", "then", "it", "verifies", "that", "we", "re", "recovering", "from", "a", "trainin...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L242-L309
[ "def", "create_serialization_dir", "(", "params", ":", "Params", ",", "serialization_dir", ":", "str", ",", "recover", ":", "bool", ",", "force", ":", "bool", ")", "->", "None", ":", "if", "recover", "and", "force", ":", "raise", "ConfigurationError", "(", ...
648a36f77db7e45784c047176074f98534c76636
train
data_parallel
Performs a forward pass using multiple GPUs. This is a simplification of torch.nn.parallel.data_parallel to support the allennlp model interface.
allennlp/training/util.py
def data_parallel(batch_group: List[TensorDict], model: Model, cuda_devices: List) -> Dict[str, torch.Tensor]: """ Performs a forward pass using multiple GPUs. This is a simplification of torch.nn.parallel.data_parallel to support the allennlp model interface. ""...
def data_parallel(batch_group: List[TensorDict], model: Model, cuda_devices: List) -> Dict[str, torch.Tensor]: """ Performs a forward pass using multiple GPUs. This is a simplification of torch.nn.parallel.data_parallel to support the allennlp model interface. ""...
[ "Performs", "a", "forward", "pass", "using", "multiple", "GPUs", ".", "This", "is", "a", "simplification", "of", "torch", ".", "nn", ".", "parallel", ".", "data_parallel", "to", "support", "the", "allennlp", "model", "interface", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L311-L337
[ "def", "data_parallel", "(", "batch_group", ":", "List", "[", "TensorDict", "]", ",", "model", ":", "Model", ",", "cuda_devices", ":", "List", ")", "->", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ":", "assert", "len", "(", "batch_group", ")...
648a36f77db7e45784c047176074f98534c76636
train
rescale_gradients
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.
allennlp/training/util.py
def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]: """ Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled. """ if grad_norm: parameters_to_clip = [p for p in model.parameters() if p.grad is not None] ...
def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]: """ Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled. """ if grad_norm: parameters_to_clip = [p for p in model.parameters() if p.grad is not None] ...
[ "Performs", "gradient", "rescaling", ".", "Is", "a", "no", "-", "op", "if", "gradient", "rescaling", "is", "not", "enabled", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L347-L355
[ "def", "rescale_gradients", "(", "model", ":", "Model", ",", "grad_norm", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "Optional", "[", "float", "]", ":", "if", "grad_norm", ":", "parameters_to_clip", "=", "[", "p", "for", "p", "in", "mo...
648a36f77db7e45784c047176074f98534c76636
train
get_metrics
Gets the metrics but sets ``"loss"`` to the total loss divided by the ``num_batches`` so that the ``"loss"`` metric is "average loss per batch".
allennlp/training/util.py
def get_metrics(model: Model, total_loss: float, num_batches: int, reset: bool = False) -> Dict[str, float]: """ Gets the metrics but sets ``"loss"`` to the total loss divided by the ``num_batches`` so that the ``"loss"`` metric is "average loss per batch". """ metrics = model.get_metrics(reset=...
def get_metrics(model: Model, total_loss: float, num_batches: int, reset: bool = False) -> Dict[str, float]: """ Gets the metrics but sets ``"loss"`` to the total loss divided by the ``num_batches`` so that the ``"loss"`` metric is "average loss per batch". """ metrics = model.get_metrics(reset=...
[ "Gets", "the", "metrics", "but", "sets", "loss", "to", "the", "total", "loss", "divided", "by", "the", "num_batches", "so", "that", "the", "loss", "metric", "is", "average", "loss", "per", "batch", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L357-L365
[ "def", "get_metrics", "(", "model", ":", "Model", ",", "total_loss", ":", "float", ",", "num_batches", ":", "int", ",", "reset", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "float", "]", ":", "metrics", "=", "model", ".", "get_metr...
648a36f77db7e45784c047176074f98534c76636
train
parse_requirements
Parse all dependencies out of the requirements.txt file.
scripts/check_requirements_and_setup.py
def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]: """Parse all dependencies out of the requirements.txt file.""" essential_packages: PackagesType = {} other_packages: PackagesType = {} duplicates: Set[str] = set() with open("requirements.txt", "r") as req_file: section...
def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]: """Parse all dependencies out of the requirements.txt file.""" essential_packages: PackagesType = {} other_packages: PackagesType = {} duplicates: Set[str] = set() with open("requirements.txt", "r") as req_file: section...
[ "Parse", "all", "dependencies", "out", "of", "the", "requirements", ".", "txt", "file", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_requirements_and_setup.py#L32-L60
[ "def", "parse_requirements", "(", ")", "->", "Tuple", "[", "PackagesType", ",", "PackagesType", ",", "Set", "[", "str", "]", "]", ":", "essential_packages", ":", "PackagesType", "=", "{", "}", "other_packages", ":", "PackagesType", "=", "{", "}", "duplicates...
648a36f77db7e45784c047176074f98534c76636
train
parse_setup
Parse all dependencies out of the setup.py script.
scripts/check_requirements_and_setup.py
def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]: """Parse all dependencies out of the setup.py script.""" essential_packages: PackagesType = {} test_packages: PackagesType = {} essential_duplicates: Set[str] = set() test_duplicates: Set[str] = set() with open('setup.p...
def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]: """Parse all dependencies out of the setup.py script.""" essential_packages: PackagesType = {} test_packages: PackagesType = {} essential_duplicates: Set[str] = set() test_duplicates: Set[str] = set() with open('setup.p...
[ "Parse", "all", "dependencies", "out", "of", "the", "setup", ".", "py", "script", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_requirements_and_setup.py#L63-L93
[ "def", "parse_setup", "(", ")", "->", "Tuple", "[", "PackagesType", ",", "PackagesType", ",", "Set", "[", "str", "]", ",", "Set", "[", "str", "]", "]", ":", "essential_packages", ":", "PackagesType", "=", "{", "}", "test_packages", ":", "PackagesType", "...
648a36f77db7e45784c047176074f98534c76636
train
enumerate_spans
Given a sentence, return all token spans within the sentence. Spans are `inclusive`. Additionally, you can provide a maximum and minimum span width, which will be used to exclude spans outside of this range. Finally, you can provide a function mapping ``List[T] -> bool``, which will be applied to every...
allennlp/data/dataset_readers/dataset_utils/span_utils.py
def enumerate_spans(sentence: List[T], offset: int = 0, max_span_width: int = None, min_span_width: int = 1, filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]: """ Given a sentence, return all token spans w...
def enumerate_spans(sentence: List[T], offset: int = 0, max_span_width: int = None, min_span_width: int = 1, filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]: """ Given a sentence, return all token spans w...
[ "Given", "a", "sentence", "return", "all", "token", "spans", "within", "the", "sentence", ".", "Spans", "are", "inclusive", ".", "Additionally", "you", "can", "provide", "a", "maximum", "and", "minimum", "span", "width", "which", "will", "be", "used", "to", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L20-L66
[ "def", "enumerate_spans", "(", "sentence", ":", "List", "[", "T", "]", ",", "offset", ":", "int", "=", "0", ",", "max_span_width", ":", "int", "=", "None", ",", "min_span_width", ":", "int", "=", "1", ",", "filter_function", ":", "Callable", "[", "[", ...
648a36f77db7e45784c047176074f98534c76636
train
bio_tags_to_spans
Given a sequence corresponding to BIO tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"), as otherwise it is possible to get a perfect precision score whilst still predicting...
allennlp/data/dataset_readers/dataset_utils/span_utils.py
def bio_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to BIO tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also in...
def bio_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to BIO tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also in...
[ "Given", "a", "sequence", "corresponding", "to", "BIO", "tags", "extracts", "spans", ".", "Spans", "are", "inclusive", "and", "can", "be", "of", "zero", "length", "representing", "a", "single", "word", "span", ".", "Ill", "-", "formed", "spans", "are", "al...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L69-L139
[ "def", "bio_tags_to_spans", "(", "tag_sequence", ":", "List", "[", "str", "]", ",", "classes_to_ignore", ":", "List", "[", "str", "]", "=", "None", ")", "->", "List", "[", "TypedStringSpan", "]", ":", "classes_to_ignore", "=", "classes_to_ignore", "or", "[",...
648a36f77db7e45784c047176074f98534c76636
train
iob1_tags_to_spans
Given a sequence corresponding to IOB1 tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also included (i.e., those where "B-LABEL" is not preceded by "I-LABEL" or "B-LABEL"). Parameters ---------- tag_sequence : List[str]...
allennlp/data/dataset_readers/dataset_utils/span_utils.py
def iob1_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to IOB1 tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also...
def iob1_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to IOB1 tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also...
[ "Given", "a", "sequence", "corresponding", "to", "IOB1", "tags", "extracts", "spans", ".", "Spans", "are", "inclusive", "and", "can", "be", "of", "zero", "length", "representing", "a", "single", "word", "span", ".", "Ill", "-", "formed", "spans", "are", "a...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L142-L201
[ "def", "iob1_tags_to_spans", "(", "tag_sequence", ":", "List", "[", "str", "]", ",", "classes_to_ignore", ":", "List", "[", "str", "]", "=", "None", ")", "->", "List", "[", "TypedStringSpan", "]", ":", "classes_to_ignore", "=", "classes_to_ignore", "or", "["...
648a36f77db7e45784c047176074f98534c76636
train
bioul_tags_to_spans
Given a sequence corresponding to BIOUL tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are not allowed and will raise ``InvalidTagSequence``. This function works properly when the spans are unlabeled (i.e., your labels are simply "B...
allennlp/data/dataset_readers/dataset_utils/span_utils.py
def bioul_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to BIOUL tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are n...
def bioul_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to BIOUL tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are n...
[ "Given", "a", "sequence", "corresponding", "to", "BIOUL", "tags", "extracts", "spans", ".", "Spans", "are", "inclusive", "and", "can", "be", "of", "zero", "length", "representing", "a", "single", "word", "span", ".", "Ill", "-", "formed", "spans", "are", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L217-L260
[ "def", "bioul_tags_to_spans", "(", "tag_sequence", ":", "List", "[", "str", "]", ",", "classes_to_ignore", ":", "List", "[", "str", "]", "=", "None", ")", "->", "List", "[", "TypedStringSpan", "]", ":", "spans", "=", "[", "]", "classes_to_ignore", "=", "...
648a36f77db7e45784c047176074f98534c76636