INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Given a tag sequence encoded with IOB1 labels recode to BIOUL. | 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 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 predicting ill - fo... | 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... |
Just converts from an argparse. Namespace object to params. | 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... |
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 The TransitionFunction object that defines and scores transitions f... | 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... |
Check if a URL is reachable. | 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 file in this repository exists. | 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) |
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 recursively casts thi... | 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... |
Wraps os. environ to filter out non - encodable values. | 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)} |
Given a flattened dict with compound keys e. g. { a. b: 0 } unflatten it: { a: { b: 0 }} | 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... |
Deep merge two dicts preferring values from preferred. | 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):
... |
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. | 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 ... |
Any class in its from_params method can request that some of its input files be added to the archive by calling this method. | 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... |
Performs the functionality associated with dict. pop ( key ) along with checking for returned dictionaries replacing them with Param objects with an updated history. | 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 a pop and coerces to an int. | 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 a float. | 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 bool. | 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 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. | 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... |
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. | 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... |
Sometimes we need to just represent the parameters as a dict for instance when we pass them to PyTorch code. | 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 ... |
Returns the parameters of a flat dictionary from keys to values. Nested structure is collapsed with periods. | 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 + ... |
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 are any ). | 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`... |
Load a Params object from a configuration file. | 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 : ``... |
Returns Ordered Dict of Params from list of partial order preferences. | 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 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.
... |
Clears out the tracked metrics but keeps the patience and should_decrease settings. | 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 |
A Trainer can use this to serialize the state of the metric tracker. | 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_... |
Record a new value of the metric and update the various things that depend on it. | 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... |
Helper to add multiple metrics at once. | def add_metrics(self, metrics: Iterable[float]) -> None:
"""
Helper to add multiple metrics at once.
"""
for metric in metrics:
self.add_metric(metric) |
Returns true if improvement has stopped for long enough. | 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 |
Archive the model weights its training configuration and its vocabulary to model. tar. gz. Include the additional files_to_archive if provided. | 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... |
Instantiates an Archive from an archived tar. gz file. | 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... |
This method can be used to load a module from the pretrained model archive. | 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... |
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. | 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
... |
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.
... |
Returns whether action history in the state evaluates to the correct denotations over all worlds. Only defined when the 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(), "... |
Start learning rate finder for given args | 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,
... |
Runs learning rate search for given num_batches and saves the results in serialization_dir | 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 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 search. end_lr: float The learning rate u... | 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... |
Exponential smoothing of values | 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 |
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.
... |
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 won t show up in the... | 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 ... |
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. | 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... |
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. | 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... |
Executes a logical form using whatever predicates you have defined. | 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 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 efficient. | 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... |
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. | 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... |
Returns a sorted list of all production rules in the grammar induced by: func: get_nonterminal_productions. | 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... |
Converts a logical form into a linearization of the production rules from its abstract syntax tree. The linearization is top - down depth - first. | 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" ... |
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.
... |
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. | 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 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. | 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... |
Determines whether an input symbol is a valid non - terminal in the grammar. | 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 |
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 - argument function ) we eva... | 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: 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. | 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 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 ). | 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... |
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 because handling higher - order... | def _get_function_transitions(self,
expression: Union[str, List],
expected_type: PredicateType) -> Tuple[List[str],
PredicateType,
... |
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. | 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... |
Chooses num_samples samples without replacement from [ 0... num_words ). Returns a tuple ( samples num_tries ). | 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... |
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 mapping from individual t... | 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... |
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. | 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... |
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. | 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... |
Join multi - word predicates to a single predicate ( V ) token. | 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:... |
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. | 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... |
Return the word indices of a predicate in BIO tags. | 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] |
Get the predicate in this prediction. | 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)]) |
Tests whether the predicate in BIO tags1 overlap with those of tags2. | 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... |
Generate a coherent tag given previous tag and current label. | 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:
... |
Merge two predictions into one. Assumes the predicate in tags1 overlap with the predicate of tags2. | 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... |
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 ). | 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,... |
Sanitize a BIO label - this deals with OIE labels sometimes having some noise as parentheses. | 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... |
Converts a batch of tokenized sentences to a tensor representing the sentences with encoded characters ( len ( batch ) max sentence length max word length ). | 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 ... |
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_size timesteps ) which represent word ids which have been pre - ca... | 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... |
Compute context insensitive token embeddings for ELMo representations. | 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)... |
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_size timesteps ) which represent word ids which have been pre - ca... | 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... |
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 the fly via the CNN encoder. | 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,... |
Performs a normalization that is very similar to that done by the normalization functions in SQuAD and TriviaQA. | 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
... |
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 this case and ha... | 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 ... |
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. | 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... |
Converts a question a passage and an optional answer ( or answers ) to an Instance for use in a reading comprehension model. | 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. | def make_reading_comprehension_instance_quac(question_list_tokens: List[List[Token]],
passage_tokens: List[Token],
token_indexers: Dict[str, TokenIndexer],
passage_text: 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. | 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_... |
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. | 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... |
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. | 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... |
Return a new BeamSearch instance that s like this one but with the specified constraint. | 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... |
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: StateType The starting state of our search. This is assumed to be batche... | 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``
... |
Lower text and remove punctuation articles and extra whitespace. | 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... |
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 | 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 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 function you... | 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 an answer JSON blob from the DROP data release and converts it into strings used for evaluation. | 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 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 top - level ke... | 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 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 release. The predic... | 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 ... |
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 instead of re - processing the data ( usi... | 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... |
Returns an Iterable containing all the instances in the specified dataset. | 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... |
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 a model for inference/ ... | 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... |
Prints predicate argument predictions and gold labels for a single verbal predicate in a sentence to two provided file references. | 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]):
""... |
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. ( ARG - 1 * ... | 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... |
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. | 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... |
Gathers all the numbers in the sentence and returns productions that lead to them. | 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... |
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. | 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 or an empty set otherwise. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.