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
- __init__(model='bert-base-uncased', is_document_embedding=False, allow_long_sentences=True, **kwargs)View on GitHub#
Bidirectional transformer embeddings of words from various transformer architectures.
- Parameters:
model (
str
) – name of transformer model (see https://huggingface.co/transformers/pretrained_models.html for options)is_document_embedding (
bool
) – If True, the embedding can be used as DocumentEmbedding too.allow_long_sentences (
bool
) – If True, too long sentences will be patched and strided and afterwards combined.**kwargs – Arguments propagated to
flair.embeddings.transformer.TransformerEmbeddings.__init__()
- classmethod create_from_state(**state)View on GitHub#
-
embeddings_name:
str
= 'TransformerWordEmbeddings'#
- name: str#
- training: bool#
- 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.
- __init__(embeddings, overwrite_names=True)View on GitHub#
The constructor takes a list of embeddings to be combined.
- name: str#
- 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'#
- training: bool#
- 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.
- __init__(embeddings, field=None, fine_tune=False, force_cpu=True, stable=False, no_header=False, vocab=None, embedding_length=None, name=None)View on GitHub#
Initializes classic word embeddings.
Constructor downloads required files if not there.
Note
When loading a new embedding, you need to have flair[gensim] installed.
- Parameters:
embeddings (
Optional
[str
]) – one of: ‘glove’, ‘extvec’, ‘crawl’ or two-letter language code or a path to a custom embeddingfield (
Optional
[str
]) – if given, the word-embeddings embed the data for the specific label-type instead of the plain text.fine_tune (
bool
) – If True, allows word-embeddings to be fine-tuned during trainingforce_cpu (
bool
) – If True, stores the large embedding matrix not on the gpu to save memory. force_cpu can only be used if fine_tune is Falsestable (
bool
) – if True, use the stable embeddings as described in https://arxiv.org/abs/2110.02861no_header (
bool
) – only for reading plain word2vec text files. If true, the reader assumes the first line to not contain embedding length and vocab size.vocab (
Optional
[Dict
[str
,int
]]) – If the embeddings are already loaded in memory, provide the vocab here.embedding_length (
Optional
[int
]) – If the embeddings are already loaded in memory, provide the embedding_length here.name (
Optional
[str
]) – The name of the embeddings.
- name: str#
- 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
- 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 complexdtype
s. In addition, this method will only cast the floating point or complex parameters and buffers todtype
(if given). The integral parameters and buffers will be moveddevice
, if that is given, but with dtypes unchanged. Whennon_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 moduledtype (
torch.dtype
) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (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:
- 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 fordestination
,prefix
andkeep_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 toTrue
, 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'#
- training: bool#
- class flair.embeddings.token.CharacterEmbeddings(path_to_char_dict=None, char_embedding_dim=25, hidden_size_char=25, name='Char')View on GitHub#
Bases:
TokenEmbeddings
Character embeddings of words, as proposed in Lample et al., 2016.
- __init__(path_to_char_dict=None, char_embedding_dim=25, hidden_size_char=25, name='Char')View on GitHub#
Instantiates a bidirectional lstm layer toi encode words by their character representation.
Uses the default character dictionary if none provided.
- name: str#
- property embedding_length: int#
Returns the length of the embedding vector.
- classmethod from_params(params)View on GitHub#
- Return type:
- to_params()View on GitHub#
- Return type:
Dict
[str
,Any
]
-
embeddings_name:
str
= 'CharacterEmbeddings'#
- training: bool#
- 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.
- __init__(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#
Initializes contextual string embeddings using a character-level language model.
- Parameters:
model – model string, one of ‘news-forward’, ‘news-backward’, ‘news-forward-fast’, ‘news-backward-fast’, ‘mix-forward’, ‘mix-backward’, ‘german-forward’, ‘german-backward’, ‘polish-backward’, ‘polish-forward’ depending on which character language model is desired.
fine_tune (
bool
) – if set to True, the gradient will propagate into the language model. This dramatically slows down training and often leads to overfitting, so use with caution.chars_per_chunk (
int
) – max number of chars per rnn pass to control speed/memory tradeoff. Higher means faster but requires more memory. Lower means slower but less memory.with_whitespace (
bool
) – If True, use hidden state after whitespace after word. If False, use hidden state at last character of word.tokenized_lm (
bool
) – Whether this lm is tokenized. Default is True, but for LMs trained over unprocessed text False might be better.has_decoder (
bool
) – Weather to load the decoder-head of the LanguageModel. This should only be true, if you intend to generate text.is_lower (
bool
) – Whether this lm is trained on lower-cased data.name (
Optional
[str
]) – The name of the embeddings
- name: str#
- 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'#
- training: bool#
- class flair.embeddings.token.PooledFlairEmbeddings(contextual_embeddings, pooling='min', only_capitalized=False, **kwargs)View on GitHub#
Bases:
TokenEmbeddings
- name: str#
- 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'#
- training: bool#
- class flair.embeddings.token.FastTextEmbeddings(embeddings, use_local=True, field=None, name=None)View on GitHub#
Bases:
TokenEmbeddings
FastText Embeddings with oov functionality.
Deprecated since version 0.14.0: The FastTextEmbeddings are no longer supported and will be removed at version 0.16.0
- __init__(embeddings, use_local=True, field=None, name=None)View on GitHub#
Initializes fasttext word embeddings.
Constructor downloads required embedding file and stores in cache if use_local is False.
- Parameters:
embeddings (
str
) – path to your embeddings ‘.bin’ fileuse_local (
bool
) – set this to False if you are using embeddings from a remote sourcefield (
Optional
[str
]) – if given, the word-embeddings embed the data for the specific label-type instead of the plain text.name (
Optional
[str
]) – The name of the embeddings.
- name: str#
- 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'#
- training: bool#
- class flair.embeddings.token.OneHotEmbeddings(vocab_dictionary, field='text', embedding_length=300, stable=False)View on GitHub#
Bases:
TokenEmbeddings
One-hot encoded embeddings.
- __init__(vocab_dictionary, field='text', embedding_length=300, stable=False)View on GitHub#
Initializes one-hot encoded word embeddings and a trainable embedding layer.
- Parameters:
vocab_dictionary (
Dictionary
) – the vocabulary that will be encodedfield (
str
) – by default, the ‘text’ of tokens is embedded, but you can also embed tags such as ‘pos’embedding_length (
int
) – dimensionality of the trainable embedding layerstable (
bool
) – if True, use the stable embeddings as described in https://arxiv.org/abs/2110.02861
- name: str#
- 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'#
- training: bool#
- class flair.embeddings.token.HashEmbeddings(num_embeddings=1000, embedding_length=300, hash_method='md5')View on GitHub#
Bases:
TokenEmbeddings
Standard embeddings with Hashing Trick.
- name: str#
- 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'#
- training: bool#
- class flair.embeddings.token.MuseCrosslingualEmbeddingsView on GitHub#
Bases:
TokenEmbeddings
- name: str#
- 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'#
- training: bool#
- class flair.embeddings.token.BytePairEmbeddings(language=None, dim=50, syllables=100000, cache_dir=None, model_file_path=None, embedding_file_path=None, name=None, force_cpu=True, field=None, preprocess=True, **kwargs)View on GitHub#
Bases:
TokenEmbeddings
- __init__(language=None, dim=50, syllables=100000, cache_dir=None, model_file_path=None, embedding_file_path=None, name=None, force_cpu=True, field=None, preprocess=True, **kwargs)View on GitHub#
Initializes BP embeddings.
Constructor downloads required files if not there.
- name: str#
- property embedding_length: int#
Returns the length of the embedding vector.
-
embeddings_name:
str
= 'BytePairEmbeddings'#
- training: bool#
- 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#
- 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 complexdtype
s. In addition, this method will only cast the floating point or complex parameters and buffers todtype
(if given). The integral parameters and buffers will be moveddevice
, if that is given, but with dtypes unchanged. Whennon_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 moduledtype (
torch.dtype
) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (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)
- 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 fordestination
,prefix
andkeep_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 toTrue
, 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']
- class flair.embeddings.token.NILCEmbeddings(embeddings, model='skip', size=100)View on GitHub#
Bases:
WordEmbeddings
-
embeddings_name:
str
= 'NILCEmbeddings'#
- name: str#
- training: bool#
- layer_norm: Optional[nn.LayerNorm]#
- __init__(embeddings, model='skip', size=100)View on GitHub#
Initializes portuguese classic word embeddings trained by NILC Lab.
See: http://www.nilc.icmc.usp.br/embeddings Constructor downloads required files if not there.
- Parameters:
embeddings (
str
) – one of: ‘fasttext’, ‘glove’, ‘wang2vec’ or ‘word2vec’model (
str
) – one of: ‘skip’ or ‘cbow’. This is not applicable to glove.size (
int
) – one of: 50, 100, 300, 600 or 1000.
- classmethod from_params(params)View on GitHub#
- Return type:
-
embeddings_name: