INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Based on the current utterance, return a dictionary where the keys are the strings in
the database that map to lists of the token indices that they are linked to. | def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]:
"""
Based on the current utterance, return a dictionary where the keys are the strings in
the database that map to lists of the token indices that they are linked to.
"""
string_linking_scores: Dict[str, List[i... |
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``
has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.
We look at all fields in all instances, and find the max values for each (field_name,
padding_key) pair, returning t... | def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``
has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.
We look at all fields in all instances, and ... |
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also
has the new entities that are extracted from the utterance. Stitching together the expressions
to form the grammar is a little tedious here, but it is worth it because we don't have to create
a new grammar from... | def _update_grammar(self):
"""
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also
has the new entities that are extracted from the utterance. Stitching together the expressions
to form the grammar is a little tedious here, but it is worth it because we ... |
This is a helper method for generating sequences, since we often want a list of expressions
with whitespaces between them. | def _get_sequence_with_spacing(self, # pylint: disable=no-self-use
new_grammar,
expressions: List[Expression],
name: str = '') -> Sequence:
"""
This is a helper method for generating sequences, since... |
When we add a new expression, there may be other expressions that refer to
it, and we need to update those to point to the new expression. | def _update_expression_reference(self, # pylint: disable=no-self-use
grammar: Grammar,
parent_expression_nonterminal: str,
child_expression_nonterminal: str) -> None:
"""
When we add a new expr... |
This is a helper method for adding different types of numbers (eg. starting time ranges) as entities.
We first go through all utterances in the interaction and find the numbers of a certain type and add
them to the set ``all_numbers``, which is initialized with default values. We want to add all numbers... | def add_to_number_linking_scores(self,
all_numbers: Set[str],
number_linking_scores: Dict[str, Tuple[str, str, List[int]]],
get_number_linking_dict: Callable[[str, List[Token]],
... |
This method gets entities from the current utterance finds which tokens they are linked to.
The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these
entities later for updating the valid actions and the grammar. | def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]:
"""
This method gets entities from the current utterance finds which tokens they are linked to.
The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these
entities later ... |
Return a sorted list of strings representing all possible actions
of the form: nonterminal -> [right_hand_side] | def all_possible_actions(self) -> List[str]:
"""
Return a sorted list of strings representing all possible actions
of the form: nonterminal -> [right_hand_side]
"""
all_actions = set()
for _, action_list in self.valid_actions.items():
for action in action_list... |
When we first get the entities and the linking scores in ``_get_linked_entities``
we represent as dictionaries for easier updates to the grammar and valid actions.
In this method, we flatten them for the model so that the entities are represented as
a list, and the linking scores are a 2D numpy ... | def _flatten_entities(self) -> Tuple[List[str], numpy.ndarray]:
"""
When we first get the entities and the linking scores in ``_get_linked_entities``
we represent as dictionaries for easier updates to the grammar and valid actions.
In this method, we flatten them for the model so that th... |
Creates a Flask app that serves up a simple configuration wizard. | def make_app(include_packages: Sequence[str] = ()) -> Flask:
"""
Creates a Flask app that serves up a simple configuration wizard.
"""
# Load modules
for package_name in include_packages:
import_submodules(package_name)
app = Flask(__name__) # pylint: disable=invalid-name
@app.err... |
Just converts from an ``argparse.Namespace`` object to string paths. | def train_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
train_model_from_file(args.param_path,
args.serialization_dir,
args.overrides,
args.file_friendl... |
A wrapper around :func:`train_model` which loads the params from a file.
Parameters
----------
parameter_filename : ``str``
A json parameter file specifying an AllenNLP experiment.
serialization_dir : ``str``
The directory in which to save results and logs. We just pass this along to
... | def train_model_from_file(parameter_filename: str,
serialization_dir: str,
overrides: str = "",
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
... |
Trains the model specified in the given :class:`Params` object, using the data and training
parameters also specified in that object, and saves the results in ``serialization_dir``.
Parameters
----------
params : ``Params``
A parameter object specifying an AllenNLP Experiment.
serialization... | def train_model(params: Params,
serialization_dir: str,
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
cache_directory: str = None,
cache_prefix: str = None) -> Model:
"""
Trains the... |
Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements to zero. | def _prf_divide(numerator, denominator):
"""Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements to zero.
"""
result = numerator / denominator
mask = denominator == 0.0
if not mask.any():
return result
# remove nan
result[mask] ... |
One sentence per line, formatted like
The###DET dog###NN ate###V the###DET apple###NN
Returns a list of pairs (tokenized_sentence, tags) | def load_data(file_path: str) -> Tuple[List[str], List[str]]:
"""
One sentence per line, formatted like
The###DET dog###NN ate###V the###DET apple###NN
Returns a list of pairs (tokenized_sentence, tags)
"""
data = []
with open(file_path) as f:
for line in f:
pairs ... |
max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token.
max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing).
But it could also be a string representing an int (in the case of environment variable
substitution). So we need some complex logic to handl... | def pop_max_vocab_size(params: Params) -> Union[int, Dict[str, int]]:
"""
max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token.
max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing).
But it could also be a string representing an int (in the case... |
Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary. | def save_to_files(self, directory: str) -> None:
"""
Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary.
... |
Loads a ``Vocabulary`` that was serialized using ``save_to_files``.
Parameters
----------
directory : ``str``
The directory containing the serialized vocabulary. | def from_files(cls, directory: str) -> 'Vocabulary':
"""
Loads a ``Vocabulary`` that was serialized using ``save_to_files``.
Parameters
----------
directory : ``str``
The directory containing the serialized vocabulary.
"""
logger.info("Loading token d... |
If you already have a vocabulary file for a trained model somewhere, and you really want to
use that vocabulary file instead of just setting the vocabulary from a dataset, for
whatever reason, you can do that with this method. You must specify the namespace to use,
and we assume that you want t... | def set_from_file(self,
filename: str,
is_padded: bool = True,
oov_token: str = DEFAULT_OOV_TOKEN,
namespace: str = "tokens"):
"""
If you already have a vocabulary file for a trained model somewhere, and you really w... |
Constructs a vocabulary given a collection of `Instances` and some parameters.
We count all of the vocabulary items in the instances, then pass those counts
and the other parameters, to :func:`__init__`. See that method for a description
of what the other parameters do. | def from_instances(cls,
instances: Iterable['adi.Instance'],
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
... |
There are two possible ways to build a vocabulary; from a
collection of instances, using :func:`Vocabulary.from_instances`, or
from a pre-saved vocabulary, using :func:`Vocabulary.from_files`.
You can also extend pre-saved vocabulary with collection of instances
using this method. This m... | def from_params(cls, params: Params, instances: Iterable['adi.Instance'] = None): # type: ignore
"""
There are two possible ways to build a vocabulary; from a
collection of instances, using :func:`Vocabulary.from_instances`, or
from a pre-saved vocabulary, using :func:`Vocabulary.from_f... |
This method can be used for extending already generated vocabulary.
It takes same parameters as Vocabulary initializer. The token2index
and indextotoken mappings of calling vocabulary will be retained.
It is an inplace operation so None will be returned. | def _extend(self,
counter: Dict[str, Dict[str, int]] = None,
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
pretrained_files: Option... |
Extends an already generated vocabulary using a collection of instances. | def extend_from_instances(self,
params: Params,
instances: Iterable['adi.Instance'] = ()) -> None:
"""
Extends an already generated vocabulary using a collection of instances.
"""
min_count = params.pop("min_count", None)
... |
Returns whether or not there are padding and OOV tokens added to the given namespace. | def is_padded(self, namespace: str) -> bool:
"""
Returns whether or not there are padding and OOV tokens added to the given namespace.
"""
return self._index_to_token[namespace][0] == self._padding_token |
Adds ``token`` to the index, if it is not already present. Either way, we return the index of
the token. | def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int:
"""
Adds ``token`` to the index, if it is not already present. Either way, we return the index of
the token.
"""
if not isinstance(token, str):
raise ValueError("Vocabulary tokens must be... |
Computes the regularization penalty for the model.
Returns 0 if the model was not configured to use regularization. | def get_regularization_penalty(self) -> Union[float, torch.Tensor]:
"""
Computes the regularization penalty for the model.
Returns 0 if the model was not configured to use regularization.
"""
if self._regularizer is None:
return 0.0
else:
return se... |
Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it,
converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays
through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing)
and returns the result. Bef... | def forward_on_instance(self, instance: Instance) -> Dict[str, numpy.ndarray]:
"""
Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it,
converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays
through :func:`self.forwar... |
Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into
arrays using this model's :class:`Vocabulary`, passes those arrays through
:func:`self.forward()` and :func:`self.decode()` (which by default does nothing)
and returns the result. Before returning the result, w... | def forward_on_instances(self,
instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]:
"""
Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into
arrays using this model's :class:`Vocabulary`, passes those arrays through
:f... |
Takes the result of :func:`forward` and runs inference / decoding / whatever
post-processing you need to do your model. The intent is that ``model.forward()`` should
produce potentials or probabilities, and then ``model.decode()`` can take those results and
run some kind of beam search or const... | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
Takes the result of :func:`forward` and runs inference / decoding / whatever
post-processing you need to do your model. The intent is that ``model.forward()`` should
produce potentials or probabilitie... |
This method checks the device of the model parameters to determine the cuda_device
this model should be run on for predictions. If there are no parameters, it returns -1.
Returns
-------
The cuda device this model should run on for predictions. | def _get_prediction_device(self) -> int:
"""
This method checks the device of the model parameters to determine the cuda_device
this model should be run on for predictions. If there are no parameters, it returns -1.
Returns
-------
The cuda device this model should run ... |
This method warns once if a user implements a model which returns a dictionary with
values which we are unable to split back up into elements of the batch. This is controlled
by a class attribute ``_warn_for_unseperable_batches`` because it would be extremely verbose
otherwise. | def _maybe_warn_for_unseparable_batches(self, output_key: str):
"""
This method warns once if a user implements a model which returns a dictionary with
values which we are unable to split back up into elements of the batch. This is controlled
by a class attribute ``_warn_for_unseperable_... |
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides. | def _load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
"""
... |
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters
----------
config: Params
The configuration that was used to train the model. It should definitely
have a `model` section, and should probably hav... | def load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters... |
Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with original vocabulary but during
fine-tuning/tranfer-learning, it will have it work with extended vocabu... | def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None:
"""
Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with... |
Takes a logical form, and the list of target values as strings from the original lisp
string, and returns True iff the logical form executes to the target list, using the
official WikiTableQuestions evaluation script. | def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool:
"""
Takes a logical form, and the list of target values as strings from the original lisp
string, and returns True iff the logical form executes to the target list, using the
official WikiTableQuestions e... |
Returns an agenda that can be used guide search.
Parameters
----------
conservative : ``bool``
Setting this flag will return a subset of the agenda items that correspond to high
confidence lexical matches. You'll need this if you are going to use this agenda to
... | def get_agenda(self,
conservative: bool = False):
"""
Returns an agenda that can be used guide search.
Parameters
----------
conservative : ``bool``
Setting this flag will return a subset of the agenda items that correspond to high
conf... |
Select function takes a list of rows and a column name and returns a list of strings as
in cells. | def select_string(self, rows: List[Row], column: StringColumn) -> List[str]:
"""
Select function takes a list of rows and a column name and returns a list of strings as
in cells.
"""
return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None] |
Select function takes a row (as a list) and a column name and returns the number in that
column. If multiple rows are given, will return the first number that is not None. | def select_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Select function takes a row (as a list) and a column name and returns the number in that
column. If multiple rows are given, will return the first number that is not None.
"""
numbers: List[float] = []
... |
Select function takes a row as a list and a column name and returns the date in that column. | def select_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Select function takes a row as a list and a column name and returns the date in that column.
"""
dates: List[Date] = []
for row in rows:
cell_value = row.values[column.name]
if isinsta... |
Takes a row and a column and returns a list of rows from the full set of rows that contain
the same value under the given column as the given row. | def same_as(self, rows: List[Row], column: Column) -> List[Row]:
"""
Takes a row and a column and returns a list of rows from the full set of rows that contain
the same value under the given column as the given row.
"""
cell_value = rows[0].values[column.name]
return_list... |
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three
numbers in that order. | def date(self, year: Number, month: Number, day: Number) -> Date:
"""
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three
numbers in that order.
"""
return Date(year, month, day) |
Takes an expression that evaluates to a list of rows, and returns the first one in that
list. | def first(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the first one in that
list.
"""
if not rows:
logger.warning("Trying to get first row from an empty list")
return []
return [rows[0]... |
Takes an expression that evaluates to a list of rows, and returns the last one in that
list. | def last(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the last one in that
list.
"""
if not rows:
logger.warning("Trying to get last row from an empty list")
return []
return [rows[-1]] |
Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list. | def previous(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list.
"""
if not... |
Takes an expression that evaluates to a single row, and returns the row that occurs after
the input row in the original set of rows. If the input row happens to be the last row, we
will return an empty list. | def next(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs after
the input row in the original set of rows. If the input row happens to be the last row, we
will return an empty list.
"""
if not row... |
Takes a list of rows and a column and returns the most frequent values (one or more) under
that column in those rows. | def mode_string(self, rows: List[Row], column: StringColumn) -> List[str]:
"""
Takes a list of rows and a column and returns the most frequent values (one or more) under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if no... |
Takes a list of rows and a column and returns the most frequent value under
that column in those rows. | def mode_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_li... |
Takes a list of rows and a column and returns the most frequent value under
that column in those rows. | def mode_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_list:
... |
Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``. | def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict... |
Takes a list of rows and a column and returns a list containing a single row (dict from
columns to cells) that has the minimum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``. | def argmin(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column and returns a list containing a single row (dict from
columns to cells) that has the minimum numerical value in the given column. We return a list
instead of a single dict to b... |
Takes a list of rows and a column and returns the max of the values under that column in
those rows. | def max_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Takes a list of rows and a column and returns the max of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return Dat... |
Takes a list of rows and a column and returns the max of the values under that column in
those rows. | def max_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the max of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
retu... |
Takes a list of rows and a column and returns the mean of the values under that column in
those rows. | def average(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the mean of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return... |
Takes a two rows and a number column and returns the difference between the values under
that column in those two rows. | def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number:
"""
Takes a two rows and a number column and returns the difference between the values under
that column in those two rows.
"""
if not first_row or not second_row:
return 0.0 ... |
Takes a row and returns its index in the full list of rows. If the row does not occur in the
table (which should never happen because this function will only be called with a row that
is the result of applying one or more functions on the table rows), the method returns -1. | def _get_row_index(self, row: Row) -> int:
"""
Takes a row and returns its index in the full list of rows. If the row does not occur in the
table (which should never happen because this function will only be called with a row that
is the result of applying one or more functions on the ta... |
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol. | def is_terminal(self, symbol: str) -> bool:
"""
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
"""
... |
For a given action, returns at most ``max_num_paths`` paths to the root (production with
``START_SYMBOL``) that are not longer than ``max_path_length``. | def get_paths_to_root(self,
action: str,
max_path_length: int = 20,
beam_size: int = 30,
max_num_paths: int = 10) -> List[List[str]]:
"""
For a given action, returns at most ``max_num_paths`` paths to... |
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches. | def get_multi_match_mapping(self) -> Dict[Type, List[Type]]:
"""
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches.
"""
if self._multi_match_mapping is None:
self._multi_match_mapping = {}
basic_types = sel... |
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
logical_form : ``str``
Logical form to parse
remove_var_function : ``bool`` (optional)
``var`` is a special function that some languages use... | def parse_logical_form(self,
logical_form: str,
remove_var_function: bool = True) -> Expression:
"""
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
l... |
Returns the sequence of actions (as strings) that resulted in the given expression. | def get_action_sequence(self, expression: Expression) -> List[str]:
"""
Returns the sequence of actions (as strings) that resulted in the given expression.
"""
# Starting with the type of the whole expression
return self._get_transitions(expression,
... |
Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions generated by a transition based
semantic parser.
Parameters
----------
action_sequence : ``List[str]``
The sequence of ... | def get_logical_form(self,
action_sequence: List[str],
add_var_function: bool = True) -> str:
"""
Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions ... |
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... | def _construct_node_from_actions(self,
current_node: Tree,
remaining_actions: List[List[str]],
add_var_function: bool) -> List[List[str]]:
"""
Given a current node in the logical form tree, and... |
Takes a type signature and infers the number of arguments the corresponding function takes.
Examples:
e -> 0
<r,e> -> 1
<e,<e,t>> -> 2
<b,<<b,#1>,<#1,b>>> -> 3 | def _infer_num_arguments(cls, type_signature: str) -> int:
"""
Takes a type signature and infers the number of arguments the corresponding function takes.
Examples:
e -> 0
<r,e> -> 1
<e,<e,t>> -> 2
<b,<<b,#1>,<#1,b>>> -> 3
"""
if no... |
``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand. | def _process_nested_expression(self, nested_expression) -> str:
"""
``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand.
"""
expression_is_li... |
Utility method to add a name and its translation to the local name mapping, and the corresponding
signature, if available to the local type signatures. This method also updates the reverse name
mapping. | def _add_name_mapping(self, name: str, translated_name: str, name_type: Type = None):
"""
Utility method to add a name and its translation to the local name mapping, and the corresponding
signature, if available to the local type signatures. This method also updates the reverse name
mapp... |
Parameters
----------
inputs : PackedSequence, required.
A tensor of shape (batch_size, num_timesteps, input_size)
to apply the LSTM over.
initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)
A tuple (state, memory) representing the i... | def forward(self, # pylint: disable=arguments-differ
inputs: PackedSequence,
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
"""
Parameters
----------
inputs : PackedSequence, required.
A tensor of shape (batch_size, num_ti... |
Creates a server running SEMPRE that we can send logical forms to for evaluation. This
uses inter-process communication, because SEMPRE is java code. We also need to be careful
to clean up the process when our program exits. | def _create_sempre_executor(self) -> None:
"""
Creates a server running SEMPRE that we can send logical forms to for evaluation. This
uses inter-process communication, because SEMPRE is java code. We also need to be careful
to clean up the process when our program exits.
"""
... |
Averaged per-mention precision and recall.
<https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf> | def b_cubed(clusters, mention_to_gold):
"""
Averaged per-mention precision and recall.
<https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf>
"""
numerator, denominator = 0, 0
for cluster in clusters:
if len(cluster) == 1:
... |
Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf> | def muc(clusters, mention_to_gold):
"""
Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf>
"""
true_p, all_p = 0, ... |
Subroutine for ceafe. Computes the mention F measure between gold and
predicted mentions in a cluster. | def phi4(gold_clustering, predicted_clustering):
"""
Subroutine for ceafe. Computes the mention F measure between gold and
predicted mentions in a cluster.
"""
return 2 * len([mention for mention in gold_clustering if mention in predicted_clustering]) \
/ float(len... |
Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters.
<https://www.semanticscholar.org/paper/On-Coreference-Resolu... | def ceafe(clusters, gold_clusters):
"""
Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters.
<htt... |
Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack. Updating the non-terminal stack involves popping
the non-terminal that was ... | def take_action(self, production_rule: str) -> 'GrammarStatelet':
"""
Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack... |
Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
----------
parameters : ``(Iterable[torch.Tensor])``
An iterable... | def sparse_clip_norm(parameters, max_norm, norm_type=2) -> float:
"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
---... |
Move the optimizer state to GPU, if necessary.
After calling, any parameter specific state in the optimizer
will be located on the same device as the parameter. | def move_optimizer_to_cuda(optimizer):
"""
Move the optimizer state to GPU, if necessary.
After calling, any parameter specific state in the optimizer
will be located on the same device as the parameter.
"""
for param_group in optimizer.param_groups:
for param in param_group['params']:
... |
Returns the size of the batch dimension. Assumes a well-formed batch,
returns 0 otherwise. | def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int:
"""
Returns the size of the batch dimension. Assumes a well-formed batch,
returns 0 otherwise.
"""
if isinstance(batch, torch.Tensor):
return batch.size(0) # type: ignore
elif isinstance(batch, Dict):
return get_batch_s... |
Convert seconds past Epoch to human readable string. | def time_to_str(timestamp: int) -> str:
"""
Convert seconds past Epoch to human readable string.
"""
datetimestamp = datetime.datetime.fromtimestamp(timestamp)
return '{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'.format(
datetimestamp.year, datetimestamp.month, datetimestamp.day,
... |
Convert human readable string to datetime.datetime. | def str_to_time(time_str: str) -> datetime.datetime:
"""
Convert human readable string to datetime.datetime.
"""
pieces: Any = [int(piece) for piece in time_str.split('-')]
return datetime.datetime(*pieces) |
Load all the datasets specified by the config.
Parameters
----------
params : ``Params``
cache_directory : ``str``, optional
If given, we will instruct the ``DatasetReaders`` that we construct to cache their
instances in this location (or read their instances from caches in this locatio... | def datasets_from_params(params: Params,
cache_directory: str = None,
cache_prefix: str = None) -> Dict[str, Iterable[Instance]]:
"""
Load all the datasets specified by the config.
Parameters
----------
params : ``Params``
cache_directory : ``st... |
This function creates the serialization directory if it doesn't exist. If it already exists
and is non-empty, then it verifies that we're recovering from a training with an identical configuration.
Parameters
----------
params: ``Params``
A parameter object specifying an AllenNLP Experiment.
... | def create_serialization_dir(
params: Params,
serialization_dir: str,
recover: bool,
force: bool) -> None:
"""
This function creates the serialization directory if it doesn't exist. If it already exists
and is non-empty, then it verifies that we're recovering from a training... |
Performs a forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface. | def data_parallel(batch_group: List[TensorDict],
model: Model,
cuda_devices: List) -> Dict[str, torch.Tensor]:
"""
Performs a forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface.
""... |
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled. | def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]:
"""
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.
"""
if grad_norm:
parameters_to_clip = [p for p in model.parameters()
if p.grad is not None]
... |
Gets the metrics but sets ``"loss"`` to
the total loss divided by the ``num_batches`` so that
the ``"loss"`` metric is "average loss per batch". | def get_metrics(model: Model, total_loss: float, num_batches: int, reset: bool = False) -> Dict[str, float]:
"""
Gets the metrics but sets ``"loss"`` to
the total loss divided by the ``num_batches`` so that
the ``"loss"`` metric is "average loss per batch".
"""
metrics = model.get_metrics(reset=... |
Parse all dependencies out of the requirements.txt file. | def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]:
"""Parse all dependencies out of the requirements.txt file."""
essential_packages: PackagesType = {}
other_packages: PackagesType = {}
duplicates: Set[str] = set()
with open("requirements.txt", "r") as req_file:
section... |
Parse all dependencies out of the setup.py script. | def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]:
"""Parse all dependencies out of the setup.py script."""
essential_packages: PackagesType = {}
test_packages: PackagesType = {}
essential_duplicates: Set[str] = set()
test_duplicates: Set[str] = set()
with open('setup.p... |
Given a sentence, return all token spans within the sentence. Spans are `inclusive`.
Additionally, you can provide a maximum and minimum span width, which will be used
to exclude spans outside of this range.
Finally, you can provide a function mapping ``List[T] -> bool``, which will
be applied to every... | def enumerate_spans(sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]:
"""
Given a sentence, return all token spans w... |
Given a sequence corresponding to BIO tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"),
as otherwise it is possible to get a perfect precision score whilst still predicting... | def bio_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIO tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also in... |
Given a sequence corresponding to IOB1 tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also included (i.e., those where "B-LABEL" is not preceded
by "I-LABEL" or "B-LABEL").
Parameters
----------
tag_sequence : List[str]... | def iob1_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to IOB1 tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also... |
Given a sequence corresponding to BIOUL tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are not allowed and will raise ``InvalidTagSequence``.
This function works properly when the spans are unlabeled (i.e., your labels are
simply "B... | def bioul_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIOUL tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are n... |
Given a 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... | 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 predictin... | 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``
... | 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 r... | 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.
This method adds a ``history`` parameter, in the off-chance... | 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.
For example, if some class ``A`` had an ``input_file`` parameter, it could call
```
params.add_file_to_archive("input_file")
```
which would... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.