flair.embeddings.token#

class flair.embeddings.token.TransformerWordEmbeddings(model='bert-base-uncased', is_document_embedding=False, allow_long_sentences=True, **kwargs)View on GitHub#

Bases: TokenEmbeddings, TransformerEmbeddings

onnx_clsView on GitHub#

alias of TransformerOnnxWordEmbeddings

classmethod create_from_state(**state)View on GitHub#
embeddings_name: str = 'TransformerWordEmbeddings'#
class flair.embeddings.token.StackedEmbeddings(embeddings, overwrite_names=True)View on GitHub#

Bases: TokenEmbeddings

A stack of embeddings, used if you need to combine several different embedding types.

embed(sentences, static_embeddings=True)View on GitHub#

Add embeddings to all words in a list of sentences.

If embeddings are already added, updates only if embeddings are non-static.

property embedding_type: str#
property embedding_length: int#

Returns the length of the embedding vector.

get_names()View on GitHub#

Returns a list of embedding names.

In most cases, it is just a list with one item, namely the name of this embedding. But in some cases, the embedding is made up by different embeddings (StackedEmbedding). Then, the list contains the names of all embeddings in the stack.

Return type:

List[str]

get_named_embeddings_dict()View on GitHub#
Return type:

Dict

classmethod from_params(params)View on GitHub#
to_params()View on GitHub#
embeddings_name: str = 'StackedEmbeddings'#
class flair.embeddings.token.WordEmbeddings(embeddings, field=None, fine_tune=False, force_cpu=True, stable=False, no_header=False, vocab=None, embedding_length=None, name=None)View on GitHub#

Bases: TokenEmbeddings

Standard static word embeddings, such as GloVe or FastText.

resolve_precomputed_path(embeddings)View on GitHub#
Return type:

Optional[Path]

property embedding_length: int#

Returns the length of the embedding vector.

get_cached_token_index(word)View on GitHub#
Return type:

int

get_vec(word)View on GitHub#
Return type:

Tensor

extra_repr()View on GitHub#

Set the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

train(mode=True)View on GitHub#

Set the module in training mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

Parameters:

mode (bool) – whether to set training mode (True) or evaluation mode (False). Default: True.

Returns:

self

Return type:

Module

to(device)View on GitHub#

Move and/or cast the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)View on GitHub
to(dtype, non_blocking=False)View on GitHub
to(tensor, non_blocking=False)View on GitHub
to(memory_format=torch.channels_last)View on GitHub

Its signature is similar to torch.Tensor.to(), but only accepts floating point or complex dtypes. In addition, this method will only cast the floating point or complex parameters and buffers to dtype (if given). The integral parameters and buffers will be moved device, if that is given, but with dtypes unchanged. When non_blocking is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

See below for examples.

Note

This method modifies the module in-place.

Parameters:
  • device (torch.device) – the desired device of the parameters and buffers in this module

  • dtype (torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this module

  • tensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module

  • memory_format (torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)

Returns:

self

Return type:

Module

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
classmethod from_params(params)View on GitHub#
Return type:

WordEmbeddings

to_params()View on GitHub#
Return type:

Dict[str, Any]

state_dict(*args, **kwargs)View on GitHub#

Return a dictionary containing references to the whole state of the module.

Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to None are not included.

Note

The returned object is a shallow copy. It contains references to the module’s parameters and buffers.

Warning

Currently state_dict() also accepts positional arguments for destination, prefix and keep_vars in order. However, this is being deprecated and keyword arguments will be enforced in future releases.

Warning

Please avoid the use of argument destination as it is not designed for end-users.

Parameters:
  • destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an OrderedDict will be created and returned. Default: None.

  • prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default: ''.

  • keep_vars (bool, optional) – by default the Tensor s returned in the state dict are detached from autograd. If it’s set to True, detaching will not be performed. Default: False.

Returns:

a dictionary containing a whole state of the module

Return type:

dict

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> module.state_dict().keys()
['bias', 'weight']
embeddings_name: str = 'WordEmbeddings'#
class flair.embeddings.token.CharacterEmbeddings(path_to_char_dict=None, char_embedding_dim=25, hidden_size_char=25)View on GitHub#

Bases: TokenEmbeddings

Character embeddings of words, as proposed in Lample et al., 2016.

property embedding_length: int#

Returns the length of the embedding vector.

classmethod from_params(params)View on GitHub#
Return type:

CharacterEmbeddings

to_params()View on GitHub#
Return type:

Dict[str, Any]

embeddings_name: str = 'CharacterEmbeddings'#
class flair.embeddings.token.FlairEmbeddings(model, fine_tune=False, chars_per_chunk=512, with_whitespace=True, tokenized_lm=True, is_lower=False, name=None, has_decoder=False)View on GitHub#

Bases: TokenEmbeddings

Contextual string embeddings of words, as proposed in Akbik et al., 2018.

train(mode=True)View on GitHub#

Set the module in training mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

Parameters:

mode (bool) – whether to set training mode (True) or evaluation mode (False). Default: True.

Returns:

self

Return type:

Module

property embedding_length: int#

Returns the length of the embedding vector.

to_params()View on GitHub#
classmethod from_params(params)View on GitHub#
embeddings_name: str = 'FlairEmbeddings'#
class flair.embeddings.token.PooledFlairEmbeddings(contextual_embeddings, pooling='min', only_capitalized=False, **kwargs)View on GitHub#

Bases: TokenEmbeddings

train(mode=True)View on GitHub#

Set the module in training mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

Parameters:

mode (bool) – whether to set training mode (True) or evaluation mode (False). Default: True.

Returns:

self

Return type:

Module

property embedding_length: int#

Returns the length of the embedding vector.

get_names()View on GitHub#

Returns a list of embedding names.

In most cases, it is just a list with one item, namely the name of this embedding. But in some cases, the embedding is made up by different embeddings (StackedEmbedding). Then, the list contains the names of all embeddings in the stack.

Return type:

List[str]

classmethod from_params(params)View on GitHub#
to_params()View on GitHub#
embeddings_name: str = 'PooledFlairEmbeddings'#
class flair.embeddings.token.FastTextEmbeddings(embeddings, use_local=True, field=None, name=None)View on GitHub#

Bases: TokenEmbeddings

FastText Embeddings with oov functionality.

property embedding_length: int#

Returns the length of the embedding vector.

get_cached_vec(word)View on GitHub#
Return type:

Tensor

extra_repr()View on GitHub#

Set the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

classmethod from_params(params)View on GitHub#
to_params()View on GitHub#
embeddings_name: str = 'FastTextEmbeddings'#
class flair.embeddings.token.OneHotEmbeddings(vocab_dictionary, field='text', embedding_length=300, stable=False)View on GitHub#

Bases: TokenEmbeddings

One-hot encoded embeddings.

property embedding_length: int#

Returns the length of the embedding vector.

classmethod from_corpus(corpus, field='text', min_freq=3, **kwargs)View on GitHub#
classmethod from_params(params)View on GitHub#
to_params()View on GitHub#
embeddings_name: str = 'OneHotEmbeddings'#
class flair.embeddings.token.HashEmbeddings(num_embeddings=1000, embedding_length=300, hash_method='md5')View on GitHub#

Bases: TokenEmbeddings

Standard embeddings with Hashing Trick.

property num_embeddings: int#
property embedding_length: int#

Returns the length of the embedding vector.

classmethod from_params(params)View on GitHub#
to_params()View on GitHub#
embeddings_name: str = 'HashEmbeddings'#
class flair.embeddings.token.MuseCrosslingualEmbeddingsView on GitHub#

Bases: TokenEmbeddings

get_cached_vec(language_code, word)View on GitHub#
Return type:

Tensor

property embedding_length: int#

Returns the length of the embedding vector.

classmethod from_params(params)View on GitHub#
to_params()View on GitHub#
embeddings_name: str = 'MuseCrosslingualEmbeddings'#
class flair.embeddings.token.BytePairEmbeddings(language=None, dim=50, syllables=100000, cache_dir=None, model_file_path=None, embedding_file_path=None, name=None, **kwargs)View on GitHub#

Bases: TokenEmbeddings

embeddings_name: str = 'BytePairEmbeddings'#
property embedding_length: int#

Returns the length of the embedding vector.

extra_repr()View on GitHub#

Set the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

classmethod from_params(params)View on GitHub#
to_params()View on GitHub#
class flair.embeddings.token.NILCEmbeddings(embeddings, model='skip', size=100)View on GitHub#

Bases: WordEmbeddings

embeddings_name: str = 'NILCEmbeddings'#
classmethod from_params(params)View on GitHub#
Return type:

WordEmbeddings