Skip to content

vocabulary

allennlp.data.vocabulary

[SOURCE]


A Vocabulary maps strings to integers, allowing for strings to be mapped to an out-of-vocabulary token.

DEFAULT_NON_PADDED_NAMESPACES#

DEFAULT_NON_PADDED_NAMESPACES = ("*tags", "*labels")

DEFAULT_PADDING_TOKEN#

DEFAULT_PADDING_TOKEN = "@@PADDING@@"

DEFAULT_OOV_TOKEN#

DEFAULT_OOV_TOKEN = "@@UNKNOWN@@"

NAMESPACE_PADDING_FILE#

NAMESPACE_PADDING_FILE = "non_padded_namespaces.txt"

Vocabulary#

class Vocabulary(Registrable):
 | def __init__(
 |     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: Optional[Dict[str, str]] = None,
 |     only_include_pretrained_words: bool = False,
 |     tokens_to_add: Dict[str, List[str]] = None,
 |     min_pretrained_embeddings: Dict[str, int] = None,
 |     padding_token: Optional[str] = DEFAULT_PADDING_TOKEN,
 |     oov_token: Optional[str] = DEFAULT_OOV_TOKEN
 | ) -> None

A Vocabulary maps strings to integers, allowing for strings to be mapped to an out-of-vocabulary token.

Vocabularies are fit to a particular dataset, which we use to decide which tokens are in-vocabulary.

Vocabularies also allow for several different namespaces, so you can have separate indices for 'a' as a word, and 'a' as a character, for instance, and so we can use this object to also map tag and label strings to indices, for a unified .fields.field.Field API. Most of the methods on this class allow you to pass in a namespace; by default we use the 'tokens' namespace, and you can omit the namespace argument everywhere and just use the default.

This class is registered as a Vocabulary with four different names, which all point to different @classmethod constructors found in this class. from_instances is registered as "from_instances", from_files is registered as "from_files", from_files_and_instances is registered as "extend", and empty is registered as "empty". If you are using a configuration file to construct a vocabulary, you can use any of those strings as the "type" key in the configuration file to use the corresponding @classmethod to construct the object. "from_instances" is the default. Look at the docstring for the @classmethod to see what keys are allowed in the configuration file (when there is an instances argument to the @classmethod, it will be passed in separately and does not need a corresponding key in the configuration file).

Parameters

  • counter : Dict[str, Dict[str, int]], optional (default = None)
    A collection of counts from which to initialize this vocabulary. We will examine the counts and, together with the other parameters to this class, use them to decide which words are in-vocabulary. If this is None, we just won't initialize the vocabulary with anything.

  • min_count : Dict[str, int], optional (default = None)
    When initializing the vocab from a counter, you can specify a minimum count, and every token with a count less than this will not be added to the dictionary. These minimum counts are namespace-specific, so you can specify different minimums for labels versus words tokens, for example. If a namespace does not have a key in the given dictionary, we will add all seen tokens to that namespace.

  • max_vocab_size : Union[int, Dict[str, int]], optional (default = None)
    If you want to cap the number of tokens in your vocabulary, you can do so with this parameter. If you specify a single integer, every namespace will have its vocabulary fixed to be no larger than this. If you specify a dictionary, then each namespace in the counter can have a separate maximum vocabulary size. Any missing key will have a value of None, which means no cap on the vocabulary size.

  • non_padded_namespaces : Iterable[str], optional
    By default, we assume you are mapping word / character tokens to integers, and so you want to reserve word indices for padding and out-of-vocabulary tokens. However, if you are mapping NER or SRL tags, or class labels, to integers, you probably do not want to reserve indices for padding and out-of-vocabulary tokens. Use this field to specify which namespaces should not have padding and OOV tokens added.

    The format of each element of this is either a string, which must match field names exactly, or * followed by a string, which we match as a suffix against field names.

    We try to make the default here reasonable, so that you don't have to think about this. The default is ("*tags", "*labels"), so as long as your namespace ends in "tags" or "labels" (which is true by default for all tag and label fields in this code), you don't have to specify anything here.

  • pretrained_files : Dict[str, str], optional
    If provided, this map specifies the path to optional pretrained embedding files for each namespace. This can be used to either restrict the vocabulary to only words which appear in this file, or to ensure that any words in this file are included in the vocabulary regardless of their count, depending on the value of only_include_pretrained_words. Words which appear in the pretrained embedding file but not in the data are NOT included in the Vocabulary.

  • min_pretrained_embeddings : Dict[str, int], optional
    If provided, specifies for each namespace a minimum number of lines (typically the most common words) to keep from pretrained embedding files, even for words not appearing in the data.

  • only_include_pretrained_words : bool, optional (default = False)
    This defines the strategy for using any pretrained embedding files which may have been specified in pretrained_files. If False, an inclusive strategy is used: and words which are in the counter and in the pretrained file are added to the Vocabulary, regardless of whether their count exceeds min_count or not. If True, we use an exclusive strategy: words are only included in the Vocabulary if they are in the pretrained embedding file (their count must still be at least min_count).

  • tokens_to_add : Dict[str, List[str]], optional (default = None)
    If given, this is a list of tokens to add to the vocabulary, keyed by the namespace to add the tokens to. This is a way to be sure that certain items appear in your vocabulary, regardless of any other vocabulary computation.

  • padding_token : str, optional (default = DEFAULT_PADDING_TOKEN)
    If given, this the string used for padding.

  • oov_token : str, optional (default = DEFAULT_OOV_TOKEN)
    If given, this the string used for the out of vocabulary (OOVs) tokens.

default_implementation#

class Vocabulary(Registrable):
 | ...
 | default_implementation = "from_instances"

from_instances#

class Vocabulary(Registrable):
 | ...
 | @classmethod
 | 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,
 |     pretrained_files: Optional[Dict[str, str]] = None,
 |     only_include_pretrained_words: bool = False,
 |     tokens_to_add: Dict[str, List[str]] = None,
 |     min_pretrained_embeddings: Dict[str, int] = None,
 |     padding_token: Optional[str] = DEFAULT_PADDING_TOKEN,
 |     oov_token: Optional[str] = DEFAULT_OOV_TOKEN
 | ) -> "Vocabulary"

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 __init__. See that method for a description of what the other parameters do.

The instances parameter does not get an entry in a typical AllenNLP configuration file, but the other parameters do (if you want non-default parameters).

from_files#

class Vocabulary(Registrable):
 | ...
 | @classmethod
 | def from_files(
 |     cls,
 |     directory: Union[str, os.PathLike],
 |     padding_token: Optional[str] = DEFAULT_PADDING_TOKEN,
 |     oov_token: Optional[str] = DEFAULT_OOV_TOKEN
 | ) -> "Vocabulary"

Loads a Vocabulary that was serialized either using save_to_files or inside a model archive file.

Parameters

  • directory : str
    The directory or archive file containing the serialized vocabulary.

from_files_and_instances#

class Vocabulary(Registrable):
 | ...
 | @classmethod
 | def from_files_and_instances(
 |     cls,
 |     instances: Iterable["adi.Instance"],
 |     directory: str,
 |     padding_token: Optional[str] = DEFAULT_PADDING_TOKEN,
 |     oov_token: Optional[str] = DEFAULT_OOV_TOKEN,
 |     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: Optional[Dict[str, str]] = None,
 |     only_include_pretrained_words: bool = False,
 |     tokens_to_add: Dict[str, List[str]] = None,
 |     min_pretrained_embeddings: Dict[str, int] = None
 | ) -> "Vocabulary"

Extends an already generated vocabulary using a collection of instances.

The instances parameter does not get an entry in a typical AllenNLP configuration file, but the other parameters do (if you want non-default parameters). See __init__ for a description of what the other parameters mean.

empty#

class Vocabulary(Registrable):
 | ...
 | @classmethod
 | def empty(cls) -> "Vocabulary"

This method returns a bare vocabulary instantiated with cls() (so, Vocabulary() if you haven't made a subclass of this object). The only reason to call Vocabulary.empty() instead of Vocabulary() is if you are instantiating this object from a config file. We register this constructor with the key "empty", so if you know that you don't need to compute a vocabulary (either because you're loading a pre-trained model from an archive file, you're using a pre-trained transformer that has its own vocabulary, or something else), you can use this to avoid having the default vocabulary construction code iterate through the data.

set_from_file#

class Vocabulary(Registrable):
 | ...
 | 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 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 to use padding and OOV tokens for this.

Parameters

  • filename : str
    The file containing the vocabulary to load. It should be formatted as one token per line, with nothing else in the line. The index we assign to the token is the line number in the file (1-indexed if is_padded, 0-indexed otherwise). Note that this file should contain the OOV token string!
  • is_padded : bool, optional (default = True)
    Is this vocabulary padded? For token / word / character vocabularies, this should be True; while for tag or label vocabularies, this should typically be False. If True, we add a padding token with index 0, and we enforce that the oov_token is present in the file.
  • oov_token : str, optional (default = DEFAULT_OOV_TOKEN)
    What token does this vocabulary use to represent out-of-vocabulary characters? This must show up as a line in the vocabulary file. When we find it, we replace oov_token with self._oov_token, because we only use one OOV token across namespaces.
  • namespace : str, optional (default = "tokens")
    What namespace should we overwrite with this vocab file?

extend_from_instances#

class Vocabulary(Registrable):
 | ...
 | def extend_from_instances(
 |     self,
 |     instances: Iterable["adi.Instance"]
 | ) -> None

extend_from_vocab#

class Vocabulary(Registrable):
 | ...
 | def extend_from_vocab(self, vocab: "Vocabulary") -> None

Adds all vocabulary items from all namespaces in the given vocabulary to this vocabulary. Useful if you want to load a model and extends its vocabulary from new instances.

We also add all non-padded namespaces from the given vocabulary to this vocabulary.

save_to_files#

class Vocabulary(Registrable):
 | ...
 | 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.

is_padded#

class Vocabulary(Registrable):
 | ...
 | def is_padded(self, namespace: str) -> bool

Returns whether or not there are padding and OOV tokens added to the given namespace.

add_token_to_namespace#

class Vocabulary(Registrable):
 | ...
 | 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.

add_tokens_to_namespace#

class Vocabulary(Registrable):
 | ...
 | def add_tokens_to_namespace(
 |     self,
 |     tokens: List[str],
 |     namespace: str = "tokens"
 | ) -> List[int]

Adds tokens to the index, if they are not already present. Either way, we return the indices of the tokens in the order that they were given.

get_index_to_token_vocabulary#

class Vocabulary(Registrable):
 | ...
 | def get_index_to_token_vocabulary(
 |     self,
 |     namespace: str = "tokens"
 | ) -> Dict[int, str]

get_token_to_index_vocabulary#

class Vocabulary(Registrable):
 | ...
 | def get_token_to_index_vocabulary(
 |     self,
 |     namespace: str = "tokens"
 | ) -> Dict[str, int]

get_token_index#

class Vocabulary(Registrable):
 | ...
 | def get_token_index(
 |     self,
 |     token: str,
 |     namespace: str = "tokens"
 | ) -> int

get_token_from_index#

class Vocabulary(Registrable):
 | ...
 | def get_token_from_index(
 |     self,
 |     index: int,
 |     namespace: str = "tokens"
 | ) -> str

get_vocab_size#

class Vocabulary(Registrable):
 | ...
 | def get_vocab_size(self, namespace: str = "tokens") -> int

get_namespaces#

class Vocabulary(Registrable):
 | ...
 | def get_namespaces(self) -> Set[str]

class Vocabulary(Registrable):
 | ...
 | def print_statistics(self) -> None