code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def most_similar_cosmul(self, positive, negative=[], topn=10,
min_similarity=None, return_similarities=True):
"""Finds the topn most similar vectors under or equal to max
distance using 3CosMul:
[Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618)
"""... | Finds the topn most similar vectors under or equal to max
distance using 3CosMul:
[Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618)
| most_similar_cosmul | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def most_similar_approx(
self,
positive,
negative=[],
topn=10,
min_similarity=None,
return_similarities=True,
effort=1.0):
"""Approximates the topn most similar vectors under or equal to max
distance using Annoy:
... | Approximates the topn most similar vectors under or equal to max
distance using Annoy:
https://github.com/spotify/annoy
| most_similar_approx | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def closer_than(self, key, q, topn=None):
"""Finds all keys closer to key than q is to key."""
epsilon = (10.0 / 10**6)
min_similarity = self.similarity(key, q) + epsilon
return self.most_similar(key, topn=topn, min_similarity=min_similarity,
return_simi... | Finds all keys closer to key than q is to key. | closer_than | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def get_vectors_mmap(self, log=True):
"""Gets a numpy.memmap of all vectors, blocks if it is still
being built.
"""
if self._all_vectors is None:
logged = False
while True:
if not self.setup_for_mmap:
self._setup_for_mmap()
... | Gets a numpy.memmap of all vectors, blocks if it is still
being built.
| get_vectors_mmap | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def get_approx_index_chunks(self):
"""Gets decompressed chunks of the AnnoyIndex of the vectors from
the database."""
try:
db = self._db(force_new=True, downloader=True)
num_chunks = db.execute(
"""
SELECT COUNT(rowid)
... | Gets decompressed chunks of the AnnoyIndex of the vectors from
the database. | get_approx_index_chunks | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def get_meta_chunks(self, meta_index):
"""Gets decompressed chunks of a meta file embedded in
the database."""
try:
db = self._db(force_new=True, downloader=True)
num_chunks = db.execute(
"""
SELECT COUNT(rowid)
FROM... | Gets decompressed chunks of a meta file embedded in
the database. | get_meta_chunks | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def get_approx_index(self, log=True):
"""Gets an AnnoyIndex of the vectors from the database."""
chunks = self.get_approx_index_chunks()
if self._approx_index is None:
logged = False
while True:
if not self.setup_for_mmap:
self._setup_f... | Gets an AnnoyIndex of the vectors from the database. | get_approx_index | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def get_elmo_embedder(self, log=True):
"""Gets an ElmoEmbedder of the vectors from the database."""
meta_1_chunks = self.get_meta_chunks(1)
meta_2_chunks = self.get_meta_chunks(2)
if self._elmo_embedder is None:
logged = False
while True:
if not se... | Gets an ElmoEmbedder of the vectors from the database. | get_elmo_embedder | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def _iter(self, put_cache, downloader=False):
"""Yields keys and vectors for all vectors in the store."""
try:
db = self._db(force_new=True, downloader=downloader)
results = db.execute(
"""
SELECT *
FROM `magnitude`
... | Yields keys and vectors for all vectors in the store. | _iter | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def __getitem__(self, q):
"""Performs the index method when indexed."""
if isinstance(q, slice):
return self.index(list(range(*q.indices(self.length))),
return_vector=True)
else:
return self.index(q, return_vector=True) | Performs the index method when indexed. | __getitem__ | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def _take(self, q, multikey, i):
"""Selects only the i'th element from the inner-most axis and
reduces the dimensions of the tensor q by 1.
"""
if multikey == -1:
return q
else:
cut = np.take(q, [i], axis=multikey)
result = np.reshape(cut, np.s... | Selects only the i'th element from the inner-most axis and
reduces the dimensions of the tensor q by 1.
| _take | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def _hstack(self, ls, use_numpy):
"""Horizontally stacks NumPy arrays or Python lists"""
if use_numpy:
return np.concatenate(ls, axis=-1)
else:
return list(chain.from_iterable(ls)) | Horizontally stacks NumPy arrays or Python lists | _hstack | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def _dstack(self, ls, use_numpy):
"""Depth stacks NumPy arrays or Python lists"""
if use_numpy:
return np.concatenate(ls, axis=-1)
else:
return [self._hstack((l3[example] for l3 in ls),
use_numpy=use_numpy) for example in xrange(len(ls[0])... | Depth stacks NumPy arrays or Python lists | _dstack | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def download_model(
model,
download_dir=os.path.expanduser('~/.magnitude/'),
remote_path='http://magnitude.plasticity.ai/',
log=False,
_download=True,
_local=False):
""" Downloads a remote Magnitude model locally (if it doesn't already
... | Downloads a remote Magnitude model locally (if it doesn't already
exist) and synchronously returns the local file path once it has
been completed | download_model | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def batchify(X, y, batch_size): # noqa: N803
""" Creates an iterator that chunks `X` and `y` into batches
that each contain `batch_size` elements and loops forever"""
X_batch_generator = cycle([X[i: i + batch_size] # noqa: N806
for i in xrange(0, len(X), batc... | Creates an iterator that chunks `X` and `y` into batches
that each contain `batch_size` elements and loops forever | batchify | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def class_encoding():
"""Creates a set of functions to add a new class, convert a
class into an integer, and the integer back to a class."""
class_to_int_map = {}
int_to_class_map = None
def add_class(c):
global int_to_class_map
int_to_class_map = None
... | Creates a set of functions to add a new class, convert a
class into an integer, and the integer back to a class. | class_encoding | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def to_categorical(y, num_classes=None):
"""Converts a class vector (integers) to binary class matrix.
"""
y = np.array(y, dtype='int')
input_shape = y.shape
if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
input_shape = tuple(input_shape[:-1])
... | Converts a class vector (integers) to binary class matrix.
| to_categorical | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def get_cache(self, amount, offset):
"""Checks if a cache exists for the data offset, and amount to read,
if so, return the cache, and the start and end range to read
from the cache's data.
Keeps track of forward sequential reads, and backward
seq... | Checks if a cache exists for the data offset, and amount to read,
if so, return the cache, and the start and end range to read
from the cache's data.
Keeps track of forward sequential reads, and backward
sequential reads for the cache.
| get_cache | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def write_data(self, start_offset, data, amount, offset):
"""Writes data fetched to the network cache and
returns only the amount requested back."""
# Writes the entire data fetched to the cache
if self.vfsfile.should_cache:
# Uses itself as a cache object... | Writes data fetched to the network cache and
returns only the amount requested back. | write_data | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def _prefetch_in_background(
self,
_prefetch_in_background,
amount,
offset,
sequential):
"""Prefetches data from the network to the cache."""
# Store the extra data fetched back in the network cache
if se... | Prefetches data from the network to the cache. | _prefetch_in_background | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def prefetch_in_background(
self,
_prefetch_in_background,
amount,
offset,
sequential=False):
"""Prefetches data from the network to the cache
in the background."""
if self.vfsfile.trace_log:
... | Prefetches data from the network to the cache
in the background. | prefetch_in_background | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def read_data(self, amount, offset, _prefetch_in_background=None):
"""Reads data from the network cache and
returns only the amount requested back or
Returns None if there is a cache miss, and prefetches more data
into the cache using _prefetch_in_background(amount, offse... | Reads data from the network cache and
returns only the amount requested back or
Returns None if there is a cache miss, and prefetches more data
into the cache using _prefetch_in_background(amount, offset)
if it detects a non-sequential access pattern in the
ca... | read_data | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def length_of_data(self):
"""Returns the length of the cached data."""
try:
return os.path.getsize(os.path.join(self.cache_dir_path,
self.cache_key))
except BaseException:
return 0 | Returns the length of the cached data. | length_of_data | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def add_to_mmaps(self, new, mm):
"""Adds a new mmap, evicting old mmaps if the maximum has been
reached."""
while (len(self.vfsfile.cache_mmaps_heap) >=
self.vfsfile.mmap_max_files):
_, evict = heapq.heappop(self.vfsfile.cache_mmaps_heap)
... | Adds a new mmap, evicting old mmaps if the maximum has been
reached. | add_to_mmaps | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def get_mmap(self, create=True):
"""Gets the mmap for a key, opening a mmap to the file
if a mmap doesn't exist, creating a file, then opening a mmap
to it if the file doesn't exist."""
if (self.cache_key not in self.vfsfile.cache_mmaps and create):
joined... | Gets the mmap for a key, opening a mmap to the file
if a mmap doesn't exist, creating a file, then opening a mmap
to it if the file doesn't exist. | get_mmap | python | plasticityai/magnitude | pymagnitude/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/__init__.py | MIT |
def dry_run_from_args(args ):
u"""
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_f... |
Just converts from an ``argparse.Namespace`` object to params.
| dry_run_from_args | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/dry_run.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/dry_run.py | MIT |
def __init__(self,
options_file = DEFAULT_OPTIONS_FILE,
weight_file = DEFAULT_WEIGHT_FILE,
cuda_device = -1) :
u"""
Parameters
----------
options_file : ``str``, optional
A path or URL to an ELMo options... |
Parameters
----------
options_file : ``str``, optional
A path or URL to an ELMo options file.
weight_file : ``str``, optional
A path or URL to an ELMo weights file.
cuda_device : ``int``, optional, (default=-1)
The GPU device to run on.
... | __init__ | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/elmo.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py | MIT |
def batch_to_embeddings(self, batch ) :
u"""
Parameters
----------
batch : ``List[List[str]]``, required
A list of tokenized sentences.
Returns
-------
A tuple of tensors, the first representing ... |
Parameters
----------
batch : ``List[List[str]]``, required
A list of tokenized sentences.
Returns
-------
A tuple of tensors, the first representing activations (batch_size, 3, num_timesteps, 1024) and
the second a mask (batch_size, num_timestep... | batch_to_embeddings | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/elmo.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py | MIT |
def embed_batch(self, batch ) :
u"""
Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
P... |
Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
batch : ``List[List[str]]``, required
... | embed_batch | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/elmo.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py | MIT |
def embed_sentences(self,
sentences ,
batch_size = DEFAULT_BATCH_SIZE) :
u"""
Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give diffe... |
Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
sentences : ``Iterable[List[str]]``, required
... | embed_sentences | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/elmo.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py | MIT |
def embed_file(self,
input_file ,
output_file_path ,
output_format = u"all",
batch_size = DEFAULT_BATCH_SIZE,
forget_sentences = False,
use_sentence_keys = False) :
... |
Computes ELMo embeddings from an input_file where each line contains a sentence tokenized by whitespace.
The ELMo embeddings are written out in HDF5 format, where each sentence embedding
is saved in a dataset with the line number in the original file as the key.
Parameters
----... | embed_file | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/elmo.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/elmo.py | MIT |
def fine_tune_model_from_args(args ):
u"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
fine_tune_model_from_file_paths(model_archive_path=args.model_archive,
config_file=args.config_file,
... |
Just converts from an ``argparse.Namespace`` object to string paths.
| fine_tune_model_from_args | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/fine_tune.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/fine_tune.py | MIT |
def fine_tune_model_from_file_paths(model_archive_path ,
config_file ,
serialization_dir ,
overrides = u"",
extend_vocab = False,
... |
A wrapper around :func:`fine_tune_model` which loads the model archive from a file.
Parameters
----------
model_archive_path : ``str``
Path to a saved model archive that is the result of running the ``train`` command.
config_file : ``str``
A configuration file specifying how to con... | fine_tune_model_from_file_paths | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/fine_tune.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/fine_tune.py | MIT |
def fine_tune_model(model ,
params ,
serialization_dir ,
extend_vocab = False,
file_friendly_logging = False) :
u"""
Fine tunes the given model, using a set of parameters that is largely identica... |
Fine tunes the given model, using a set of parameters that is largely identical to those used
for :func:`~allennlp.commands.train.train_model`, except that the ``model`` section is ignored,
if it is present (as we are already given a ``Model`` here).
The main difference between the logic done here and... | fine_tune_model | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/fine_tune.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/fine_tune.py | MIT |
def train_model_from_file(parameter_filename ,
serialization_dir ,
overrides = u"",
file_friendly_logging = False,
recover = False) :
u"""
A wrapper around :func:`train_model`... |
A wrapper around :func:`train_model` which loads the params from a file.
Parameters
----------
param_path : ``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
... | train_model_from_file | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/train.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py | MIT |
def datasets_from_params(params ) :
u"""
Load all the datasets specified by the config.
"""
dataset_reader = DatasetReader.from_params(params.pop(u'dataset_reader'))
validation_dataset_reader_params = params.pop(u"validation_dataset_reader", None)
validati... |
Load all the datasets specified by the config.
| datasets_from_params | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/train.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py | MIT |
def create_serialization_dir(params , serialization_dir , recover ) :
u"""
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.
Parame... |
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 Experime... | create_serialization_dir | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/train.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py | MIT |
def train_model(params ,
serialization_dir ,
file_friendly_logging = False,
recover = False) :
u"""
Trains the model specified in the given :class:`Params` object, using the data and training
parameters also specified in that obj... |
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.
serializ... | train_model | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/train.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/train.py | MIT |
def main(prog = None,
subcommand_overrides = {}) :
u"""
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp``
codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't
work for them, unl... |
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp``
codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't
work for them, unless you use the ``--include-package`` flag.
| main | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/commands/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/commands/__init__.py | MIT |
def full_name(cla55 ) :
u"""
Return the full name (including module) of the given class.
"""
# Special case to handle None:
if cla55 is None:
return u"?"
if issubclass(cla55, Initializer) and cla55 != Initializer:
init_fn = cla55()._init_function
ret... |
Return the full name (including module) of the given class.
| full_name | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/configuration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py | MIT |
def _get_config_type(cla55 ) :
u"""
Find the name (if any) that a subclass was registered under.
We do this simply by iterating through the registry until we
find it.
"""
# Special handling for pytorch RNN types:
if cla55 == torch.nn.RNN:
return u"rnn"
elif c... |
Find the name (if any) that a subclass was registered under.
We do this simply by iterating through the registry until we
find it.
| _get_config_type | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/configuration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py | MIT |
def _docspec_comments(obj) :
u"""
Inspect the docstring and get the comments for each parameter.
"""
# Sometimes our docstring is on the class, and sometimes it's on the initializer,
# so we've got to check both.
class_docstring = getattr(obj, u'__doc__', None)
init_docstrin... |
Inspect the docstring and get the comments for each parameter.
| _docspec_comments | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/configuration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py | MIT |
def _auto_config(cla55 ) :
u"""
Create the ``Config`` for a class by reflecting on its ``__init__``
method and applying a few hacks.
"""
typ3 = _get_config_type(cla55)
# Don't include self, or vocab
names_to_ignore = set([u"self", u"vocab"])
# Hack for RNNs
if c... |
Create the ``Config`` for a class by reflecting on its ``__init__``
method and applying a few hacks.
| _auto_config | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/configuration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py | MIT |
def render_config(config , indent = u"") :
u"""
Pretty-print a config in sort-of-JSON+comments.
"""
# Add four spaces to the indent.
new_indent = indent + u" "
return u"".join([
# opening brace + newline
u"{\n",
# "type": "...", (if prese... |
Pretty-print a config in sort-of-JSON+comments.
| render_config | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/configuration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py | MIT |
def _render(item , indent = u"") :
u"""
Render a single config item, with the provided indent
"""
optional = item.default_value != _NO_DEFAULT
if is_configurable(item.annotation):
rendered_annotation = "{item.annotation} (configurable)"
else:
rendered_annot... |
Render a single config item, with the provided indent
| _render | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/configuration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py | MIT |
def _valid_choices(cla55 ) :
u"""
Return a mapping {registered_name -> subclass_name}
for the registered subclasses of `cla55`.
"""
choices = {}
if cla55 not in Registrable._registry:
raise ValueError("{cla55} is not a known Registrable class")
... |
Return a mapping {registered_name -> subclass_name}
for the registered subclasses of `cla55`.
| _valid_choices | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/configuration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/configuration.py | MIT |
def takes_arg(obj, arg ) :
u"""
Checks whether the provided obj takes a certain arg.
If it's a class, we're really checking whether its constructor does.
If it's a function or method, we're checking the object itself.
Otherwise, we raise an error.
"""
if inspect.isclass(obj):
... |
Checks whether the provided obj takes a certain arg.
If it's a class, we're really checking whether its constructor does.
If it's a function or method, we're checking the object itself.
Otherwise, we raise an error.
| takes_arg | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/from_params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/from_params.py | MIT |
def remove_optional(annotation ):
u"""
Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optional" part is not interesting, so here we
throw it away.
"""
origin = getattr(annotation, u'__origin__', None)
args = getattr(annotation, u'__args__'... |
Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optional" part is not interesting, so here we
throw it away.
| remove_optional | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/from_params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/from_params.py | MIT |
def create_kwargs(cls , params , **extras) :
u"""
Given some class, a `Params` object, and potentially other keyword arguments,
create a dict of keyword args suitable for passing to the class's constructor.
The function does this by finding the class's constructor, match... |
Given some class, a `Params` object, and potentially other keyword arguments,
create a dict of keyword args suitable for passing to the class's constructor.
The function does this by finding the class's constructor, matching the constructor
arguments to entries in the `params` object, and instantiatin... | create_kwargs | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/from_params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/from_params.py | MIT |
def from_params(cls , params , **extras) :
u"""
This is the automatic implementation of `from_params`. Any class that subclasses `FromParams`
(or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free.
If you want your class to be instan... |
This is the automatic implementation of `from_params`. Any class that subclasses `FromParams`
(or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free.
If you want your class to be instantiated from params in the "obvious" way -- pop off parameters
and ... | from_params | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/from_params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/from_params.py | MIT |
def unflatten(flat_dict ) :
u"""
Given a "flattened" dict with compound keys, e.g.
{"a.b": 0}
unflatten it:
{"a": {"b": 0}}
"""
unflat = {}
for compound_key, value in list(flat_dict.items()):
curr_dict = unflat
part... |
Given a "flattened" dict with compound keys, e.g.
{"a.b": 0}
unflatten it:
{"a": {"b": 0}}
| unflatten | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def with_fallback(preferred , fallback ) :
u"""
Deep merge two dicts, preferring values from `preferred`.
"""
preferred_keys = set(preferred.keys())
fallback_keys = set(fallback.keys())
common_keys = preferred_keys & fallback_keys
merged ... |
Deep merge two dicts, preferring values from `preferred`.
| with_fallback | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def add_file_to_archive(self, name ) :
u"""
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
```
pa... |
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")
```
wh... | add_file_to_archive | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def pop(self, key , default = DEFAULT) :
u"""
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 wa... |
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 t... | pop | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def pop_int(self, key , default = DEFAULT) :
u"""
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.
| pop_int | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def pop_float(self, key , default = DEFAULT) :
u"""
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.
| pop_float | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def pop_bool(self, key , default = DEFAULT) :
u"""
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 == u"true":
... |
Performs a pop and coerces to a bool.
| pop_bool | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def get(self, key , default = DEFAULT):
u"""
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:
v... |
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.
| get | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def pop_choice(self, key , choices , default_to_first_choice = False) :
u"""
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,
consist... |
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: st... | pop_choice | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def as_dict(self, quiet=False):
u"""
Sometimes we need to just represent the parameters as a dict, for instance when we pass
them to a Keras layer(so that they can be serialised).
Parameters
----------
quiet: bool, optional (default = False)
Whether to log th... |
Sometimes we need to just represent the parameters as a dict, for instance when we pass
them to a Keras layer(so that they can be serialised).
Parameters
----------
quiet: bool, optional (default = False)
Whether to log the parameters before returning them as a dict... | as_dict | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def as_flat_dict(self):
u"""
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 list(parameters.items()):
newpath = ... |
Returns the parameters of a flat dictionary from keys to values.
Nested structure is collapsed with periods.
| as_flat_dict | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def assert_empty(self, class_name ):
u"""
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 there
was one. ``class_name`` should be the name of the `calling` class, the one that got extra
parameters (i... | assert_empty | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def from_file(params_file , params_overrides = u"") :
u"""
Load a `Params` object from a configuration file.
"""
# redirect to cache, if necessary
params_file = cached_path(params_file)
ext_vars = dict(os.environ)
file_dict = json.loads(evalua... |
Load a `Params` object from a configuration file.
| from_file | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def as_ordered_dict(self, preference_orders = None) :
u"""
Returns Ordered Dict of Params from list of partial order preferences.
Parameters
----------
preference_orders: List[List[str]], optional
``preference_orders`` is list of partia... |
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_o... | as_ordered_dict | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def pop_choice(params ,
key ,
choices ,
default_to_first_choice = False,
history = u"?.") :
u"""
Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with
places tha... |
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-c... | pop_choice | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/params.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/params.py | MIT |
def list_available(cls) :
u"""List default first if it exists"""
keys = list(Registrable._registry[cls].keys())
default = cls.default_implementation
if default is None:
return keys
elif default not in keys:
message = u"Default implementation %... | List default first if it exists | list_available | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/registrable.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/registrable.py | MIT |
def replace_cr_with_newline(message ):
u"""
TQDM and requests use carriage returns to get the training line to update for each batch
without adding more lines to the terminal output. Displaying those in a file won't work
correctly, so we'll just make sure that each batch shows up on its one line.
... |
TQDM and requests use carriage returns to get the training line to update for each batch
without adding more lines to the terminal output. Displaying those in a file won't work
correctly, so we'll just make sure that each batch shows up on its one line.
:param message: the message to permute
:retu... | replace_cr_with_newline | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/tee_logger.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/tee_logger.py | MIT |
def set_slower_interval(use_slower_interval ) :
u"""
If ``use_slower_interval`` is ``True``, we will dramatically slow down ``tqdm's`` default
output rate. ``tqdm's`` default output rate is great for interactively watching progress,
but it is not great for log files. You mi... |
If ``use_slower_interval`` is ``True``, we will dramatically slow down ``tqdm's`` default
output rate. ``tqdm's`` default output rate is great for interactively watching progress,
but it is not great for log files. You might want to set this if you are primarily going
to be looking at... | set_slower_interval | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/tqdm.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/tqdm.py | MIT |
def sanitize(x ) : # pylint: disable=invalid-name,too-many-return-statements
u"""
Sanitize turns PyTorch and Numpy types into basic Python types so they
can be serialized into JSON.
"""
if isinstance(x, (unicode, float, int, bool)):
# x is already serializable
return x
... |
Sanitize turns PyTorch and Numpy types into basic Python types so they
can be serialized into JSON.
| sanitize | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def pad_sequence_to_length(sequence ,
desired_length ,
default_value = lambda: 0,
padding_on_right = True) :
u"""
Take a list of objects and pads it to the desired length, returning the padd... |
Take a list of objects and pads it to the desired length, returning the padded list. The
original list is not modified.
Parameters
----------
sequence : List
A list of objects to be padded.
desired_length : int
Maximum length of each sequence. Longer sequences are truncated t... | pad_sequence_to_length | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def add_noise_to_dict_values(dictionary , noise_param ) :
u"""
Returns a new dictionary with noise added to every key in ``dictionary``. The noise is
uniformly distributed within ``noise_param`` percent of the value for every value in the
dictionary.
"""
ne... |
Returns a new dictionary with noise added to every key in ``dictionary``. The noise is
uniformly distributed within ``noise_param`` percent of the value for every value in the
dictionary.
| add_noise_to_dict_values | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def namespace_match(pattern , namespace ):
u"""
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``.
"""
if pattern[0] == u'*' and namespace.endswith(pa... |
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``.
| namespace_match | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def prepare_environment(params ):
u"""
Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
y... |
Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
your experiments should be reasonably reproducible... | prepare_environment | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def prepare_global_logging(serialization_dir , file_friendly_logging ) :
u"""
This function configures 3 global logging attributes - streaming stdout and stderr
to a file as well as the terminal, setting the formatting for the python logging
library and setting the interval frequency for... |
This function configures 3 global logging attributes - streaming stdout and stderr
to a file as well as the terminal, setting the formatting for the python logging
library and setting the interval frequency for the Tqdm progress bar.
Note that this function does not set the logging level, which is set... | prepare_global_logging | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def get_spacy_model(spacy_model_name , pos_tags , parse , ner ) :
u"""
In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loade... |
In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loaded once.
| get_spacy_model | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def import_submodules(package_name ) :
u"""
Import all submodules under the given package.
Primarily useful so that people using AllenNLP as a library
can specify their own custom packages and have their custom
classes get loaded and registered.
"""
importlib.invalidate_caches()
... |
Import all submodules under the given package.
Primarily useful so that people using AllenNLP as a library
can specify their own custom packages and have their custom
classes get loaded and registered.
| import_submodules | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def peak_memory_mb() :
u"""
Get peak memory usage for this process, as measured by
max-resident-set size:
https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size
Only works on OSX and Linux, returns 0.0 otherwise.
"""
if resource is No... |
Get peak memory usage for this process, as measured by
max-resident-set size:
https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size
Only works on OSX and Linux, returns 0.0 otherwise.
| peak_memory_mb | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def gpu_memory_mb() :
u"""
Get the current GPU memory usage.
Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4
Returns
-------
``Dict[int, int]``
Keys are device ids as integers.
Values are memory usage as integers in MB.
R... |
Get the current GPU memory usage.
Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4
Returns
-------
``Dict[int, int]``
Keys are device ids as integers.
Values are memory usage as integers in MB.
Returns an empty ``dict`` if GPUs are not availa... | gpu_memory_mb | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def ensure_list(iterable ) :
u"""
An Iterable may be a list or a generator.
This ensures we get a list without making an unnecessary copy.
"""
if isinstance(iterable, list):
return iterable
else:
return list(iterable) |
An Iterable may be a list or a generator.
This ensures we get a list without making an unnecessary copy.
| ensure_list | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/common/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/common/util.py | MIT |
def __init__(self, instances ) :
u"""
A Batch just takes an iterable of instances in its constructor and hangs onto them
in a list.
"""
super(Batch, self).__init__()
self.instances = ensure_list(instances)
self._check_types() |
A Batch just takes an iterable of instances in its constructor and hangs onto them
in a list.
| __init__ | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset.py | MIT |
def _check_types(self) :
u"""
Check that all the instances have the same types.
"""
all_instance_fields_and_types = [dict((k, v.__class__.__name__)
for k, v in x.fields.items())
... |
Check that all the instances have the same types.
| _check_types | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset.py | MIT |
def get_padding_lengths(self) :
u"""
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``
has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.
We look at all fields in all instances, and... |
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``
has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.
We look at all fields in all instances, and find the max values for each (field_name,
padding_key) pair, re... | get_padding_lengths | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset.py | MIT |
def as_tensor_dict(self,
padding_lengths = None,
cuda_device = -1,
verbose = False) :
# This complex return type is actually predefined elsewhere a... |
This method converts this ``Batch`` into a set of pytorch Tensors that can be passed
through a model. In order for the tensors to be valid tensors, all ``Instances`` in this
batch need to be padded to the same lengths wherever padding is necessary, so we do that
first, then we combine ... | as_tensor_dict | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset.py | MIT |
def add_field(self, field_name , field , vocab = None) :
u"""
Add the field to the existing fields mapping.
If we have already indexed the Instance, then we also index `field`, so
it is necessary to supply the vocab.
"""
self.fields[field_name... |
Add the field to the existing fields mapping.
If we have already indexed the Instance, then we also index `field`, so
it is necessary to supply the vocab.
| add_field | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/instance.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/instance.py | MIT |
def index_fields(self, vocab ) :
u"""
Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.
This `mutates` the current object, it does not return a new ``Instance``.
A ``DataIterator`` will call this on each pass through a dataset; we use the ``inde... |
Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.
This `mutates` the current object, it does not return a new ``Instance``.
A ``DataIterator`` will call this on each pass through a dataset; we use the ``indexed``
flag to make sure that indexing only happens once... | index_fields | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/instance.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/instance.py | MIT |
def get_padding_lengths(self) :
u"""
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name.
"""
lengths = {}
for field_... |
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name.
| get_padding_lengths | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/instance.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/instance.py | MIT |
def pop_max_vocab_size(params ) :
u"""
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 handle it.
... |
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 handle it.
| pop_max_vocab_size | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def save_to_files(self, directory ) :
u"""
Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary.
... |
Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary.
| save_to_files | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def from_files(cls, directory ) :
u"""
Loads a ``Vocabulary`` that was serialized using ``save_to_files``.
Parameters
----------
directory : ``str``
The directory containing the serialized vocabulary.
"""
logger.info(u"Loading token... |
Loads a ``Vocabulary`` that was serialized using ``save_to_files``.
Parameters
----------
directory : ``str``
The directory containing the serialized vocabulary.
| from_files | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def set_from_file(self,
filename ,
is_padded = True,
oov_token = DEFAULT_OOV_TOKEN,
namespace = u"tokens"):
u"""
If you already have a vocabulary file for a trained model somewhere, and you really... |
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 y... | set_from_file | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def from_instances(cls,
instances ,
min_count = None,
max_vocab_size = None,
non_padded_namespaces = DEFAULT_NON_PADDED_NAMESPACES,
... |
Constructs a vocabulary given a collection of `Instances` and some parameters.
We count all of the vocabulary items in the instances, then pass those counts
and the other parameters, to :func:`__init__`. See that method for a description
of what the other parameters do.
| from_instances | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def from_params(cls, params , instances = None): # type: ignore
u"""
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_... |
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 metho... | from_params | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def _extend(self,
counter = None,
min_count = None,
max_vocab_size = None,
non_padded_namespaces = DEFAULT_NON_PADDED_NAMESPACES,
pretrained_files ... |
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.
| _extend | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def extend_from_instances(self,
params ,
instances = ()) :
u"""
Extends an already generated vocabulary using a collection of instances.
"""
min_count = params.pop(u"min_count", None)
... |
Extends an already generated vocabulary using a collection of instances.
| extend_from_instances | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def add_token_to_namespace(self, token , namespace = u'tokens') :
u"""
Adds ``token`` to the index, if it is not already present. Either way, we return the index of
the token.
"""
if not isinstance(token, unicode):
raise ValueError(u"Vocabulary tokens ... |
Adds ``token`` to the index, if it is not already present. Either way, we return the index of
the token.
| add_token_to_namespace | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/vocabulary.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/vocabulary.py | MIT |
def text_to_instance(self, # type: ignore
utterances ,
sql_query = None) :
# pylint: disable=arguments-differ
u"""
Parameters
----------
utterances: ``List[str]``, required.
List of utterance... |
Parameters
----------
utterances: ``List[str]``, required.
List of utterances in the interaction, the last element is the current utterance.
sql_query: ``str``, optional
The SQL query, given as label during training or validation.
| text_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset_readers/atis.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset_readers/atis.py | MIT |
def text_to_instance(self, # type: ignore
tokens ,
ccg_categories = None,
original_pos_tags = None,
modified_pos_tags = None,
predicate_arg_categories ... |
We take `pre-tokenized` input here, because we don't have a tokenizer in this class.
Parameters
----------
tokens : ``List[str]``, required.
The tokens in a given sentence.
ccg_categories : ``List[str]``, optional, (default = None).
The CCG categories fo... | text_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset_readers/ccgbank.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset_readers/ccgbank.py | MIT |
def text_to_instance(self, # type: ignore
tokens ,
pos_tags = None,
chunk_tags = None,
ner_tags = None) :
u"""
We take `pre-tokenized` input here, b... |
We take `pre-tokenized` input here, because we don't have a tokenizer in this class.
| text_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset_readers/conll2003.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset_readers/conll2003.py | MIT |
def read(self, file_path ) :
u"""
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 ``sel... |
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__`... | read | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset_readers/dataset_reader.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset_readers/dataset_reader.py | MIT |
def text_to_instance(self, # type: ignore
sentence ,
structured_representations ,
labels = None,
target_sequences = None,
identifier ... |
Parameters
----------
sentence : ``str``
The query sentence.
structured_representations : ``List[List[List[JsonDict]]]``
A list of Json representations of all the worlds. See expected format in this class' docstring.
labels : ``List[str]`` (optional)
... | text_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/data/dataset_readers/nlvr.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/data/dataset_readers/nlvr.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.