flair.models.SequenceTagger#
- class flair.models.SequenceTagger(embeddings, tag_dictionary, tag_type, use_rnn=True, rnn=None, rnn_type='LSTM', tag_format='BIOES', hidden_size=256, rnn_layers=1, bidirectional=True, use_crf=True, reproject_embeddings=True, dropout=0.0, word_dropout=0.05, locked_dropout=0.5, train_initial_hidden_state=False, loss_weights=None, init_from_state_dict=False, allow_unk_predictions=False)View on GitHub#
Bases:
Classifier
[Sentence
]The SequenceTagger is one of two main architectures in Flair used for sequence tagging.
Sequence tagging means classifying words in a sentence, for instance for part-of-speech tagging or named entity recognition. The SequenceTagger implements the “classic” model based on the LSTM-CRF architecture: words are first embedded using one or multiple
flair.embeddings.TokenEmbeddings
, these embeddings are then passed to the LSTM. Its hidden states for each input word are used to make the final prediction with a softmax classifier. For decoding, the SequenceTagger by default uses a CRF approach.Alternatively, you can use the class
flair.models.TokenClassifier
for sequence tagging without a LSTM-CRF.- __init__(embeddings, tag_dictionary, tag_type, use_rnn=True, rnn=None, rnn_type='LSTM', tag_format='BIOES', hidden_size=256, rnn_layers=1, bidirectional=True, use_crf=True, reproject_embeddings=True, dropout=0.0, word_dropout=0.05, locked_dropout=0.5, train_initial_hidden_state=False, loss_weights=None, init_from_state_dict=False, allow_unk_predictions=False)View on GitHub#
Constructor for this class.
- Parameters:
embeddings (
TokenEmbeddings
) – Embeddings to use during training and predictiontag_dictionary (
Dictionary
) – Dictionary containing all tags from corpus which can be predictedtag_type (
str
) – type of tag which is going to be predicted in case a corpus has multiple annotationsuse_rnn (
bool
) – If true, use a RNN, else Linear layer.rnn (
Optional
[RNN
]) – Takes a torch.nn.Module as parameter by which you can pass a shared RNN between different tasks.rnn_type (
str
) – Specifies the RNN type to use, default is ‘LSTM’, can choose between ‘GRU’ and ‘RNN’ as well.hidden_size (
int
) – Hidden size of RNN layerrnn_layers (
int
) – number of RNN layersbidirectional (
bool
) – If True, RNN becomes bidirectionaluse_crf (
bool
) – If True, use a Conditional Random Field for prediction, else linear map to tag space.reproject_embeddings (
bool
) – If True, add a linear layer on top of embeddings, if you want to imitate fine tune non-trainable embeddings.dropout (
float
) – If > 0, then use dropout.word_dropout (
float
) – If > 0, then use word dropout.locked_dropout (
float
) – If > 0, then use locked dropout.train_initial_hidden_state (
bool
) – if True, trains initial hidden state of RNNloss_weights (
Optional
[dict
[str
,float
]]) – Dictionary of weights for labels for the loss function. If any label’s weight is unspecified it will default to 1.0.init_from_state_dict (
bool
) – Indicator whether we are loading a model from state dict since we need to transform previous models’ weights into CRF instance weightsallow_unk_predictions (
bool
) – If True, allows spans to predict <unk> too.tag_format (
str
) – the format to encode spans as tags, either “BIO” or “BIOES”
Methods
RNN
(rnn_type, rnn_layers, hidden_size, ...)Static wrapper function returning an RNN instance from PyTorch.
__init__
(embeddings, tag_dictionary, tag_type)Constructor for this class.
add_module
(name, module)Add a child module to the current module.
apply
(fn)Apply
fn
recursively to every submodule (as returned by.children()
) as well as self.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Return an iterator over module buffers.
children
()Return an iterator over immediate children modules.
compile
(*args, **kwargs)Compile this Module's forward using
torch.compile()
.cpu
()Move all model parameters and buffers to the CPU.
cuda
([device])Move all model parameters and buffers to the GPU.
double
()Casts all floating point parameters and buffers to
double
datatype.eval
()Set the module in evaluation mode.
evaluate
(data_points, gold_label_type[, ...])Evaluates the model.
extra_repr
()Set the extra representation of the module.
float
()Casts all floating point parameters and buffers to
float
datatype.forward
(sentence_tensor, lengths)Forward pass through the SequenceTagger.
forward_loss
(sentences)Conducts a forward pass through the SequenceTagger using labeled sentences and return the loss.
get_buffer
(target)Return the buffer given by
target
if it exists, otherwise throw an error.get_extra_state
()Return any extra state to include in the module's state_dict.
get_parameter
(target)Return the parameter given by
target
if it exists, otherwise throw an error.get_submodule
(target)Return the submodule given by
target
if it exists, otherwise throw an error.get_used_tokens
(corpus[, context_length, ...])half
()Casts all floating point parameters and buffers to
half
datatype.ipu
([device])Move all model parameters and buffers to the IPU.
load
(model_path)Loads a Flair model from the given file or state dictionary.
load_state_dict
(state_dict[, strict, assign])Copy parameters and buffers from
state_dict
into this module and its descendants.modules
()Return an iterator over all modules in the network.
mtia
([device])Move all model parameters and buffers to the MTIA.
named_buffers
([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
named_children
()Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
parameters
([recurse])Return an iterator over module parameters.
predict
(sentences[, mini_batch_size, ...])Call this method to predict labels for sentences.
print_model_card
()This method produces a log message that includes all recorded parameters the model was trained with.
push_to_hub
(repo_id[, token, private, ...])Uploads the Sequence Tagger model to a Hugging Face Hub repository.
register_backward_hook
(hook)Register a backward hook on the module.
register_buffer
(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook
(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook
(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook
(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook
(hook[, prepend])Register a backward pre-hook on the module.
register_load_state_dict_post_hook
(hook)Register a post-hook to be run after module's
load_state_dict()
is called.register_load_state_dict_pre_hook
(hook)Register a pre-hook to be run before module's
load_state_dict()
is called.register_module
(name, module)Alias for
add_module()
.register_parameter
(name, param)Add a parameter to the module.
register_state_dict_post_hook
(hook)Register a post-hook for the
state_dict()
method.register_state_dict_pre_hook
(hook)Register a pre-hook for the
state_dict()
method.requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
save
(model_file[, checkpoint])Saves the current model to the provided file.
set_extra_state
(state)Set extra state contained in the loaded state_dict.
set_submodule
(target, module)Set the submodule given by
target
if it exists, otherwise throw an error.share_memory
()See
torch.Tensor.share_memory_()
.state_dict
(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
to
(*args, **kwargs)Move and/or cast the parameters and buffers.
to_empty
(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
train
([mode])Set the module in training mode.
type
(dst_type)Casts all parameters and buffers to
dst_type
.xpu
([device])Move all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Reset gradients of all model parameters.
Attributes
T_destination
call_super_init
dump_patches
Each model predicts labels of a certain type.
model_card
training
- property label_type#
Each model predicts labels of a certain type.
- static RNN(rnn_type, rnn_layers, hidden_size, bidirectional, rnn_input_dim)View on GitHub#
Static wrapper function returning an RNN instance from PyTorch.
- Parameters:
rnn_type (
str
) – Type of RNN from torch.nnrnn_layers (
int
) – number of layers to includehidden_size (
int
) – hidden size of RNN cellbidirectional (
bool
) – If True, RNN cell is bidirectionalrnn_input_dim (
int
) – Input dimension to RNN cell
- Return type:
RNN
- forward_loss(sentences)View on GitHub#
Conducts a forward pass through the SequenceTagger using labeled sentences and return the loss.
- Parameters:
sentences (
list
[Sentence
]) – A batch of labeled sentences.- Return type:
tuple
[Tensor
,int
]- Returns:
A tuple consisting of the loss tensor and the number of tokens in the batch.
- forward(sentence_tensor, lengths)View on GitHub#
Forward pass through the SequenceTagger.
- Parameters:
sentence_tensor (
Tensor
) – A tensor representing the batch of sentences.lengths (
LongTensor
) – A IntTensor representing the lengths of the respective sentences.
- predict(sentences, mini_batch_size=32, return_probabilities_for_all_classes=False, verbose=False, label_name=None, return_loss=False, embedding_storage_mode='none', force_token_predictions=False)View on GitHub#
Call this method to predict labels for sentences.
Predictions are directly added to the Sentence objects that are passed to this method. This means that the predict() method does not return predictions. Rather, predictions are stored at each sentence and can be retrieved by calling
flair.data.Sentence.get_labels()
on eachflair.data.Sentence
.- Parameters:
sentences (
Union
[list
[Sentence
],Sentence
]) – List of sentences in batchmini_batch_size (
int
) – batch size for test datareturn_probabilities_for_all_classes (
bool
) – Whether to return probabilities for all classesverbose (
bool
) – whether to use progress barlabel_name (
Optional
[str
]) – which label to predictreturn_loss – whether to return loss value
embedding_storage_mode – determines where to store embeddings - can be “gpu”, “cpu” or None.
force_token_predictions (
bool
) – add labels per token instead of span labels, even if self.predict_spans is True
- push_to_hub(repo_id, token=None, private=None, commit_message='Add new SequenceTagger model.')View on GitHub#
Uploads the Sequence Tagger model to a Hugging Face Hub repository.
- Parameters:
repo_id (
str
) – A namespace (user or an organization) and a repo name separated by a /.token (
Optional
[str
]) – An authentication token (See https://huggingface.co/settings/token).private (
Optional
[bool
]) – Whether the repository is private.commit_message (
str
) – Message to commit while pushing.
Returns: The url of the repository.
- classmethod load(model_path)View on GitHub#
Loads a Flair model from the given file or state dictionary.
- Parameters:
model_path (
Union
[str
,Path
,dict
[str
,Any
]]) – Either the path to the model (as string or Path variable) or the already loaded state dict.- Return type:
- Returns:
The loaded Flair model.