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
to_bioul
Given a tag sequence encoded with IOB1 labels, recode to BIOUL. In the IOB1 scheme, I is a token inside a span, O is a token outside a span and B is the beginning of span immediately following another span of the same type. In the BIO scheme, I is a token inside a span, O is a token outside a span...
allennlp/data/dataset_readers/dataset_utils/span_utils.py
def to_bioul(tag_sequence: List[str], encoding: str = "IOB1") -> List[str]: """ Given a tag sequence encoded with IOB1 labels, recode to BIOUL. In the IOB1 scheme, I is a token inside a span, O is a token outside a span and B is the beginning of span immediately following another span of the same t...
def to_bioul(tag_sequence: List[str], encoding: str = "IOB1") -> List[str]: """ Given a tag sequence encoded with IOB1 labels, recode to BIOUL. In the IOB1 scheme, I is a token inside a span, O is a token outside a span and B is the beginning of span immediately following another span of the same t...
[ "Given", "a", "tag", "sequence", "encoded", "with", "IOB1", "labels", "recode", "to", "BIOUL", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L267-L373
[ "def", "to_bioul", "(", "tag_sequence", ":", "List", "[", "str", "]", ",", "encoding", ":", "str", "=", "\"IOB1\"", ")", "->", "List", "[", "str", "]", ":", "if", "not", "encoding", "in", "{", "\"IOB1\"", ",", "\"BIO\"", "}", ":", "raise", "Configura...
648a36f77db7e45784c047176074f98534c76636
train
bmes_tags_to_spans
Given a sequence corresponding to BMES 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 predictin...
allennlp/data/dataset_readers/dataset_utils/span_utils.py
def bmes_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to BMES tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also...
def bmes_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to BMES 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", "BMES", "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#L376-L435
[ "def", "bmes_tags_to_spans", "(", "tag_sequence", ":", "List", "[", "str", "]", ",", "classes_to_ignore", ":", "List", "[", "str", "]", "=", "None", ")", "->", "List", "[", "TypedStringSpan", "]", ":", "def", "extract_bmes_tag_label", "(", "text", ")", ":"...
648a36f77db7e45784c047176074f98534c76636
train
dry_run_from_args
Just converts from an ``argparse.Namespace`` object to params.
allennlp/commands/dry_run.py
def dry_run_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path serialization_dir = args.serialization_dir overrides = args.overrides params = Params.from_file(parameter_path, overrides) dry_run_fr...
def dry_run_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path serialization_dir = args.serialization_dir overrides = args.overrides params = Params.from_file(parameter_path, overrides) dry_run_fr...
[ "Just", "converts", "from", "an", "argparse", ".", "Namespace", "object", "to", "params", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/dry_run.py#L72-L82
[ "def", "dry_run_from_args", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "parameter_path", "=", "args", ".", "param_path", "serialization_dir", "=", "args", ".", "serialization_dir", "overrides", "=", "args", ".", "overrides", "params", "=", "Params...
648a36f77db7e45784c047176074f98534c76636
train
ConstrainedBeamSearch.search
Parameters ---------- initial_state : ``State`` The starting state of our search. This is assumed to be `batched`, and our beam search is batch-aware - we'll keep ``beam_size`` states around for each instance in the batch. transition_function : ``TransitionFunction`` ...
allennlp/state_machines/constrained_beam_search.py
def search(self, initial_state: State, transition_function: TransitionFunction) -> Dict[int, List[State]]: """ Parameters ---------- initial_state : ``State`` The starting state of our search. This is assumed to be `batched`, and our beam search...
def search(self, initial_state: State, transition_function: TransitionFunction) -> Dict[int, List[State]]: """ Parameters ---------- initial_state : ``State`` The starting state of our search. This is assumed to be `batched`, and our beam search...
[ "Parameters", "----------", "initial_state", ":", "State", "The", "starting", "state", "of", "our", "search", ".", "This", "is", "assumed", "to", "be", "batched", "and", "our", "beam", "search", "is", "batch", "-", "aware", "-", "we", "ll", "keep", "beam_s...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/constrained_beam_search.py#L60-L114
[ "def", "search", "(", "self", ",", "initial_state", ":", "State", ",", "transition_function", ":", "TransitionFunction", ")", "->", "Dict", "[", "int", ",", "List", "[", "State", "]", "]", ":", "finished_states", ":", "Dict", "[", "int", ",", "List", "["...
648a36f77db7e45784c047176074f98534c76636
train
url_ok
Check if a URL is reachable.
scripts/check_links.py
def url_ok(match_tuple: MatchTuple) -> bool: """Check if a URL is reachable.""" try: result = requests.get(match_tuple.link, timeout=5) return result.ok except (requests.ConnectionError, requests.Timeout): return False
def url_ok(match_tuple: MatchTuple) -> bool: """Check if a URL is reachable.""" try: result = requests.get(match_tuple.link, timeout=5) return result.ok except (requests.ConnectionError, requests.Timeout): return False
[ "Check", "if", "a", "URL", "is", "reachable", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_links.py#L24-L30
[ "def", "url_ok", "(", "match_tuple", ":", "MatchTuple", ")", "->", "bool", ":", "try", ":", "result", "=", "requests", ".", "get", "(", "match_tuple", ".", "link", ",", "timeout", "=", "5", ")", "return", "result", ".", "ok", "except", "(", "requests",...
648a36f77db7e45784c047176074f98534c76636
train
path_ok
Check if a file in this repository exists.
scripts/check_links.py
def path_ok(match_tuple: MatchTuple) -> bool: """Check if a file in this repository exists.""" relative_path = match_tuple.link.split("#")[0] full_path = os.path.join(os.path.dirname(str(match_tuple.source)), relative_path) return os.path.exists(full_path)
def path_ok(match_tuple: MatchTuple) -> bool: """Check if a file in this repository exists.""" relative_path = match_tuple.link.split("#")[0] full_path = os.path.join(os.path.dirname(str(match_tuple.source)), relative_path) return os.path.exists(full_path)
[ "Check", "if", "a", "file", "in", "this", "repository", "exists", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_links.py#L33-L37
[ "def", "path_ok", "(", "match_tuple", ":", "MatchTuple", ")", "->", "bool", ":", "relative_path", "=", "match_tuple", ".", "link", ".", "split", "(", "\"#\"", ")", "[", "0", "]", "full_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path...
648a36f77db7e45784c047176074f98534c76636
train
infer_and_cast
In some cases we'll be feeding params dicts to functions we don't own; for example, PyTorch optimizers. In that case we can't use ``pop_int`` or similar to force casts (which means you can't specify ``int`` parameters using environment variables). This function takes something that looks JSON-like and r...
allennlp/common/params.py
def infer_and_cast(value: Any): """ In some cases we'll be feeding params dicts to functions we don't own; for example, PyTorch optimizers. In that case we can't use ``pop_int`` or similar to force casts (which means you can't specify ``int`` parameters using environment variables). This function ta...
def infer_and_cast(value: Any): """ In some cases we'll be feeding params dicts to functions we don't own; for example, PyTorch optimizers. In that case we can't use ``pop_int`` or similar to force casts (which means you can't specify ``int`` parameters using environment variables). This function ta...
[ "In", "some", "cases", "we", "ll", "be", "feeding", "params", "dicts", "to", "functions", "we", "don", "t", "own", ";", "for", "example", "PyTorch", "optimizers", ".", "In", "that", "case", "we", "can", "t", "use", "pop_int", "or", "similar", "to", "fo...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L35-L72
[ "def", "infer_and_cast", "(", "value", ":", "Any", ")", ":", "# pylint: disable=too-many-return-statements", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "bool", ")", ")", ":", "# Already one of our desired types, so leave as is.", "return", ...
648a36f77db7e45784c047176074f98534c76636
train
_environment_variables
Wraps `os.environ` to filter out non-encodable values.
allennlp/common/params.py
def _environment_variables() -> Dict[str, str]: """ Wraps `os.environ` to filter out non-encodable values. """ return {key: value for key, value in os.environ.items() if _is_encodable(value)}
def _environment_variables() -> Dict[str, str]: """ Wraps `os.environ` to filter out non-encodable values. """ return {key: value for key, value in os.environ.items() if _is_encodable(value)}
[ "Wraps", "os", ".", "environ", "to", "filter", "out", "non", "-", "encodable", "values", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L85-L91
[ "def", "_environment_variables", "(", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "os", ".", "environ", ".", "items", "(", ")", "if", "_is_encodable", "(", "value", ")", ...
648a36f77db7e45784c047176074f98534c76636
train
unflatten
Given a "flattened" dict with compound keys, e.g. {"a.b": 0} unflatten it: {"a": {"b": 0}}
allennlp/common/params.py
def unflatten(flat_dict: Dict[str, Any]) -> Dict[str, Any]: """ Given a "flattened" dict with compound keys, e.g. {"a.b": 0} unflatten it: {"a": {"b": 0}} """ unflat: Dict[str, Any] = {} for compound_key, value in flat_dict.items(): curr_dict = unflat parts = com...
def unflatten(flat_dict: Dict[str, Any]) -> Dict[str, Any]: """ Given a "flattened" dict with compound keys, e.g. {"a.b": 0} unflatten it: {"a": {"b": 0}} """ unflat: Dict[str, Any] = {} for compound_key, value in flat_dict.items(): curr_dict = unflat parts = com...
[ "Given", "a", "flattened", "dict", "with", "compound", "keys", "e", ".", "g", ".", "{", "a", ".", "b", ":", "0", "}", "unflatten", "it", ":", "{", "a", ":", "{", "b", ":", "0", "}}" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L93-L119
[ "def", "unflatten", "(", "flat_dict", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "unflat", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "for", "compound_key", ",", "value", "in", "...
648a36f77db7e45784c047176074f98534c76636
train
with_fallback
Deep merge two dicts, preferring values from `preferred`.
allennlp/common/params.py
def with_fallback(preferred: Dict[str, Any], fallback: Dict[str, Any]) -> Dict[str, Any]: """ Deep merge two dicts, preferring values from `preferred`. """ def merge(preferred_value: Any, fallback_value: Any) -> Any: if isinstance(preferred_value, dict) and isinstance(fallback_value, dict): ...
def with_fallback(preferred: Dict[str, Any], fallback: Dict[str, Any]) -> Dict[str, Any]: """ Deep merge two dicts, preferring values from `preferred`. """ def merge(preferred_value: Any, fallback_value: Any) -> Any: if isinstance(preferred_value, dict) and isinstance(fallback_value, dict): ...
[ "Deep", "merge", "two", "dicts", "preferring", "values", "from", "preferred", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L121-L161
[ "def", "with_fallback", "(", "preferred", ":", "Dict", "[", "str", ",", "Any", "]", ",", "fallback", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "def", "merge", "(", "preferred_value", ":", "Any", ...
648a36f77db7e45784c047176074f98534c76636
train
pop_choice
Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with places that the Params object is not welcome, such as inside Keras layers. See the docstring of that method for more detail on how this function works. This method adds a ``history`` parameter, in the off-chance...
allennlp/common/params.py
def pop_choice(params: Dict[str, Any], key: str, choices: List[Any], default_to_first_choice: bool = False, history: str = "?.") -> Any: """ Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with places that ...
def pop_choice(params: Dict[str, Any], key: str, choices: List[Any], default_to_first_choice: bool = False, history: str = "?.") -> Any: """ Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with places that ...
[ "Performs", "the", "same", "function", "as", ":", "func", ":", "Params", ".", "pop_choice", "but", "is", "required", "in", "order", "to", "deal", "with", "places", "that", "the", "Params", "object", "is", "not", "welcome", "such", "as", "inside", "Keras", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L518-L534
[ "def", "pop_choice", "(", "params", ":", "Dict", "[", "str", ",", "Any", "]", ",", "key", ":", "str", ",", "choices", ":", "List", "[", "Any", "]", ",", "default_to_first_choice", ":", "bool", "=", "False", ",", "history", ":", "str", "=", "\"?.\"", ...
648a36f77db7e45784c047176074f98534c76636
train
Params.add_file_to_archive
Any class in its ``from_params`` method can request that some of its input files be added to the archive by calling this method. For example, if some class ``A`` had an ``input_file`` parameter, it could call ``` params.add_file_to_archive("input_file") ``` which would...
allennlp/common/params.py
def add_file_to_archive(self, name: str) -> None: """ Any class in its ``from_params`` method can request that some of its input files be added to the archive by calling this method. For example, if some class ``A`` had an ``input_file`` parameter, it could call ``` par...
def add_file_to_archive(self, name: str) -> None: """ Any class in its ``from_params`` method can request that some of its input files be added to the archive by calling this method. For example, if some class ``A`` had an ``input_file`` parameter, it could call ``` par...
[ "Any", "class", "in", "its", "from_params", "method", "can", "request", "that", "some", "of", "its", "input", "files", "be", "added", "to", "the", "archive", "by", "calling", "this", "method", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L209-L232
[ "def", "add_file_to_archive", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "if", "not", "self", ".", "loading_from_archive", ":", "self", ".", "files_to_archive", "[", "f\"{self.history}{name}\"", "]", "=", "cached_path", "(", "self", ".", "...
648a36f77db7e45784c047176074f98534c76636
train
Params.pop
Performs the functionality associated with dict.pop(key), along with checking for returned dictionaries, replacing them with Param objects with an updated history. If ``key`` is not present in the dictionary, and no default was specified, we raise a ``ConfigurationError``, instead of the typica...
allennlp/common/params.py
def pop(self, key: str, default: Any = DEFAULT) -> Any: """ Performs the functionality associated with dict.pop(key), along with checking for returned dictionaries, replacing them with Param objects with an updated history. If ``key`` is not present in the dictionary, and no default was...
def pop(self, key: str, default: Any = DEFAULT) -> Any: """ Performs the functionality associated with dict.pop(key), along with checking for returned dictionaries, replacing them with Param objects with an updated history. If ``key`` is not present in the dictionary, and no default was...
[ "Performs", "the", "functionality", "associated", "with", "dict", ".", "pop", "(", "key", ")", "along", "with", "checking", "for", "returned", "dictionaries", "replacing", "them", "with", "Param", "objects", "with", "an", "updated", "history", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L235-L252
[ "def", "pop", "(", "self", ",", "key", ":", "str", ",", "default", ":", "Any", "=", "DEFAULT", ")", "->", "Any", ":", "if", "default", "is", "self", ".", "DEFAULT", ":", "try", ":", "value", "=", "self", ".", "params", ".", "pop", "(", "key", "...
648a36f77db7e45784c047176074f98534c76636
train
Params.pop_int
Performs a pop and coerces to an int.
allennlp/common/params.py
def pop_int(self, key: str, default: Any = DEFAULT) -> int: """ Performs a pop and coerces to an int. """ value = self.pop(key, default) if value is None: return None else: return int(value)
def pop_int(self, key: str, default: Any = DEFAULT) -> int: """ Performs a pop and coerces to an int. """ value = self.pop(key, default) if value is None: return None else: return int(value)
[ "Performs", "a", "pop", "and", "coerces", "to", "an", "int", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L254-L262
[ "def", "pop_int", "(", "self", ",", "key", ":", "str", ",", "default", ":", "Any", "=", "DEFAULT", ")", "->", "int", ":", "value", "=", "self", ".", "pop", "(", "key", ",", "default", ")", "if", "value", "is", "None", ":", "return", "None", "else...
648a36f77db7e45784c047176074f98534c76636
train
Params.pop_float
Performs a pop and coerces to a float.
allennlp/common/params.py
def pop_float(self, key: str, default: Any = DEFAULT) -> float: """ Performs a pop and coerces to a float. """ value = self.pop(key, default) if value is None: return None else: return float(value)
def pop_float(self, key: str, default: Any = DEFAULT) -> float: """ Performs a pop and coerces to a float. """ value = self.pop(key, default) if value is None: return None else: return float(value)
[ "Performs", "a", "pop", "and", "coerces", "to", "a", "float", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L264-L272
[ "def", "pop_float", "(", "self", ",", "key", ":", "str", ",", "default", ":", "Any", "=", "DEFAULT", ")", "->", "float", ":", "value", "=", "self", ".", "pop", "(", "key", ",", "default", ")", "if", "value", "is", "None", ":", "return", "None", "...
648a36f77db7e45784c047176074f98534c76636
train
Params.pop_bool
Performs a pop and coerces to a bool.
allennlp/common/params.py
def pop_bool(self, key: str, default: Any = DEFAULT) -> bool: """ Performs a pop and coerces to a bool. """ value = self.pop(key, default) if value is None: return None elif isinstance(value, bool): return value elif value == "true": ...
def pop_bool(self, key: str, default: Any = DEFAULT) -> bool: """ Performs a pop and coerces to a bool. """ value = self.pop(key, default) if value is None: return None elif isinstance(value, bool): return value elif value == "true": ...
[ "Performs", "a", "pop", "and", "coerces", "to", "a", "bool", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L274-L288
[ "def", "pop_bool", "(", "self", ",", "key", ":", "str", ",", "default", ":", "Any", "=", "DEFAULT", ")", "->", "bool", ":", "value", "=", "self", ".", "pop", "(", "key", ",", "default", ")", "if", "value", "is", "None", ":", "return", "None", "el...
648a36f77db7e45784c047176074f98534c76636
train
Params.get
Performs the functionality associated with dict.get(key) but also checks for returned dicts and returns a Params object in their place with an updated history.
allennlp/common/params.py
def get(self, key: str, default: Any = DEFAULT): """ Performs the functionality associated with dict.get(key) but also checks for returned dicts and returns a Params object in their place with an updated history. """ if default is self.DEFAULT: try: va...
def get(self, key: str, default: Any = DEFAULT): """ Performs the functionality associated with dict.get(key) but also checks for returned dicts and returns a Params object in their place with an updated history. """ if default is self.DEFAULT: try: va...
[ "Performs", "the", "functionality", "associated", "with", "dict", ".", "get", "(", "key", ")", "but", "also", "checks", "for", "returned", "dicts", "and", "returns", "a", "Params", "object", "in", "their", "place", "with", "an", "updated", "history", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L291-L303
[ "def", "get", "(", "self", ",", "key", ":", "str", ",", "default", ":", "Any", "=", "DEFAULT", ")", ":", "if", "default", "is", "self", ".", "DEFAULT", ":", "try", ":", "value", "=", "self", ".", "params", ".", "get", "(", "key", ")", "except", ...
648a36f77db7e45784c047176074f98534c76636
train
Params.pop_choice
Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of the given choices. Note that this `pops` the key from params, modifying the dictionary, consistent with how parameters are processed in this codebase. Parameters ---------- key: str ...
allennlp/common/params.py
def pop_choice(self, key: str, choices: List[Any], default_to_first_choice: bool = False) -> Any: """ Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of the given choices. Note that this `pops` the key from params, modifying the dictionary, consiste...
def pop_choice(self, key: str, choices: List[Any], default_to_first_choice: bool = False) -> Any: """ Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of the given choices. Note that this `pops` the key from params, modifying the dictionary, consiste...
[ "Gets", "the", "value", "of", "key", "in", "the", "params", "dictionary", "ensuring", "that", "the", "value", "is", "one", "of", "the", "given", "choices", ".", "Note", "that", "this", "pops", "the", "key", "from", "params", "modifying", "the", "dictionary...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L305-L335
[ "def", "pop_choice", "(", "self", ",", "key", ":", "str", ",", "choices", ":", "List", "[", "Any", "]", ",", "default_to_first_choice", ":", "bool", "=", "False", ")", "->", "Any", ":", "default", "=", "choices", "[", "0", "]", "if", "default_to_first_...
648a36f77db7e45784c047176074f98534c76636
train
Params.as_dict
Sometimes we need to just represent the parameters as a dict, for instance when we pass them to PyTorch code. Parameters ---------- quiet: bool, optional (default = False) Whether to log the parameters before returning them as a dict. infer_type_and_cast : bool, opti...
allennlp/common/params.py
def as_dict(self, quiet: bool = False, infer_type_and_cast: bool = False): """ Sometimes we need to just represent the parameters as a dict, for instance when we pass them to PyTorch code. Parameters ---------- quiet: bool, optional (default = False) Whether ...
def as_dict(self, quiet: bool = False, infer_type_and_cast: bool = False): """ Sometimes we need to just represent the parameters as a dict, for instance when we pass them to PyTorch code. Parameters ---------- quiet: bool, optional (default = False) Whether ...
[ "Sometimes", "we", "need", "to", "just", "represent", "the", "parameters", "as", "a", "dict", "for", "instance", "when", "we", "pass", "them", "to", "PyTorch", "code", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L337-L370
[ "def", "as_dict", "(", "self", ",", "quiet", ":", "bool", "=", "False", ",", "infer_type_and_cast", ":", "bool", "=", "False", ")", ":", "if", "infer_type_and_cast", ":", "params_as_dict", "=", "infer_and_cast", "(", "self", ".", "params", ")", "else", ":"...
648a36f77db7e45784c047176074f98534c76636
train
Params.as_flat_dict
Returns the parameters of a flat dictionary from keys to values. Nested structure is collapsed with periods.
allennlp/common/params.py
def as_flat_dict(self): """ Returns the parameters of a flat dictionary from keys to values. Nested structure is collapsed with periods. """ flat_params = {} def recurse(parameters, path): for key, value in parameters.items(): newpath = path + ...
def as_flat_dict(self): """ Returns the parameters of a flat dictionary from keys to values. Nested structure is collapsed with periods. """ flat_params = {} def recurse(parameters, path): for key, value in parameters.items(): newpath = path + ...
[ "Returns", "the", "parameters", "of", "a", "flat", "dictionary", "from", "keys", "to", "values", ".", "Nested", "structure", "is", "collapsed", "with", "periods", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L372-L387
[ "def", "as_flat_dict", "(", "self", ")", ":", "flat_params", "=", "{", "}", "def", "recurse", "(", "parameters", ",", "path", ")", ":", "for", "key", ",", "value", "in", "parameters", ".", "items", "(", ")", ":", "newpath", "=", "path", "+", "[", "...
648a36f77db7e45784c047176074f98534c76636
train
Params.assert_empty
Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling` class, the one that got extra parameters (if there a...
allennlp/common/params.py
def assert_empty(self, class_name: str): """ Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling`...
def assert_empty(self, class_name: str): """ Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling`...
[ "Raises", "a", "ConfigurationError", "if", "self", ".", "params", "is", "not", "empty", ".", "We", "take", "class_name", "as", "an", "argument", "so", "that", "the", "error", "message", "gives", "some", "idea", "of", "where", "an", "error", "happened", "if...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L396-L404
[ "def", "assert_empty", "(", "self", ",", "class_name", ":", "str", ")", ":", "if", "self", ".", "params", ":", "raise", "ConfigurationError", "(", "\"Extra parameters passed to {}: {}\"", ".", "format", "(", "class_name", ",", "self", ".", "params", ")", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
Params.from_file
Load a `Params` object from a configuration file. Parameters ---------- params_file : ``str`` The path to the configuration file to load. params_overrides : ``str``, optional A dict of overrides that can be applied to final object. e.g. {"model.embedd...
allennlp/common/params.py
def from_file(params_file: str, params_overrides: str = "", ext_vars: dict = None) -> 'Params': """ Load a `Params` object from a configuration file. Parameters ---------- params_file : ``str`` The path to the configuration file to load. params_overrides : ``...
def from_file(params_file: str, params_overrides: str = "", ext_vars: dict = None) -> 'Params': """ Load a `Params` object from a configuration file. Parameters ---------- params_file : ``str`` The path to the configuration file to load. params_overrides : ``...
[ "Load", "a", "Params", "object", "from", "a", "configuration", "file", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L436-L466
[ "def", "from_file", "(", "params_file", ":", "str", ",", "params_overrides", ":", "str", "=", "\"\"", ",", "ext_vars", ":", "dict", "=", "None", ")", "->", "'Params'", ":", "if", "ext_vars", "is", "None", ":", "ext_vars", "=", "{", "}", "# redirect to ca...
648a36f77db7e45784c047176074f98534c76636
train
Params.as_ordered_dict
Returns Ordered Dict of Params from list of partial order preferences. Parameters ---------- preference_orders: List[List[str]], optional ``preference_orders`` is list of partial preference orders. ["A", "B", "C"] means "A" > "B" > "C". For multiple preference_orders fir...
allennlp/common/params.py
def as_ordered_dict(self, preference_orders: List[List[str]] = None) -> OrderedDict: """ Returns Ordered Dict of Params from list of partial order preferences. Parameters ---------- preference_orders: List[List[str]], optional ``preference_orders`` is list of partial...
def as_ordered_dict(self, preference_orders: List[List[str]] = None) -> OrderedDict: """ Returns Ordered Dict of Params from list of partial order preferences. Parameters ---------- preference_orders: List[List[str]], optional ``preference_orders`` is list of partial...
[ "Returns", "Ordered", "Dict", "of", "Params", "from", "list", "of", "partial", "order", "preferences", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L472-L507
[ "def", "as_ordered_dict", "(", "self", ",", "preference_orders", ":", "List", "[", "List", "[", "str", "]", "]", "=", "None", ")", "->", "OrderedDict", ":", "params_dict", "=", "self", ".", "as_dict", "(", "quiet", "=", "True", ")", "if", "not", "prefe...
648a36f77db7e45784c047176074f98534c76636
train
Params.get_hash
Returns a hash code representing the current state of this ``Params`` object. We don't want to implement ``__hash__`` because that has deeper python implications (and this is a mutable object), but this will give you a representation of the current state.
allennlp/common/params.py
def get_hash(self) -> str: """ Returns a hash code representing the current state of this ``Params`` object. We don't want to implement ``__hash__`` because that has deeper python implications (and this is a mutable object), but this will give you a representation of the current state. ...
def get_hash(self) -> str: """ Returns a hash code representing the current state of this ``Params`` object. We don't want to implement ``__hash__`` because that has deeper python implications (and this is a mutable object), but this will give you a representation of the current state. ...
[ "Returns", "a", "hash", "code", "representing", "the", "current", "state", "of", "this", "Params", "object", ".", "We", "don", "t", "want", "to", "implement", "__hash__", "because", "that", "has", "deeper", "python", "implications", "(", "and", "this", "is",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L509-L515
[ "def", "get_hash", "(", "self", ")", "->", "str", ":", "return", "str", "(", "hash", "(", "json", ".", "dumps", "(", "self", ".", "params", ",", "sort_keys", "=", "True", ")", ")", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
MetricTracker.clear
Clears out the tracked metrics, but keeps the patience and should_decrease settings.
allennlp/training/metric_tracker.py
def clear(self) -> None: """ Clears out the tracked metrics, but keeps the patience and should_decrease settings. """ self._best_so_far = None self._epochs_with_no_improvement = 0 self._is_best_so_far = True self._epoch_number = 0 self.best_epoch = None
def clear(self) -> None: """ Clears out the tracked metrics, but keeps the patience and should_decrease settings. """ self._best_so_far = None self._epochs_with_no_improvement = 0 self._is_best_so_far = True self._epoch_number = 0 self.best_epoch = None
[ "Clears", "out", "the", "tracked", "metrics", "but", "keeps", "the", "patience", "and", "should_decrease", "settings", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L59-L67
[ "def", "clear", "(", "self", ")", "->", "None", ":", "self", ".", "_best_so_far", "=", "None", "self", ".", "_epochs_with_no_improvement", "=", "0", "self", ".", "_is_best_so_far", "=", "True", "self", ".", "_epoch_number", "=", "0", "self", ".", "best_epo...
648a36f77db7e45784c047176074f98534c76636
train
MetricTracker.state_dict
A ``Trainer`` can use this to serialize the state of the metric tracker.
allennlp/training/metric_tracker.py
def state_dict(self) -> Dict[str, Any]: """ A ``Trainer`` can use this to serialize the state of the metric tracker. """ return { "best_so_far": self._best_so_far, "patience": self._patience, "epochs_with_no_improvement": self._epochs_with_...
def state_dict(self) -> Dict[str, Any]: """ A ``Trainer`` can use this to serialize the state of the metric tracker. """ return { "best_so_far": self._best_so_far, "patience": self._patience, "epochs_with_no_improvement": self._epochs_with_...
[ "A", "Trainer", "can", "use", "this", "to", "serialize", "the", "state", "of", "the", "metric", "tracker", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L69-L82
[ "def", "state_dict", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "{", "\"best_so_far\"", ":", "self", ".", "_best_so_far", ",", "\"patience\"", ":", "self", ".", "_patience", ",", "\"epochs_with_no_improvement\"", ":", "self",...
648a36f77db7e45784c047176074f98534c76636
train
MetricTracker.add_metric
Record a new value of the metric and update the various things that depend on it.
allennlp/training/metric_tracker.py
def add_metric(self, metric: float) -> None: """ Record a new value of the metric and update the various things that depend on it. """ new_best = ((self._best_so_far is None) or (self._should_decrease and metric < self._best_so_far) or (not self._s...
def add_metric(self, metric: float) -> None: """ Record a new value of the metric and update the various things that depend on it. """ new_best = ((self._best_so_far is None) or (self._should_decrease and metric < self._best_so_far) or (not self._s...
[ "Record", "a", "new", "value", "of", "the", "metric", "and", "update", "the", "various", "things", "that", "depend", "on", "it", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L97-L113
[ "def", "add_metric", "(", "self", ",", "metric", ":", "float", ")", "->", "None", ":", "new_best", "=", "(", "(", "self", ".", "_best_so_far", "is", "None", ")", "or", "(", "self", ".", "_should_decrease", "and", "metric", "<", "self", ".", "_best_so_f...
648a36f77db7e45784c047176074f98534c76636
train
MetricTracker.add_metrics
Helper to add multiple metrics at once.
allennlp/training/metric_tracker.py
def add_metrics(self, metrics: Iterable[float]) -> None: """ Helper to add multiple metrics at once. """ for metric in metrics: self.add_metric(metric)
def add_metrics(self, metrics: Iterable[float]) -> None: """ Helper to add multiple metrics at once. """ for metric in metrics: self.add_metric(metric)
[ "Helper", "to", "add", "multiple", "metrics", "at", "once", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L115-L120
[ "def", "add_metrics", "(", "self", ",", "metrics", ":", "Iterable", "[", "float", "]", ")", "->", "None", ":", "for", "metric", "in", "metrics", ":", "self", ".", "add_metric", "(", "metric", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
MetricTracker.should_stop_early
Returns true if improvement has stopped for long enough.
allennlp/training/metric_tracker.py
def should_stop_early(self) -> bool: """ Returns true if improvement has stopped for long enough. """ if self._patience is None: return False else: return self._epochs_with_no_improvement >= self._patience
def should_stop_early(self) -> bool: """ Returns true if improvement has stopped for long enough. """ if self._patience is None: return False else: return self._epochs_with_no_improvement >= self._patience
[ "Returns", "true", "if", "improvement", "has", "stopped", "for", "long", "enough", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L128-L135
[ "def", "should_stop_early", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_patience", "is", "None", ":", "return", "False", "else", ":", "return", "self", ".", "_epochs_with_no_improvement", ">=", "self", ".", "_patience" ]
648a36f77db7e45784c047176074f98534c76636
train
archive_model
Archive the model weights, its training configuration, and its vocabulary to `model.tar.gz`. Include the additional ``files_to_archive`` if provided. Parameters ---------- serialization_dir: ``str`` The directory where the weights and vocabulary are written out. weights: ``str``, option...
allennlp/models/archival.py
def archive_model(serialization_dir: str, weights: str = _DEFAULT_WEIGHTS, files_to_archive: Dict[str, str] = None, archive_path: str = None) -> None: """ Archive the model weights, its training configuration, and its vocabulary to `model.tar.gz`. Includ...
def archive_model(serialization_dir: str, weights: str = _DEFAULT_WEIGHTS, files_to_archive: Dict[str, str] = None, archive_path: str = None) -> None: """ Archive the model weights, its training configuration, and its vocabulary to `model.tar.gz`. Includ...
[ "Archive", "the", "model", "weights", "its", "training", "configuration", "and", "its", "vocabulary", "to", "model", ".", "tar", ".", "gz", ".", "Include", "the", "additional", "files_to_archive", "if", "provided", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/archival.py#L89-L148
[ "def", "archive_model", "(", "serialization_dir", ":", "str", ",", "weights", ":", "str", "=", "_DEFAULT_WEIGHTS", ",", "files_to_archive", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "archive_path", ":", "str", "=", "None", ")", "->", "N...
648a36f77db7e45784c047176074f98534c76636
train
load_archive
Instantiates an Archive from an archived `tar.gz` file. Parameters ---------- archive_file: ``str`` The archive file to load the model from. weights_file: ``str``, optional (default = None) The weights file to use. If unspecified, weights.th in the archive_file will be used. cuda_d...
allennlp/models/archival.py
def load_archive(archive_file: str, cuda_device: int = -1, overrides: str = "", weights_file: str = None) -> Archive: """ Instantiates an Archive from an archived `tar.gz` file. Parameters ---------- archive_file: ``str`` The archive file t...
def load_archive(archive_file: str, cuda_device: int = -1, overrides: str = "", weights_file: str = None) -> Archive: """ Instantiates an Archive from an archived `tar.gz` file. Parameters ---------- archive_file: ``str`` The archive file t...
[ "Instantiates", "an", "Archive", "from", "an", "archived", "tar", ".", "gz", "file", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/archival.py#L150-L232
[ "def", "load_archive", "(", "archive_file", ":", "str", ",", "cuda_device", ":", "int", "=", "-", "1", ",", "overrides", ":", "str", "=", "\"\"", ",", "weights_file", ":", "str", "=", "None", ")", "->", "Archive", ":", "# redirect to the cache, if necessary"...
648a36f77db7e45784c047176074f98534c76636
train
Archive.extract_module
This method can be used to load a module from the pretrained model archive. It is also used implicitly in FromParams based construction. So instead of using standard params to construct a module, you can instead load a pretrained module from the model archive directly. For eg, instead of using ...
allennlp/models/archival.py
def extract_module(self, path: str, freeze: bool = True) -> Module: """ This method can be used to load a module from the pretrained model archive. It is also used implicitly in FromParams based construction. So instead of using standard params to construct a module, you can instead loa...
def extract_module(self, path: str, freeze: bool = True) -> Module: """ This method can be used to load a module from the pretrained model archive. It is also used implicitly in FromParams based construction. So instead of using standard params to construct a module, you can instead loa...
[ "This", "method", "can", "be", "used", "to", "load", "a", "module", "from", "the", "pretrained", "model", "archive", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/archival.py#L28-L76
[ "def", "extract_module", "(", "self", ",", "path", ":", "str", ",", "freeze", ":", "bool", "=", "True", ")", "->", "Module", ":", "modules_dict", "=", "{", "path", ":", "module", "for", "path", ",", "module", "in", "self", ".", "model", ".", "named_m...
648a36f77db7e45784c047176074f98534c76636
train
NlvrSemanticParser._get_action_strings
Takes a list of possible actions and indices of decoded actions into those possible actions for a batch and returns sequences of action strings. We assume ``action_indices`` is a dict mapping batch indices to k-best decoded sequence lists.
allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py
def _get_action_strings(cls, possible_actions: List[List[ProductionRule]], action_indices: Dict[int, List[List[int]]]) -> List[List[List[str]]]: """ Takes a list of possible actions and indices of decoded actions into those possible actions ...
def _get_action_strings(cls, possible_actions: List[List[ProductionRule]], action_indices: Dict[int, List[List[int]]]) -> List[List[List[str]]]: """ Takes a list of possible actions and indices of decoded actions into those possible actions ...
[ "Takes", "a", "list", "of", "possible", "actions", "and", "indices", "of", "decoded", "actions", "into", "those", "possible", "actions", "for", "a", "batch", "and", "returns", "sequences", "of", "action", "strings", ".", "We", "assume", "action_indices", "is",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py#L122-L140
[ "def", "_get_action_strings", "(", "cls", ",", "possible_actions", ":", "List", "[", "List", "[", "ProductionRule", "]", "]", ",", "action_indices", ":", "Dict", "[", "int", ",", "List", "[", "List", "[", "int", "]", "]", "]", ")", "->", "List", "[", ...
648a36f77db7e45784c047176074f98534c76636
train
NlvrSemanticParser.decode
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test time, to finalize predictions. We only transform the action string sequences into logical forms here.
allennlp/models/semantic_parsing/nlvr/nlvr_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. We only transform the action string sequences into logical forms here. ...
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. We only transform the action string sequences into logical forms here. ...
[ "This", "method", "overrides", "Model", ".", "decode", "which", "gets", "called", "after", "Model", ".", "forward", "at", "test", "time", "to", "finalize", "predictions", ".", "We", "only", "transform", "the", "action", "string", "sequences", "into", "logical"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py#L201-L244
[ "def", "decode", "(", "self", ",", "output_dict", ":", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ")", "->", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ":", "best_action_strings", "=", "output_dict", "[", "\"best_action_strings\"", ...
648a36f77db7e45784c047176074f98534c76636
train
NlvrSemanticParser._check_state_denotations
Returns whether action history in the state evaluates to the correct denotations over all worlds. Only defined when the state is finished.
allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py
def _check_state_denotations(self, state: GrammarBasedState, worlds: List[NlvrLanguage]) -> List[bool]: """ Returns whether action history in the state evaluates to the correct denotations over all worlds. Only defined when the state is finished. """ assert state.is_finished(), "...
def _check_state_denotations(self, state: GrammarBasedState, worlds: List[NlvrLanguage]) -> List[bool]: """ Returns whether action history in the state evaluates to the correct denotations over all worlds. Only defined when the state is finished. """ assert state.is_finished(), "...
[ "Returns", "whether", "action", "history", "in", "the", "state", "evaluates", "to", "the", "correct", "denotations", "over", "all", "worlds", ".", "Only", "defined", "when", "the", "state", "is", "finished", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py#L246-L258
[ "def", "_check_state_denotations", "(", "self", ",", "state", ":", "GrammarBasedState", ",", "worlds", ":", "List", "[", "NlvrLanguage", "]", ")", "->", "List", "[", "bool", "]", ":", "assert", "state", ".", "is_finished", "(", ")", ",", "\"Cannot compute de...
648a36f77db7e45784c047176074f98534c76636
train
find_learning_rate_from_args
Start learning rate finder for given args
allennlp/commands/find_learning_rate.py
def find_learning_rate_from_args(args: argparse.Namespace) -> None: """ Start learning rate finder for given args """ params = Params.from_file(args.param_path, args.overrides) find_learning_rate_model(params, args.serialization_dir, start_lr=args.start_lr, ...
def find_learning_rate_from_args(args: argparse.Namespace) -> None: """ Start learning rate finder for given args """ params = Params.from_file(args.param_path, args.overrides) find_learning_rate_model(params, args.serialization_dir, start_lr=args.start_lr, ...
[ "Start", "learning", "rate", "finder", "for", "given", "args" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/find_learning_rate.py#L121-L132
[ "def", "find_learning_rate_from_args", "(", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "params", "=", "Params", ".", "from_file", "(", "args", ".", "param_path", ",", "args", ".", "overrides", ")", "find_learning_rate_model", "(", "para...
648a36f77db7e45784c047176074f98534c76636
train
find_learning_rate_model
Runs learning rate search for given `num_batches` and saves the results in ``serialization_dir`` Parameters ---------- params : ``Params`` A parameter object specifying an AllenNLP Experiment. serialization_dir : ``str`` The directory in which to save results. start_lr: ``float`` ...
allennlp/commands/find_learning_rate.py
def find_learning_rate_model(params: Params, serialization_dir: str, start_lr: float = 1e-5, end_lr: float = 10, num_batches: int = 100, linear_steps: bool = False, stopping_f...
def find_learning_rate_model(params: Params, serialization_dir: str, start_lr: float = 1e-5, end_lr: float = 10, num_batches: int = 100, linear_steps: bool = False, stopping_f...
[ "Runs", "learning", "rate", "search", "for", "given", "num_batches", "and", "saves", "the", "results", "in", "serialization_dir" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/find_learning_rate.py#L134-L229
[ "def", "find_learning_rate_model", "(", "params", ":", "Params", ",", "serialization_dir", ":", "str", ",", "start_lr", ":", "float", "=", "1e-5", ",", "end_lr", ":", "float", "=", "10", ",", "num_batches", ":", "int", "=", "100", ",", "linear_steps", ":",...
648a36f77db7e45784c047176074f98534c76636
train
search_learning_rate
Runs training loop on the model using :class:`~allennlp.training.trainer.Trainer` increasing learning rate from ``start_lr`` to ``end_lr`` recording the losses. Parameters ---------- trainer: :class:`~allennlp.training.trainer.Trainer` start_lr: ``float`` The learning rate to start the searc...
allennlp/commands/find_learning_rate.py
def search_learning_rate(trainer: Trainer, start_lr: float = 1e-5, end_lr: float = 10, num_batches: int = 100, linear_steps: bool = False, stopping_factor: float = None) -> Tuple[List[float], Lis...
def search_learning_rate(trainer: Trainer, start_lr: float = 1e-5, end_lr: float = 10, num_batches: int = 100, linear_steps: bool = False, stopping_factor: float = None) -> Tuple[List[float], Lis...
[ "Runs", "training", "loop", "on", "the", "model", "using", ":", "class", ":", "~allennlp", ".", "training", ".", "trainer", ".", "Trainer", "increasing", "learning", "rate", "from", "start_lr", "to", "end_lr", "recording", "the", "losses", ".", "Parameters", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/find_learning_rate.py#L231-L312
[ "def", "search_learning_rate", "(", "trainer", ":", "Trainer", ",", "start_lr", ":", "float", "=", "1e-5", ",", "end_lr", ":", "float", "=", "10", ",", "num_batches", ":", "int", "=", "100", ",", "linear_steps", ":", "bool", "=", "False", ",", "stopping_...
648a36f77db7e45784c047176074f98534c76636
train
_smooth
Exponential smoothing of values
allennlp/commands/find_learning_rate.py
def _smooth(values: List[float], beta: float) -> List[float]: """ Exponential smoothing of values """ avg_value = 0. smoothed = [] for i, value in enumerate(values): avg_value = beta * avg_value + (1 - beta) * value smoothed.append(avg_value / (1 - beta ** (i + 1))) return smoothed
def _smooth(values: List[float], beta: float) -> List[float]: """ Exponential smoothing of values """ avg_value = 0. smoothed = [] for i, value in enumerate(values): avg_value = beta * avg_value + (1 - beta) * value smoothed.append(avg_value / (1 - beta ** (i + 1))) return smoothed
[ "Exponential", "smoothing", "of", "values" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/find_learning_rate.py#L315-L322
[ "def", "_smooth", "(", "values", ":", "List", "[", "float", "]", ",", "beta", ":", "float", ")", "->", "List", "[", "float", "]", ":", "avg_value", "=", "0.", "smoothed", "=", "[", "]", "for", "i", ",", "value", "in", "enumerate", "(", "values", ...
648a36f77db7e45784c047176074f98534c76636
train
ScalarMix.forward
Compute a weighted average of the ``tensors``. The input tensors an be any shape with at least two dimensions, but must all be the same shape. When ``do_layer_norm=True``, the ``mask`` is required input. If the ``tensors`` are dimensioned ``(dim_0, ..., dim_{n-1}, dim_n)``, then the ``mask``...
allennlp/modules/scalar_mix.py
def forward(self, tensors: List[torch.Tensor], # pylint: disable=arguments-differ mask: torch.Tensor = None) -> torch.Tensor: """ Compute a weighted average of the ``tensors``. The input tensors an be any shape with at least two dimensions, but must all be the same shape. ...
def forward(self, tensors: List[torch.Tensor], # pylint: disable=arguments-differ mask: torch.Tensor = None) -> torch.Tensor: """ Compute a weighted average of the ``tensors``. The input tensors an be any shape with at least two dimensions, but must all be the same shape. ...
[ "Compute", "a", "weighted", "average", "of", "the", "tensors", ".", "The", "input", "tensors", "an", "be", "any", "shape", "with", "at", "least", "two", "dimensions", "but", "must", "all", "be", "the", "same", "shape", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/scalar_mix.py#L38-L81
[ "def", "forward", "(", "self", ",", "tensors", ":", "List", "[", "torch", ".", "Tensor", "]", ",", "# pylint: disable=arguments-differ", "mask", ":", "torch", ".", "Tensor", "=", "None", ")", "->", "torch", ".", "Tensor", ":", "if", "len", "(", "tensors"...
648a36f77db7e45784c047176074f98534c76636
train
predicate_with_side_args
Like :func:`predicate`, but used when some of the arguments to the function are meant to be provided by the decoder or other state, instead of from the language. For example, you might want to have a function use the decoder's attention over some input text when a terminal was predicted. That attention wo...
allennlp/semparse/domain_languages/domain_language.py
def predicate_with_side_args(side_arguments: List[str]) -> Callable: # pylint: disable=invalid-name """ Like :func:`predicate`, but used when some of the arguments to the function are meant to be provided by the decoder or other state, instead of from the language. For example, you might want to have ...
def predicate_with_side_args(side_arguments: List[str]) -> Callable: # pylint: disable=invalid-name """ Like :func:`predicate`, but used when some of the arguments to the function are meant to be provided by the decoder or other state, instead of from the language. For example, you might want to have ...
[ "Like", ":", "func", ":", "predicate", "but", "used", "when", "some", "of", "the", "arguments", "to", "the", "function", "are", "meant", "to", "be", "provided", "by", "the", "decoder", "or", "other", "state", "instead", "of", "from", "the", "language", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L182-L198
[ "def", "predicate_with_side_args", "(", "side_arguments", ":", "List", "[", "str", "]", ")", "->", "Callable", ":", "# pylint: disable=invalid-name", "def", "decorator", "(", "function", ":", "Callable", ")", "->", "Callable", ":", "setattr", "(", "function", ",...
648a36f77db7e45784c047176074f98534c76636
train
nltk_tree_to_logical_form
Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted into the correct number of parentheses. This is used in the logic that converts action sequences back into logical form...
allennlp/semparse/domain_languages/domain_language.py
def nltk_tree_to_logical_form(tree: Tree) -> str: """ Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted into the correct number of parentheses. This is used in t...
def nltk_tree_to_logical_form(tree: Tree) -> str: """ Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted into the correct number of parentheses. This is used in t...
[ "Given", "an", "nltk", ".", "Tree", "representing", "the", "syntax", "tree", "that", "generates", "a", "logical", "form", "this", "method", "produces", "the", "actual", "(", "lisp", "-", "like", ")", "logical", "form", "with", "all", "of", "the", "non", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L201-L218
[ "def", "nltk_tree_to_logical_form", "(", "tree", ":", "Tree", ")", "->", "str", ":", "# nltk.Tree actually inherits from `list`, so you use `len()` to get the number of children.", "# We're going to be explicit about checking length, instead of using `if tree:`, just to avoid", "# any funny ...
648a36f77db7e45784c047176074f98534c76636
train
PredicateType.get_type
Converts a python ``Type`` (as you might get from a type annotation) into a ``PredicateType``. If the ``Type`` is callable, this will return a ``FunctionType``; otherwise, it will return a ``BasicType``. ``BasicTypes`` have a single ``name`` parameter - we typically get this from ``typ...
allennlp/semparse/domain_languages/domain_language.py
def get_type(type_: Type) -> 'PredicateType': """ Converts a python ``Type`` (as you might get from a type annotation) into a ``PredicateType``. If the ``Type`` is callable, this will return a ``FunctionType``; otherwise, it will return a ``BasicType``. ``BasicTypes`` have a si...
def get_type(type_: Type) -> 'PredicateType': """ Converts a python ``Type`` (as you might get from a type annotation) into a ``PredicateType``. If the ``Type`` is callable, this will return a ``FunctionType``; otherwise, it will return a ``BasicType``. ``BasicTypes`` have a si...
[ "Converts", "a", "python", "Type", "(", "as", "you", "might", "get", "from", "a", "type", "annotation", ")", "into", "a", "PredicateType", ".", "If", "the", "Type", "is", "callable", "this", "will", "return", "a", "FunctionType", ";", "otherwise", "it", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L60-L82
[ "def", "get_type", "(", "type_", ":", "Type", ")", "->", "'PredicateType'", ":", "if", "is_callable", "(", "type_", ")", ":", "callable_args", "=", "type_", ".", "__args__", "argument_types", "=", "[", "PredicateType", ".", "get_type", "(", "t", ")", "for"...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.execute
Executes a logical form, using whatever predicates you have defined.
allennlp/semparse/domain_languages/domain_language.py
def execute(self, logical_form: str): """Executes a logical form, using whatever predicates you have defined.""" if not hasattr(self, '_functions'): raise RuntimeError("You must call super().__init__() in your Language constructor") logical_form = logical_form.replace(",", " ") ...
def execute(self, logical_form: str): """Executes a logical form, using whatever predicates you have defined.""" if not hasattr(self, '_functions'): raise RuntimeError("You must call super().__init__() in your Language constructor") logical_form = logical_form.replace(",", " ") ...
[ "Executes", "a", "logical", "form", "using", "whatever", "predicates", "you", "have", "defined", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L307-L313
[ "def", "execute", "(", "self", ",", "logical_form", ":", "str", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_functions'", ")", ":", "raise", "RuntimeError", "(", "\"You must call super().__init__() in your Language constructor\"", ")", "logical_form", "=",...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.execute_action_sequence
Executes the program defined by an action sequence directly, without needing the overhead of translating to a logical form first. For any given program, :func:`execute` and this function are equivalent, they just take different representations of the program, so you can use whichever is more ef...
allennlp/semparse/domain_languages/domain_language.py
def execute_action_sequence(self, action_sequence: List[str], side_arguments: List[Dict] = None): """ Executes the program defined by an action sequence directly, without needing the overhead of translating to a logical form first. For any given program, :func:`execute` and this functio...
def execute_action_sequence(self, action_sequence: List[str], side_arguments: List[Dict] = None): """ Executes the program defined by an action sequence directly, without needing the overhead of translating to a logical form first. For any given program, :func:`execute` and this functio...
[ "Executes", "the", "program", "defined", "by", "an", "action", "sequence", "directly", "without", "needing", "the", "overhead", "of", "translating", "to", "a", "logical", "form", "first", ".", "For", "any", "given", "program", ":", "func", ":", "execute", "a...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L315-L333
[ "def", "execute_action_sequence", "(", "self", ",", "action_sequence", ":", "List", "[", "str", "]", ",", "side_arguments", ":", "List", "[", "Dict", "]", "=", "None", ")", ":", "# We'll strip off the first action, because it doesn't matter for execution.", "first_actio...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.get_nonterminal_productions
Induces a grammar from the defined collection of predicates in this language and returns all productions in that grammar, keyed by the non-terminal they are expanding. This includes terminal productions implied by each predicate as well as productions for the `return type` of each defined predi...
allennlp/semparse/domain_languages/domain_language.py
def get_nonterminal_productions(self) -> Dict[str, List[str]]: """ Induces a grammar from the defined collection of predicates in this language and returns all productions in that grammar, keyed by the non-terminal they are expanding. This includes terminal productions implied by each p...
def get_nonterminal_productions(self) -> Dict[str, List[str]]: """ Induces a grammar from the defined collection of predicates in this language and returns all productions in that grammar, keyed by the non-terminal they are expanding. This includes terminal productions implied by each p...
[ "Induces", "a", "grammar", "from", "the", "defined", "collection", "of", "predicates", "in", "this", "language", "and", "returns", "all", "productions", "in", "that", "grammar", "keyed", "by", "the", "non", "-", "terminal", "they", "are", "expanding", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L335-L367
[ "def", "get_nonterminal_productions", "(", "self", ")", "->", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ":", "if", "not", "self", ".", "_nonterminal_productions", ":", "actions", ":", "Dict", "[", "str", ",", "Set", "[", "str", "]", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.all_possible_productions
Returns a sorted list of all production rules in the grammar induced by :func:`get_nonterminal_productions`.
allennlp/semparse/domain_languages/domain_language.py
def all_possible_productions(self) -> List[str]: """ Returns a sorted list of all production rules in the grammar induced by :func:`get_nonterminal_productions`. """ all_actions = set() for action_set in self.get_nonterminal_productions().values(): all_actions...
def all_possible_productions(self) -> List[str]: """ Returns a sorted list of all production rules in the grammar induced by :func:`get_nonterminal_productions`. """ all_actions = set() for action_set in self.get_nonterminal_productions().values(): all_actions...
[ "Returns", "a", "sorted", "list", "of", "all", "production", "rules", "in", "the", "grammar", "induced", "by", ":", "func", ":", "get_nonterminal_productions", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L369-L377
[ "def", "all_possible_productions", "(", "self", ")", "->", "List", "[", "str", "]", ":", "all_actions", "=", "set", "(", ")", "for", "action_set", "in", "self", ".", "get_nonterminal_productions", "(", ")", ".", "values", "(", ")", ":", "all_actions", ".",...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.logical_form_to_action_sequence
Converts a logical form into a linearization of the production rules from its abstract syntax tree. The linearization is top-down, depth-first. Each production rule is formatted as "LHS -> RHS", where "LHS" is a single non-terminal type, and RHS is either a terminal or a list of non-terminals ...
allennlp/semparse/domain_languages/domain_language.py
def logical_form_to_action_sequence(self, logical_form: str) -> List[str]: """ Converts a logical form into a linearization of the production rules from its abstract syntax tree. The linearization is top-down, depth-first. Each production rule is formatted as "LHS -> RHS", where "LHS" ...
def logical_form_to_action_sequence(self, logical_form: str) -> List[str]: """ Converts a logical form into a linearization of the production rules from its abstract syntax tree. The linearization is top-down, depth-first. Each production rule is formatted as "LHS -> RHS", where "LHS" ...
[ "Converts", "a", "logical", "form", "into", "a", "linearization", "of", "the", "production", "rules", "from", "its", "abstract", "syntax", "tree", ".", "The", "linearization", "is", "top", "-", "down", "depth", "-", "first", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L379-L409
[ "def", "logical_form_to_action_sequence", "(", "self", ",", "logical_form", ":", "str", ")", "->", "List", "[", "str", "]", ":", "expression", "=", "util", ".", "lisp_to_nested_expression", "(", "logical_form", ")", "try", ":", "transitions", ",", "start_type", ...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.action_sequence_to_logical_form
Takes an action sequence as produced by :func:`logical_form_to_action_sequence`, which is a linearization of an abstract syntax tree, and reconstructs the logical form defined by that abstract syntax tree.
allennlp/semparse/domain_languages/domain_language.py
def action_sequence_to_logical_form(self, action_sequence: List[str]) -> str: """ Takes an action sequence as produced by :func:`logical_form_to_action_sequence`, which is a linearization of an abstract syntax tree, and reconstructs the logical form defined by that abstract syntax tree. ...
def action_sequence_to_logical_form(self, action_sequence: List[str]) -> str: """ Takes an action sequence as produced by :func:`logical_form_to_action_sequence`, which is a linearization of an abstract syntax tree, and reconstructs the logical form defined by that abstract syntax tree. ...
[ "Takes", "an", "action", "sequence", "as", "produced", "by", ":", "func", ":", "logical_form_to_action_sequence", "which", "is", "a", "linearization", "of", "an", "abstract", "syntax", "tree", "and", "reconstructs", "the", "logical", "form", "defined", "by", "th...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L411-L436
[ "def", "action_sequence_to_logical_form", "(", "self", ",", "action_sequence", ":", "List", "[", "str", "]", ")", "->", "str", ":", "# Basic outline: we assume that the bracketing that we get in the RHS of each action is the", "# correct bracketing for reconstructing the logical form...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.add_predicate
Adds a predicate to this domain language. Typically you do this with the ``@predicate`` decorator on the methods in your class. But, if you need to for whatever reason, you can also call this function yourself with a (type-annotated) function to add it to your language. Parameters ...
allennlp/semparse/domain_languages/domain_language.py
def add_predicate(self, name: str, function: Callable, side_arguments: List[str] = None): """ Adds a predicate to this domain language. Typically you do this with the ``@predicate`` decorator on the methods in your class. But, if you need to for whatever reason, you can also call this ...
def add_predicate(self, name: str, function: Callable, side_arguments: List[str] = None): """ Adds a predicate to this domain language. Typically you do this with the ``@predicate`` decorator on the methods in your class. But, if you need to for whatever reason, you can also call this ...
[ "Adds", "a", "predicate", "to", "this", "domain", "language", ".", "Typically", "you", "do", "this", "with", "the", "@predicate", "decorator", "on", "the", "methods", "in", "your", "class", ".", "But", "if", "you", "need", "to", "for", "whatever", "reason"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L438-L470
[ "def", "add_predicate", "(", "self", ",", "name", ":", "str", ",", "function", ":", "Callable", ",", "side_arguments", ":", "List", "[", "str", "]", "=", "None", ")", ":", "side_arguments", "=", "side_arguments", "or", "[", "]", "signature", "=", "inspec...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.add_constant
Adds a constant to this domain language. You would typically just pass in a list of constants to the ``super().__init__()`` call in your constructor, but you can also call this method to add constants if it is more convenient. Because we construct a grammar over this language for you, in order...
allennlp/semparse/domain_languages/domain_language.py
def add_constant(self, name: str, value: Any, type_: Type = None): """ Adds a constant to this domain language. You would typically just pass in a list of constants to the ``super().__init__()`` call in your constructor, but you can also call this method to add constants if it is more c...
def add_constant(self, name: str, value: Any, type_: Type = None): """ Adds a constant to this domain language. You would typically just pass in a list of constants to the ``super().__init__()`` call in your constructor, but you can also call this method to add constants if it is more c...
[ "Adds", "a", "constant", "to", "this", "domain", "language", ".", "You", "would", "typically", "just", "pass", "in", "a", "list", "of", "constants", "to", "the", "super", "()", ".", "__init__", "()", "call", "in", "your", "constructor", "but", "you", "ca...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L472-L486
[ "def", "add_constant", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Any", ",", "type_", ":", "Type", "=", "None", ")", ":", "value_type", "=", "type_", "if", "type_", "else", "type", "(", "value", ")", "constant_type", "=", "PredicateType"...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage.is_nonterminal
Determines whether an input symbol is a valid non-terminal in the grammar.
allennlp/semparse/domain_languages/domain_language.py
def is_nonterminal(self, symbol: str) -> bool: """ Determines whether an input symbol is a valid non-terminal in the grammar. """ nonterminal_productions = self.get_nonterminal_productions() return symbol in nonterminal_productions
def is_nonterminal(self, symbol: str) -> bool: """ Determines whether an input symbol is a valid non-terminal in the grammar. """ nonterminal_productions = self.get_nonterminal_productions() return symbol in nonterminal_productions
[ "Determines", "whether", "an", "input", "symbol", "is", "a", "valid", "non", "-", "terminal", "in", "the", "grammar", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L488-L493
[ "def", "is_nonterminal", "(", "self", ",", "symbol", ":", "str", ")", "->", "bool", ":", "nonterminal_productions", "=", "self", ".", "get_nonterminal_productions", "(", ")", "return", "symbol", "in", "nonterminal_productions" ]
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage._execute_expression
This does the bulk of the work of executing a logical form, recursively executing a single expression. Basically, if the expression is a function we know about, we evaluate its arguments then call the function. If it's a list, we evaluate all elements of the list. If it's a constant (or a zero...
allennlp/semparse/domain_languages/domain_language.py
def _execute_expression(self, expression: Any): """ This does the bulk of the work of executing a logical form, recursively executing a single expression. Basically, if the expression is a function we know about, we evaluate its arguments then call the function. If it's a list, we eval...
def _execute_expression(self, expression: Any): """ This does the bulk of the work of executing a logical form, recursively executing a single expression. Basically, if the expression is a function we know about, we evaluate its arguments then call the function. If it's a list, we eval...
[ "This", "does", "the", "bulk", "of", "the", "work", "of", "executing", "a", "logical", "form", "recursively", "executing", "a", "single", "expression", ".", "Basically", "if", "the", "expression", "is", "a", "function", "we", "know", "about", "we", "evaluate...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L496-L539
[ "def", "_execute_expression", "(", "self", ",", "expression", ":", "Any", ")", ":", "# pylint: disable=too-many-return-statements", "if", "isinstance", "(", "expression", ",", "list", ")", ":", "if", "isinstance", "(", "expression", "[", "0", "]", ",", "list", ...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage._execute_sequence
This does the bulk of the work of :func:`execute_action_sequence`, recursively executing the functions it finds and trimming actions off of the action sequence. The return value is a tuple of (execution, remaining_actions), where the second value is necessary to handle the recursion.
allennlp/semparse/domain_languages/domain_language.py
def _execute_sequence(self, action_sequence: List[str], side_arguments: List[Dict]) -> Tuple[Any, List[str], List[Dict]]: """ This does the bulk of the work of :func:`execute_action_sequence`, recursively executing the functions it finds and tr...
def _execute_sequence(self, action_sequence: List[str], side_arguments: List[Dict]) -> Tuple[Any, List[str], List[Dict]]: """ This does the bulk of the work of :func:`execute_action_sequence`, recursively executing the functions it finds and tr...
[ "This", "does", "the", "bulk", "of", "the", "work", "of", ":", "func", ":", "execute_action_sequence", "recursively", "executing", "the", "functions", "it", "finds", "and", "trimming", "actions", "off", "of", "the", "action", "sequence", ".", "The", "return", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L541-L607
[ "def", "_execute_sequence", "(", "self", ",", "action_sequence", ":", "List", "[", "str", "]", ",", "side_arguments", ":", "List", "[", "Dict", "]", ")", "->", "Tuple", "[", "Any", ",", "List", "[", "str", "]", ",", "List", "[", "Dict", "]", "]", "...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage._get_transitions
This is used when converting a logical form into an action sequence. This piece recursively translates a lisp expression into an action sequence, making sure we match the expected type (or using the expected type to get the right type for constant expressions).
allennlp/semparse/domain_languages/domain_language.py
def _get_transitions(self, expression: Any, expected_type: PredicateType) -> Tuple[List[str], PredicateType]: """ This is used when converting a logical form into an action sequence. This piece recursively translates a lisp expression into an action sequence, making sure we match the ex...
def _get_transitions(self, expression: Any, expected_type: PredicateType) -> Tuple[List[str], PredicateType]: """ This is used when converting a logical form into an action sequence. This piece recursively translates a lisp expression into an action sequence, making sure we match the ex...
[ "This", "is", "used", "when", "converting", "a", "logical", "form", "into", "an", "action", "sequence", ".", "This", "piece", "recursively", "translates", "a", "lisp", "expression", "into", "an", "action", "sequence", "making", "sure", "we", "match", "the", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L609-L645
[ "def", "_get_transitions", "(", "self", ",", "expression", ":", "Any", ",", "expected_type", ":", "PredicateType", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "PredicateType", "]", ":", "if", "isinstance", "(", "expression", ",", "(", "list", ...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage._get_function_transitions
A helper method for ``_get_transitions``. This gets the transitions for the predicate itself in a function call. If we only had simple functions (e.g., "(add 2 3)"), this would be pretty straightforward and we wouldn't need a separate method to handle it. We split it out into its own method b...
allennlp/semparse/domain_languages/domain_language.py
def _get_function_transitions(self, expression: Union[str, List], expected_type: PredicateType) -> Tuple[List[str], PredicateType, ...
def _get_function_transitions(self, expression: Union[str, List], expected_type: PredicateType) -> Tuple[List[str], PredicateType, ...
[ "A", "helper", "method", "for", "_get_transitions", ".", "This", "gets", "the", "transitions", "for", "the", "predicate", "itself", "in", "a", "function", "call", ".", "If", "we", "only", "had", "simple", "functions", "(", "e", ".", "g", ".", "(", "add",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L647-L691
[ "def", "_get_function_transitions", "(", "self", ",", "expression", ":", "Union", "[", "str", ",", "List", "]", ",", "expected_type", ":", "PredicateType", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "PredicateType", ",", "List", "[", "Predicate...
648a36f77db7e45784c047176074f98534c76636
train
DomainLanguage._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/domain_languages/domain_language.py
def _construct_node_from_actions(self, current_node: Tree, remaining_actions: List[List[str]]) -> List[List[str]]: """ Given a current node in the logical form tree, and a list of actions in an action sequence, this method...
def _construct_node_from_actions(self, current_node: Tree, remaining_actions: List[List[str]]) -> List[List[str]]: """ Given a current node in the logical form tree, and a list of actions in an action sequence, this method...
[ "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/domain_languages/domain_language.py#L693-L733
[ "def", "_construct_node_from_actions", "(", "self", ",", "current_node", ":", "Tree", ",", "remaining_actions", ":", "List", "[", "List", "[", "str", "]", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "if", "not", "remaining_actions", "...
648a36f77db7e45784c047176074f98534c76636
train
_choice
Chooses ``num_samples`` samples without replacement from [0, ..., num_words). Returns a tuple (samples, num_tries).
allennlp/modules/sampled_softmax_loss.py
def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]: """ Chooses ``num_samples`` samples without replacement from [0, ..., num_words). Returns a tuple (samples, num_tries). """ num_tries = 0 num_chosen = 0 def get_buffer() -> np.ndarray: log_samples = np.random.r...
def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]: """ Chooses ``num_samples`` samples without replacement from [0, ..., num_words). Returns a tuple (samples, num_tries). """ num_tries = 0 num_chosen = 0 def get_buffer() -> np.ndarray: log_samples = np.random.r...
[ "Chooses", "num_samples", "samples", "without", "replacement", "from", "[", "0", "...", "num_words", ")", ".", "Returns", "a", "tuple", "(", "samples", "num_tries", ")", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/sampled_softmax_loss.py#L11-L42
[ "def", "_choice", "(", "num_words", ":", "int", ",", "num_samples", ":", "int", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "int", "]", ":", "num_tries", "=", "0", "num_chosen", "=", "0", "def", "get_buffer", "(", ")", "->", "np", ".", "nda...
648a36f77db7e45784c047176074f98534c76636
train
TokenIndexer.tokens_to_indices
Takes a list of tokens and converts them to one or more sets of indices. This could be just an ID for each token from the vocabulary. Or it could split each token into characters and return one ID per character. Or (for instance, in the case of byte-pair encoding) there might not be a clean ...
allennlp/data/token_indexers/token_indexer.py
def tokens_to_indices(self, tokens: List[Token], vocabulary: Vocabulary, index_name: str) -> Dict[str, List[TokenType]]: """ Takes a list of tokens and converts them to one or more sets of indices. This could be just a...
def tokens_to_indices(self, tokens: List[Token], vocabulary: Vocabulary, index_name: str) -> Dict[str, List[TokenType]]: """ Takes a list of tokens and converts them to one or more sets of indices. This could be just a...
[ "Takes", "a", "list", "of", "tokens", "and", "converts", "them", "to", "one", "or", "more", "sets", "of", "indices", ".", "This", "could", "be", "just", "an", "ID", "for", "each", "token", "from", "the", "vocabulary", ".", "Or", "it", "could", "split",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/token_indexers/token_indexer.py#L33-L44
[ "def", "tokens_to_indices", "(", "self", ",", "tokens", ":", "List", "[", "Token", "]", ",", "vocabulary", ":", "Vocabulary", ",", "index_name", ":", "str", ")", "->", "Dict", "[", "str", ",", "List", "[", "TokenType", "]", "]", ":", "raise", "NotImple...
648a36f77db7e45784c047176074f98534c76636
train
TokenIndexer.pad_token_sequence
This method pads a list of tokens to ``desired_num_tokens`` and returns a padded copy of the input tokens. If the input token list is longer than ``desired_num_tokens`` then it will be truncated. ``padding_lengths`` is used to provide supplemental padding parameters which are needed in...
allennlp/data/token_indexers/token_indexer.py
def pad_token_sequence(self, tokens: Dict[str, List[TokenType]], desired_num_tokens: Dict[str, int], padding_lengths: Dict[str, int]) -> Dict[str, List[TokenType]]: """ This method pads a list of tokens to ``desired_num_tok...
def pad_token_sequence(self, tokens: Dict[str, List[TokenType]], desired_num_tokens: Dict[str, int], padding_lengths: Dict[str, int]) -> Dict[str, List[TokenType]]: """ This method pads a list of tokens to ``desired_num_tok...
[ "This", "method", "pads", "a", "list", "of", "tokens", "to", "desired_num_tokens", "and", "returns", "a", "padded", "copy", "of", "the", "input", "tokens", ".", "If", "the", "input", "token", "list", "is", "longer", "than", "desired_num_tokens", "then", "it"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/token_indexers/token_indexer.py#L62-L75
[ "def", "pad_token_sequence", "(", "self", ",", "tokens", ":", "Dict", "[", "str", ",", "List", "[", "TokenType", "]", "]", ",", "desired_num_tokens", ":", "Dict", "[", "str", ",", "int", "]", ",", "padding_lengths", ":", "Dict", "[", "str", ",", "int",...
648a36f77db7e45784c047176074f98534c76636
train
canonicalize_clusters
The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters containing the identical spans.
allennlp/data/dataset_readers/coreference_resolution/conll.py
def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]: """ The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters co...
def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]: """ The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters co...
[ "The", "CONLL", "2012", "data", "includes", "2", "annotated", "spans", "which", "are", "identical", "but", "have", "different", "ids", ".", "This", "checks", "all", "clusters", "for", "spans", "which", "are", "identical", "and", "if", "it", "finds", "any", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/coreference_resolution/conll.py#L18-L47
[ "def", "canonicalize_clusters", "(", "clusters", ":", "DefaultDict", "[", "int", ",", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", "]", ")", "->", "List", "[", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", "]", ":", "merged_clu...
648a36f77db7e45784c047176074f98534c76636
train
join_mwp
Join multi-word predicates to a single predicate ('V') token.
allennlp/predictors/open_information_extraction.py
def join_mwp(tags: List[str]) -> List[str]: """ Join multi-word predicates to a single predicate ('V') token. """ ret = [] verb_flag = False for tag in tags: if "V" in tag: # Create a continuous 'V' BIO span prefix, _ = tag.split("-") if verb_flag:...
def join_mwp(tags: List[str]) -> List[str]: """ Join multi-word predicates to a single predicate ('V') token. """ ret = [] verb_flag = False for tag in tags: if "V" in tag: # Create a continuous 'V' BIO span prefix, _ = tag.split("-") if verb_flag:...
[ "Join", "multi", "-", "word", "predicates", "to", "a", "single", "predicate", "(", "V", ")", "token", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L13-L33
[ "def", "join_mwp", "(", "tags", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "ret", "=", "[", "]", "verb_flag", "=", "False", "for", "tag", "in", "tags", ":", "if", "\"V\"", "in", "tag", ":", "# Create a continuous 'V' BIO s...
648a36f77db7e45784c047176074f98534c76636
train
make_oie_string
Converts a list of model outputs (i.e., a list of lists of bio tags, each pertaining to a single word), returns an inline bracket representation of the prediction.
allennlp/predictors/open_information_extraction.py
def make_oie_string(tokens: List[Token], tags: List[str]) -> str: """ Converts a list of model outputs (i.e., a list of lists of bio tags, each pertaining to a single word), returns an inline bracket representation of the prediction. """ frame = [] chunk = [] words = [token.text for toke...
def make_oie_string(tokens: List[Token], tags: List[str]) -> str: """ Converts a list of model outputs (i.e., a list of lists of bio tags, each pertaining to a single word), returns an inline bracket representation of the prediction. """ frame = [] chunk = [] words = [token.text for toke...
[ "Converts", "a", "list", "of", "model", "outputs", "(", "i", ".", "e", ".", "a", "list", "of", "lists", "of", "bio", "tags", "each", "pertaining", "to", "a", "single", "word", ")", "returns", "an", "inline", "bracket", "representation", "of", "the", "p...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L35-L61
[ "def", "make_oie_string", "(", "tokens", ":", "List", "[", "Token", "]", ",", "tags", ":", "List", "[", "str", "]", ")", "->", "str", ":", "frame", "=", "[", "]", "chunk", "=", "[", "]", "words", "=", "[", "token", ".", "text", "for", "token", ...
648a36f77db7e45784c047176074f98534c76636
train
get_predicate_indices
Return the word indices of a predicate in BIO tags.
allennlp/predictors/open_information_extraction.py
def get_predicate_indices(tags: List[str]) -> List[int]: """ Return the word indices of a predicate in BIO tags. """ return [ind for ind, tag in enumerate(tags) if 'V' in tag]
def get_predicate_indices(tags: List[str]) -> List[int]: """ Return the word indices of a predicate in BIO tags. """ return [ind for ind, tag in enumerate(tags) if 'V' in tag]
[ "Return", "the", "word", "indices", "of", "a", "predicate", "in", "BIO", "tags", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L63-L67
[ "def", "get_predicate_indices", "(", "tags", ":", "List", "[", "str", "]", ")", "->", "List", "[", "int", "]", ":", "return", "[", "ind", "for", "ind", ",", "tag", "in", "enumerate", "(", "tags", ")", "if", "'V'", "in", "tag", "]" ]
648a36f77db7e45784c047176074f98534c76636
train
get_predicate_text
Get the predicate in this prediction.
allennlp/predictors/open_information_extraction.py
def get_predicate_text(sent_tokens: List[Token], tags: List[str]) -> str: """ Get the predicate in this prediction. """ return " ".join([sent_tokens[pred_id].text for pred_id in get_predicate_indices(tags)])
def get_predicate_text(sent_tokens: List[Token], tags: List[str]) -> str: """ Get the predicate in this prediction. """ return " ".join([sent_tokens[pred_id].text for pred_id in get_predicate_indices(tags)])
[ "Get", "the", "predicate", "in", "this", "prediction", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L69-L74
[ "def", "get_predicate_text", "(", "sent_tokens", ":", "List", "[", "Token", "]", ",", "tags", ":", "List", "[", "str", "]", ")", "->", "str", ":", "return", "\" \"", ".", "join", "(", "[", "sent_tokens", "[", "pred_id", "]", ".", "text", "for", "pred...
648a36f77db7e45784c047176074f98534c76636
train
predicates_overlap
Tests whether the predicate in BIO tags1 overlap with those of tags2.
allennlp/predictors/open_information_extraction.py
def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool: """ Tests whether the predicate in BIO tags1 overlap with those of tags2. """ # Get predicate word indices from both predictions pred_ind1 = get_predicate_indices(tags1) pred_ind2 = get_predicate_indices(tags2) # Return...
def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool: """ Tests whether the predicate in BIO tags1 overlap with those of tags2. """ # Get predicate word indices from both predictions pred_ind1 = get_predicate_indices(tags1) pred_ind2 = get_predicate_indices(tags2) # Return...
[ "Tests", "whether", "the", "predicate", "in", "BIO", "tags1", "overlap", "with", "those", "of", "tags2", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L76-L86
[ "def", "predicates_overlap", "(", "tags1", ":", "List", "[", "str", "]", ",", "tags2", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "# Get predicate word indices from both predictions", "pred_ind1", "=", "get_predicate_indices", "(", "tags1", ")", "pred...
648a36f77db7e45784c047176074f98534c76636
train
get_coherent_next_tag
Generate a coherent tag, given previous tag and current label.
allennlp/predictors/open_information_extraction.py
def get_coherent_next_tag(prev_label: str, cur_label: str) -> str: """ Generate a coherent tag, given previous tag and current label. """ if cur_label == "O": # Don't need to add prefix to an "O" label return "O" if prev_label == cur_label: return f"I-{cur_label}" else: ...
def get_coherent_next_tag(prev_label: str, cur_label: str) -> str: """ Generate a coherent tag, given previous tag and current label. """ if cur_label == "O": # Don't need to add prefix to an "O" label return "O" if prev_label == cur_label: return f"I-{cur_label}" else: ...
[ "Generate", "a", "coherent", "tag", "given", "previous", "tag", "and", "current", "label", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L88-L99
[ "def", "get_coherent_next_tag", "(", "prev_label", ":", "str", ",", "cur_label", ":", "str", ")", "->", "str", ":", "if", "cur_label", "==", "\"O\"", ":", "# Don't need to add prefix to an \"O\" label", "return", "\"O\"", "if", "prev_label", "==", "cur_label", ":"...
648a36f77db7e45784c047176074f98534c76636
train
merge_overlapping_predictions
Merge two predictions into one. Assumes the predicate in tags1 overlap with the predicate of tags2.
allennlp/predictors/open_information_extraction.py
def merge_overlapping_predictions(tags1: List[str], tags2: List[str]) -> List[str]: """ Merge two predictions into one. Assumes the predicate in tags1 overlap with the predicate of tags2. """ ret_sequence = [] prev_label = "O" # Build a coherent sequence out of two # spans which predica...
def merge_overlapping_predictions(tags1: List[str], tags2: List[str]) -> List[str]: """ Merge two predictions into one. Assumes the predicate in tags1 overlap with the predicate of tags2. """ ret_sequence = [] prev_label = "O" # Build a coherent sequence out of two # spans which predica...
[ "Merge", "two", "predictions", "into", "one", ".", "Assumes", "the", "predicate", "in", "tags1", "overlap", "with", "the", "predicate", "of", "tags2", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L101-L130
[ "def", "merge_overlapping_predictions", "(", "tags1", ":", "List", "[", "str", "]", ",", "tags2", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "ret_sequence", "=", "[", "]", "prev_label", "=", "\"O\"", "# Build a coherent sequence...
648a36f77db7e45784c047176074f98534c76636
train
consolidate_predictions
Identify that certain predicates are part of a multiword predicate (e.g., "decided to run") in which case, we don't need to return the embedded predicate ("run").
allennlp/predictors/open_information_extraction.py
def consolidate_predictions(outputs: List[List[str]], sent_tokens: List[Token]) -> Dict[str, List[str]]: """ Identify that certain predicates are part of a multiword predicate (e.g., "decided to run") in which case, we don't need to return the embedded predicate ("run"). """ pred_dict: Dict[str,...
def consolidate_predictions(outputs: List[List[str]], sent_tokens: List[Token]) -> Dict[str, List[str]]: """ Identify that certain predicates are part of a multiword predicate (e.g., "decided to run") in which case, we don't need to return the embedded predicate ("run"). """ pred_dict: Dict[str,...
[ "Identify", "that", "certain", "predicates", "are", "part", "of", "a", "multiword", "predicate", "(", "e", ".", "g", ".", "decided", "to", "run", ")", "in", "which", "case", "we", "don", "t", "need", "to", "return", "the", "embedded", "predicate", "(", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L132-L158
[ "def", "consolidate_predictions", "(", "outputs", ":", "List", "[", "List", "[", "str", "]", "]", ",", "sent_tokens", ":", "List", "[", "Token", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ":", "pred_dict", ":", "Dict", "...
648a36f77db7e45784c047176074f98534c76636
train
sanitize_label
Sanitize a BIO label - this deals with OIE labels sometimes having some noise, as parentheses.
allennlp/predictors/open_information_extraction.py
def sanitize_label(label: str) -> str: """ Sanitize a BIO label - this deals with OIE labels sometimes having some noise, as parentheses. """ if "-" in label: prefix, suffix = label.split("-") suffix = suffix.split("(")[-1] return f"{prefix}-{suffix}" else: return...
def sanitize_label(label: str) -> str: """ Sanitize a BIO label - this deals with OIE labels sometimes having some noise, as parentheses. """ if "-" in label: prefix, suffix = label.split("-") suffix = suffix.split("(")[-1] return f"{prefix}-{suffix}" else: return...
[ "Sanitize", "a", "BIO", "label", "-", "this", "deals", "with", "OIE", "labels", "sometimes", "having", "some", "noise", "as", "parentheses", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L161-L171
[ "def", "sanitize_label", "(", "label", ":", "str", ")", "->", "str", ":", "if", "\"-\"", "in", "label", ":", "prefix", ",", "suffix", "=", "label", ".", "split", "(", "\"-\"", ")", "suffix", "=", "suffix", ".", "split", "(", "\"(\"", ")", "[", "-",...
648a36f77db7e45784c047176074f98534c76636
train
batch_to_ids
Converts a batch of tokenized sentences to a tensor representing the sentences with encoded characters (len(batch), max sentence length, max word length). Parameters ---------- batch : ``List[List[str]]``, required A list of tokenized sentences. Returns ------- A tensor of padd...
allennlp/modules/elmo.py
def batch_to_ids(batch: List[List[str]]) -> torch.Tensor: """ Converts a batch of tokenized sentences to a tensor representing the sentences with encoded characters (len(batch), max sentence length, max word length). Parameters ---------- batch : ``List[List[str]]``, required A list of ...
def batch_to_ids(batch: List[List[str]]) -> torch.Tensor: """ Converts a batch of tokenized sentences to a tensor representing the sentences with encoded characters (len(batch), max sentence length, max word length). Parameters ---------- batch : ``List[List[str]]``, required A list of ...
[ "Converts", "a", "batch", "of", "tokenized", "sentences", "to", "a", "tensor", "representing", "the", "sentences", "with", "encoded", "characters", "(", "len", "(", "batch", ")", "max", "sentence", "length", "max", "word", "length", ")", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L230-L256
[ "def", "batch_to_ids", "(", "batch", ":", "List", "[", "List", "[", "str", "]", "]", ")", "->", "torch", ".", "Tensor", ":", "instances", "=", "[", "]", "indexer", "=", "ELMoTokenCharactersIndexer", "(", ")", "for", "sentence", "in", "batch", ":", "tok...
648a36f77db7e45784c047176074f98534c76636
train
Elmo.forward
Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch. word_inputs : ``torch.Tensor``, required. If you passed a cached vocab, you can in addition pass a tensor of shape ``(b...
allennlp/modules/elmo.py
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]: """ Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_size...
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]: """ Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_size...
[ "Parameters", "----------", "inputs", ":", "torch", ".", "Tensor", "required", ".", "Shape", "(", "batch_size", "timesteps", "50", ")", "of", "character", "ids", "representing", "the", "current", "batch", ".", "word_inputs", ":", "torch", ".", "Tensor", "requi...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L127-L201
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "torch", ".", "Tensor", ",", "word_inputs", ":", "torch", ".", "Tensor", "=", "None", ")", "->", "Dict", "[", "str", ",", "Union", "[", "torch", ".", "Tensor", ",", ...
648a36f77db7e45784c047176074f98534c76636
train
_ElmoCharacterEncoder.forward
Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs: ``torch.Tensor`` Shape ``(batch_size, sequence_length, 50)`` of character ids representing the current batch. Returns ------- Dict with keys: ...
allennlp/modules/elmo.py
def forward(self, inputs: torch.Tensor) -> Dict[str, torch.Tensor]: # pylint: disable=arguments-differ """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs: ``torch.Tensor`` Shape ``(batch_size, sequence_length, 50)...
def forward(self, inputs: torch.Tensor) -> Dict[str, torch.Tensor]: # pylint: disable=arguments-differ """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs: ``torch.Tensor`` Shape ``(batch_size, sequence_length, 50)...
[ "Compute", "context", "insensitive", "token", "embeddings", "for", "ELMo", "representations", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L324-L395
[ "def", "forward", "(", "self", ",", "inputs", ":", "torch", ".", "Tensor", ")", "->", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ":", "# pylint: disable=arguments-differ", "# Add BOS/EOS", "mask", "=", "(", "(", "inputs", ">", "0", ")", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
_ElmoBiLm.forward
Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch. word_inputs : ``torch.Tensor``, required. If you passed a cached vocab, you can in addition pass a tensor of shape ``(batch_siz...
allennlp/modules/elmo.py
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]: """ Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_si...
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]: """ Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_si...
[ "Parameters", "----------", "inputs", ":", "torch", ".", "Tensor", "required", ".", "Shape", "(", "batch_size", "timesteps", "50", ")", "of", "character", "ids", "representing", "the", "current", "batch", ".", "word_inputs", ":", "torch", ".", "Tensor", "requi...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L561-L625
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "torch", ".", "Tensor", ",", "word_inputs", ":", "torch", ".", "Tensor", "=", "None", ")", "->", "Dict", "[", "str", ",", "Union", "[", "torch", ".", "Tensor", ",", ...
648a36f77db7e45784c047176074f98534c76636
train
_ElmoBiLm.create_cached_cnn_embeddings
Given a list of tokens, this method precomputes word representations by running just the character convolutions and highway layers of elmo, essentially creating uncontextual word vectors. On subsequent forward passes, the word ids are looked up from an embedding, rather than being computed on ...
allennlp/modules/elmo.py
def create_cached_cnn_embeddings(self, tokens: List[str]) -> None: """ Given a list of tokens, this method precomputes word representations by running just the character convolutions and highway layers of elmo, essentially creating uncontextual word vectors. On subsequent forward passes,...
def create_cached_cnn_embeddings(self, tokens: List[str]) -> None: """ Given a list of tokens, this method precomputes word representations by running just the character convolutions and highway layers of elmo, essentially creating uncontextual word vectors. On subsequent forward passes,...
[ "Given", "a", "list", "of", "tokens", "this", "method", "precomputes", "word", "representations", "by", "running", "just", "the", "character", "convolutions", "and", "highway", "layers", "of", "elmo", "essentially", "creating", "uncontextual", "word", "vectors", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L627-L685
[ "def", "create_cached_cnn_embeddings", "(", "self", ",", "tokens", ":", "List", "[", "str", "]", ")", "->", "None", ":", "tokens", "=", "[", "ELMoCharacterMapper", ".", "bos_token", ",", "ELMoCharacterMapper", ".", "eos_token", "]", "+", "tokens", "timesteps",...
648a36f77db7e45784c047176074f98534c76636
train
normalize_text
Performs a normalization that is very similar to that done by the normalization functions in SQuAD and TriviaQA. This involves splitting and rejoining the text, and could be a somewhat expensive operation.
allennlp/data/dataset_readers/reading_comprehension/util.py
def normalize_text(text: str) -> str: """ Performs a normalization that is very similar to that done by the normalization functions in SQuAD and TriviaQA. This involves splitting and rejoining the text, and could be a somewhat expensive operation. """ return ' '.join([token ...
def normalize_text(text: str) -> str: """ Performs a normalization that is very similar to that done by the normalization functions in SQuAD and TriviaQA. This involves splitting and rejoining the text, and could be a somewhat expensive operation. """ return ' '.join([token ...
[ "Performs", "a", "normalization", "that", "is", "very", "similar", "to", "that", "done", "by", "the", "normalization", "functions", "in", "SQuAD", "and", "TriviaQA", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L24-L33
[ "def", "normalize_text", "(", "text", ":", "str", ")", "->", "str", ":", "return", "' '", ".", "join", "(", "[", "token", "for", "token", "in", "text", ".", "lower", "(", ")", ".", "strip", "(", "STRIPPED_CHARACTERS", ")", ".", "split", "(", ")", "...
648a36f77db7e45784c047176074f98534c76636
train
char_span_to_token_span
Converts a character span from a passage into the corresponding token span in the tokenized version of the passage. If you pass in a character span that does not correspond to complete tokens in the tokenized version, we'll do our best, but the behavior is officially undefined. We return an error flag in t...
allennlp/data/dataset_readers/reading_comprehension/util.py
def char_span_to_token_span(token_offsets: List[Tuple[int, int]], character_span: Tuple[int, int]) -> Tuple[Tuple[int, int], bool]: """ Converts a character span from a passage into the corresponding token span in the tokenized version of the passage. If you pass in a character ...
def char_span_to_token_span(token_offsets: List[Tuple[int, int]], character_span: Tuple[int, int]) -> Tuple[Tuple[int, int], bool]: """ Converts a character span from a passage into the corresponding token span in the tokenized version of the passage. If you pass in a character ...
[ "Converts", "a", "character", "span", "from", "a", "passage", "into", "the", "corresponding", "token", "span", "in", "the", "tokenized", "version", "of", "the", "passage", ".", "If", "you", "pass", "in", "a", "character", "span", "that", "does", "not", "co...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L36-L94
[ "def", "char_span_to_token_span", "(", "token_offsets", ":", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ",", "character_span", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "Tuple", "[", "Tuple", "[", "int", ",", "int", "]", ",",...
648a36f77db7e45784c047176074f98534c76636
train
find_valid_answer_spans
Finds a list of token spans in ``passage_tokens`` that match the given ``answer_texts``. This tries to find all spans that would evaluate to correct given the SQuAD and TriviaQA official evaluation scripts, which do some normalization of the input text. Note that this could return duplicate spans! The ca...
allennlp/data/dataset_readers/reading_comprehension/util.py
def find_valid_answer_spans(passage_tokens: List[Token], answer_texts: List[str]) -> List[Tuple[int, int]]: """ Finds a list of token spans in ``passage_tokens`` that match the given ``answer_texts``. This tries to find all spans that would evaluate to correct given the SQuAD an...
def find_valid_answer_spans(passage_tokens: List[Token], answer_texts: List[str]) -> List[Tuple[int, int]]: """ Finds a list of token spans in ``passage_tokens`` that match the given ``answer_texts``. This tries to find all spans that would evaluate to correct given the SQuAD an...
[ "Finds", "a", "list", "of", "token", "spans", "in", "passage_tokens", "that", "match", "the", "given", "answer_texts", ".", "This", "tries", "to", "find", "all", "spans", "that", "would", "evaluate", "to", "correct", "given", "the", "SQuAD", "and", "TriviaQA...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L97-L135
[ "def", "find_valid_answer_spans", "(", "passage_tokens", ":", "List", "[", "Token", "]", ",", "answer_texts", ":", "List", "[", "str", "]", ")", "->", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "normalized_tokens", "=", "[", "token", ...
648a36f77db7e45784c047176074f98534c76636
train
make_reading_comprehension_instance
Converts a question, a passage, and an optional answer (or answers) to an ``Instance`` for use in a reading comprehension model. Creates an ``Instance`` with at least these fields: ``question`` and ``passage``, both ``TextFields``; and ``metadata``, a ``MetadataField``. Additionally, if both ``answer_text...
allennlp/data/dataset_readers/reading_comprehension/util.py
def make_reading_comprehension_instance(question_tokens: List[Token], passage_tokens: List[Token], token_indexers: Dict[str, TokenIndexer], passage_text: str, t...
def make_reading_comprehension_instance(question_tokens: List[Token], passage_tokens: List[Token], token_indexers: Dict[str, TokenIndexer], passage_text: str, t...
[ "Converts", "a", "question", "a", "passage", "and", "an", "optional", "answer", "(", "or", "answers", ")", "to", "an", "Instance", "for", "use", "in", "a", "reading", "comprehension", "model", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L138-L214
[ "def", "make_reading_comprehension_instance", "(", "question_tokens", ":", "List", "[", "Token", "]", ",", "passage_tokens", ":", "List", "[", "Token", "]", ",", "token_indexers", ":", "Dict", "[", "str", ",", "TokenIndexer", "]", ",", "passage_text", ":", "st...
648a36f77db7e45784c047176074f98534c76636
train
make_reading_comprehension_instance_quac
Converts a question, a passage, and an optional answer (or answers) to an ``Instance`` for use in a reading comprehension model. Creates an ``Instance`` with at least these fields: ``question`` and ``passage``, both ``TextFields``; and ``metadata``, a ``MetadataField``. Additionally, if both ``answer_text...
allennlp/data/dataset_readers/reading_comprehension/util.py
def make_reading_comprehension_instance_quac(question_list_tokens: List[List[Token]], passage_tokens: List[Token], token_indexers: Dict[str, TokenIndexer], passage_text: str, ...
def make_reading_comprehension_instance_quac(question_list_tokens: List[List[Token]], passage_tokens: List[Token], token_indexers: Dict[str, TokenIndexer], passage_text: str, ...
[ "Converts", "a", "question", "a", "passage", "and", "an", "optional", "answer", "(", "or", "answers", ")", "to", "an", "Instance", "for", "use", "in", "a", "reading", "comprehension", "model", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L217-L351
[ "def", "make_reading_comprehension_instance_quac", "(", "question_list_tokens", ":", "List", "[", "List", "[", "Token", "]", "]", ",", "passage_tokens", ":", "List", "[", "Token", "]", ",", "token_indexers", ":", "Dict", "[", "str", ",", "TokenIndexer", "]", "...
648a36f77db7e45784c047176074f98534c76636
train
handle_cannot
Process a list of reference answers. If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold. Otherwise, return answers that are not "CANNOTANSWER".
allennlp/data/dataset_readers/reading_comprehension/util.py
def handle_cannot(reference_answers: List[str]): """ Process a list of reference answers. If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold. Otherwise, return answers that are not "CANNOTANSWER". """ num_cannot = 0 num_spans = 0 for ref in reference_...
def handle_cannot(reference_answers: List[str]): """ Process a list of reference answers. If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold. Otherwise, return answers that are not "CANNOTANSWER". """ num_cannot = 0 num_spans = 0 for ref in reference_...
[ "Process", "a", "list", "of", "reference", "answers", ".", "If", "equal", "or", "more", "than", "half", "of", "the", "reference", "answers", "are", "CANNOTANSWER", "take", "it", "as", "gold", ".", "Otherwise", "return", "answers", "that", "are", "not", "CA...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L354-L371
[ "def", "handle_cannot", "(", "reference_answers", ":", "List", "[", "str", "]", ")", ":", "num_cannot", "=", "0", "num_spans", "=", "0", "for", "ref", "in", "reference_answers", ":", "if", "ref", "==", "'CANNOTANSWER'", ":", "num_cannot", "+=", "1", "else"...
648a36f77db7e45784c047176074f98534c76636
train
get_best_span
This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()`` in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can directly import this function without the class. We call the inputs "logits" - they could either be unnormalized logits or normaliz...
allennlp/models/reading_comprehension/util.py
def get_best_span(span_start_logits: torch.Tensor, span_end_logits: torch.Tensor) -> torch.Tensor: """ This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()`` in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can directly import this func...
def get_best_span(span_start_logits: torch.Tensor, span_end_logits: torch.Tensor) -> torch.Tensor: """ This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()`` in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can directly import this func...
[ "This", "acts", "the", "same", "as", "the", "static", "method", "BidirectionalAttentionFlow", ".", "get_best_span", "()", "in", "allennlp", "/", "models", "/", "reading_comprehension", "/", "bidaf", ".", "py", ".", "We", "keep", "it", "here", "so", "that", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/reading_comprehension/util.py#L4-L33
[ "def", "get_best_span", "(", "span_start_logits", ":", "torch", ".", "Tensor", ",", "span_end_logits", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "if", "span_start_logits", ".", "dim", "(", ")", "!=", "2", "or", "span_end_logits", ...
648a36f77db7e45784c047176074f98534c76636
train
WordSplitter.batch_split_words
Spacy needs to do batch processing, or it can be really slow. This method lets you take advantage of that if you want. Default implementation is to just iterate of the sentences and call ``split_words``, but the ``SpacyWordSplitter`` will actually do batched processing.
allennlp/data/tokenizers/word_splitter.py
def batch_split_words(self, sentences: List[str]) -> List[List[Token]]: """ Spacy needs to do batch processing, or it can be really slow. This method lets you take advantage of that if you want. Default implementation is to just iterate of the sentences and call ``split_words``, but th...
def batch_split_words(self, sentences: List[str]) -> List[List[Token]]: """ Spacy needs to do batch processing, or it can be really slow. This method lets you take advantage of that if you want. Default implementation is to just iterate of the sentences and call ``split_words``, but th...
[ "Spacy", "needs", "to", "do", "batch", "processing", "or", "it", "can", "be", "really", "slow", ".", "This", "method", "lets", "you", "take", "advantage", "of", "that", "if", "you", "want", ".", "Default", "implementation", "is", "to", "just", "iterate", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/tokenizers/word_splitter.py#L25-L32
[ "def", "batch_split_words", "(", "self", ",", "sentences", ":", "List", "[", "str", "]", ")", "->", "List", "[", "List", "[", "Token", "]", "]", ":", "return", "[", "self", ".", "split_words", "(", "sentence", ")", "for", "sentence", "in", "sentences",...
648a36f77db7e45784c047176074f98534c76636
train
BeamSearch.constrained_to
Return a new BeamSearch instance that's like this one but with the specified constraint.
allennlp/state_machines/beam_search.py
def constrained_to(self, initial_sequence: torch.Tensor, keep_beam_details: bool = True) -> 'BeamSearch': """ Return a new BeamSearch instance that's like this one but with the specified constraint. """ return BeamSearch(self._beam_size, self._per_node_beam_size, initial_sequence, keep_b...
def constrained_to(self, initial_sequence: torch.Tensor, keep_beam_details: bool = True) -> 'BeamSearch': """ Return a new BeamSearch instance that's like this one but with the specified constraint. """ return BeamSearch(self._beam_size, self._per_node_beam_size, initial_sequence, keep_b...
[ "Return", "a", "new", "BeamSearch", "instance", "that", "s", "like", "this", "one", "but", "with", "the", "specified", "constraint", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/beam_search.py#L70-L74
[ "def", "constrained_to", "(", "self", ",", "initial_sequence", ":", "torch", ".", "Tensor", ",", "keep_beam_details", ":", "bool", "=", "True", ")", "->", "'BeamSearch'", ":", "return", "BeamSearch", "(", "self", ".", "_beam_size", ",", "self", ".", "_per_no...
648a36f77db7e45784c047176074f98534c76636
train
BeamSearch.search
Parameters ---------- num_steps : ``int`` How many steps should we take in our search? This is an upper bound, as it's possible for the search to run out of valid actions before hitting this number, or for all states on the beam to finish. initial_state : ``S...
allennlp/state_machines/beam_search.py
def search(self, num_steps: int, initial_state: StateType, transition_function: TransitionFunction, keep_final_unfinished_states: bool = True) -> Dict[int, List[StateType]]: """ Parameters ---------- num_steps : ``int`` ...
def search(self, num_steps: int, initial_state: StateType, transition_function: TransitionFunction, keep_final_unfinished_states: bool = True) -> Dict[int, List[StateType]]: """ Parameters ---------- num_steps : ``int`` ...
[ "Parameters", "----------", "num_steps", ":", "int", "How", "many", "steps", "should", "we", "take", "in", "our", "search?", "This", "is", "an", "upper", "bound", "as", "it", "s", "possible", "for", "the", "search", "to", "run", "out", "of", "valid", "ac...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/beam_search.py#L76-L175
[ "def", "search", "(", "self", ",", "num_steps", ":", "int", ",", "initial_state", ":", "StateType", ",", "transition_function", ":", "TransitionFunction", ",", "keep_final_unfinished_states", ":", "bool", "=", "True", ")", "->", "Dict", "[", "int", ",", "List"...
648a36f77db7e45784c047176074f98534c76636
train
_normalize_answer
Lower text and remove punctuation, articles and extra whitespace.
allennlp/tools/drop_eval.py
def _normalize_answer(text: str) -> str: """Lower text and remove punctuation, articles and extra whitespace.""" parts = [_white_space_fix(_remove_articles(_normalize_number(_remove_punc(_lower(token))))) for token in _tokenize(text)] parts = [part for part in parts if part.strip()] normal...
def _normalize_answer(text: str) -> str: """Lower text and remove punctuation, articles and extra whitespace.""" parts = [_white_space_fix(_remove_articles(_normalize_number(_remove_punc(_lower(token))))) for token in _tokenize(text)] parts = [part for part in parts if part.strip()] normal...
[ "Lower", "text", "and", "remove", "punctuation", "articles", "and", "extra", "whitespace", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L36-L43
[ "def", "_normalize_answer", "(", "text", ":", "str", ")", "->", "str", ":", "parts", "=", "[", "_white_space_fix", "(", "_remove_articles", "(", "_normalize_number", "(", "_remove_punc", "(", "_lower", "(", "token", ")", ")", ")", ")", ")", "for", "token",...
648a36f77db7e45784c047176074f98534c76636
train
_align_bags
Takes gold and predicted answer sets and first finds a greedy 1-1 alignment between them and gets maximum metric values over all the answers
allennlp/tools/drop_eval.py
def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]: """ Takes gold and predicted answer sets and first finds a greedy 1-1 alignment between them and gets maximum metric values over all the answers """ f1_scores = [] for gold_index, gold_item in enumerate(gold): ...
def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]: """ Takes gold and predicted answer sets and first finds a greedy 1-1 alignment between them and gets maximum metric values over all the answers """ f1_scores = [] for gold_index, gold_item in enumerate(gold): ...
[ "Takes", "gold", "and", "predicted", "answer", "sets", "and", "first", "finds", "a", "greedy", "1", "-", "1", "alignment", "between", "them", "and", "gets", "maximum", "metric", "values", "over", "all", "the", "answers" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L73-L99
[ "def", "_align_bags", "(", "predicted", ":", "List", "[", "Set", "[", "str", "]", "]", ",", "gold", ":", "List", "[", "Set", "[", "str", "]", "]", ")", "->", "List", "[", "float", "]", ":", "f1_scores", "=", "[", "]", "for", "gold_index", ",", ...
648a36f77db7e45784c047176074f98534c76636
train
get_metrics
Takes a predicted answer and a gold answer (that are both either a string or a list of strings), and returns exact match and the DROP F1 metric for the prediction. If you are writing a script for evaluating objects in memory (say, the output of predictions during validation, or while training), this is the...
allennlp/tools/drop_eval.py
def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]], gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]: """ Takes a predicted answer and a gold answer (that are both either a string or a list of strings), and returns exact match and the DROP F1 metric for the...
def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]], gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]: """ Takes a predicted answer and a gold answer (that are both either a string or a list of strings), and returns exact match and the DROP F1 metric for the...
[ "Takes", "a", "predicted", "answer", "and", "a", "gold", "answer", "(", "that", "are", "both", "either", "a", "string", "or", "a", "list", "of", "strings", ")", "and", "returns", "exact", "match", "and", "the", "DROP", "F1", "metric", "for", "the", "pr...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L130-L147
[ "def", "get_metrics", "(", "predicted", ":", "Union", "[", "str", ",", "List", "[", "str", "]", ",", "Tuple", "[", "str", ",", "...", "]", "]", ",", "gold", ":", "Union", "[", "str", ",", "List", "[", "str", "]", ",", "Tuple", "[", "str", ",", ...
648a36f77db7e45784c047176074f98534c76636
train
answer_json_to_strings
Takes an answer JSON blob from the DROP data release and converts it into strings used for evaluation.
allennlp/tools/drop_eval.py
def answer_json_to_strings(answer: Dict[str, Any]) -> Tuple[Tuple[str, ...], str]: """ Takes an answer JSON blob from the DROP data release and converts it into strings used for evaluation. """ if "number" in answer and answer["number"]: return tuple([str(answer["number"])]), "number" el...
def answer_json_to_strings(answer: Dict[str, Any]) -> Tuple[Tuple[str, ...], str]: """ Takes an answer JSON blob from the DROP data release and converts it into strings used for evaluation. """ if "number" in answer and answer["number"]: return tuple([str(answer["number"])]), "number" el...
[ "Takes", "an", "answer", "JSON", "blob", "from", "the", "DROP", "data", "release", "and", "converts", "it", "into", "strings", "used", "for", "evaluation", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L150-L164
[ "def", "answer_json_to_strings", "(", "answer", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "Tuple", "[", "str", ",", "...", "]", ",", "str", "]", ":", "if", "\"number\"", "in", "answer", "and", "answer", "[", "\"number\"", "]"...
648a36f77db7e45784c047176074f98534c76636
train
evaluate_json
Takes gold annotations and predicted answers and evaluates the predictions for each question in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to match predictions to gold annotations (note that these are somewhat deep in the JSON for the gold annotations, but must be...
allennlp/tools/drop_eval.py
def evaluate_json(annotations: Dict[str, Any], predicted_answers: Dict[str, Any]) -> Tuple[float, float]: """ Takes gold annotations and predicted answers and evaluates the predictions for each question in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to match pr...
def evaluate_json(annotations: Dict[str, Any], predicted_answers: Dict[str, Any]) -> Tuple[float, float]: """ Takes gold annotations and predicted answers and evaluates the predictions for each question in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to match pr...
[ "Takes", "gold", "annotations", "and", "predicted", "answers", "and", "evaluates", "the", "predictions", "for", "each", "question", "in", "the", "gold", "annotations", ".", "Both", "JSON", "dictionaries", "must", "have", "query_id", "keys", "which", "are", "used...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L167-L226
[ "def", "evaluate_json", "(", "annotations", ":", "Dict", "[", "str", ",", "Any", "]", ",", "predicted_answers", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "float", ",", "float", "]", ":", "instance_exact_match", "=", "[", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
evaluate_prediction_file
Takes a prediction file and a gold file and evaluates the predictions for each question in the gold file. Both files must be json formatted and must have query_id keys, which are used to match predictions to gold annotations. The gold file is assumed to have the format of the dev set in the DROP data rele...
allennlp/tools/drop_eval.py
def evaluate_prediction_file(prediction_path: str, gold_path: str) -> Tuple[float, float]: """ Takes a prediction file and a gold file and evaluates the predictions for each question in the gold file. Both files must be json formatted and must have query_id keys, which are used to match predictions to ...
def evaluate_prediction_file(prediction_path: str, gold_path: str) -> Tuple[float, float]: """ Takes a prediction file and a gold file and evaluates the predictions for each question in the gold file. Both files must be json formatted and must have query_id keys, which are used to match predictions to ...
[ "Takes", "a", "prediction", "file", "and", "a", "gold", "file", "and", "evaluates", "the", "predictions", "for", "each", "question", "in", "the", "gold", "file", ".", "Both", "files", "must", "be", "json", "formatted", "and", "must", "have", "query_id", "k...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L229-L240
[ "def", "evaluate_prediction_file", "(", "prediction_path", ":", "str", ",", "gold_path", ":", "str", ")", "->", "Tuple", "[", "float", ",", "float", "]", ":", "predicted_answers", "=", "json", ".", "load", "(", "open", "(", "prediction_path", ",", "encoding"...
648a36f77db7e45784c047176074f98534c76636
train
DatasetReader.cache_data
When you call this method, we will use this directory to store a cache of already-processed ``Instances`` in every file passed to :func:`read`, serialized as one string-formatted ``Instance`` per line. If the cache file for a given ``file_path`` exists, we read the ``Instances`` from the cache ...
allennlp/data/dataset_readers/dataset_reader.py
def cache_data(self, cache_directory: str) -> None: """ When you call this method, we will use this directory to store a cache of already-processed ``Instances`` in every file passed to :func:`read`, serialized as one string-formatted ``Instance`` per line. If the cache file for a given...
def cache_data(self, cache_directory: str) -> None: """ When you call this method, we will use this directory to store a cache of already-processed ``Instances`` in every file passed to :func:`read`, serialized as one string-formatted ``Instance`` per line. If the cache file for a given...
[ "When", "you", "call", "this", "method", "we", "will", "use", "this", "directory", "to", "store", "a", "cache", "of", "already", "-", "processed", "Instances", "in", "every", "file", "passed", "to", ":", "func", ":", "read", "serialized", "as", "one", "s...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_reader.py#L72-L89
[ "def", "cache_data", "(", "self", ",", "cache_directory", ":", "str", ")", "->", "None", ":", "self", ".", "_cache_directory", "=", "pathlib", ".", "Path", "(", "cache_directory", ")", "os", ".", "makedirs", "(", "self", ".", "_cache_directory", ",", "exis...
648a36f77db7e45784c047176074f98534c76636
train
DatasetReader.read
Returns an ``Iterable`` containing all the instances in the specified dataset. If ``self.lazy`` is False, this calls ``self._read()``, ensures that the result is a list, then returns the resulting list. If ``self.lazy`` is True, this returns an object whose ``__iter__`` method ...
allennlp/data/dataset_readers/dataset_reader.py
def read(self, file_path: str) -> Iterable[Instance]: """ Returns an ``Iterable`` containing all the instances in the specified dataset. If ``self.lazy`` is False, this calls ``self._read()``, ensures that the result is a list, then returns the resulting list. If ``self...
def read(self, file_path: str) -> Iterable[Instance]: """ Returns an ``Iterable`` containing all the instances in the specified dataset. If ``self.lazy`` is False, this calls ``self._read()``, ensures that the result is a list, then returns the resulting list. If ``self...
[ "Returns", "an", "Iterable", "containing", "all", "the", "instances", "in", "the", "specified", "dataset", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_reader.py#L91-L145
[ "def", "read", "(", "self", ",", "file_path", ":", "str", ")", "->", "Iterable", "[", "Instance", "]", ":", "lazy", "=", "getattr", "(", "self", ",", "'lazy'", ",", "None", ")", "if", "lazy", "is", "None", ":", "logger", ".", "warning", "(", "\"Dat...
648a36f77db7e45784c047176074f98534c76636
train
Checkpointer.restore_checkpoint
Restores a model from a serialization_dir to the last saved checkpoint. This includes a training state (typically consisting of an epoch count and optimizer state), which is serialized separately from model parameters. This function should only be used to continue training - if you wish to load...
allennlp/training/checkpointer.py
def restore_checkpoint(self) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Restores a model from a serialization_dir to the last saved checkpoint. This includes a training state (typically consisting of an epoch count and optimizer state), which is serialized separately from model param...
def restore_checkpoint(self) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Restores a model from a serialization_dir to the last saved checkpoint. This includes a training state (typically consisting of an epoch count and optimizer state), which is serialized separately from model param...
[ "Restores", "a", "model", "from", "a", "serialization_dir", "to", "the", "last", "saved", "checkpoint", ".", "This", "includes", "a", "training", "state", "(", "typically", "consisting", "of", "an", "epoch", "count", "and", "optimizer", "state", ")", "which", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/checkpointer.py#L114-L145
[ "def", "restore_checkpoint", "(", "self", ")", "->", "Tuple", "[", "Dict", "[", "str", ",", "Any", "]", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "latest_checkpoint", "=", "self", ".", "find_latest_checkpoint", "(", ")", "if", "latest_checkpoin...
648a36f77db7e45784c047176074f98534c76636
train
write_to_conll_eval_file
Prints predicate argument predictions and gold labels for a single verbal predicate in a sentence to two provided file references. Parameters ---------- prediction_file : TextIO, required. A file reference to print predictions to. gold_file : TextIO, required. A file reference to pr...
allennlp/models/semantic_role_labeler.py
def write_to_conll_eval_file(prediction_file: TextIO, gold_file: TextIO, verb_index: Optional[int], sentence: List[str], prediction: List[str], gold_labels: List[str]): ""...
def write_to_conll_eval_file(prediction_file: TextIO, gold_file: TextIO, verb_index: Optional[int], sentence: List[str], prediction: List[str], gold_labels: List[str]): ""...
[ "Prints", "predicate", "argument", "predictions", "and", "gold", "labels", "for", "a", "single", "verbal", "predicate", "in", "a", "sentence", "to", "two", "provided", "file", "references", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_role_labeler.py#L226-L268
[ "def", "write_to_conll_eval_file", "(", "prediction_file", ":", "TextIO", ",", "gold_file", ":", "TextIO", ",", "verb_index", ":", "Optional", "[", "int", "]", ",", "sentence", ":", "List", "[", "str", "]", ",", "prediction", ":", "List", "[", "str", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
convert_bio_tags_to_conll_format
Converts BIO formatted SRL tags to the format required for evaluation with the official CONLL 2005 perl script. Spans are represented by bracketed labels, with the labels of words inside spans being the same as those outside spans. Beginning spans always have a opening bracket and a closing asterisk (e.g. "...
allennlp/models/semantic_role_labeler.py
def convert_bio_tags_to_conll_format(labels: List[str]): """ Converts BIO formatted SRL tags to the format required for evaluation with the official CONLL 2005 perl script. Spans are represented by bracketed labels, with the labels of words inside spans being the same as those outside spans. Beginni...
def convert_bio_tags_to_conll_format(labels: List[str]): """ Converts BIO formatted SRL tags to the format required for evaluation with the official CONLL 2005 perl script. Spans are represented by bracketed labels, with the labels of words inside spans being the same as those outside spans. Beginni...
[ "Converts", "BIO", "formatted", "SRL", "tags", "to", "the", "format", "required", "for", "evaluation", "with", "the", "official", "CONLL", "2005", "perl", "script", ".", "Spans", "are", "represented", "by", "bracketed", "labels", "with", "the", "labels", "of",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_role_labeler.py#L271-L310
[ "def", "convert_bio_tags_to_conll_format", "(", "labels", ":", "List", "[", "str", "]", ")", ":", "sentence_length", "=", "len", "(", "labels", ")", "conll_labels", "=", "[", "]", "for", "i", ",", "label", "in", "enumerate", "(", "labels", ")", ":", "if"...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage.get_agenda_for_sentence
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The ``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This is a simplistic mapping at this point, and can be expanded. Parameters ---------- sentence : ``...
allennlp/semparse/domain_languages/nlvr_language.py
def get_agenda_for_sentence(self, sentence: str) -> List[str]: """ Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The ``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This is a simplistic mapping at this point...
def get_agenda_for_sentence(self, sentence: str) -> List[str]: """ Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The ``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This is a simplistic mapping at this point...
[ "Given", "a", "sentence", "returns", "a", "list", "of", "actions", "the", "sentence", "triggers", "as", "an", "agenda", ".", "The", "agenda", "can", "be", "used", "while", "by", "a", "parser", "to", "guide", "the", "decoder", ".", "sequences", "as", "pos...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L125-L199
[ "def", "get_agenda_for_sentence", "(", "self", ",", "sentence", ":", "str", ")", "->", "List", "[", "str", "]", ":", "agenda", "=", "[", "]", "sentence", "=", "sentence", ".", "lower", "(", ")", "if", "sentence", ".", "startswith", "(", "\"there is a box...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage._get_number_productions
Gathers all the numbers in the sentence, and returns productions that lead to them.
allennlp/semparse/domain_languages/nlvr_language.py
def _get_number_productions(sentence: str) -> List[str]: """ Gathers all the numbers in the sentence, and returns productions that lead to them. """ # The mapping here is very simple and limited, which also shouldn't be a problem # because numbers seem to be represented fairly re...
def _get_number_productions(sentence: str) -> List[str]: """ Gathers all the numbers in the sentence, and returns productions that lead to them. """ # The mapping here is very simple and limited, which also shouldn't be a problem # because numbers seem to be represented fairly re...
[ "Gathers", "all", "the", "numbers", "in", "the", "sentence", "and", "returns", "productions", "that", "lead", "to", "them", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L202-L218
[ "def", "_get_number_productions", "(", "sentence", ":", "str", ")", "->", "List", "[", "str", "]", ":", "# The mapping here is very simple and limited, which also shouldn't be a problem", "# because numbers seem to be represented fairly regularly.", "number_strings", "=", "{", "\...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage.same_color
Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual name for what the method does, but just as ``blue`` filters objects to th...
allennlp/semparse/domain_languages/nlvr_language.py
def same_color(self, objects: Set[Object]) -> Set[Object]: """ Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual na...
def same_color(self, objects: Set[Object]) -> Set[Object]: """ Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual na...
[ "Filters", "the", "set", "of", "objects", "and", "returns", "those", "objects", "whose", "color", "is", "the", "most", "frequent", "color", "in", "the", "initial", "set", "of", "objects", "if", "the", "highest", "frequency", "is", "greater", "than", "1", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L275-L284
[ "def", "same_color", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "return", "self", ".", "_get_objects_with_same_attribute", "(", "objects", ",", "lambda", "x", ":", "x", ".", "color", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage.same_shape
Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual name for what the method does, but just as ``triangle`` filters objects t...
allennlp/semparse/domain_languages/nlvr_language.py
def same_shape(self, objects: Set[Object]) -> Set[Object]: """ Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual na...
def same_shape(self, objects: Set[Object]) -> Set[Object]: """ Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual na...
[ "Filters", "the", "set", "of", "objects", "and", "returns", "those", "objects", "whose", "color", "is", "the", "most", "frequent", "color", "in", "the", "initial", "set", "of", "objects", "if", "the", "highest", "frequency", "is", "greater", "than", "1", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L287-L296
[ "def", "same_shape", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "return", "self", ".", "_get_objects_with_same_attribute", "(", "objects", ",", "lambda", "x", ":", "x", ".", "shape", ")" ]
648a36f77db7e45784c047176074f98534c76636